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