1.0.7.19: SB-EXT:COMPARE-AND-SWAP
[sbcl/simd.git] / src / pcl / cache.lisp
blobf70a2a8f8ac8f6e2350423a90357c0077896964b
1 ;;;; the basics of the PCL wrapper cache mechanism
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
6 ;;;; This software is derived from software originally released by Xerox
7 ;;;; Corporation. Copyright and release statements follow. Later modifications
8 ;;;; to the software are in the public domain and are provided with
9 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
10 ;;;; information.
12 ;;;; copyright information from original PCL sources:
13 ;;;;
14 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
15 ;;;; All rights reserved.
16 ;;;;
17 ;;;; Use and copying of this software and preparation of derivative works based
18 ;;;; upon this software are permitted. Any distribution of this software or
19 ;;;; derivative works must comply with all applicable United States export
20 ;;;; control laws.
21 ;;;;
22 ;;;; This software is made available AS IS, and Xerox Corporation makes no
23 ;;;; warranty about the software, its performance or its conformity to any
24 ;;;; specification.
26 ;;;; Note: as of SBCL 1.0.6.3 it is questionable if cache.lisp can
27 ;;;; anymore be considered to be "derived from software originally
28 ;;;; released by Xerox Corporation", as at that time the whole cache
29 ;;;; implementation was essentially redone from scratch.
31 (in-package "SB-PCL")
33 ;;;; Public API:
34 ;;;;
35 ;;;; fill-cache
36 ;;;; probe-cache
37 ;;;; make-cache
38 ;;;; map-cache
39 ;;;; emit-cache-lookup
40 ;;;; copy-cache
41 ;;;; hash-table-to-cache
42 ;;;;
43 ;;;; This is a thread and interrupt safe reimplementation loosely
44 ;;;; based on the original PCL cache by Kickzales and Rodrigues,
45 ;;;; as described in "Efficient Method Dispatch in PCL".
46 ;;;;
47 ;;;; * Writes to cache are made atomic using compare-and-swap on
48 ;;;; wrappers. Wrappers are never moved or deleted after they have
49 ;;;; been written: to clean them out the cache need to be copied.
50 ;;;;
51 ;;;; * Copying or expanding the cache drops out incomplete and invalid
52 ;;;; lines.
53 ;;;;
54 ;;;; * Since the cache is used for memoization only we don't need to
55 ;;;; worry about which of simultaneous replacements (when expanding
56 ;;;; the cache) takes place: the loosing one will have its work
57 ;;;; redone later. This also allows us to drop entries when the
58 ;;;; cache is about to grow insanely huge.
59 ;;;;
60 ;;;; The cache is essentially a specialized hash-table for layouts, used
61 ;;;; for memoization of effective methods, slot locations, and constant
62 ;;;; return values.
63 ;;;;
64 ;;;; Subsequences of the cache vector are called cache lines.
65 ;;;;
66 ;;;; The cache vector uses the symbol SB-PCL::..EMPTY.. as a sentinel
67 ;;;; value, to allow storing NILs in the vector as well.
69 (defstruct (cache (:constructor %make-cache)
70 (:copier %copy-cache))
71 ;; Number of keys the cache uses.
72 (key-count 1 :type (integer 1 (#.call-arguments-limit)))
73 ;; True if we store values in the cache.
74 (value)
75 ;; Number of vector elements a single cache line uses in the vector.
76 ;; This is always a power of two, so that the vector length can be both
77 ;; an exact multiple of this and a power of two.
78 (line-size 1 :type (integer 1 #.most-positive-fixnum))
79 ;; Cache vector, its length is always both a multiple of line-size
80 ;; and a power of two. This is so that we can calculate
81 ;; (mod index (length vector))
82 ;; using a bitmask.
83 (vector #() :type simple-vector)
84 ;; The bitmask used to calculate
85 ;; (mod (* line-size line-hash) (length vector))).
86 (mask 0 :type fixnum)
87 ;; Current probe-depth needed in the cache.
88 (depth 0 :type index)
89 ;; Maximum allowed probe-depth before the cache needs to expand.
90 (limit 0 :type index))
92 (defun compute-cache-mask (vector-length line-size)
93 ;; Since both vector-length and line-size are powers of two, we
94 ;; can compute a bitmask such that
96 ;; (logand <mask> <combined-layout-hash>)
98 ;; is "morally equal" to
100 ;; (mod (* <line-size> <combined-layout-hash>) <vector-length>)
102 ;; This is it: (1- vector-length) is #b111... of the approriate size
103 ;; to get the MOD, and (- line-size) gives right the number of zero
104 ;; bits at the low end.
105 (logand (1- vector-length) (- line-size)))
107 ;;; The smallest power of two that is equal to or greater then X.
108 (declaim (inline power-of-two-ceiling))
109 (defun power-of-two-ceiling (x)
110 (ash 1 (integer-length (1- x))))
112 (defun cache-statistics (cache)
113 (let* ((vector (cache-vector cache))
114 (size (length vector))
115 (line-size (cache-line-size cache))
116 (total-lines (/ size line-size))
117 (free-lines (loop for i from 0 by line-size below size
118 unless (eq (svref vector i) '..empty..)
119 count t)))
120 (values (- total-lines free-lines) total-lines
121 (cache-depth cache) (cache-limit cache))))
123 ;;; Don't allocate insanely huge caches: this is 4096 lines for a
124 ;;; value cache with 8-15 keys -- probably "big enough for anyone",
125 ;;; and 16384 lines for a commonplace 2-key value cache.
126 (defconstant +cache-vector-max-length+ (expt 2 16))
128 ;;; Compute the maximum allowed probe depth as a function of cache size.
129 ;;; Cache size refers to number of cache lines, not the length of the
130 ;;; cache vector.
132 ;;; FIXME: It would be nice to take the generic function optimization
133 ;;; policy into account here (speed vs. space.)
134 (declaim (inline compute-limit))
135 (defun compute-limit (size)
136 (ceiling (sqrt (sqrt size))))
138 ;;; Returns VALUE if it is not ..EMPTY.., otherwise executes ELSE:
139 (defmacro non-empty-or (value else)
140 (with-unique-names (n-value)
141 `(let ((,n-value ,value))
142 (if (eq ,n-value '..empty..)
143 ,else
144 ,n-value))))
146 ;;; Fast way to check if a thing found at the position of a cache key is one:
147 ;;; it is always either a wrapper, or the ..EMPTY.. symbol.
148 (declaim (inline cache-key-p))
149 (defun cache-key-p (thing)
150 (not (symbolp thing)))
152 ;;; Atomically update the current probe depth of a cache.
153 (defun note-cache-depth (cache depth)
154 (loop for old = (cache-depth cache)
155 while (and (< old depth)
156 (not (eq old (compare-and-swap (cache-depth cache)
157 old depth))))))
159 ;;; Compute the starting index of the next cache line in the cache vector.
160 (declaim (inline next-cache-index))
161 (defun next-cache-index (mask index line-size)
162 (logand mask (+ index line-size)))
164 ;;; Returns the hash-value for layout, or executes ELSE if the layout
165 ;;; is invalid.
166 (defmacro hash-layout-or (layout else)
167 (with-unique-names (n-hash)
168 `(let ((,n-hash (layout-clos-hash ,layout)))
169 (if (zerop ,n-hash)
170 ,else
171 ,n-hash))))
173 ;;; Compute cache index for the cache and a list of layouts.
174 (declaim (inline compute-cache-index))
175 (defun compute-cache-index (cache layouts)
176 (let ((index (hash-layout-or (car layouts)
177 (return-from compute-cache-index nil))))
178 (declare (fixnum index))
179 (dolist (layout (cdr layouts))
180 (mixf index (hash-layout-or layout (return-from compute-cache-index nil))))
181 ;; align with cache lines
182 (logand index (cache-mask cache))))
184 ;;; Emit code that does lookup in cache bound to CACHE-VAR using
185 ;;; layouts bound to LAYOUT-VARS. Go to MISS-TAG on event of a miss or
186 ;;; invalid layout. Otherwise, if VALUE-VAR is non-nil, set it to the
187 ;;; value found. (VALUE-VAR is non-nil only when CACHE-VALUE is true.)
189 ;;; In other words, produces inlined code for COMPUTE-CACHE-INDEX when
190 ;;; number of keys and presence of values in the cache is known
191 ;;; beforehand.
192 (defun emit-cache-lookup (cache-var layout-vars miss-tag value-var)
193 (let ((line-size (power-of-two-ceiling (+ (length layout-vars)
194 (if value-var 1 0)))))
195 (with-unique-names (n-index n-vector n-depth n-pointer n-mask
196 MATCH-WRAPPERS EXIT-WITH-HIT)
197 `(let* ((,n-index (hash-layout-or ,(car layout-vars) (go ,miss-tag)))
198 (,n-vector (cache-vector ,cache-var))
199 (,n-mask (cache-mask ,cache-var)))
200 (declare (index ,n-index))
201 ,@(mapcar (lambda (layout-var)
202 `(mixf ,n-index (hash-layout-or ,layout-var (go ,miss-tag))))
203 (cdr layout-vars))
204 ;; align with cache lines
205 (setf ,n-index (logand ,n-index ,n-mask))
206 (let ((,n-depth (cache-depth ,cache-var))
207 (,n-pointer ,n-index))
208 (declare (index ,n-depth ,n-pointer))
209 (tagbody
210 ,MATCH-WRAPPERS
211 (when (and ,@(mapcar
212 (lambda (layout-var)
213 `(prog1
214 (eq ,layout-var (svref ,n-vector ,n-pointer))
215 (incf ,n-pointer)))
216 layout-vars))
217 ,@(when value-var
218 `((setf ,value-var (non-empty-or (svref ,n-vector ,n-pointer)
219 (go ,miss-tag)))))
220 (go ,EXIT-WITH-HIT))
221 (if (zerop ,n-depth)
222 (go ,miss-tag)
223 (decf ,n-depth))
224 (setf ,n-index (next-cache-index ,n-mask ,n-index ,line-size)
225 ,n-pointer ,n-index)
226 (go ,MATCH-WRAPPERS)
227 ,EXIT-WITH-HIT))))))
229 ;;; Probes CACHE for LAYOUTS.
231 ;;; Returns two values: a boolean indicating a hit or a miss, and a secondary
232 ;;; value that is the value that was stored in the cache if any.
233 (defun probe-cache (cache layouts)
234 (unless (consp layouts)
235 (setf layouts (list layouts)))
236 (let ((vector (cache-vector cache))
237 (key-count (cache-key-count cache))
238 (line-size (cache-line-size cache))
239 (mask (cache-mask cache)))
240 (flet ((probe-line (base)
241 (tagbody
242 (loop for offset from 0 below key-count
243 for layout in layouts do
244 (unless (eq layout (svref vector (+ base offset)))
245 ;; missed
246 (go :miss)))
247 ;; all layouts match!
248 (let ((value (when (cache-value cache)
249 (non-empty-or (svref vector (+ base key-count))
250 (go :miss)))))
251 (return-from probe-cache (values t value)))
252 :miss
253 (return-from probe-line (next-cache-index mask base line-size)))))
254 (let ((index (compute-cache-index cache layouts)))
255 (when index
256 (loop repeat (1+ (cache-depth cache)) do
257 (setf index (probe-line index)))))))
258 (values nil nil))
260 ;;; Tries to write LAYOUTS and VALUE at the cache line starting at
261 ;;; the index BASE. Returns true on success, and false on failure.
262 (defun try-update-cache-line (cache base layouts value)
263 (declare (index base))
264 (let ((vector (cache-vector cache))
265 (new (pop layouts)))
266 ;; If we unwind from here, we will be left with an incomplete
267 ;; cache line, but that is OK: next write using the same layouts
268 ;; will fill it, and reads will treat an incomplete line as a
269 ;; miss -- causing it to be filled.
270 (loop for old = (compare-and-swap (svref vector base) '..empty.. new) do
271 (when (and (cache-key-p old) (not (eq old new)))
272 ;; The place was already taken, and doesn't match our key.
273 (return-from try-update-cache-line nil))
274 (unless layouts
275 ;; All keys match or succesfully saved, save our value --
276 ;; just smash it in. Until the first time it is written
277 ;; there is ..EMPTY.. here, which probes look for, so we
278 ;; don't get bogus hits. This is necessary because we want
279 ;; to be able store arbitrary values here for use with
280 ;; constant-value dispatch functions.
281 (when (cache-value cache)
282 (setf (svref vector (1+ base)) value))
283 (return-from try-update-cache-line t))
284 (setf new (pop layouts))
285 (incf base))))
287 ;;; Tries to write LAYOUTS and VALUE somewhere in the cache. Returns
288 ;;; true on success and false on failure, meaning the cache is too
289 ;;; full.
290 (defun try-update-cache (cache layouts value)
291 (let ((vector (cache-vector cache))
292 (index (or (compute-cache-index cache layouts)
293 ;; At least one of the layouts was invalid: just
294 ;; pretend we updated the cache, and let the next
295 ;; read pick up the mess.
296 (return-from try-update-cache t)))
297 (line-size (cache-line-size cache))
298 (mask (cache-mask cache)))
299 (declare (index index))
300 (loop for depth from 0 upto (cache-limit cache) do
301 (when (try-update-cache-line cache index layouts value)
302 (note-cache-depth cache depth)
303 (return-from try-update-cache t))
304 (setf index (next-cache-index mask index line-size)))))
306 ;;; Constructs a new cache.
307 (defun make-cache (&key (key-count (missing-arg)) (value (missing-arg))
308 (size 1))
309 (let* ((line-size (power-of-two-ceiling (+ key-count (if value 1 0))))
310 (adjusted-size (power-of-two-ceiling size))
311 (length (* adjusted-size line-size)))
312 (if (<= length +cache-vector-max-length+)
313 (%make-cache :key-count key-count
314 :line-size line-size
315 :vector (make-array length :initial-element '..empty..)
316 :value value
317 :mask (compute-cache-mask length line-size)
318 :limit (compute-limit adjusted-size))
319 ;; Make a smaller one, then
320 (make-cache :key-count key-count :value value :size (ceiling size 2)))))
322 ;;;; Copies and expands the cache, dropping any invalidated or
323 ;;;; incomplete lines.
324 (defun copy-and-expand-cache (cache layouts value)
325 (let ((copy (%copy-cache cache))
326 (length (length (cache-vector cache))))
327 (when (< length +cache-vector-max-length+)
328 (setf length (* 2 length)))
329 (tagbody
330 :again
331 ;; Blow way the old vector first, so a GC potentially triggered by
332 ;; MAKE-ARRAY can collect it.
333 (setf (cache-vector copy) #()
334 (cache-vector copy) (make-array length :initial-element '..empty..)
335 (cache-depth copy) 0
336 (cache-mask copy) (compute-cache-mask length (cache-line-size cache))
337 (cache-limit copy) (compute-limit (/ length (cache-line-size cache))))
338 ;; First insert the new one -- if we don't do this first and
339 ;; the cache has reached it's maximum size we may end up
340 ;; looping in FILL-CACHE.
341 (unless (try-update-cache copy layouts value)
342 (bug "Could not insert ~S:~S to supposedly empty ~S." layouts value cache))
343 (map-cache (lambda (layouts value)
344 (unless (try-update-cache copy layouts value)
345 ;; If the cache would grow too much we drop the
346 ;; remaining the entries that don't fit. FIXME:
347 ;; It would be better to drop random entries to
348 ;; avoid getting into a rut here (best done by
349 ;; making MAP-CACHE map in a random order?), and
350 ;; possibly to downsize the cache more
351 ;; aggressively (on the assumption that most
352 ;; entries aren't getting used at the moment.)
353 (when (< length +cache-vector-max-length+)
354 (setf length (* 2 length))
355 (go :again))))
356 cache))
357 copy))
359 (defun cache-has-invalid-entries-p (cache)
360 (let ((vector (cache-vector cache))
361 (line-size (cache-line-size cache))
362 (key-count (cache-key-count cache))
363 (mask (cache-mask cache))
364 (index 0))
365 (loop
366 ;; Check if the line is in use, and check validity of the keys.
367 (let ((key1 (svref vector index)))
368 (when (cache-key-p key1)
369 (if (zerop (layout-clos-hash key1))
370 ;; First key invalid.
371 (return-from cache-has-invalid-entries-p t)
372 ;; Line is in use and the first key is valid: check the rest.
373 (loop for offset from 1 below key-count
374 do (let ((thing (svref vector (+ index offset))))
375 (when (or (not (cache-key-p thing))
376 (zerop (layout-clos-hash thing)))
377 ;; Incomplete line or invalid layout.
378 (return-from cache-has-invalid-entries-p t)))))))
379 ;; Line empty of valid, onwards.
380 (setf index (next-cache-index mask index line-size))
381 (when (zerop index)
382 ;; wrapped around
383 (return-from cache-has-invalid-entries-p nil)))))
385 (defun hash-table-to-cache (table &key value key-count)
386 (let ((cache (make-cache :key-count key-count :value value
387 :size (hash-table-count table))))
388 (maphash (lambda (class value)
389 (setq cache (fill-cache cache (class-wrapper class) value)))
390 table)
391 cache))
393 ;;; Inserts VALUE to CACHE keyd by LAYOUTS. Expands the cache if
394 ;;; necessary, and returns the new cache.
395 (defun fill-cache (cache layouts value)
396 (labels
397 ((%fill-cache (cache layouts value)
398 (cond ((try-update-cache cache layouts value)
399 cache)
400 ((cache-has-invalid-entries-p cache)
401 ;; Don't expand yet: maybe there will be enough space if
402 ;; we just drop the invalid entries.
403 (%fill-cache (copy-cache cache) layouts value))
405 (copy-and-expand-cache cache layouts value)))))
406 (if (listp layouts)
407 (%fill-cache cache layouts value)
408 (%fill-cache cache (list layouts) value))))
410 ;;; Calls FUNCTION with all layouts and values in cache.
411 (defun map-cache (function cache)
412 (let* ((vector (cache-vector cache))
413 (key-count (cache-key-count cache))
414 (valuep (cache-value cache))
415 (line-size (cache-line-size cache))
416 (mask (cache-mask cache))
417 (fun (if (functionp function)
418 function
419 (fdefinition function)))
420 (index 0)
421 (key nil))
422 (tagbody
423 :map
424 (let ((layouts
425 (loop for offset from 0 below key-count
426 collect (non-empty-or (svref vector (+ offset index))
427 (go :next)))))
428 (let ((value (when valuep
429 (non-empty-or (svref vector (+ index key-count))
430 (go :next)))))
431 ;; Let the callee worry about invalid layouts
432 (funcall fun layouts value)))
433 :next
434 (setf index (next-cache-index mask index line-size))
435 (unless (zerop index)
436 (go :map))))
437 cache)
439 ;;; Copying a cache without expanding it is very much like mapping it:
440 ;;; we need to be carefull because there may be updates while we are
441 ;;; copying it, and we don't want to copy incomplete entries or invalid
442 ;;; ones.
443 (defun copy-cache (cache)
444 (let* ((vector (cache-vector cache))
445 (copy (make-array (length vector) :initial-element '..empty..))
446 (line-size (cache-line-size cache))
447 (key-count (cache-key-count cache))
448 (valuep (cache-value cache))
449 (mask (cache-mask cache))
450 (size (/ (length vector) line-size))
451 (index 0)
452 (elt nil)
453 (depth 0))
454 (tagbody
455 :copy
456 (let ((layouts (loop for offset from 0 below key-count
457 collect (non-empty-or (svref vector (+ index offset))
458 (go :next)))))
459 ;; Check validity & compute primary index.
460 (let ((primary (or (compute-cache-index cache layouts)
461 (go :next))))
462 ;; Check & copy value.
463 (when valuep
464 (setf (svref copy (+ index key-count))
465 (non-empty-or (svref vector (+ index key-count))
466 (go :next))))
467 ;; Copy layouts.
468 (loop for offset from 0 below key-count do
469 (setf (svref copy (+ index offset)) (pop layouts)))
470 ;; Update probe depth.
471 (let ((distance (/ (- index primary) line-size)))
472 (setf depth (max depth (if (minusp distance)
473 ;; account for wrap-around
474 (+ distance size)
475 distance))))))
476 :next
477 (setf index (next-cache-index mask index line-size))
478 (unless (zerop index)
479 (go :copy)))
480 (%make-cache :vector copy
481 :depth depth
482 :key-count (cache-key-count cache)
483 :line-size line-size
484 :value valuep
485 :mask mask
486 :limit (cache-limit cache))))
488 ;;;; For debugging & collecting statistics.
490 (defun map-all-caches (function)
491 (dolist (p (list-all-packages))
492 (do-symbols (s p)
493 (when (eq p (symbol-package s))
494 (dolist (name (list s
495 `(setf ,s)
496 (slot-reader-name s)
497 (slot-writer-name s)
498 (slot-boundp-name s)))
499 (when (fboundp name)
500 (let ((fun (fdefinition name)))
501 (when (typep fun 'generic-function)
502 (let ((cache (gf-dfun-cache fun)))
503 (when cache
504 (funcall function name cache)))))))))))
506 (defun check-cache-consistency (cache)
507 (let ((table (make-hash-table :test 'equal)))
508 (map-cache (lambda (layouts value)
509 (declare (ignore value))
510 (if (gethash layouts table)
511 (cerror "Check futher."
512 "Multiple appearances of ~S." layouts)
513 (setf (gethash layouts table) t)))
514 cache)))