1.0.6.33: small CLOS cache improvements
[sbcl.git] / src / pcl / cache.lisp
1 ;;;; the basics of the PCL wrapper cache mechanism
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5
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.
11
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.
25
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.
30
31 (in-package "SB-PCL")
32
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.
68
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 (mod (* line-size line-hash) (length vector))).
85   (mask 0 :type fixnum)
86   ;; Current probe-depth needed in the cache.
87   (depth 0 :type index)
88   ;; Maximum allowed probe-depth before the cache needs to expand.
89   (limit 0 :type index))
90
91 (defun compute-cache-mask (vector-length line-size)
92   ;; Since both vector-length and line-size are powers of two, we
93   ;; can compute a bitmask such that
94   ;;
95   ;;  (logand <mask> <combined-layout-hash>)
96   ;;
97   ;; is "morally equal" to
98   ;;
99   ;;  (mod (* <line-size> <combined-layout-hash>) <vector-length>)
100   ;;
101   ;; This is it: (1- vector-length) is #b111... of the approriate size
102   ;; to get the MOD, and (- line-size) gives right the number of zero
103   ;; bits at the low end.
104   (logand (1- vector-length) (- line-size)))
105
106 ;;; The smallest power of two that is equal to or greater then X.
107 (declaim (inline power-of-two-ceiling))
108 (defun power-of-two-ceiling (x)
109   (ash 1 (integer-length (1- x))))
110
111 (defun cache-statistics (cache)
112   (let* ((vector (cache-vector cache))
113          (size (length vector))
114          (line-size (cache-line-size cache))
115          (total-lines (/ size line-size))
116          (free-lines (loop for i from 0 by line-size below size
117                            unless (eq (svref vector i) '..empty..)
118                            count t)))
119     (values (- total-lines free-lines) total-lines
120             (cache-depth cache) (cache-limit cache))))
121
122 ;;; Don't allocate insanely huge caches.
123 (defconstant +cache-vector-max-length+ (expt 2 14))
124
125 ;;; Compute the maximum allowed probe depth as a function of cache size.
126 ;;; Cache size refers to number of cache lines, not the length of the
127 ;;; cache vector.
128 ;;;
129 ;;; FIXME: It would be nice to take the generic function optimization
130 ;;; policy into account here (speed vs. space.)
131 (declaim (inline compute-limit))
132 (defun compute-limit (size)
133   (ceiling (sqrt (sqrt size))))
134
135 ;;; Returns VALUE if it is not ..EMPTY.., otherwise executes ELSE:
136 (defmacro non-empty-or (value else)
137   (with-unique-names (n-value)
138     `(let ((,n-value ,value))
139        (if (eq ,n-value '..empty..)
140            ,else
141            ,n-value))))
142
143 ;;; Fast way to check if a thing found at the position of a cache key is one:
144 ;;; it is always either a wrapper, or the ..EMPTY.. symbol.
145 (declaim (inline cache-key-p))
146 (defun cache-key-p (thing)
147   (not (symbolp thing)))
148
149 (eval-when (:compile-toplevel :load-toplevel :execute)
150   (sb-kernel:define-structure-slot-compare-and-swap compare-and-swap-cache-depth
151       :structure cache
152       :slot depth))
153
154 ;;; Utility macro for atomic updates without locking... doesn't
155 ;;; do much right now, and it would be nice to make this more magical.
156 (defmacro compare-and-swap (place old new)
157   (unless (consp place)
158     (error "Don't know how to compare and swap ~S." place))
159   (ecase (car place)
160     (svref
161      `(simple-vector-compare-and-swap ,@(cdr place) ,old ,new))
162     (cache-depth
163      `(compare-and-swap-cache-depth ,@(cdr place) ,old ,new))))
164
165 ;;; Atomically update the current probe depth of a cache.
166 (defun note-cache-depth (cache depth)
167   (loop for old = (cache-depth cache)
168         while (and (< old depth)
169                    (not (eq old (compare-and-swap (cache-depth cache)
170                                                   old depth))))))
171
172 ;;; Compute the starting index of the next cache line in the cache vector.
173 (declaim (inline next-cache-index))
174 (defun next-cache-index (mask index line-size)
175   (logand mask (+ index line-size)))
176
177 ;;; Returns the hash-value for layout, or executes ELSE if the layout
178 ;;; is invalid.
179 (defmacro hash-layout-or (layout else)
180   (with-unique-names (n-hash)
181     `(let ((,n-hash (layout-clos-hash ,layout)))
182        (if (zerop ,n-hash)
183            ,else
184            ,n-hash))))
185
186 ;;; Compute cache index for the cache and a list of layouts.
187 (declaim (inline compute-cache-index))
188 (defun compute-cache-index (cache layouts)
189   (let ((index (hash-layout-or (car layouts)
190                                (return-from compute-cache-index nil))))
191     (declare (fixnum index))
192     (dolist (layout (cdr layouts))
193       (mixf index (hash-layout-or layout (return-from compute-cache-index nil))))
194     ;; align with cache lines
195     (logand index (cache-mask cache))))
196
197 ;;; Emit code that does lookup in cache bound to CACHE-VAR using
198 ;;; layouts bound to LAYOUT-VARS. Go to MISS-TAG on event of a miss or
199 ;;; invalid layout. Otherwise, if VALUE-VAR is non-nil, set it to the
200 ;;; value found. (VALUE-VAR is non-nil only when CACHE-VALUE is true.)
201 ;;;
202 ;;; In other words, produces inlined code for COMPUTE-CACHE-INDEX when
203 ;;; number of keys and presence of values in the cache is known
204 ;;; beforehand.
205 (defun emit-cache-lookup (cache-var layout-vars miss-tag value-var)
206   (let ((line-size (power-of-two-ceiling (+ (length layout-vars)
207                                             (if value-var 1 0)))))
208     (with-unique-names (n-index n-vector n-depth n-pointer n-mask
209                        MATCH-WRAPPERS EXIT-WITH-HIT)
210       `(let* ((,n-index (hash-layout-or ,(car layout-vars) (go ,miss-tag)))
211               (,n-vector (cache-vector ,cache-var))
212               (,n-mask (cache-mask ,cache-var)))
213          (declare (index ,n-index))
214          ,@(mapcar (lambda (layout-var)
215                      `(mixf ,n-index (hash-layout-or ,layout-var (go ,miss-tag))))
216                    (cdr layout-vars))
217          ;; align with cache lines
218          (setf ,n-index (logand ,n-index ,n-mask))
219          (let ((,n-depth (cache-depth ,cache-var))
220                (,n-pointer ,n-index))
221            (declare (index ,n-depth ,n-pointer))
222            (tagbody
223             ,MATCH-WRAPPERS
224               (when (and ,@(mapcar
225                             (lambda (layout-var)
226                               `(prog1
227                                    (eq ,layout-var (svref ,n-vector ,n-pointer))
228                                  (incf ,n-pointer)))
229                             layout-vars))
230                 ,@(when value-var
231                     `((setf ,value-var (non-empty-or (svref ,n-vector ,n-pointer)
232                                                      (go ,miss-tag)))))
233                 (go ,EXIT-WITH-HIT))
234               (if (zerop ,n-depth)
235                   (go ,miss-tag)
236                   (decf ,n-depth))
237               (setf ,n-index (next-cache-index ,n-mask ,n-index ,line-size)
238                     ,n-pointer ,n-index)
239               (go ,MATCH-WRAPPERS)
240             ,EXIT-WITH-HIT))))))
241
242 ;;; Probes CACHE for LAYOUTS.
243 ;;;
244 ;;; Returns two values: a boolean indicating a hit or a miss, and a secondary
245 ;;; value that is the value that was stored in the cache if any.
246 (defun probe-cache (cache layouts)
247   (unless (consp layouts)
248     (setf layouts (list layouts)))
249   (let ((vector (cache-vector cache))
250         (key-count (cache-key-count cache))
251         (line-size (cache-line-size cache))
252         (mask (cache-mask cache)))
253     (flet ((probe-line (base)
254              (tagbody
255                 (loop for offset from 0 below key-count
256                       for layout in layouts do
257                       (unless (eq layout (svref vector (+ base offset)))
258                         ;; missed
259                         (go :miss)))
260                 ;; all layouts match!
261                 (let ((value (when (cache-value cache)
262                                (non-empty-or (svref vector (+ base key-count))
263                                              (go :miss)))))
264                   (return-from probe-cache (values t value)))
265               :miss
266                 (return-from probe-line (next-cache-index mask base line-size)))))
267       (let ((index (compute-cache-index cache layouts)))
268         (when index
269           (loop repeat (1+ (cache-depth cache)) do
270                 (setf index (probe-line index)))))))
271   (values nil nil))
272
273 ;;; Tries to write LAYOUTS and VALUE at the cache line starting at
274 ;;; the index BASE. Returns true on success, and false on failure.
275 (defun try-update-cache-line (cache base layouts value)
276   (declare (index base))
277   (let ((vector (cache-vector cache))
278         (new (pop layouts)))
279     ;; If we unwind from here, we will be left with an incomplete
280     ;; cache line, but that is OK: next write using the same layouts
281     ;; will fill it, and reads will treat an incomplete line as a
282     ;; miss -- causing it to be filled.
283     (loop for old = (compare-and-swap (svref vector base) '..empty.. new)  do
284           (when (and (cache-key-p old) (not (eq old new)))
285             ;; The place was already taken, and doesn't match our key.
286             (return-from try-update-cache-line nil))
287           (unless layouts
288             ;; All keys match or succesfully saved, save our value --
289             ;; just smash it in. Until the first time it is written
290             ;; there is ..EMPTY.. here, which probes look for, so we
291             ;; don't get bogus hits. This is necessary because we want
292             ;; to be able store arbitrary values here for use with
293             ;; constant-value dispatch functions.
294             (when (cache-value cache)
295               (setf (svref vector (1+ base)) value))
296             (return-from try-update-cache-line t))
297           (setf new (pop layouts))
298           (incf base))))
299
300 ;;; Tries to write LAYOUTS and VALUE somewhere in the cache. Returns
301 ;;; true on success and false on failure, meaning the cache is too
302 ;;; full.
303 (defun try-update-cache (cache layouts value)
304   (let ((vector (cache-vector cache))
305         (index (or (compute-cache-index cache layouts)
306                    ;; At least one of the layouts was invalid: just
307                    ;; pretend we updated the cache, and let the next
308                    ;; read pick up the mess.
309                    (return-from try-update-cache t)))
310         (line-size (cache-line-size cache))
311         (mask (cache-mask cache)))
312     (declare (index index))
313     (loop for depth from 0 upto (cache-limit cache) do
314           (when (try-update-cache-line cache index layouts value)
315             (note-cache-depth cache depth)
316             (return-from try-update-cache t))
317           (setf index (next-cache-index mask index line-size)))))
318
319 ;;; Constructs a new cache.
320 (defun make-cache (&key (key-count (missing-arg)) (value (missing-arg))
321                    (size 1))
322   (let* ((line-size (power-of-two-ceiling (+ key-count (if value 1 0))))
323          (adjusted-size (power-of-two-ceiling size))
324          (length (* adjusted-size line-size)))
325     (if (<= length +cache-vector-max-length+)
326         (%make-cache :key-count key-count
327                      :line-size line-size
328                      :vector (make-array length :initial-element '..empty..)
329                      :value value
330                      :mask (compute-cache-mask length line-size)
331                      :limit (compute-limit adjusted-size))
332         ;; Make a smaller one, then
333         (make-cache :key-count key-count :value value :size (ceiling size 2)))))
334
335 ;;;; Copies and expands the cache, dropping any invalidated or
336 ;;;; incomplete lines.
337 (defun copy-and-expand-cache (cache)
338   (let ((copy (%copy-cache cache))
339         (length (length (cache-vector cache))))
340     (when (< length +cache-vector-max-length+)
341       (setf length (* 2 length)))
342     (tagbody
343      :again
344        (setf (cache-vector copy) (make-array length :initial-element '..empty..)
345              (cache-depth copy) 0
346              (cache-mask copy) (compute-cache-mask length (cache-line-size cache))
347              (cache-limit copy) (compute-limit (/ length (cache-line-size cache))))
348        (map-cache (lambda (layouts value)
349                     (unless (try-update-cache copy layouts value)
350                       ;; If the cache would grow too much we drop the
351                       ;; remaining the entries that don't fit. FIXME:
352                       ;; It would be better to drop random entries to
353                       ;; avoid getting into a rut here (best done by
354                       ;; making MAP-CACHE map in a random order?), and
355                       ;; possibly to downsize the cache more
356                       ;; aggressively (on the assumption that most
357                       ;; entries aren't getting used at the moment.)
358                       (when (< length +cache-vector-max-length+)
359                         (setf length (* 2 length))
360                         (go :again))))
361                   cache))
362     copy))
363
364 (defun cache-has-invalid-entries-p (cache)
365   (let ((vector (cache-vector cache))
366         (line-size (cache-line-size cache))
367         (key-count (cache-key-count cache))
368         (mask (cache-mask cache))
369         (index 0))
370     (loop
371       ;; Check if the line is in use, and check validity of the keys.
372       (let ((key1 (svref vector index)))
373         (when (cache-key-p key1)
374           (if (zerop (layout-clos-hash key1))
375               ;; First key invalid.
376               (return-from cache-has-invalid-entries-p t)
377               ;; Line is in use and the first key is valid: check the rest.
378               (loop for offset from 1 below key-count
379                     do (let ((thing (svref vector (+ index offset))))
380                          (when (or (not (cache-key-p thing))
381                                    (zerop (layout-clos-hash thing)))
382                            ;; Incomplete line or invalid layout.
383                            (return-from cache-has-invalid-entries-p t)))))))
384       ;; Line empty of valid, onwards.
385       (setf index (next-cache-index mask index line-size))
386       (when (zerop index)
387         ;; wrapped around
388         (return-from cache-has-invalid-entries-p nil)))))
389
390 (defun hash-table-to-cache (table &key value key-count)
391   (let ((cache (make-cache :key-count key-count :value value
392                            :size (hash-table-count table))))
393     (maphash (lambda (class value)
394                (setq cache (fill-cache cache (class-wrapper class) value)))
395              table)
396     cache))
397
398 ;;; Inserts VALUE to CACHE keyd by LAYOUTS. Expands the cache if
399 ;;; necessary, and returns the new cache.
400 (defun fill-cache (cache layouts value)
401   (labels
402       ((%fill-cache (cache layouts value)
403          (cond ((try-update-cache cache layouts value)
404                 cache)
405                ((cache-has-invalid-entries-p cache)
406                 ;; Don't expand yet: maybe there will be enough space if
407                 ;; we just drop the invalid entries.
408                 (%fill-cache (copy-cache cache) layouts value))
409                (t
410                 (%fill-cache (copy-and-expand-cache cache) layouts value)))))
411     (if (listp layouts)
412         (%fill-cache cache layouts value)
413         (%fill-cache cache (list layouts) value))))
414
415 ;;; Calls FUNCTION with all layouts and values in cache.
416 (defun map-cache (function cache)
417   (let* ((vector (cache-vector cache))
418          (key-count (cache-key-count cache))
419          (valuep (cache-value cache))
420          (line-size (cache-line-size cache))
421          (mask (cache-mask cache))
422          (fun (if (functionp function)
423                   function
424                   (fdefinition function)))
425          (index 0)
426          (key nil))
427     (tagbody
428      :map
429        (let ((layouts
430               (loop for offset from 0 below key-count
431                     collect (non-empty-or (svref vector (+ offset index))
432                                           (go :next)))))
433          (let ((value (when valuep
434                         (non-empty-or (svref vector (+ index key-count))
435                                       (go :next)))))
436            ;; Let the callee worry about invalid layouts
437            (funcall fun layouts value)))
438      :next
439        (setf index (next-cache-index mask index line-size))
440        (unless (zerop index)
441          (go :map))))
442   cache)
443
444 ;;; Copying a cache without expanding it is very much like mapping it:
445 ;;; we need to be carefull because there may be updates while we are
446 ;;; copying it, and we don't want to copy incomplete entries or invalid
447 ;;; ones.
448 (defun copy-cache (cache)
449   (let* ((vector (cache-vector cache))
450          (copy (make-array (length vector) :initial-element '..empty..))
451          (line-size (cache-line-size cache))
452          (key-count (cache-key-count cache))
453          (valuep (cache-value cache))
454          (mask (cache-mask cache))
455          (size (/ (length vector) line-size))
456          (index 0)
457          (elt nil)
458          (depth 0))
459     (tagbody
460      :copy
461        (let ((layouts (loop for offset from 0 below key-count
462                             collect (non-empty-or (svref vector (+ index offset))
463                                                   (go :next)))))
464          ;; Check validity & compute primary index.
465          (let ((primary (or (compute-cache-index cache layouts)
466                             (go :next))))
467            ;; Check & copy value.
468            (when valuep
469              (setf (svref copy (+ index key-count))
470                    (non-empty-or (svref vector (+ index key-count))
471                                  (go :next))))
472            ;; Copy layouts.
473            (loop for offset from 0 below key-count do
474                  (setf (svref copy (+ index offset)) (pop layouts)))
475            ;; Update probe depth.
476            (let ((distance (/ (- index primary) line-size)))
477              (setf depth (max depth (if (minusp distance)
478                                         ;; account for wrap-around
479                                         (+ distance size)
480                                         distance))))))
481      :next
482        (setf index (next-cache-index mask index line-size))
483        (unless (zerop index)
484          (go :copy)))
485     (%make-cache :vector copy
486                  :depth depth
487                  :key-count (cache-key-count cache)
488                  :line-size line-size
489                  :value valuep
490                  :mask mask
491                  :limit (cache-limit cache))))
492
493 ;;;; For debugging & collecting statistics.
494
495 (defun map-all-caches (function)
496   (dolist (p (list-all-packages))
497     (do-symbols (s p)
498       (when (eq p (symbol-package s))
499         (dolist (name (list s
500                             `(setf ,s)
501                             (slot-reader-name s)
502                             (slot-writer-name s)
503                             (slot-boundp-name s)))
504           (when (fboundp name)
505             (let ((fun (fdefinition name)))
506               (when (typep fun 'generic-function)
507                 (let ((cache (gf-dfun-cache fun)))
508                   (when cache
509                     (funcall function name cache)))))))))))
510
511 (defun check-cache-consistency (cache)
512   (let ((table (make-hash-table :test 'equal)))
513     (map-cache (lambda (layouts value)
514                  (declare (ignore value))
515                  (if (gethash layouts table)
516                      (cerror "Check futher."
517                              "Multiple appearances of ~S." layouts)
518                      (setf (gethash layouts table) t)))
519                cache)))