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