Debian Codegraph @

rpython/jit/metainterp/counter.py

raw symbols SCIP
1 from rpython.rlib.rarithmetic import r_singlefloat, r_uint
2 from rpython.rtyper.lltypesystem import lltype, rffi
3 from rpython.translator.tool.cbuild import ExternalCompilationInfo
4
5
6 r_uint32 = rffi.r_uint
7 assert r_uint32.BITS == 32
8 UINT32MAX = 2 ** 32 - 1
9
10 # keep in sync with the C code in pypy__decay_jit_counters below
11 ENTRY = lltype.Struct('timetable_entry',
12 ('times', lltype.FixedSizeArray(rffi.FLOAT, 5)),
13 ('subhashes', lltype.FixedSizeArray(rffi.USHORT, 5)))
14
15
16 class JitCounter:
17 """A process translated with the JIT contains one prebuilt instance
18 of this class. It is used for three things:
19
20 * It maps greenkey hashes to counters, to know when we have seen this
21 greenkey enough to reach the 'threshold' or 'function_threshold'
22 parameters. This is done in a lossy way by a fixed-size 'timetable'.
23
24 * It handles the counters on the failing guards, for 'trace_eagerness'.
25 This is done in the same 'timetable'.
26
27 * It records the JitCell objects that are created when we compile
28 a loop, in a non-lossy dictionary-like strurcture. This is done
29 in the 'celltable'.
30
31 The 'timetable' is a table of DEFAULT_SIZE entries, each of which
32 containing 5 entries. From a hash value, we use the index number
33 '_get_index(hash)', and then we look in all five entries for a
34 matching '_get_subhash(hash)'. The five entries are roughly kept
35 sorted by decreasing recorded time. The hash value itself should be
36 computed accordingly: we only use bits 21:32 for _get_index and
37 bits 0:16 for _get_subhash. (This organization is "probably good"
38 to get not-too-random behavior; another motivation for it was for
39 the STM branch, to avoid pointless conflicts between threads.)
40
41 The time value stored in the timetable is a (short-precision)
42 floating-point number. The idea is that a value of 0.0 means
43 absent, and values go up to the maximum of 1.0.
44
45 'compute_threshold(threshold)' returns basically the fraction
46 1.0/threshold, corresponding to the 'increment' value for the
47 following APIs.
48
49 'tick(hash, increment)' adds 'increment' to the time value stored
50 with the 'hash'. Remember that only bits 0:16,21:32 of the hash
51 are used; in case of collision between two hashes, they will grow
52 twice as fast, because each tick() call will contribute to the
53 colliding time value.
54
55 'fetch_next_hash()' returns a "random" hash value suitable for
56 using in tick() later. Used when compiling guards; when the
57 guard actually fails, we'll tick() the guard's stored random hash.
58
59 'reset(hash)', 'change_current_fraction(hash, new_time_value)'
60 change the time value associated with a hash. The former resets
61 it to zero, and the latter changes it to the given value (which
62 should be a value close to 1.0).
63
64 'set_decay(decay)', 'decay_all_counters()' is used to globally
65 reduce all the stored time values. They all get multiplied by
66 a fraction close to (but smaller than) 1.0, computed from the
67 'decay' parameter.
68
69 'install_new_cell(hash, newcell)' adds the new JitCell to the
70 celltable, at the index given by 'hash' (bits 21:32). Unlike
71 the timetable, the celltable stores a linked list of JitCells
72 for every entry, and so it is not lossy.
73
74 'lookup_chain(hash)' returns the first JitCell at 'hash'. You can
75 then walk the chain by following the '.next' attributes until you
76 reach None.
77
78 'cleanup_chain(hash)' resets the timetable's 'hash' entry and
79 cleans up the celltable at 'hash'. It removes those JitCells
80 for which 'cell.should_remove_jitcell()' returns True.
81 """
82 DEFAULT_SIZE = 2048
83
84 def __init__(self, size=DEFAULT_SIZE, translator=None):
85 "NOT_RPYTHON"
86 self.size = size
87 self.shift = 16
88 while (UINT32MAX >> self.shift) != size - 1:
89 self.shift += 1
90 assert self.shift < 999, "size is not a power of two <= 2**16"
91 #
92 # The table of timings. This is a 5-ways associative cache.
93 # We index into it using a number between 0 and (size - 1),
94 # and we're getting a 32-bytes-long entry; then this entry
95 # contains 5 possible ways, each occupying 6 bytes: 4 bytes
96 # for a float, and the 2 lowest bytes from the original hash.
97 self.timetable = lltype.malloc(rffi.CArray(ENTRY), self.size,
98 flavor='raw', zero=True,
99 track_allocation=False)
100 self._nexthash = r_uint(0)
101 #
102 # The table of JitCell entries, recording already-compiled loops
103 self.celltable = [None] * size
104 #
105 if translator is not None:
106 class Glob:
107 step = 0
108 glob = Glob()
109 def invoke_after_minor_collection():
110 # After 32 minor collections, we call decay_all_counters().
111 # The "--jit decay=N" option measures the amount the
112 # counters are then reduced by.
113 glob.step += 1
114 if glob.step == 32:
115 glob.step = 0
116 self.decay_all_counters()
117 if not hasattr(translator, '_jit2gc'):
118 translator._jit2gc = {}
119 translator._jit2gc['invoke_after_minor_collection'] = (
120 invoke_after_minor_collection)
121
122 def compute_threshold(self, threshold):
123 """Return the 'increment' value corresponding to the given number."""
124 if threshold <= 0:
125 return 0.0 # no increment, never reach 1.0
126 return 1.0 / (threshold - 0.001)
127
128 def _get_index(self, hash):
129 """Return the index (< self.size) from a hash. This truncates
130 the hash to 32 bits, and then keep the *highest* remaining bits.
131 Be sure that hash is computed correctly, by multiplying with
132 a large odd number or by fetch_next_hash()."""
133 hash32 = r_uint(r_uint32(hash)) # mask off the bits higher than 32
134 index = hash32 >> self.shift # shift, resulting in a value < size
135 return index # return the result as a r_uint
136 _get_index._always_inline_ = True
137
138 @staticmethod
139 def _get_subhash(hash):
140 return hash & 65535
141
142 def fetch_next_hash(self):
143 result = self._nexthash
144 # note: all three "1" bits in the following constant are needed
145 # to make test_counter.test_fetch_next_index pass. The first
146 # is to increment the "subhash" (lower 16 bits of the hash).
147 # The second is to increment the "index" portion of the hash.
148 # The third is so that after 65536 passes, the "index" is
149 # incremented by one more (by overflow), so that the next
150 # 65536 passes don't end up with the same subhashes.
151 self._nexthash = result + r_uint(1 | (1 << self.shift) |
152 (1 << (self.shift - 16)))
153 return result
154
155 def _swap(self, p_entry, n):
156 if float(p_entry.times[n]) > float(p_entry.times[n + 1]):
157 return n + 1
158 else:
159 x = p_entry.times[n]
160 p_entry.times[n] = p_entry.times[n + 1]
161 p_entry.times[n + 1] = x
162 x = p_entry.subhashes[n]
163 p_entry.subhashes[n] = p_entry.subhashes[n + 1]
164 p_entry.subhashes[n + 1] = x
165 return n
166 _swap._always_inline_ = True
167
168 def _tick_slowpath(self, p_entry, subhash):
169 if p_entry.subhashes[1] == subhash:
170 n = self._swap(p_entry, 0)
171 elif p_entry.subhashes[2] == subhash:
172 n = self._swap(p_entry, 1)
173 elif p_entry.subhashes[3] == subhash:
174 n = self._swap(p_entry, 2)
175 elif p_entry.subhashes[4] == subhash:
176 n = self._swap(p_entry, 3)
177 else:
178 n = 4
179 while n > 0 and float(p_entry.times[n - 1]) == 0.0:
180 n -= 1
181 p_entry.subhashes[n] = rffi.cast(rffi.USHORT, subhash)
182 p_entry.times[n] = r_singlefloat(0.0)
183 return n
184
185 def tick(self, hash, increment):
186 p_entry = self.timetable[self._get_index(hash)]
187 subhash = self._get_subhash(hash)
188 #
189 if p_entry.subhashes[0] == subhash:
190 n = 0
191 else:
192 n = self._tick_slowpath(p_entry, subhash)
193 #
194 counter = float(p_entry.times[n]) + increment
195 if counter < 1.0:
196 p_entry.times[n] = r_singlefloat(counter)
197 return False
198 else:
199 # when the bound is reached, we immediately reset the value to 0.0
200 self.reset(hash)
201 return True
202 tick._always_inline_ = True
203
204 def change_current_fraction(self, hash, new_fraction):
205 """Change the value stored for 'hash' to be the given 'new_fraction',
206 which should be a float equal to or slightly lower than 1.0.
207 """
208 p_entry = self.timetable[self._get_index(hash)]
209 subhash = self._get_subhash(hash)
210
211 # find in 'n' the index that will be overwritten: the first within
212 # range(5) that contains either the right subhash, or a null time
213 # (or, if there isn't any, then just n == 4 will do).
214 n = 0
215 while n < 4 and (p_entry.subhashes[n] != subhash and
216 float(p_entry.times[n]) != 0.0):
217 n += 1
218
219 # move one step to the right all elements [n - 1, n - 2, ..., 0],
220 # (this overwrites the old item at index 'n')
221 while n > 0:
222 n -= 1
223 p_entry.subhashes[n + 1] = p_entry.subhashes[n]
224 p_entry.times[n + 1] = p_entry.times[n]
225
226 # insert the new hash at index 0. This is a good approximation,
227 # because change_current_fraction() should be used for
228 # new_fraction == value close to 1.0.
229 p_entry.subhashes[0] = rffi.cast(rffi.USHORT, subhash)
230 p_entry.times[0] = r_singlefloat(new_fraction)
231
232 def reset(self, hash):
233 p_entry = self.timetable[self._get_index(hash)]
234 subhash = self._get_subhash(hash)
235 for i in range(5):
236 if p_entry.subhashes[i] == subhash:
237 p_entry.times[i] = r_singlefloat(0.0)
238
239 def lookup_chain(self, hash):
240 return self.celltable[self._get_index(hash)]
241
242 def cleanup_chain(self, hash):
243 self.reset(hash)
244 self.install_new_cell(hash, None)
245
246 def install_new_cell(self, hash, newcell):
247 index = self._get_index(hash)
248 cell = self.celltable[index]
249 keep = newcell
250 while cell is not None:
251 nextcell = cell.next
252 if not cell.should_remove_jitcell():
253 cell.next = keep
254 keep = cell
255 cell = nextcell
256 self.celltable[index] = keep
257
258 def set_decay(self, decay):
259 """Set the decay, from 0 (none) to 1000 (max)."""
260 if decay < 0:
261 decay = 0
262 elif decay > 1000:
263 decay = 1000
264 self.decay_by_mult = 1.0 - (decay * 0.001)
265
266 def decay_all_counters(self):
267 # Called during a minor collection by the GC, to gradually decay
268 # counters that didn't reach their maximum. Thus if a counter
269 # is incremented very slowly, it will never reach the maximum.
270 # This avoids altogether the JIT compilation of rare paths.
271 # We also call this function when any maximum bound is reached,
272 # to avoid sudden bursts of JIT-compilation (the next one will
273 # not reach the maximum bound immmediately after). This is
274 # important in corner cases where we would suddenly compile more
275 # than one loop because all counters reach the bound at the same
276 # time, but where compiling all but the first one is pointless.
277 p = rffi.cast(rffi.CCHARP, self.timetable)
278 pypy__decay_jit_counters(p, self.decay_by_mult, self.size)
279
280
281 # this function is written directly in C; gcc will optimize it using SSE
282 eci = ExternalCompilationInfo(post_include_bits=["""
283 static void pypy__decay_jit_counters(char *data, double f1, long size) {
284 struct rpy_jitcnt { float times[5]; unsigned short subhashes[5]; };
285 struct rpy_jitcnt *p = (struct rpy_jitcnt *)data;
286 float f = (float)f1;
287 long i;
288 for (i=0; i<size; i++) {
289 p->times[0] *= f;
290 p->times[1] *= f;
291 p->times[2] *= f;
292 p->times[3] *= f;
293 p->times[4] *= f;
294 ++p;
295 }
296 }
297 """])
298
299 pypy__decay_jit_counters = rffi.llexternal(
300 "pypy__decay_jit_counters", [rffi.CCHARP, lltype.Float, lltype.Signed],
301 lltype.Void, compilation_info=eci, _nowrapper=True, sandboxsafe=True)
302
303
304 # ____________________________________________________________
305 #
306 # A non-RPython version that avoids issues with rare random collisions,
307 # which make all tests brittle
308
309 class DeterministicJitCounter(JitCounter):
310 def __init__(self):
311 from collections import defaultdict
312 JitCounter.__init__(self, size=8)
313 def make_null_entry():
314 return lltype.malloc(ENTRY, immortal=True, zero=True)
315 self.timetable = defaultdict(make_null_entry)
316 self.celltable = defaultdict(lambda: None)
317
318 def _get_index(self, hash):
319 "NOT_RPYTHON"
320 return hash
321
322 def decay_all_counters(self):
323 "NOT_RPYTHON"
324 pass
325
326 def _clear_all(self):
327 self.timetable.clear()
328 self.celltable.clear()