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