0.6.8.9:
[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 (in-package "SB-PCL")
27 \f
28 ;;; FIXME: SB-PCL should probably USE-PACKAGE SB-KERNEL, since SB-PCL
29 ;;; is built on SB-KERNEL, and in the absence of USE-PACKAGE, it ends
30 ;;; up using a thundering herd of explicit prefixes to get to
31 ;;; SB-KERNEL symbols. Using the SB-INT and SB-EXT packages as well
32 ;;; would help reduce prefixing and make it more natural to reuse
33 ;;; things (ONCE-ONLY, *KEYWORD-PACKAGE*..) used in the main body of
34 ;;; the system. However, that would cause a conflict between the
35 ;;; SB-ITERATE:ITERATE macro and the SB-INT:ITERATE macro. (This could
36 ;;; be resolved by renaming SB-INT:ITERATE to SB-INT:NAMED-LET, or
37 ;;; with more gruntwork by punting the SB-ITERATE package and
38 ;;; replacing calls to SB-ITERATE:ITERATE with calls to CL:LOOP.
39
40 ;;; The caching algorithm implemented:
41 ;;;
42 ;;; << put a paper here >>
43 ;;;
44 ;;; For now, understand that as far as most of this code goes, a cache
45 ;;; has two important properties. The first is the number of wrappers
46 ;;; used as keys in each cache line. Throughout this code, this value
47 ;;; is always called NKEYS. The second is whether or not the cache
48 ;;; lines of a cache store a value. Throughout this code, this always
49 ;;; called VALUEP.
50 ;;;
51 ;;; Depending on these values, there are three kinds of caches.
52 ;;;
53 ;;; NKEYS = 1, VALUEP = NIL
54 ;;;
55 ;;; In this kind of cache, each line is 1 word long. No cache locking
56 ;;; is needed since all read's in the cache are a single value.
57 ;;; Nevertheless line 0 (location 0) is reserved, to ensure that
58 ;;; invalid wrappers will not get a first probe hit.
59 ;;;
60 ;;; To keep the code simpler, a cache lock count does appear in
61 ;;; location 0 of these caches, that count is incremented whenever
62 ;;; data is written to the cache. But, the actual lookup code (see
63 ;;; make-dlap) doesn't need to do locking when reading the cache.
64 ;;;
65 ;;; NKEYS = 1, VALUEP = T
66 ;;;
67 ;;; In this kind of cache, each line is 2 words long. Cache locking
68 ;;; must be done to ensure the synchronization of cache reads. Line 0
69 ;;; of the cache (location 0) is reserved for the cache lock count.
70 ;;; Location 1 of the cache is unused (in effect wasted).
71 ;;;
72 ;;; NKEYS > 1
73 ;;;
74 ;;; In this kind of cache, the 0 word of the cache holds the lock
75 ;;; count. The 1 word of the cache is line 0. Line 0 of these caches
76 ;;; is not reserved.
77 ;;;
78 ;;; This is done because in this sort of cache, the overhead of doing
79 ;;; the cache probe is high enough that the 1+ required to offset the
80 ;;; location is not a significant cost. In addition, because of the
81 ;;; larger line sizes, the space that would be wasted by reserving
82 ;;; line 0 to hold the lock count is more significant.
83 \f
84 ;;; caches
85 ;;;
86 ;;; A cache is essentially just a vector. The use of the individual
87 ;;; `words' in the vector depends on particular properties of the
88 ;;; cache as described above.
89 ;;;
90 ;;; This defines an abstraction for caches in terms of their most
91 ;;; obvious implementation as simple vectors. But, please notice that
92 ;;; part of the implementation of this abstraction, is the function
93 ;;; lap-out-cache-ref. This means that most port-specific
94 ;;; modifications to the implementation of caches will require
95 ;;; corresponding port-specific modifications to the lap code
96 ;;; assembler.
97 (defmacro cache-vector-ref (cache-vector location)
98   `(svref (the simple-vector ,cache-vector)
99           (sb-ext:truly-the fixnum ,location)))
100
101 (defmacro cache-vector-size (cache-vector)
102   `(array-dimension (the simple-vector ,cache-vector) 0))
103
104 (defun allocate-cache-vector (size)
105   (make-array size :adjustable nil))
106
107 (defmacro cache-vector-lock-count (cache-vector)
108   `(cache-vector-ref ,cache-vector 0))
109
110 (defun flush-cache-vector-internal (cache-vector)
111   (without-interrupts
112     (fill (the simple-vector cache-vector) nil)
113     (setf (cache-vector-lock-count cache-vector) 0))
114   cache-vector)
115
116 (defmacro modify-cache (cache-vector &body body)
117   `(without-interrupts
118      (multiple-value-prog1
119        (progn ,@body)
120        (let ((old-count (cache-vector-lock-count ,cache-vector)))
121          (declare (fixnum old-count))
122          (setf (cache-vector-lock-count ,cache-vector)
123                (if (= old-count most-positive-fixnum)
124                    1 (the fixnum (1+ old-count))))))))
125
126 (deftype field-type ()
127   '(mod #.sb-kernel:layout-clos-hash-length))
128
129 (eval-when (:compile-toplevel :load-toplevel :execute)
130 (defun power-of-two-ceiling (x)
131   (declare (fixnum x))
132   ;;(expt 2 (ceiling (log x 2)))
133   (the fixnum (ash 1 (integer-length (1- x)))))
134 ) ; EVAL-WHEN
135
136 (defconstant +nkeys-limit+ 256)
137
138 (defstruct (cache (:constructor make-cache ())
139                   (:copier copy-cache-internal))
140   (owner nil)
141   (nkeys 1 :type (integer 1 #.+nkeys-limit+))
142   (valuep nil :type (member nil t))
143   (nlines 0 :type fixnum)
144   (field 0 :type field-type)
145   (limit-fn #'default-limit-fn :type function)
146   (mask 0 :type fixnum)
147   (size 0 :type fixnum)
148   (line-size 1 :type (integer 1 #.(power-of-two-ceiling (1+ +nkeys-limit+))))
149   (max-location 0 :type fixnum)
150   (vector #() :type simple-vector)
151   (overflow nil :type list))
152
153 #-sb-fluid (declaim (sb-ext:freeze-type cache))
154
155 (defmacro cache-lock-count (cache)
156   `(cache-vector-lock-count (cache-vector ,cache)))
157 \f
158 ;;; some facilities for allocation and freeing caches as they are needed
159
160 ;;; This is done on the assumption that a better port of PCL will
161 ;;; arrange to cons these all in the same static area. Given that, the
162 ;;; fact that PCL tries to reuse them should be a win.
163
164 (defvar *free-cache-vectors* (make-hash-table :size 16 :test 'eql))
165
166 ;;; Return a cache that has had FLUSH-CACHE-VECTOR-INTERNAL called on
167 ;;; it. This returns a cache of exactly the size requested, it won't
168 ;;; ever return a larger cache.
169 (defun get-cache-vector (size)
170   (let ((entry (gethash size *free-cache-vectors*)))
171     (without-interrupts
172       (cond ((null entry)
173              (setf (gethash size *free-cache-vectors*) (cons 0 nil))
174              (get-cache-vector size))
175             ((null (cdr entry))
176              (incf (car entry))
177              (flush-cache-vector-internal (allocate-cache-vector size)))
178             (t
179              (let ((cache (cdr entry)))
180                (setf (cdr entry) (cache-vector-ref cache 0))
181                (flush-cache-vector-internal cache)))))))
182
183 (defun free-cache-vector (cache-vector)
184   (let ((entry (gethash (cache-vector-size cache-vector) *free-cache-vectors*)))
185     (without-interrupts
186       (if (null entry)
187           (error
188            "attempt to free a cache-vector not allocated by GET-CACHE-VECTOR")
189           (let ((thread (cdr entry)))
190             (loop (unless thread (return))
191                   (when (eq thread cache-vector)
192                     (error "freeing a cache twice"))
193                   (setq thread (cache-vector-ref thread 0)))
194             (flush-cache-vector-internal cache-vector) ; to help the GC
195             (setf (cache-vector-ref cache-vector 0) (cdr entry))
196             (setf (cdr entry) cache-vector)
197             nil)))))
198
199 ;;; This is just for debugging and analysis. It shows the state of the
200 ;;; free cache resource.
201 #+sb-show
202 (defun show-free-cache-vectors ()
203   (let ((elements ()))
204     (maphash #'(lambda (s e) (push (list s e) elements)) *free-cache-vectors*)
205     (setq elements (sort elements #'< :key #'car))
206     (dolist (e elements)
207       (let* ((size (car e))
208              (entry (cadr e))
209              (allocated (car entry))
210              (head (cdr entry))
211              (free 0))
212         (loop (when (null head) (return t))
213               (setq head (cache-vector-ref head 0))
214               (incf free))
215         (format t
216                 "~&There  ~4D are caches of size ~4D. (~D free  ~3D%)"
217                 allocated
218                 size
219                 free
220                 (floor (* 100 (/ free (float allocated)))))))))
221 \f
222 ;;;; wrapper cache numbers
223
224 ;;; The constant WRAPPER-CACHE-NUMBER-ADDS-OK controls the number of
225 ;;; non-zero bits wrapper cache numbers will have.
226 ;;;
227 ;;; The value of this constant is the number of wrapper cache numbers
228 ;;; which can be added and still be certain the result will be a
229 ;;; fixnum. This is used by all the code that computes primary cache
230 ;;; locations from multiple wrappers.
231 ;;;
232 ;;; The value of this constant is used to derive the next two which
233 ;;; are the forms of this constant which it is more convenient for the
234 ;;; runtime code to use.
235 (defconstant wrapper-cache-number-length
236   (integer-length sb-kernel:layout-clos-hash-max))
237 (defconstant wrapper-cache-number-mask sb-kernel:layout-clos-hash-max)
238 (defconstant wrapper-cache-number-adds-ok
239   (truncate most-positive-fixnum sb-kernel:layout-clos-hash-max))
240 \f
241 ;;;; wrappers themselves
242
243 ;;; This caching algorithm requires that wrappers have more than one
244 ;;; wrapper cache number. You should think of these multiple numbers
245 ;;; as being in columns. That is, for a given cache, the same column
246 ;;; of wrapper cache numbers will be used.
247 ;;;
248 ;;; If at some point the cache distribution of a cache gets bad, the
249 ;;; cache can be rehashed by switching to a different column.
250 ;;;
251 ;;; The columns are referred to by field number which is that number
252 ;;; which, when used as a second argument to wrapper-ref, will return
253 ;;; that column of wrapper cache number.
254 ;;;
255 ;;; This code is written to allow flexibility as to how many wrapper
256 ;;; cache numbers will be in each wrapper, and where they will be
257 ;;; located. It is also set up to allow port specific modifications to
258 ;;; `pack' the wrapper cache numbers on machines where the addressing
259 ;;; modes make that a good idea.
260
261 ;;; In SBCL, as in CMU CL, we want to do type checking as early as
262 ;;; possible; structures help this. The structures are hard-wired to
263 ;;; have a fixed number of cache hash values, and that number must
264 ;;; correspond to the number of cache lines we use.
265 (defconstant wrapper-cache-number-vector-length
266   sb-kernel:layout-clos-hash-length)
267
268 (unless (boundp '*the-class-t*)
269   (setq *the-class-t* nil))
270
271 ;;; Note that for SBCL, as for CMU CL, the WRAPPER of a built-in or
272 ;;; structure class will be some other kind of SB-KERNEL:LAYOUT, but
273 ;;; this shouldn't matter, since the only two slots that WRAPPER adds
274 ;;; are meaningless in those cases.
275 (defstruct (wrapper
276             (:include sb-kernel:layout
277                       ;; KLUDGE: In CMU CL, the initialization default
278                       ;; for LAYOUT-INVALID was NIL. In SBCL, that has
279                       ;; changed to :UNINITIALIZED, but PCL code might
280                       ;; still expect NIL for the initialization
281                       ;; default of WRAPPER-INVALID. Instead of trying
282                       ;; to find out, I just overrode the LAYOUT
283                       ;; default here. -- WHN 19991204
284                       (invalid nil))
285             (:conc-name %wrapper-)
286             (:constructor make-wrapper-internal))
287   (instance-slots-layout nil :type list)
288   (class-slots nil :type list))
289 #-sb-fluid (declaim (sb-ext:freeze-type wrapper))
290
291 (defmacro wrapper-class (wrapper)
292   `(sb-kernel:class-pcl-class (sb-kernel:layout-class ,wrapper)))
293 (defmacro wrapper-no-of-instance-slots (wrapper)
294   `(sb-kernel:layout-length ,wrapper))
295
296 ;;; WRAPPER-STATE returns T (not generalized boolean, but T exactly)
297 ;;; iff the wrapper is valid. Any other return value denotes some
298 ;;; invalid state. Special conventions have been set up for certain
299 ;;; invalid states, e.g. obsoleteness or flushedness, but I (WHN
300 ;;; 19991204) haven't been motivated to reverse engineer them from the
301 ;;; code and document them here.
302 ;;;
303 ;;; FIXME: This is awkward and unmnemonic. There is a function
304 ;;; (INVALID-WRAPPER-P) to test this return result abstractly for
305 ;;; invalidness but it's not called consistently; the functions that
306 ;;; need to know whether a wrapper is invalid often test (EQ
307 ;;; (WRAPPER-STATE X) T), ick. It would be good to use the abstract
308 ;;; test instead. It would probably be even better to switch the sense
309 ;;; of the WRAPPER-STATE function, renaming it to WRAPPER-INVALID and
310 ;;; making it synonymous with LAYOUT-INVALID. Then the
311 ;;; INVALID-WRAPPER-P function would become trivial and would go away
312 ;;; (replaced with WRAPPER-INVALID), since all the various invalid
313 ;;; wrapper states would become generalized boolean "true" values. --
314 ;;; WHN 19991204
315 #-sb-fluid (declaim (inline wrapper-state (setf wrapper-state)))
316 (defun wrapper-state (wrapper)
317   (let ((invalid (sb-kernel:layout-invalid wrapper)))
318     (cond ((null invalid)
319            t)
320           ((atom invalid)
321            ;; some non-PCL object. INVALID is probably :INVALID. We
322            ;; should arguably compute the new wrapper here instead of
323            ;; returning NIL, but we don't bother, since
324            ;; OBSOLETE-INSTANCE-TRAP can't use it.
325            '(:obsolete nil))
326           (t
327            invalid))))
328 (defun (setf wrapper-state) (new-value wrapper)
329   (setf (sb-kernel:layout-invalid wrapper)
330         (if (eq new-value 't)
331             nil
332           new-value)))
333
334 (defmacro wrapper-instance-slots-layout (wrapper)
335   `(%wrapper-instance-slots-layout ,wrapper))
336 (defmacro wrapper-class-slots (wrapper)
337   `(%wrapper-class-slots ,wrapper))
338 (defmacro wrapper-cache-number-vector (x) x)
339
340 ;;; This is called in BRAID when we are making wrappers for classes
341 ;;; whose slots are not initialized yet, and which may be built-in
342 ;;; classes. We pass in the class name in addition to the class.
343 (defun boot-make-wrapper (length name &optional class)
344   (let ((found (cl:find-class name nil)))
345     (cond
346      (found
347       (unless (sb-kernel:class-pcl-class found)
348         (setf (sb-kernel:class-pcl-class found) class))
349       (assert (eq (sb-kernel:class-pcl-class found) class))
350       (let ((layout (sb-kernel:class-layout found)))
351         (assert layout)
352         layout))
353      (t
354       (make-wrapper-internal
355        :length length
356        :class (sb-kernel:make-standard-class :name name :pcl-class class))))))
357
358 ;;; The following variable may be set to a standard-class that has
359 ;;; already been created by the lisp code and which is to be redefined
360 ;;; by PCL. This allows standard-classes to be defined and used for
361 ;;; type testing and dispatch before PCL is loaded.
362 (defvar *pcl-class-boot* nil)
363
364 ;;; In SBCL, as in CMU CL, the layouts (a.k.a wrappers) for built-in
365 ;;; and structure classes already exist when PCL is initialized, so we
366 ;;; don't necessarily always make a wrapper. Also, we help maintain
367 ;;; the mapping between cl:class and pcl::class objects.
368 (defun make-wrapper (length class)
369   (cond
370    ((typep class 'std-class)
371     (make-wrapper-internal
372      :length length
373      :class
374      (let ((owrap (class-wrapper class)))
375        (cond (owrap
376               (sb-kernel:layout-class owrap))
377              ((*subtypep (class-of class)
378                          *the-class-standard-class*)
379               (cond ((and *pcl-class-boot*
380                           (eq (slot-value class 'name) *pcl-class-boot*))
381                      (let ((found (cl:find-class (slot-value class 'name))))
382                        (unless (sb-kernel:class-pcl-class found)
383                          (setf (sb-kernel:class-pcl-class found) class))
384                        (assert (eq (sb-kernel:class-pcl-class found) class))
385                        found))
386                     (t
387                      (sb-kernel:make-standard-class :pcl-class class))))
388              (t
389               (sb-kernel:make-random-pcl-class :pcl-class class))))))
390    (t
391     (let* ((found (cl:find-class (slot-value class 'name)))
392            (layout (sb-kernel:class-layout found)))
393       (unless (sb-kernel:class-pcl-class found)
394         (setf (sb-kernel:class-pcl-class found) class))
395       (assert (eq (sb-kernel:class-pcl-class found) class))
396       (assert layout)
397       layout))))
398
399 ;;; FIXME: The immediately following macros could become inline functions.
400
401 (defmacro first-wrapper-cache-number-index ()
402   0)
403
404 (defmacro next-wrapper-cache-number-index (field-number)
405   `(and (< ,field-number #.(1- wrapper-cache-number-vector-length))
406         (1+ ,field-number)))
407
408 (defmacro cache-number-vector-ref (cnv n)
409   `(wrapper-cache-number-vector-ref ,cnv ,n))
410
411 (defmacro wrapper-cache-number-vector-ref (wrapper n)
412   `(sb-kernel:layout-clos-hash ,wrapper ,n))
413
414 (defmacro class-no-of-instance-slots (class)
415   `(wrapper-no-of-instance-slots (class-wrapper ,class)))
416
417 (defmacro wrapper-class* (wrapper)
418   `(let ((wrapper ,wrapper))
419      (or (wrapper-class wrapper)
420          (find-structure-class
421           (cl:class-name (sb-kernel:layout-class wrapper))))))
422
423 ;;; The wrapper cache machinery provides general mechanism for
424 ;;; trapping on the next access to any instance of a given class. This
425 ;;; mechanism is used to implement the updating of instances when the
426 ;;; class is redefined (MAKE-INSTANCES-OBSOLETE). The same mechanism
427 ;;; is also used to update generic function caches when there is a
428 ;;; change to the superclasses of a class.
429 ;;;
430 ;;; Basically, a given wrapper can be valid or invalid. If it is
431 ;;; invalid, it means that any attempt to do a wrapper cache lookup
432 ;;; using the wrapper should trap. Also, methods on
433 ;;; SLOT-VALUE-USING-CLASS check the wrapper validity as well. This is
434 ;;; done by calling CHECK-WRAPPER-VALIDITY.
435
436 ;;; FIXME: could become inline function
437 (defmacro invalid-wrapper-p (wrapper)
438   `(neq (wrapper-state ,wrapper) 't))
439
440 (defvar *previous-nwrappers* (make-hash-table))
441
442 (defun invalidate-wrapper (owrapper state nwrapper)
443   (ecase state
444     ((:flush :obsolete)
445      (let ((new-previous ()))
446        ;; First off, a previous call to INVALIDATE-WRAPPER may have
447        ;; recorded OWRAPPER as an NWRAPPER to update to. Since
448        ;; OWRAPPER is about to be invalid, it no longer makes sense to
449        ;; update to it.
450        ;;
451        ;; We go back and change the previously invalidated wrappers so
452        ;; that they will now update directly to NWRAPPER. This
453        ;; corresponds to a kind of transitivity of wrapper updates.
454        (dolist (previous (gethash owrapper *previous-nwrappers*))
455          (when (eq state ':obsolete)
456            (setf (car previous) ':obsolete))
457          (setf (cadr previous) nwrapper)
458          (push previous new-previous))
459
460        (let ((ocnv (wrapper-cache-number-vector owrapper)))
461          (dotimes (i sb-kernel:layout-clos-hash-length)
462            (setf (cache-number-vector-ref ocnv i) 0)))
463        (push (setf (wrapper-state owrapper) (list state nwrapper))
464              new-previous)
465
466        (setf (gethash owrapper *previous-nwrappers*) ()
467              (gethash nwrapper *previous-nwrappers*) new-previous)))))
468
469 (defun check-wrapper-validity (instance)
470   (let* ((owrapper (wrapper-of instance))
471          (state (wrapper-state owrapper)))
472     (if (eq state 't)
473         owrapper
474         (let ((nwrapper
475                 (ecase (car state)
476                   (:flush
477                     (flush-cache-trap owrapper (cadr state) instance))
478                   (:obsolete
479                     (obsolete-instance-trap owrapper (cadr state) instance)))))
480           ;; This little bit of error checking is superfluous. It only
481           ;; checks to see whether the person who implemented the trap
482           ;; handling screwed up. Since that person is hacking
483           ;; internal PCL code, and is not a user, this should be
484           ;; needless. Also, since this directly slows down instance
485           ;; update and generic function cache refilling, feel free to
486           ;; take it out sometime soon.
487           ;;
488           ;; FIXME: We probably need to add a #+SB-PARANOID feature to
489           ;; make stuff like this optional. Until then, it stays in.
490           (cond ((neq nwrapper (wrapper-of instance))
491                  (error "wrapper returned from trap not wrapper of instance"))
492                 ((invalid-wrapper-p nwrapper)
493                  (error "wrapper returned from trap invalid")))
494           nwrapper))))
495
496 (defmacro check-wrapper-validity1 (object)
497   (let ((owrapper (gensym)))
498     `(let ((,owrapper (sb-kernel:layout-of object)))
499        (if (sb-kernel:layout-invalid ,owrapper)
500            (check-wrapper-validity ,object)
501            ,owrapper))))
502 \f
503 (defvar *free-caches* nil)
504
505 (defun get-cache (nkeys valuep limit-fn nlines)
506   (let ((cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
507     (declare (type cache cache))
508     (multiple-value-bind (cache-mask actual-size line-size nlines)
509         (compute-cache-parameters nkeys valuep nlines)
510       (setf (cache-nkeys cache) nkeys
511             (cache-valuep cache) valuep
512             (cache-nlines cache) nlines
513             (cache-field cache) (first-wrapper-cache-number-index)
514             (cache-limit-fn cache) limit-fn
515             (cache-mask cache) cache-mask
516             (cache-size cache) actual-size
517             (cache-line-size cache) line-size
518             (cache-max-location cache) (let ((line (1- nlines)))
519                                          (if (= nkeys 1)
520                                              (* line line-size)
521                                              (1+ (* line line-size))))
522             (cache-vector cache) (get-cache-vector actual-size)
523             (cache-overflow cache) nil)
524       cache)))
525
526 (defun get-cache-from-cache (old-cache new-nlines
527                              &optional (new-field (first-wrapper-cache-number-index)))
528   (let ((nkeys (cache-nkeys old-cache))
529         (valuep (cache-valuep old-cache))
530         (cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
531     (declare (type cache cache))
532     (multiple-value-bind (cache-mask actual-size line-size nlines)
533         (if (= new-nlines (cache-nlines old-cache))
534             (values (cache-mask old-cache) (cache-size old-cache)
535                     (cache-line-size old-cache) (cache-nlines old-cache))
536             (compute-cache-parameters nkeys valuep new-nlines))
537       (setf (cache-owner cache) (cache-owner old-cache)
538             (cache-nkeys cache) nkeys
539             (cache-valuep cache) valuep
540             (cache-nlines cache) nlines
541             (cache-field cache) new-field
542             (cache-limit-fn cache) (cache-limit-fn old-cache)
543             (cache-mask cache) cache-mask
544             (cache-size cache) actual-size
545             (cache-line-size cache) line-size
546             (cache-max-location cache) (let ((line (1- nlines)))
547                                          (if (= nkeys 1)
548                                              (* line line-size)
549                                              (1+ (* line line-size))))
550             (cache-vector cache) (get-cache-vector actual-size)
551             (cache-overflow cache) nil)
552       cache)))
553
554 (defun copy-cache (old-cache)
555   (let* ((new-cache (copy-cache-internal old-cache))
556          (size (cache-size old-cache))
557          (old-vector (cache-vector old-cache))
558          (new-vector (get-cache-vector size)))
559     (declare (simple-vector old-vector new-vector))
560     (dotimes-fixnum (i size)
561       (setf (svref new-vector i) (svref old-vector i)))
562     (setf (cache-vector new-cache) new-vector)
563     new-cache))
564
565 (defun free-cache (cache)
566   (free-cache-vector (cache-vector cache))
567   (setf (cache-vector cache) #())
568   (setf (cache-owner cache) nil)
569   (push cache *free-caches*)
570   nil)
571
572 (defun compute-line-size (x)
573   (power-of-two-ceiling x))
574
575 (defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
576   ;;(declare (values cache-mask actual-size line-size nlines))
577   (declare (fixnum nkeys))
578   (if (= nkeys 1)
579       (let* ((line-size (if valuep 2 1))
580              (cache-size (if (typep nlines-or-cache-vector 'fixnum)
581                              (the fixnum
582                                   (* line-size
583                                      (the fixnum
584                                           (power-of-two-ceiling
585                                             nlines-or-cache-vector))))
586                              (cache-vector-size nlines-or-cache-vector))))
587         (declare (fixnum line-size cache-size))
588         (values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
589                 cache-size
590                 line-size
591                 (the fixnum (floor cache-size line-size))))
592       (let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
593              (cache-size (if (typep nlines-or-cache-vector 'fixnum)
594                              (the fixnum
595                                   (* line-size
596                                      (the fixnum
597                                           (power-of-two-ceiling
598                                             nlines-or-cache-vector))))
599                              (1- (cache-vector-size nlines-or-cache-vector)))))
600         (declare (fixnum line-size cache-size))
601         (values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
602                 (the fixnum (1+ cache-size))
603                 line-size
604                 (the fixnum (floor cache-size line-size))))))
605 \f
606 ;;; the various implementations of computing a primary cache location from
607 ;;; wrappers. Because some implementations of this must run fast there are
608 ;;; several implementations of the same algorithm.
609 ;;;
610 ;;; The algorithm is:
611 ;;;
612 ;;;  SUM       over the wrapper cache numbers,
613 ;;;  ENSURING  that the result is a fixnum
614 ;;;  MASK      the result against the mask argument.
615
616 ;;; COMPUTE-PRIMARY-CACHE-LOCATION
617 ;;;
618 ;;; The basic functional version. This is used by the cache miss code to
619 ;;; compute the primary location of an entry.
620 (defun compute-primary-cache-location (field mask wrappers)
621
622   (declare (type field-type field) (fixnum mask))
623   (if (not (listp wrappers))
624       (logand mask
625               (the fixnum (wrapper-cache-number-vector-ref wrappers field)))
626       (let ((location 0) (i 0))
627         (declare (fixnum location i))
628         (dolist (wrapper wrappers)
629           ;; First add the cache number of this wrapper to location.
630           (let ((wrapper-cache-number (wrapper-cache-number-vector-ref wrapper
631                                                                        field)))
632             (declare (fixnum wrapper-cache-number))
633             (if (zerop wrapper-cache-number)
634                 (return-from compute-primary-cache-location 0)
635                 (setq location
636                       (the fixnum (+ location wrapper-cache-number)))))
637           ;; Then, if we are working with lots of wrappers, deal with
638           ;; the wrapper-cache-number-mask stuff.
639           (when (and (not (zerop i))
640                      (zerop (mod i wrapper-cache-number-adds-ok)))
641             (setq location
642                   (logand location wrapper-cache-number-mask)))
643           (incf i))
644         (the fixnum (1+ (logand mask location))))))
645
646 ;;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION
647 ;;;
648 ;;; This version is called on a cache line. It fetches the wrappers
649 ;;; from the cache line and determines the primary location. Various
650 ;;; parts of the cache filling code call this to determine whether it
651 ;;; is appropriate to displace a given cache entry.
652 ;;;
653 ;;; If this comes across a wrapper whose CACHE-NO is 0, it returns the
654 ;;; symbol invalid to suggest to its caller that it would be provident
655 ;;; to blow away the cache line in question.
656 (defun compute-primary-cache-location-from-location (to-cache
657                                                      from-location
658                                                      &optional
659                                                      (from-cache to-cache))
660   (declare (type cache to-cache from-cache) (fixnum from-location))
661   (let ((result 0)
662         (cache-vector (cache-vector from-cache))
663         (field (cache-field to-cache))
664         (mask (cache-mask to-cache))
665         (nkeys (cache-nkeys to-cache)))
666     (declare (type field-type field) (fixnum result mask nkeys)
667              (simple-vector cache-vector))
668     (dotimes-fixnum (i nkeys)
669       (let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
670              (wcn (wrapper-cache-number-vector-ref wrapper field)))
671         (declare (fixnum wcn))
672         (setq result (+ result wcn)))
673       (when (and (not (zerop i))
674                  (zerop (mod i wrapper-cache-number-adds-ok)))
675         (setq result (logand result wrapper-cache-number-mask))))
676     (if (= nkeys 1)
677         (logand mask result)
678         (the fixnum (1+ (logand mask result))))))
679 \f
680 ;;;  NIL              means nothing so far, no actual arg info has NILs
681 ;;;                in the metatype
682 ;;;  CLASS          seen all sorts of metaclasses
683 ;;;                (specifically, more than one of the next 4 values)
684 ;;;  T          means everything so far is the class T
685 ;;;  STANDARD-CLASS   seen only standard classes
686 ;;;  BUILT-IN-CLASS   seen only built in classes
687 ;;;  STRUCTURE-CLASS  seen only structure classes
688 (defun raise-metatype (metatype new-specializer)
689   (let ((slot      (find-class 'slot-class))
690         (std       (find-class 'std-class))
691         (standard  (find-class 'standard-class))
692         (fsc       (find-class 'funcallable-standard-class))
693         (structure (find-class 'structure-class))
694         (built-in  (find-class 'built-in-class)))
695     (flet ((specializer->metatype (x)
696              (let ((meta-specializer
697                      (if (eq *boot-state* 'complete)
698                          (class-of (specializer-class x))
699                          (class-of x))))
700                (cond ((eq x *the-class-t*) t)
701                      ((*subtypep meta-specializer std)
702                       'standard-instance)
703                      ((*subtypep meta-specializer standard)
704                       'standard-instance)
705                      ((*subtypep meta-specializer fsc)
706                       'standard-instance)
707                      ((*subtypep meta-specializer structure)
708                       'structure-instance)
709                      ((*subtypep meta-specializer built-in)
710                       'built-in-instance)
711                      ((*subtypep meta-specializer slot)
712                       'slot-instance)
713                      (t (error "PCL cannot handle the specializer ~S (meta-specializer ~S)."
714                                new-specializer
715                                meta-specializer))))))
716       ;; We implement the following table. The notation is
717       ;; that X and Y are distinct meta specializer names.
718       ;;
719       ;;   NIL    <anything>    ===>  <anything>
720       ;;    X      X        ===>      X
721       ;;    X      Y        ===>    CLASS
722       (let ((new-metatype (specializer->metatype new-specializer)))
723         (cond ((eq new-metatype 'slot-instance) 'class)
724               ((null metatype) new-metatype)
725               ((eq metatype new-metatype) new-metatype)
726               (t 'class))))))
727
728 (defmacro with-dfun-wrappers ((args metatypes)
729                               (dfun-wrappers invalid-wrapper-p
730                                              &optional wrappers classes types)
731                               invalid-arguments-form
732                               &body body)
733   `(let* ((args-tail ,args) (,invalid-wrapper-p nil) (invalid-arguments-p nil)
734           (,dfun-wrappers nil) (dfun-wrappers-tail nil)
735           ,@(when wrappers
736               `((wrappers-rev nil) (types-rev nil) (classes-rev nil))))
737      (dolist (mt ,metatypes)
738        (unless args-tail
739          (setq invalid-arguments-p t)
740          (return nil))
741        (let* ((arg (pop args-tail))
742               (wrapper nil)
743               ,@(when wrappers
744                   `((class *the-class-t*)
745                     (type 't))))
746          (unless (eq mt 't)
747            (setq wrapper (wrapper-of arg))
748            (when (invalid-wrapper-p wrapper)
749              (setq ,invalid-wrapper-p t)
750              (setq wrapper (check-wrapper-validity arg)))
751            (cond ((null ,dfun-wrappers)
752                   (setq ,dfun-wrappers wrapper))
753                  ((not (consp ,dfun-wrappers))
754                   (setq dfun-wrappers-tail (list wrapper))
755                   (setq ,dfun-wrappers (cons ,dfun-wrappers dfun-wrappers-tail)))
756                  (t
757                   (let ((new-dfun-wrappers-tail (list wrapper)))
758                     (setf (cdr dfun-wrappers-tail) new-dfun-wrappers-tail)
759                     (setf dfun-wrappers-tail new-dfun-wrappers-tail))))
760            ,@(when wrappers
761                `((setq class (wrapper-class* wrapper))
762                  (setq type `(class-eq ,class)))))
763          ,@(when wrappers
764              `((push wrapper wrappers-rev)
765                (push class classes-rev)
766                (push type types-rev)))))
767      (if invalid-arguments-p
768          ,invalid-arguments-form
769          (let* (,@(when wrappers
770                     `((,wrappers (nreverse wrappers-rev))
771                       (,classes (nreverse classes-rev))
772                       (,types (mapcar #'(lambda (class)
773                                           `(class-eq ,class))
774                                       ,classes)))))
775            ,@body))))
776 \f
777 ;;;; some support stuff for getting a hold of symbols that we need when
778 ;;;; building the discriminator codes. It's OK for these to be interned
779 ;;;; symbols because we don't capture any user code in the scope in which
780 ;;;; these symbols are bound.
781
782 (defvar *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
783
784 (defun dfun-arg-symbol (arg-number)
785   (or (nth arg-number (the list *dfun-arg-symbols*))
786       (intern (format nil ".ARG~A." arg-number) *pcl-package*)))
787
788 (defvar *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
789
790 (defun slot-vector-symbol (arg-number)
791   (or (nth arg-number (the list *slot-vector-symbols*))
792       (intern (format nil ".SLOTS~A." arg-number) *pcl-package*)))
793
794 (defun make-dfun-lambda-list (metatypes applyp)
795   (gathering1 (collecting)
796     (iterate ((i (interval :from 0))
797               (s (list-elements metatypes)))
798       (progn s)
799       (gather1 (dfun-arg-symbol i)))
800     (when applyp
801       (gather1 '&rest)
802       (gather1 '.dfun-rest-arg.))))
803
804 (defun make-dlap-lambda-list (metatypes applyp)
805   (gathering1 (collecting)
806     (iterate ((i (interval :from 0))
807               (s (list-elements metatypes)))
808       (progn s)
809       (gather1 (dfun-arg-symbol i)))
810     (when applyp
811       (gather1 '&rest))))
812
813 (defun make-emf-call (metatypes applyp fn-variable &optional emf-type)
814   (let ((required
815          (gathering1 (collecting)
816             (iterate ((i (interval :from 0))
817                       (s (list-elements metatypes)))
818               (progn s)
819               (gather1 (dfun-arg-symbol i))))))
820     `(,(if (eq emf-type 'fast-method-call)
821            'invoke-effective-method-function-fast
822            'invoke-effective-method-function)
823       ,fn-variable ,applyp ,@required ,@(when applyp `(.dfun-rest-arg.)))))
824
825 (defun make-dfun-call (metatypes applyp fn-variable)
826   (let ((required
827           (gathering1 (collecting)
828             (iterate ((i (interval :from 0))
829                       (s (list-elements metatypes)))
830               (progn s)
831               (gather1 (dfun-arg-symbol i))))))
832     (if applyp
833         `(function-apply   ,fn-variable ,@required .dfun-rest-arg.)
834         `(function-funcall ,fn-variable ,@required))))
835
836 (defun make-dfun-arg-list (metatypes applyp)
837   (let ((required
838           (gathering1 (collecting)
839             (iterate ((i (interval :from 0))
840                       (s (list-elements metatypes)))
841               (progn s)
842               (gather1 (dfun-arg-symbol i))))))
843     (if applyp
844         `(list* ,@required .dfun-rest-arg.)
845         `(list ,@required))))
846
847 (defun make-fast-method-call-lambda-list (metatypes applyp)
848   (gathering1 (collecting)
849     (gather1 '.pv-cell.)
850     (gather1 '.next-method-call.)
851     (iterate ((i (interval :from 0))
852               (s (list-elements metatypes)))
853       (progn s)
854       (gather1 (dfun-arg-symbol i)))
855     (when applyp
856       (gather1 '.dfun-rest-arg.))))
857 \f
858 ;;;; a comment from some PCL implementor:
859 ;;;;     Its too bad Common Lisp compilers freak out when you have a
860 ;;;;   DEFUN with a lot of LABELS in it. If I could do that I could
861 ;;;;   make this code much easier to read and work with.
862 ;;;;     Ahh Scheme...
863 ;;;;     In the absence of that, the following little macro makes the
864 ;;;;   code that follows a little bit more reasonable. I would like to
865 ;;;;   add that having to practically write my own compiler in order to
866 ;;;;   get just this simple thing is something of a drag.
867 ;;;;
868 ;;;; KLUDGE: Maybe we could actually implement this as LABELS now,
869 ;;;; since AFAIK CMU CL doesn't freak out when you have a DEFUN with a
870 ;;;; lot of LABELS in it (and if it does we can fix it instead of
871 ;;;; working around it). -- WHN 19991204
872
873 (eval-when (:compile-toplevel :load-toplevel :execute)
874
875 (defvar *cache* nil)
876
877 ;;; FIXME: should be undefined after bootstrapping
878 (defparameter *local-cache-functions*
879   '((cache () .cache.)
880     (nkeys () (cache-nkeys .cache.))
881     (line-size () (cache-line-size .cache.))
882     (vector () (cache-vector .cache.))
883     (valuep () (cache-valuep .cache.))
884     (nlines () (cache-nlines .cache.))
885     (max-location () (cache-max-location .cache.))
886     (limit-fn () (cache-limit-fn .cache.))
887     (size () (cache-size .cache.))
888     (mask () (cache-mask .cache.))
889     (field () (cache-field .cache.))
890     (overflow () (cache-overflow .cache.))
891
892     ;; Return T IFF this cache location is reserved. The only time
893     ;; this is true is for line number 0 of an nkeys=1 cache.
894     (line-reserved-p (line)
895       (declare (fixnum line))
896       (and (= (nkeys) 1)
897            (= line 0)))
898     (location-reserved-p (location)
899       (declare (fixnum location))
900       (and (= (nkeys) 1)
901            (= location 0)))
902     ;; Given a line number, return the cache location. This is the
903     ;; value that is the second argument to cache-vector-ref. Basically,
904     ;; this deals with the offset of nkeys>1 caches and multiplies
905     ;; by line size.
906     (line-location (line)
907       (declare (fixnum line))
908       (when (line-reserved-p line)
909         (error "Line is reserved."))
910       (if (= (nkeys) 1)
911           (the fixnum (* line (line-size)))
912           (the fixnum (1+ (the fixnum (* line (line-size)))))))
913
914     ;; Given a cache location, return the line. This is the inverse
915     ;; of LINE-LOCATION.
916     (location-line (location)
917       (declare (fixnum location))
918       (if (= (nkeys) 1)
919           (floor location (line-size))
920           (floor (the fixnum (1- location)) (line-size))))
921
922     ;; Given a line number, return the wrappers stored at that line.
923     ;; As usual, if nkeys=1, this returns a single value. Only when
924     ;; nkeys>1 does it return a list. An error is signalled if the
925     ;; line is reserved.
926     (line-wrappers (line)
927       (declare (fixnum line))
928       (when (line-reserved-p line) (error "Line is reserved."))
929       (location-wrappers (line-location line)))
930     (location-wrappers (location) ; avoid multiplies caused by line-location
931       (declare (fixnum location))
932       (if (= (nkeys) 1)
933           (cache-vector-ref (vector) location)
934           (let ((list (make-list (nkeys)))
935                 (vector (vector)))
936             (declare (simple-vector vector))
937             (dotimes-fixnum (i (nkeys) list)
938               (setf (nth i list) (cache-vector-ref vector (+ location i)))))))
939
940     ;; Given a line number, return true IFF the line's
941     ;; wrappers are the same as wrappers.
942     (line-matches-wrappers-p (line wrappers)
943       (declare (fixnum line))
944       (and (not (line-reserved-p line))
945            (location-matches-wrappers-p (line-location line) wrappers)))
946     (location-matches-wrappers-p (loc wrappers) ; must not be reserved
947       (declare (fixnum loc))
948       (let ((cache-vector (vector)))
949         (declare (simple-vector cache-vector))
950         (if (= (nkeys) 1)
951             (eq wrappers (cache-vector-ref cache-vector loc))
952             (dotimes-fixnum (i (nkeys) t)
953               (unless (eq (pop wrappers)
954                           (cache-vector-ref cache-vector (+ loc i)))
955                 (return nil))))))
956
957     ;; Given a line number, return the value stored at that line.
958     ;; If valuep is NIL, this returns NIL. As with line-wrappers,
959     ;; an error is signalled if the line is reserved.
960     (line-value (line)
961       (declare (fixnum line))
962       (when (line-reserved-p line) (error "Line is reserved."))
963       (location-value (line-location line)))
964     (location-value (loc)
965       (declare (fixnum loc))
966       (and (valuep)
967            (cache-vector-ref (vector) (+ loc (nkeys)))))
968
969     ;; Given a line number, return true iff that line has data in
970     ;; it. The state of the wrappers stored in the line is not
971     ;; checked. An error is signalled if line is reserved.
972     (line-full-p (line)
973       (when (line-reserved-p line) (error "Line is reserved."))
974       (not (null (cache-vector-ref (vector) (line-location line)))))
975
976     ;; Given a line number, return true iff the line is full and
977     ;; there are no invalid wrappers in the line, and the line's
978     ;; wrappers are different from wrappers.
979     ;; An error is signalled if the line is reserved.
980     (line-valid-p (line wrappers)
981       (declare (fixnum line))
982       (when (line-reserved-p line) (error "Line is reserved."))
983       (location-valid-p (line-location line) wrappers))
984     (location-valid-p (loc wrappers)
985       (declare (fixnum loc))
986       (let ((cache-vector (vector))
987             (wrappers-mismatch-p (null wrappers)))
988         (declare (simple-vector cache-vector))
989         (dotimes-fixnum (i (nkeys) wrappers-mismatch-p)
990           (let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
991             (when (or (null wrapper)
992                       (invalid-wrapper-p wrapper))
993               (return nil))
994             (unless (and wrappers
995                          (eq wrapper
996                              (if (consp wrappers) (pop wrappers) wrappers)))
997               (setq wrappers-mismatch-p t))))))
998
999     ;; how many unreserved lines separate line-1 and line-2
1000     (line-separation (line-1 line-2)
1001      (declare (fixnum line-1 line-2))
1002      (let ((diff (the fixnum (- line-2 line-1))))
1003        (declare (fixnum diff))
1004        (when (minusp diff)
1005          (setq diff (+ diff (nlines)))
1006          (when (line-reserved-p 0)
1007            (setq diff (1- diff))))
1008        diff))
1009
1010     ;; Given a cache line, get the next cache line. This will not
1011     ;; return a reserved line.
1012     (next-line (line)
1013      (declare (fixnum line))
1014      (if (= line (the fixnum (1- (nlines))))
1015          (if (line-reserved-p 0) 1 0)
1016          (the fixnum (1+ line))))
1017     (next-location (loc)
1018       (declare (fixnum loc))
1019       (if (= loc (max-location))
1020           (if (= (nkeys) 1)
1021               (line-size)
1022               1)
1023           (the fixnum (+ loc (line-size)))))
1024
1025     ;; Given a line which has a valid entry in it, this will return
1026     ;; the primary cache line of the wrappers in that line. We just
1027     ;; call COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this is an
1028     ;; easier packaging up of the call to it.
1029     (line-primary (line)
1030       (declare (fixnum line))
1031       (location-line (line-primary-location line)))
1032     (line-primary-location (line)
1033      (declare (fixnum line))
1034      (compute-primary-cache-location-from-location
1035        (cache) (line-location line)))))
1036
1037 (defmacro with-local-cache-functions ((cache) &body body)
1038   `(let ((.cache. ,cache))
1039      (declare (type cache .cache.))
1040      (macrolet ,(mapcar #'(lambda (fn)
1041                             `(,(car fn) ,(cadr fn)
1042                                 `(let (,,@(mapcar #'(lambda (var)
1043                                                       ``(,',var ,,var))
1044                                                   (cadr fn)))
1045                                     ,@',(cddr fn))))
1046                         *local-cache-functions*)
1047        ,@body)))
1048
1049 ) ; EVAL-WHEN
1050 \f
1051 ;;; Here is where we actually fill, recache and expand caches.
1052 ;;;
1053 ;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
1054 ;;; entrypoints into this code.
1055 ;;;
1056 ;;; FILL-CACHE returns 1 value: a new cache
1057 ;;;
1058 ;;;   a wrapper field number
1059 ;;;   a cache
1060 ;;;   a mask
1061 ;;;   an absolute cache size (the size of the actual vector)
1062 ;;; It tries to re-adjust the cache every time it makes a new fill.
1063 ;;; The intuition here is that we want uniformity in the number of
1064 ;;; probes needed to find an entry. Furthermore, adjusting has the
1065 ;;; nice property of throwing out any entries that are invalid.
1066 (defvar *cache-expand-threshold* 1.25)
1067
1068 (defun fill-cache (cache wrappers value &optional free-cache-p)
1069
1070   ;; FILL-CACHE won't return if WRAPPERS is nil, might as well check..
1071   (unless wrappers
1072     (error "fill-cache: WRAPPERS arg is NIL!"))
1073
1074   (or (fill-cache-p nil cache wrappers value)
1075       (and (< (ceiling (* (cache-count cache) 1.25))
1076               (if (= (cache-nkeys cache) 1)
1077                   (1- (cache-nlines cache))
1078                   (cache-nlines cache)))
1079            (adjust-cache cache wrappers value free-cache-p))
1080       (expand-cache cache wrappers value free-cache-p)))
1081
1082 (defvar *check-cache-p* nil)
1083
1084 (defmacro maybe-check-cache (cache)
1085   `(progn
1086      (when *check-cache-p*
1087        (check-cache ,cache))
1088      ,cache))
1089
1090 (defun check-cache (cache)
1091   (with-local-cache-functions (cache)
1092     (let ((location (if (= (nkeys) 1) 0 1))
1093           (limit (funcall (limit-fn) (nlines))))
1094       (dotimes-fixnum (i (nlines) cache)
1095         (when (and (not (location-reserved-p location))
1096                    (line-full-p i))
1097           (let* ((home-loc (compute-primary-cache-location-from-location
1098                             cache location))
1099                  (home (location-line (if (location-reserved-p home-loc)
1100                                           (next-location home-loc)
1101                                           home-loc)))
1102                  (sep (when home (line-separation home i))))
1103             (when (and sep (> sep limit))
1104               (error "bad cache ~S ~@
1105                       value at location ~D: ~D lines from its home. The limit is ~D."
1106                      cache location sep limit))))
1107         (setq location (next-location location))))))
1108
1109 (defun probe-cache (cache wrappers &optional default limit-fn)
1110   ;;(declare (values value))
1111   (unless wrappers
1112     ;; FIXME: This and another earlier test on a WRAPPERS arg can
1113     ;; be compact assertoids.
1114     (error "WRAPPERS arg is NIL!"))
1115   (with-local-cache-functions (cache)
1116     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
1117            (limit (funcall (or limit-fn (limit-fn)) (nlines))))
1118       (declare (fixnum location limit))
1119       (when (location-reserved-p location)
1120         (setq location (next-location location)))
1121       (dotimes-fixnum (i (1+ limit))
1122         (when (location-matches-wrappers-p location wrappers)
1123           (return-from probe-cache (or (not (valuep))
1124                                        (location-value location))))
1125         (setq location (next-location location)))
1126       (dolist (entry (overflow))
1127         (when (equal (car entry) wrappers)
1128           (return-from probe-cache (or (not (valuep))
1129                                        (cdr entry)))))
1130       default)))
1131
1132 (defun map-cache (function cache &optional set-p)
1133   (with-local-cache-functions (cache)
1134     (let ((set-p (and set-p (valuep))))
1135       (dotimes-fixnum (i (nlines) cache)
1136         (unless (or (line-reserved-p i) (not (line-valid-p i nil)))
1137           (let ((value (funcall function (line-wrappers i) (line-value i))))
1138             (when set-p
1139               (setf (cache-vector-ref (vector) (+ (line-location i) (nkeys)))
1140                     value)))))
1141       (dolist (entry (overflow))
1142         (let ((value (funcall function (car entry) (cdr entry))))
1143           (when set-p
1144             (setf (cdr entry) value))))))
1145   cache)
1146
1147 (defun cache-count (cache)
1148   (with-local-cache-functions (cache)
1149     (let ((count 0))
1150       (declare (fixnum count))
1151       (dotimes-fixnum (i (nlines) count)
1152         (unless (line-reserved-p i)
1153           (when (line-full-p i)
1154             (incf count)))))))
1155
1156 (defun entry-in-cache-p (cache wrappers value)
1157   (declare (ignore value))
1158   (with-local-cache-functions (cache)
1159     (dotimes-fixnum (i (nlines))
1160       (unless (line-reserved-p i)
1161         (when (equal (line-wrappers i) wrappers)
1162           (return t))))))
1163
1164 ;;; returns T or NIL
1165 (defun fill-cache-p (forcep cache wrappers value)
1166   (with-local-cache-functions (cache)
1167     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
1168            (primary (location-line location)))
1169       (declare (fixnum location primary))
1170       (multiple-value-bind (free emptyp)
1171           (find-free-cache-line primary cache wrappers)
1172         (when (or forcep emptyp)
1173           (when (not emptyp)
1174             (push (cons (line-wrappers free) (line-value free))
1175                   (cache-overflow cache)))
1176           ;;(fill-line free wrappers value)
1177           (let ((line free))
1178             (declare (fixnum line))
1179             (when (line-reserved-p line)
1180               (error "attempt to fill a reserved line"))
1181             (let ((loc (line-location line))
1182                   (cache-vector (vector)))
1183               (declare (fixnum loc) (simple-vector cache-vector))
1184               (cond ((= (nkeys) 1)
1185                      (setf (cache-vector-ref cache-vector loc) wrappers)
1186                      (when (valuep)
1187                        (setf (cache-vector-ref cache-vector (1+ loc)) value)))
1188                     (t
1189                      (let ((i 0))
1190                        (declare (fixnum i))
1191                        (dolist (w wrappers)
1192                          (setf (cache-vector-ref cache-vector (+ loc i)) w)
1193                          (setq i (the fixnum (1+ i)))))
1194                      (when (valuep)
1195                        (setf (cache-vector-ref cache-vector (+ loc (nkeys)))
1196                              value))))
1197               (maybe-check-cache cache))))))))
1198
1199 (defun fill-cache-from-cache-p (forcep cache from-cache from-line)
1200   (declare (fixnum from-line))
1201   (with-local-cache-functions (cache)
1202     (let ((primary (location-line
1203                     (compute-primary-cache-location-from-location
1204                      cache (line-location from-line) from-cache))))
1205       (declare (fixnum primary))
1206       (multiple-value-bind (free emptyp)
1207           (find-free-cache-line primary cache)
1208         (when (or forcep emptyp)
1209           (when (not emptyp)
1210             (push (cons (line-wrappers free) (line-value free))
1211                   (cache-overflow cache)))
1212           ;;(transfer-line from-cache-vector from-line cache-vector free)
1213           (let ((from-cache-vector (cache-vector from-cache))
1214                 (to-cache-vector (vector))
1215                 (to-line free))
1216             (declare (fixnum to-line))
1217             (if (line-reserved-p to-line)
1218                 (error "transferring something into a reserved cache line")
1219                 (let ((from-loc (line-location from-line))
1220                       (to-loc (line-location to-line)))
1221                   (declare (fixnum from-loc to-loc))
1222                   (modify-cache to-cache-vector
1223                                 (dotimes-fixnum (i (line-size))
1224                                   (setf (cache-vector-ref to-cache-vector
1225                                                           (+ to-loc i))
1226                                         (cache-vector-ref from-cache-vector
1227                                                           (+ from-loc i)))))))
1228             (maybe-check-cache cache)))))))
1229
1230 ;;; Returns NIL or (values <field> <cache-vector>)
1231 ;;;
1232 ;;; This is only called when it isn't possible to put the entry in the
1233 ;;; cache the easy way. That is, this function assumes that
1234 ;;; FILL-CACHE-P has been called as returned NIL.
1235 ;;;
1236 ;;; If this returns NIL, it means that it wasn't possible to find a
1237 ;;; wrapper field for which all of the entries could be put in the
1238 ;;; cache (within the limit).
1239 (defun adjust-cache (cache wrappers value free-old-cache-p)
1240   (with-local-cache-functions (cache)
1241     (let ((ncache (get-cache-from-cache cache (nlines) (field))))
1242       (do ((nfield (cache-field ncache) (next-wrapper-cache-number-index nfield)))
1243           ((null nfield) (free-cache ncache) nil)
1244         (setf (cache-field ncache) nfield)
1245         (labels ((try-one-fill-from-line (line)
1246                    (fill-cache-from-cache-p nil ncache cache line))
1247                  (try-one-fill (wrappers value)
1248                    (fill-cache-p nil ncache wrappers value)))
1249           (if (and (dotimes-fixnum (i (nlines) t)
1250                      (when (and (null (line-reserved-p i))
1251                                 (line-valid-p i wrappers))
1252                        (unless (try-one-fill-from-line i) (return nil))))
1253                    (dolist (wrappers+value (cache-overflow cache) t)
1254                      (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
1255                        (return nil)))
1256                    (try-one-fill wrappers value))
1257               (progn (when free-old-cache-p (free-cache cache))
1258                      (return (maybe-check-cache ncache)))
1259               (flush-cache-vector-internal (cache-vector ncache))))))))
1260
1261 ;;; returns: (values <cache>)
1262 (defun expand-cache (cache wrappers value free-old-cache-p)
1263   ;;(declare (values cache))
1264   (with-local-cache-functions (cache)
1265     (let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
1266       (labels ((do-one-fill-from-line (line)
1267                  (unless (fill-cache-from-cache-p nil ncache cache line)
1268                    (do-one-fill (line-wrappers line) (line-value line))))
1269                (do-one-fill (wrappers value)
1270                  (setq ncache (or (adjust-cache ncache wrappers value t)
1271                                   (fill-cache-p t ncache wrappers value))))
1272                (try-one-fill (wrappers value)
1273                  (fill-cache-p nil ncache wrappers value)))
1274         (dotimes-fixnum (i (nlines))
1275           (when (and (null (line-reserved-p i))
1276                      (line-valid-p i wrappers))
1277             (do-one-fill-from-line i)))
1278         (dolist (wrappers+value (cache-overflow cache))
1279           (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
1280             (do-one-fill (car wrappers+value) (cdr wrappers+value))))
1281         (unless (try-one-fill wrappers value)
1282           (do-one-fill wrappers value))
1283         (when free-old-cache-p (free-cache cache))
1284         (maybe-check-cache ncache)))))
1285 \f
1286 ;;; This is the heart of the cache filling mechanism. It implements
1287 ;;; the decisions about where entries are placed.
1288 ;;;
1289 ;;; Find a line in the cache at which a new entry can be inserted.
1290 ;;;
1291 ;;;   <line>
1292 ;;;   <empty?>     is <line> in fact empty?
1293 (defun find-free-cache-line (primary cache &optional wrappers)
1294   ;;(declare (values line empty?))
1295   (declare (fixnum primary))
1296   (with-local-cache-functions (cache)
1297     (when (line-reserved-p primary) (setq primary (next-line primary)))
1298     (let ((limit (funcall (limit-fn) (nlines)))
1299           (wrappedp nil)
1300           (lines nil)
1301           (p primary) (s primary))
1302       (declare (fixnum p s limit))
1303       (block find-free
1304         (loop
1305          ;; Try to find a free line starting at <s>. <p> is the
1306          ;; primary line of the entry we are finding a free
1307          ;; line for, it is used to compute the separations.
1308          (do* ((line s (next-line line))
1309                (nsep (line-separation p s) (1+ nsep)))
1310               (())
1311            (declare (fixnum line nsep))
1312            (when (null (line-valid-p line wrappers)) ;If this line is empty or
1313              (push line lines)          ;invalid, just use it.
1314              (return-from find-free))
1315            (when (and wrappedp (>= line primary))
1316              ;; have gone all the way around the cache, time to quit
1317              (return-from find-free-cache-line (values primary nil)))
1318            (let ((osep (line-separation (line-primary line) line)))
1319              (when (>= osep limit)
1320                (return-from find-free-cache-line (values primary nil)))
1321              (when (cond ((= nsep limit) t)
1322                          ((= nsep osep) (zerop (random 2)))
1323                          ((> nsep osep) t)
1324                          (t nil))
1325                ;; See whether we can displace what is in this line so that we
1326                ;; can use the line.
1327                (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
1328                (setq p (line-primary line))
1329                (setq s (next-line line))
1330                (push line lines)
1331                (return nil)))
1332            (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
1333       ;; Do all the displacing.
1334       (loop
1335        (when (null (cdr lines)) (return nil))
1336        (let ((dline (pop lines))
1337              (line (car lines)))
1338          (declare (fixnum dline line))
1339          ;;Copy from line to dline (dline is known to be free).
1340          (let ((from-loc (line-location line))
1341                (to-loc (line-location dline))
1342                (cache-vector (vector)))
1343            (declare (fixnum from-loc to-loc) (simple-vector cache-vector))
1344            (modify-cache cache-vector
1345                          (dotimes-fixnum (i (line-size))
1346                            (setf (cache-vector-ref cache-vector
1347                                                    (+ to-loc i))
1348                                  (cache-vector-ref cache-vector
1349                                                    (+ from-loc i)))
1350                            (setf (cache-vector-ref cache-vector
1351                                                    (+ from-loc i))
1352                                  nil))))))
1353       (values (car lines) t))))
1354
1355 (defun default-limit-fn (nlines)
1356   (case nlines
1357     ((1 2 4) 1)
1358     ((8 16)  4)
1359     (otherwise 6)))
1360
1361 (defvar *empty-cache* (make-cache)) ; for defstruct slot initial value forms
1362 \f
1363 ;;; Pre-allocate generic function caches. The hope is that this will
1364 ;;; put them nicely together in memory, and that that may be a win. Of
1365 ;;; course the first GC copy will probably blow that out, this really
1366 ;;; wants to be wrapped in something that declares the area static.
1367 ;;;
1368 ;;; This preallocation only creates about 25% more caches than PCL
1369 ;;; itself uses. Some ports may want to preallocate some more of
1370 ;;; these.
1371 ;;;
1372 ;;; KLUDGE: Isn't something very similar going on in precom1.lisp? Do
1373 ;;; we need it both here and there? Why? -- WHN 19991203
1374 (eval-when (:load-toplevel)
1375   (dolist (n-size '((1 513)(3 257)(3 129)(14 128)(6 65)(2 64)(7 33)(16 32)
1376                     (16 17)(32 16)(64 9)(64 8)(6 5)(128 4)(35 2)))
1377     (let ((n (car n-size))
1378           (size (cadr n-size)))
1379       (mapcar #'free-cache-vector
1380               (mapcar #'get-cache-vector
1381                       (make-list n :initial-element size))))))
1382
1383 (defun caches-to-allocate ()
1384   (sort (let ((l nil))
1385           (maphash #'(lambda (size entry)
1386                        (push (list (car entry) size) l))
1387                    sb-pcl::*free-caches*)
1388           l)
1389         #'>
1390         :key #'cadr))