c463a91e6b6f9ce29515fbc50768b07478283523
[sbcl.git] / src / pcl / dfun.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3
4 ;;;; This software is derived from software originally released by Xerox
5 ;;;; Corporation. Copyright and release statements follow. Later modifications
6 ;;;; to the software are in the public domain and are provided with
7 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
8 ;;;; information.
9
10 ;;;; copyright information from original PCL sources:
11 ;;;;
12 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
13 ;;;; All rights reserved.
14 ;;;;
15 ;;;; Use and copying of this software and preparation of derivative works based
16 ;;;; upon this software are permitted. Any distribution of this software or
17 ;;;; derivative works must comply with all applicable United States export
18 ;;;; control laws.
19 ;;;;
20 ;;;; This software is made available AS IS, and Xerox Corporation makes no
21 ;;;; warranty about the software, its performance or its conformity to any
22 ;;;; specification.
23
24 (in-package "SB-PCL")
25 \f
26 #|
27
28 This implementation of method lookup was redone in early August of 89.
29
30 It has the following properties:
31
32  - Its modularity makes it easy to modify the actual caching algorithm.
33    The caching algorithm is almost completely separated into the files
34    cache.lisp and dlap.lisp. This file just contains the various uses
35    of it. There will be more tuning as we get more results from Luis'
36    measurements of caching behavior.
37
38  - The metacircularity issues have been dealt with properly. All of
39    PCL now grounds out properly. Moreover, it is now possible to have
40    metaobject classes which are themselves not instances of standard
41    metaobject classes.
42
43 ** Modularity of the code **
44
45 The actual caching algorithm is isolated in a modest number of functions.
46 The code which generates cache lookup code is all found in cache.lisp and
47 dlap.lisp. Certain non-wrapper-caching special cases are in this file.
48
49 ** Handling the metacircularity **
50
51 In CLOS, method lookup is the potential source of infinite metacircular
52 regress. The metaobject protocol specification gives us wide flexibility
53 in how to address this problem. PCL uses a technique which handles the
54 problem not only for the metacircular language described in Chapter 3, but
55 also for the PCL protocol which includes additional generic functions
56 which control more aspects of the CLOS implementation.
57
58 The source of the metacircular regress can be seen in a number of ways.
59 One is that the specified method lookup protocol must, as part of doing
60 the method lookup (or at least the cache miss case), itself call generic
61 functions. It is easy to see that if the method lookup for a generic
62 function ends up calling that same generic function there can be trouble.
63
64 Fortunately, there is an easy solution at hand. The solution is based on
65 the restriction that portable code cannot change the class of a specified
66 metaobject. This restriction implies that for specified generic functions,
67 the method lookup protocol they follow is fixed.
68
69 More precisely, for such specified generic functions, most generic functions
70 that are called during their own method lookup will not run portable methods.
71 This allows the implementation to usurp the actual generic function call in
72 this case. In short, method lookup of a standard generic function, in the
73 case where the only applicable methods are themselves standard doesn't
74 have to do any method lookup to implement itself.
75
76 And so, we are saved.
77
78 Except see also BREAK-VICIOUS-METACIRCLE.  -- CSR, 2003-05-28
79
80 |#
81 \f
82 ;;; an alist in which each entry is of the form
83 ;;;   (<generator> . (<subentry> ...)).
84 ;;; Each subentry is of the form
85 ;;;   (<args> <constructor> <system>).
86 (defvar *dfun-constructors* ())
87
88 ;;; If this is NIL, then the whole mechanism for caching dfun constructors is
89 ;;; turned off. The only time that makes sense is when debugging LAP code.
90 (defvar *enable-dfun-constructor-caching* t)
91
92 (defun show-dfun-constructors ()
93   (format t "~&DFUN constructor caching is ~A."
94           (if *enable-dfun-constructor-caching*
95               "enabled" "disabled"))
96   (dolist (generator-entry *dfun-constructors*)
97     (dolist (args-entry (cdr generator-entry))
98       (format t "~&~S ~S"
99               (cons (car generator-entry) (caar args-entry))
100               (caddr args-entry)))))
101
102 (defvar *raise-metatypes-to-class-p* t)
103
104 (defun get-dfun-constructor (generator &rest args)
105   (when (and *raise-metatypes-to-class-p*
106              (member generator '(emit-checking emit-caching
107                                  emit-in-checking-cache-p emit-constant-value)))
108     (setq args (cons (mapcar (lambda (mt)
109                                (if (eq mt t)
110                                    mt
111                                    'class))
112                              (car args))
113                      (cdr args))))
114   (let* ((generator-entry (assq generator *dfun-constructors*))
115          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
116     (if (null *enable-dfun-constructor-caching*)
117         (apply (fdefinition generator) args)
118         (or (cadr args-entry)
119             (multiple-value-bind (new not-best-p)
120                 (apply (symbol-function generator) args)
121               (let ((entry (list (copy-list args) new (unless not-best-p 'pcl)
122                                  not-best-p)))
123                 (if generator-entry
124                     (push entry (cdr generator-entry))
125                     (push (list generator entry)
126                           *dfun-constructors*)))
127               (values new not-best-p))))))
128
129 (defun load-precompiled-dfun-constructor (generator args system constructor)
130   (let* ((generator-entry (assq generator *dfun-constructors*))
131          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
132     (if args-entry
133         (when (fourth args-entry)
134           (let* ((dfun-type (case generator
135                               (emit-checking 'checking)
136                               (emit-caching 'caching)
137                               (emit-constant-value 'constant-value)
138                               (emit-default-only 'default-method-only)))
139                  (metatypes (car args))
140                  (gfs (when dfun-type (gfs-of-type dfun-type))))
141             (dolist (gf gfs)
142               (when (and (equal metatypes
143                                 (arg-info-metatypes (gf-arg-info gf)))
144                          (let ((gf-name (generic-function-name gf)))
145                            (and (not (eq gf-name 'slot-value-using-class))
146                                 (not (equal gf-name
147                                             '(setf slot-value-using-class)))
148                                 (not (eq gf-name 'slot-boundp-using-class)))))
149                 (update-dfun gf)))
150             (setf (second args-entry) constructor)
151             (setf (third args-entry) system)
152             (setf (fourth args-entry) nil)))
153         (let ((entry (list args constructor system nil)))
154           (if generator-entry
155               (push entry (cdr generator-entry))
156               (push (list generator entry) *dfun-constructors*))))))
157
158 (defmacro precompile-dfun-constructors (&optional system)
159   (let ((*precompiling-lap* t))
160     `(progn
161        ,@(let (collect)
162            (dolist (generator-entry *dfun-constructors*)
163              (dolist (args-entry (cdr generator-entry))
164                (when (or (null (caddr args-entry))
165                          (eq (caddr args-entry) system))
166                  (when system (setf (caddr args-entry) system))
167                  (push `(load-precompiled-dfun-constructor
168                          ',(car generator-entry)
169                          ',(car args-entry)
170                          ',system
171                          ,(apply (fdefinition (car generator-entry))
172                                  (car args-entry)))
173                        collect))))
174            (nreverse collect)))))
175 \f
176 ;;; Standardized class slot access: when trying to break vicious
177 ;;; metacircles, we need a way to get at the values of slots of some
178 ;;; standard classes without going through the whole meta machinery,
179 ;;; because that would likely enter the vicious circle again.  The
180 ;;; following are helper functions that short-circuit the generic
181 ;;; lookup machinery.
182
183 (defvar *standard-classes*
184   ;; KLUDGE: order matters!  finding effective slot definitions
185   ;; involves calling slot-definition-name, and we need to do that to
186   ;; break metacycles, so STANDARD-EFFECTIVE-SLOT-DEFINITION must
187   ;; precede STANDARD-DIRECT-SLOT-DEFINITION in this list, at least
188   ;; until ACCESSES-STANDARD-CLASS-SLOT-P is generalized
189   '(standard-method standard-generic-function standard-class
190     standard-effective-slot-definition standard-direct-slot-definition))
191
192 (defvar *standard-slot-locations* (make-hash-table :test 'equal))
193
194 (defun compute-standard-slot-locations ()
195   (let ((new (make-hash-table :test 'equal)))
196     (dolist (class-name *standard-classes*)
197       (let ((class (find-class class-name)))
198         (dolist (slot (class-slots class))
199           (setf (gethash (cons class (slot-definition-name slot)) new)
200                 (slot-definition-location slot)))))
201     (setf *standard-slot-locations* new)))
202
203 (defun maybe-update-standard-slot-locations (class)
204   (when (and (eq **boot-state** 'complete)
205              (memq (class-name class) *standard-classes*))
206     (compute-standard-slot-locations)))
207
208 (defun standard-slot-value (object slot-name class)
209   (let ((location (gethash (cons class slot-name) *standard-slot-locations*)))
210     (if location
211         (let ((value (if (funcallable-instance-p object)
212                          (funcallable-standard-instance-access object location)
213                          (standard-instance-access object location))))
214           (when (eq +slot-unbound+ value)
215             (error "~@<slot ~S of class ~S is unbound in object ~S~@:>"
216                    slot-name class object))
217           value)
218         (error "~@<cannot get standard value of slot ~S of class ~S ~
219                 in object ~S~@:>"
220                slot-name class object))))
221
222 (defun standard-slot-value/gf (gf slot-name)
223   (standard-slot-value gf slot-name *the-class-standard-generic-function*))
224
225 (defun standard-slot-value/method (method slot-name)
226   (standard-slot-value method slot-name *the-class-standard-method*))
227
228 (defun standard-slot-value/eslotd (slotd slot-name)
229   (standard-slot-value slotd slot-name
230                        *the-class-standard-effective-slot-definition*))
231
232 (defun standard-slot-value/dslotd (slotd slot-name)
233   (standard-slot-value slotd slot-name
234                        *the-class-standard-direct-slot-definition*))
235
236 (defun standard-slot-value/class (class slot-name)
237   (standard-slot-value class slot-name *the-class-standard-class*))
238 \f
239 ;;; When all the methods of a generic function are automatically
240 ;;; generated reader or writer methods a number of special
241 ;;; optimizations are possible. These are important because of the
242 ;;; large number of generic functions of this type.
243 ;;;
244 ;;; There are a number of cases:
245 ;;;
246 ;;;   ONE-CLASS-ACCESSOR
247 ;;;     In this case, the accessor generic function has only been
248 ;;;     called with one class of argument. There is no cache vector,
249 ;;;     the wrapper of the one class, and the slot index are stored
250 ;;;     directly as closure variables of the discriminating function.
251 ;;;     This case can convert to either of the next kind.
252 ;;;
253 ;;;   TWO-CLASS-ACCESSOR
254 ;;;     Like above, but two classes. This is common enough to do
255 ;;;     specially. There is no cache vector. The two classes are
256 ;;;     stored a separate closure variables.
257 ;;;
258 ;;;   ONE-INDEX-ACCESSOR
259 ;;;     In this case, the accessor generic function has seen more than
260 ;;;     one class of argument, but the index of the slot is the same
261 ;;;     for all the classes that have been seen. A cache vector is
262 ;;;     used to store the wrappers that have been seen, the slot index
263 ;;;     is stored directly as a closure variable of the discriminating
264 ;;;     function. This case can convert to the next kind.
265 ;;;
266 ;;;   N-N-ACCESSOR
267 ;;;     This is the most general case. In this case, the accessor
268 ;;;     generic function has seen more than one class of argument and
269 ;;;     more than one slot index. A cache vector stores the wrappers
270 ;;;     and corresponding slot indexes.
271
272 (defstruct (dfun-info (:constructor nil)
273                       (:copier nil))
274   (cache nil))
275
276 (defstruct (no-methods (:constructor no-methods-dfun-info ())
277                        (:include dfun-info)
278                        (:copier nil)))
279
280 (defstruct (initial (:constructor initial-dfun-info ())
281                     (:include dfun-info)
282                     (:copier nil)))
283
284 (defstruct (dispatch (:constructor dispatch-dfun-info ())
285                      (:include dfun-info)
286                      (:copier nil)))
287
288 (defstruct (default-method-only (:constructor default-method-only-dfun-info ())
289                                 (:include dfun-info)
290                                 (:copier nil)))
291
292 ;without caching:
293 ;  dispatch one-class two-class default-method-only
294
295 ;with caching:
296 ;  one-index n-n checking caching
297
298 ;accessor:
299 ;  one-class two-class one-index n-n
300 (defstruct (accessor-dfun-info (:constructor nil)
301                                (:include dfun-info)
302                                (:copier nil))
303   accessor-type) ; (member reader writer)
304
305 (defmacro dfun-info-accessor-type (di)
306   `(accessor-dfun-info-accessor-type ,di))
307
308 (defstruct (one-index-dfun-info (:constructor nil)
309                                 (:include accessor-dfun-info)
310                                 (:copier nil))
311   index)
312
313 (defmacro dfun-info-index (di)
314   `(one-index-dfun-info-index ,di))
315
316 (defstruct (n-n (:constructor n-n-dfun-info (accessor-type cache))
317                 (:include accessor-dfun-info)
318                 (:copier nil)))
319
320 (defstruct (one-class (:constructor one-class-dfun-info
321                                     (accessor-type index wrapper0))
322                       (:include one-index-dfun-info)
323                       (:copier nil))
324   wrapper0)
325
326 (defmacro dfun-info-wrapper0 (di)
327   `(one-class-wrapper0 ,di))
328
329 (defstruct (two-class (:constructor two-class-dfun-info
330                                     (accessor-type index wrapper0 wrapper1))
331                       (:include one-class)
332                       (:copier nil))
333   wrapper1)
334
335 (defmacro dfun-info-wrapper1 (di)
336   `(two-class-wrapper1 ,di))
337
338 (defstruct (one-index (:constructor one-index-dfun-info
339                                     (accessor-type index cache))
340                       (:include one-index-dfun-info)
341                       (:copier nil)))
342
343 (defstruct (checking (:constructor checking-dfun-info (function cache))
344                      (:include dfun-info)
345                      (:copier nil))
346   function)
347
348 (defmacro dfun-info-function (di)
349   `(checking-function ,di))
350
351 (defstruct (caching (:constructor caching-dfun-info (cache))
352                     (:include dfun-info)
353                     (:copier nil)))
354
355 (defstruct (constant-value (:constructor constant-value-dfun-info (cache))
356                            (:include dfun-info)
357                            (:copier nil)))
358
359 (defmacro dfun-update (generic-function function &rest args)
360   `(multiple-value-bind (dfun cache info)
361        (funcall ,function ,generic-function ,@args)
362      (update-dfun ,generic-function dfun cache info)))
363
364 (defun accessor-miss-function (gf dfun-info)
365   (ecase (dfun-info-accessor-type dfun-info)
366     ((reader boundp)
367      (lambda (arg)
368        (accessor-miss gf nil arg dfun-info)))
369     (writer
370      (lambda (new arg)
371        (accessor-miss gf new arg dfun-info)))))
372
373 #-sb-fluid (declaim (sb-ext:freeze-type dfun-info))
374 \f
375 (defun make-one-class-accessor-dfun (gf type wrapper index)
376   (let ((emit (ecase type
377                 (reader 'emit-one-class-reader)
378                 (boundp 'emit-one-class-boundp)
379                 (writer 'emit-one-class-writer)))
380         (dfun-info (one-class-dfun-info type index wrapper)))
381     (values
382      (funcall (get-dfun-constructor emit (consp index))
383               wrapper index
384               (accessor-miss-function gf dfun-info))
385      nil
386      dfun-info)))
387
388 (defun make-two-class-accessor-dfun (gf type w0 w1 index)
389   (let ((emit (ecase type
390                 (reader 'emit-two-class-reader)
391                 (boundp 'emit-two-class-boundp)
392                 (writer 'emit-two-class-writer)))
393         (dfun-info (two-class-dfun-info type index w0 w1)))
394     (values
395      (funcall (get-dfun-constructor emit (consp index))
396               w0 w1 index
397               (accessor-miss-function gf dfun-info))
398      nil
399      dfun-info)))
400
401 ;;; std accessors same index dfun
402 (defun make-one-index-accessor-dfun (gf type index &optional cache)
403   (let* ((emit (ecase type
404                  (reader 'emit-one-index-readers)
405                  (boundp 'emit-one-index-boundps)
406                  (writer 'emit-one-index-writers)))
407          (cache (or cache (make-cache :key-count 1 :value nil :size 4)))
408          (dfun-info (one-index-dfun-info type index cache)))
409     (declare (type cache cache))
410     (values
411      (funcall (get-dfun-constructor emit (consp index))
412               cache
413               index
414               (accessor-miss-function gf dfun-info))
415      cache
416      dfun-info)))
417
418 (defun make-n-n-accessor-dfun (gf type &optional cache)
419   (let* ((emit (ecase type
420                  (reader 'emit-n-n-readers)
421                  (boundp 'emit-n-n-boundps)
422                  (writer 'emit-n-n-writers)))
423          (cache (or cache (make-cache :key-count 1 :value t :size 2)))
424          (dfun-info (n-n-dfun-info type cache)))
425     (declare (type cache cache))
426     (values
427      (funcall (get-dfun-constructor emit)
428               cache
429               (accessor-miss-function gf dfun-info))
430      cache
431      dfun-info)))
432
433 (defun make-checking-dfun (generic-function function &optional cache)
434   (unless cache
435     (when (use-caching-dfun-p generic-function)
436       (return-from make-checking-dfun (make-caching-dfun generic-function)))
437     (when (use-dispatch-dfun-p generic-function)
438       (return-from make-checking-dfun (make-dispatch-dfun generic-function))))
439   (multiple-value-bind (nreq applyp metatypes nkeys)
440       (get-generic-fun-info generic-function)
441     (declare (ignore nreq))
442     (if (every (lambda (mt) (eq mt t)) metatypes)
443         (let ((dfun-info (default-method-only-dfun-info)))
444           (values
445            (funcall (get-dfun-constructor 'emit-default-only metatypes applyp)
446                     function)
447            nil
448            dfun-info))
449         (let* ((cache (or cache (make-cache :key-count nkeys :value nil :size 2)))
450                (dfun-info (checking-dfun-info function cache)))
451           (values
452            (funcall (get-dfun-constructor 'emit-checking metatypes applyp)
453                     cache
454                     function
455                     (lambda (&rest args)
456                       (checking-miss generic-function args dfun-info)))
457            cache
458            dfun-info)))))
459
460 (defun make-final-checking-dfun (generic-function function classes-list new-class)
461   (multiple-value-bind (nreq applyp metatypes nkeys)
462       (get-generic-fun-info generic-function)
463     (declare (ignore nreq applyp nkeys))
464     (if (every (lambda (mt) (eq mt t)) metatypes)
465         (values (lambda (&rest args)
466                   (invoke-emf function args))
467                 nil (default-method-only-dfun-info))
468         (let ((cache (make-final-ordinary-dfun-cache
469                       generic-function nil classes-list new-class)))
470           (make-checking-dfun generic-function function cache)))))
471
472 (defun use-default-method-only-dfun-p (generic-function)
473   (multiple-value-bind (nreq applyp metatypes nkeys)
474       (get-generic-fun-info generic-function)
475     (declare (ignore nreq applyp nkeys))
476     (every (lambda (mt) (eq mt t)) metatypes)))
477
478 (defun use-caching-dfun-p (generic-function)
479   (some (lambda (method) (method-plist-value method :slot-name-lists))
480         ;; KLUDGE: As of sbcl-0.6.4, it's very important for
481         ;; efficiency to know the type of the sequence argument to
482         ;; quantifiers (SOME/NOTANY/etc.) at compile time, but
483         ;; the compiler isn't smart enough to understand the :TYPE
484         ;; slot option for DEFCLASS, so we just tell
485         ;; it the type by hand here.
486         (the list
487              (if (early-gf-p generic-function)
488                  (early-gf-methods generic-function)
489                  (generic-function-methods generic-function)))))
490 \f
491 (defun make-caching-dfun (generic-function &optional cache)
492   (unless cache
493     (when (use-constant-value-dfun-p generic-function)
494       (return-from make-caching-dfun
495         (make-constant-value-dfun generic-function)))
496     (when (use-dispatch-dfun-p generic-function)
497       (return-from make-caching-dfun
498         (make-dispatch-dfun generic-function))))
499   (multiple-value-bind (nreq applyp metatypes nkeys)
500       (get-generic-fun-info generic-function)
501     (declare (ignore nreq))
502     (let* ((cache (or cache (make-cache :key-count nkeys :value t :size 2)))
503            (dfun-info (caching-dfun-info cache)))
504       (values
505        (funcall (get-dfun-constructor 'emit-caching metatypes applyp)
506                 cache
507                 (lambda (&rest args)
508                   (caching-miss generic-function args dfun-info)))
509        cache
510        dfun-info))))
511
512 (defun make-final-caching-dfun (generic-function classes-list new-class)
513   (let ((cache (make-final-ordinary-dfun-cache
514                 generic-function t classes-list new-class)))
515     (make-caching-dfun generic-function cache)))
516
517 (defun insure-caching-dfun (gf)
518   (multiple-value-bind (nreq applyp metatypes nkeys)
519       (get-generic-fun-info gf)
520     (declare (ignore nreq nkeys))
521     (when (and metatypes
522                (not (null (car metatypes)))
523                (dolist (mt metatypes nil)
524                  (unless (eq mt t) (return t))))
525       (get-dfun-constructor 'emit-caching metatypes applyp))))
526
527 (defun use-constant-value-dfun-p (gf &optional boolean-values-p)
528   (multiple-value-bind (nreq applyp metatypes nkeys)
529       (get-generic-fun-info gf)
530     (declare (ignore nreq metatypes nkeys))
531     (let* ((early-p (early-gf-p gf))
532            (methods (if early-p
533                         (early-gf-methods gf)
534                         (generic-function-methods gf)))
535            (default '(unknown)))
536       (and (null applyp)
537            (or (not (eq **boot-state** 'complete))
538                ;; If COMPUTE-APPLICABLE-METHODS is specialized, we
539                ;; can't use this, of course, because we can't tell
540                ;; which methods will be considered applicable.
541                ;;
542                ;; Also, don't use this dfun method if the generic
543                ;; function has a non-standard method combination,
544                ;; because if it has, it's not sure that method
545                ;; functions are used directly as effective methods,
546                ;; which CONSTANT-VALUE-MISS depends on.  The
547                ;; pre-defined method combinations like LIST are
548                ;; examples of that.
549                (and (compute-applicable-methods-emf-std-p gf)
550                     (eq (generic-function-method-combination gf)
551                         *standard-method-combination*)))
552            ;; Check that no method is eql-specialized, and that all
553            ;; methods return a constant value.  If BOOLEAN-VALUES-P,
554            ;; check that all return T or NIL.  Also, check that no
555            ;; method has qualifiers, to make sure that emfs are really
556            ;; method functions; see above.
557            (dolist (method methods t)
558              (when (eq **boot-state** 'complete)
559                (when (or (some #'eql-specializer-p
560                                (safe-method-specializers method))
561                          (safe-method-qualifiers method))
562                  (return nil)))
563              (let ((value (method-plist-value method :constant-value default)))
564                (when (or (eq value default)
565                          (and boolean-values-p
566                               (not (member value '(t nil)))))
567                  (return nil))))))))
568
569 (defun make-constant-value-dfun (generic-function &optional cache)
570   (multiple-value-bind (nreq applyp metatypes nkeys)
571       (get-generic-fun-info generic-function)
572     (declare (ignore nreq applyp))
573     (let* ((cache (or cache (make-cache :key-count nkeys :value t :size 2)))
574            (dfun-info (constant-value-dfun-info cache)))
575       (declare (type cache cache))
576       (values
577        (funcall (get-dfun-constructor 'emit-constant-value metatypes)
578                 cache
579                 (lambda (&rest args)
580                   (constant-value-miss generic-function args dfun-info)))
581        cache
582        dfun-info))))
583
584 (defun make-final-constant-value-dfun (generic-function classes-list new-class)
585   (let ((cache (make-final-ordinary-dfun-cache
586                 generic-function :constant-value classes-list new-class)))
587     (make-constant-value-dfun generic-function cache)))
588
589 (defun gf-has-method-with-nonstandard-specializer-p (gf)
590   (let ((methods (generic-function-methods gf)))
591     (dolist (method methods nil)
592       (unless (every (lambda (s) (standard-specializer-p s))
593                      (method-specializers method))
594         (return t)))))
595
596 (defun use-dispatch-dfun-p (gf &optional (caching-p (use-caching-dfun-p gf)))
597   (when (eq **boot-state** 'complete)
598     (unless (or caching-p
599                 (gf-requires-emf-keyword-checks gf)
600                 ;; DISPATCH-DFUN-COST will error if it encounters a
601                 ;; method with a non-standard specializer.
602                 (gf-has-method-with-nonstandard-specializer-p gf))
603       ;; This should return T when almost all dispatching is by
604       ;; eql specializers or built-in classes. In other words,
605       ;; return NIL if we might ever need to do more than
606       ;; one (non built-in) typep.
607       ;; Otherwise, it is probably at least as fast to use
608       ;; a caching dfun first, possibly followed by secondary dispatching.
609
610       #||;;; Original found in cmu 17f -- S L O W
611       (< (dispatch-dfun-cost gf) (caching-dfun-cost gf))
612       ||#
613       ;; This uses improved dispatch-dfun-cost below
614       (let ((cdc  (caching-dfun-cost gf))) ; fast
615         (> cdc (dispatch-dfun-cost gf cdc))))))
616
617 (defparameter *non-built-in-typep-cost* 100)
618 (defparameter *structure-typep-cost*  15)
619 (defparameter *built-in-typep-cost* 5)
620
621 ;;; According to comments in the original CMU CL version of PCL,
622 ;;; the cost LIMIT is important to cut off exponential growth for
623 ;;; large numbers of gf methods and argument lists.
624 (defun dispatch-dfun-cost (gf &optional limit)
625   (generate-discrimination-net-internal
626    gf (generic-function-methods gf) nil
627    (lambda (methods known-types)
628      (declare (ignore methods known-types))
629      0)
630    (lambda (position type true-value false-value)
631      (declare (ignore position))
632      (let* ((type-test-cost
633              (if (eq 'class (car type))
634                  (let* ((metaclass (class-of (cadr type)))
635                         (mcpl (class-precedence-list metaclass)))
636                    (cond ((memq *the-class-built-in-class* mcpl)
637                           *built-in-typep-cost*)
638                          ((memq *the-class-structure-class* mcpl)
639                           *structure-typep-cost*)
640                          (t
641                           *non-built-in-typep-cost*)))
642                  0))
643             (max-cost-so-far
644              (+ (max true-value false-value) type-test-cost)))
645        (when (and limit (<= limit max-cost-so-far))
646          (return-from dispatch-dfun-cost max-cost-so-far))
647        max-cost-so-far))
648    #'identity))
649
650 (defparameter *cache-lookup-cost*  30)
651 (defparameter *wrapper-of-cost* 15)
652 (defparameter *secondary-dfun-call-cost* 30)
653
654 (defun caching-dfun-cost (gf)
655   (let ((nreq (get-generic-fun-info gf)))
656     (+ *cache-lookup-cost*
657        (* *wrapper-of-cost* nreq)
658        (if (methods-contain-eql-specializer-p
659             (generic-function-methods gf))
660            *secondary-dfun-call-cost*
661            0))))
662
663 (declaim (inline make-callable))
664 (defun make-callable (gf methods generator method-alist wrappers)
665   (let* ((*applicable-methods* methods)
666          (callable (function-funcall generator method-alist wrappers)))
667     callable))
668
669 (defun make-dispatch-dfun (gf)
670   (values (get-dispatch-function gf) nil (dispatch-dfun-info)))
671
672 (defun get-dispatch-function (gf)
673   (let* ((methods (generic-function-methods gf))
674          (generator (get-secondary-dispatch-function1
675                      gf methods nil nil nil nil nil t)))
676     (make-callable gf methods generator nil nil)))
677
678 (defun make-final-dispatch-dfun (gf)
679   (make-dispatch-dfun gf))
680
681 (defun update-dispatch-dfuns ()
682   (dolist (gf (gfs-of-type '(dispatch)))
683     (dfun-update gf #'make-dispatch-dfun)))
684
685 (defun make-final-ordinary-dfun-cache
686     (generic-function valuep classes-list new-class)
687   (let* ((arg-info (gf-arg-info generic-function))
688          (nkeys (arg-info-nkeys arg-info))
689          (new-class (and new-class
690                          (equal (type-of (gf-dfun-info generic-function))
691                                 (cond ((eq valuep t) 'caching)
692                                       ((eq valuep :constant-value) 'constant-value)
693                                       ((null valuep) 'checking)))
694                          new-class))
695          (cache (if new-class
696                     (copy-cache (gf-dfun-cache generic-function))
697                     (make-cache :key-count nkeys :value (not (null valuep))
698                                 :size 4))))
699     (make-emf-cache generic-function valuep cache classes-list new-class)))
700 \f
701 (defvar *dfun-miss-gfs-on-stack* ())
702
703 (defmacro dfun-miss ((gf args wrappers invalidp nemf
704                       &optional type index caching-p applicable)
705                      &body body)
706   (unless applicable (setq applicable (gensym)))
707   `(multiple-value-bind (,nemf ,applicable ,wrappers ,invalidp
708                          ,@(when type `(,type ,index)))
709        (cache-miss-values ,gf ,args ',(cond (caching-p 'caching)
710                                             (type 'accessor)
711                                             (t 'checking)))
712     (when (and ,applicable (not (memq ,gf *dfun-miss-gfs-on-stack*)))
713       (let ((*dfun-miss-gfs-on-stack* (cons ,gf *dfun-miss-gfs-on-stack*)))
714         ,@body))
715     ;; Create a FAST-INSTANCE-BOUNDP structure instance for a cached
716     ;; SLOT-BOUNDP so that INVOKE-EMF does the right thing, that is,
717     ;; does not signal a SLOT-UNBOUND error for a boundp test.
718     ,@(if type
719           ;; FIXME: could the NEMF not be a CONS (for :CLASS-allocated
720           ;; slots?)
721           `((if (and (eq ,type 'boundp) (integerp ,nemf))
722                 (invoke-emf (make-fast-instance-boundp :index ,nemf) ,args)
723                 (invoke-emf ,nemf ,args)))
724           `((invoke-emf ,nemf ,args)))))
725
726 ;;; The dynamically adaptive method lookup algorithm is implemented is
727 ;;; implemented as a kind of state machine. The kinds of
728 ;;; discriminating function is the state, the various kinds of reasons
729 ;;; for a cache miss are the state transitions.
730 ;;;
731 ;;; The code which implements the transitions is all in the miss
732 ;;; handlers for each kind of dfun. Those appear here.
733 ;;;
734 ;;; Note that within the states that cache, there are dfun updates
735 ;;; which simply select a new cache or cache field. Those are not
736 ;;; considered as state transitions.
737 (defvar *lazy-dfun-compute-p* t)
738 (defvar *early-p* nil)
739
740 (defun make-initial-dfun (gf)
741   (let ((initial-dfun #'(lambda (&rest args) (initial-dfun gf args))))
742     (multiple-value-bind (dfun cache info)
743         (if (eq **boot-state** 'complete)
744             (values initial-dfun nil (initial-dfun-info))
745             (let ((arg-info (if (early-gf-p gf)
746                                 (early-gf-arg-info gf)
747                                 (gf-arg-info gf)))
748                   (type nil))
749               (if (and (gf-precompute-dfun-and-emf-p arg-info)
750                        (setq type (final-accessor-dfun-type gf)))
751                   (if *early-p*
752                       (values (make-early-accessor gf type) nil nil)
753                       (make-final-accessor-dfun gf type))
754                   (values initial-dfun nil (initial-dfun-info)))))
755       (set-dfun gf dfun cache info))))
756
757 (defun make-early-accessor (gf type)
758   (let* ((methods (early-gf-methods gf))
759          (slot-name (early-method-standard-accessor-slot-name (car methods))))
760     (ecase type
761       (reader #'(lambda (instance)
762                   (let* ((class (class-of instance))
763                          (class-name (!bootstrap-get-slot 'class class 'name)))
764                     (!bootstrap-get-slot class-name instance slot-name))))
765       (boundp #'(lambda (instance)
766                   (let* ((class (class-of instance))
767                          (class-name (!bootstrap-get-slot 'class class 'name)))
768                     (not (eq +slot-unbound+
769                              (!bootstrap-get-slot class-name
770                                                   instance slot-name))))))
771       (writer #'(lambda (new-value instance)
772                   (let* ((class (class-of instance))
773                          (class-name (!bootstrap-get-slot 'class class 'name)))
774                     (!bootstrap-set-slot class-name instance slot-name new-value)))))))
775
776 (defun initial-dfun (gf args)
777   (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
778     (cond (invalidp)
779           ((and ntype nindex)
780            (dfun-update
781             gf #'make-one-class-accessor-dfun ntype wrappers nindex))
782           ((use-caching-dfun-p gf)
783            (dfun-update gf #'make-caching-dfun))
784           (t
785            (dfun-update gf #'make-checking-dfun
786             ;; nemf is suitable only for caching, have to do this:
787             (cache-miss-values gf args 'checking))))))
788
789 (defun make-final-dfun (gf &optional classes-list)
790   (multiple-value-bind (dfun cache info)
791       (make-final-dfun-internal gf classes-list)
792     (set-dfun gf dfun cache info)))
793
794 ;;; FIXME: What is this?
795 (defvar *new-class* nil)
796
797 (defun final-accessor-dfun-type (gf)
798   (let ((methods (if (early-gf-p gf)
799                      (early-gf-methods gf)
800                      (generic-function-methods gf))))
801     (cond ((every (lambda (method)
802                     (if (consp method)
803                         (let ((class (early-method-class method)))
804                           (or (eq class *the-class-standard-reader-method*)
805                               (eq class *the-class-global-reader-method*)))
806                         (or (standard-reader-method-p method)
807                             (global-reader-method-p method))))
808                   methods)
809            'reader)
810           ((every (lambda (method)
811                     (if (consp method)
812                         (let ((class (early-method-class method)))
813                           (or (eq class *the-class-standard-boundp-method*)
814                               (eq class *the-class-global-boundp-method*)))
815                         (or (standard-boundp-method-p method)
816                             (global-boundp-method-p method))))
817                   methods)
818            'boundp)
819           ((every (lambda (method)
820                     (if (consp method)
821                         (let ((class (early-method-class method)))
822                           (or (eq class *the-class-standard-writer-method*)
823                               (eq class *the-class-global-writer-method*)))
824                         (and
825                          (or (standard-writer-method-p method)
826                              (global-writer-method-p method))
827                          (not (safe-p
828                                (slot-definition-class
829                                 (accessor-method-slot-definition method)))))))
830                   methods)
831            'writer))))
832
833 (defun make-final-accessor-dfun (gf type &optional classes-list new-class)
834   (let ((table (make-hash-table :test #'eq)))
835     (multiple-value-bind (table all-index first second size no-class-slots-p)
836         (make-accessor-table gf type table)
837       (if table
838           (cond ((= size 1)
839                  (let ((w (class-wrapper first)))
840                    (make-one-class-accessor-dfun gf type w all-index)))
841                 ((and (= size 2) (or (integerp all-index) (consp all-index)))
842                  (let ((w0 (class-wrapper first))
843                        (w1 (class-wrapper second)))
844                    (make-two-class-accessor-dfun gf type w0 w1 all-index)))
845                 ((or (integerp all-index) (consp all-index))
846                  (let ((cache (hash-table-to-cache table :value nil :key-count 1)))
847                    (make-one-index-accessor-dfun gf type all-index cache)))
848                 (no-class-slots-p
849                  (let ((cache (hash-table-to-cache table :value t :key-count 1)))
850                    (make-n-n-accessor-dfun gf type cache)))
851                 (t
852                  (make-final-caching-dfun gf classes-list new-class)))
853           (make-final-caching-dfun gf classes-list new-class)))))
854
855 (defun make-final-dfun-internal (gf &optional classes-list)
856   (let ((methods (generic-function-methods gf)) type
857         (new-class *new-class*) (*new-class* nil)
858         specls all-same-p)
859     (cond ((null methods)
860            (values
861             #'(lambda (&rest args)
862                 (call-no-applicable-method gf args))
863             nil
864             (no-methods-dfun-info)))
865           ((setq type (final-accessor-dfun-type gf))
866            (make-final-accessor-dfun gf type classes-list new-class))
867           ((and (not (and (every (lambda (specl) (eq specl *the-class-t*))
868                                  (setq specls
869                                        (method-specializers (car methods))))
870                           (setq all-same-p
871                                 (every (lambda (method)
872                                          (and (equal specls
873                                                      (method-specializers
874                                                       method))))
875                                        methods))))
876                 (use-constant-value-dfun-p gf))
877            (make-final-constant-value-dfun gf classes-list new-class))
878           ((use-dispatch-dfun-p gf)
879            (make-final-dispatch-dfun gf))
880           ((and all-same-p (not (use-caching-dfun-p gf)))
881            (let ((emf (get-secondary-dispatch-function gf methods nil)))
882              (make-final-checking-dfun gf emf classes-list new-class)))
883           (t
884            (make-final-caching-dfun gf classes-list new-class)))))
885
886 (defvar *pcl-misc-random-state* (make-random-state))
887
888 (defun accessor-miss (gf new object dfun-info)
889   (let* ((ostate (type-of dfun-info))
890          (otype (dfun-info-accessor-type dfun-info))
891          oindex ow0 ow1 cache
892          (args (ecase otype
893                  ((reader boundp) (list object))
894                  (writer (list new object)))))
895     (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
896       ;; The following lexical functions change the state of the
897       ;; dfun to that which is their name.  They accept arguments
898       ;; which are the parameters of the new state, and get other
899       ;; information from the lexical variables bound above.
900       (flet ((two-class (index w0 w1)
901                (when (zerop (random 2 *pcl-misc-random-state*))
902                  (psetf w0 w1 w1 w0))
903                (dfun-update gf
904                             #'make-two-class-accessor-dfun
905                             ntype
906                             w0
907                             w1
908                             index))
909              (one-index (index &optional cache)
910                (dfun-update gf
911                             #'make-one-index-accessor-dfun
912                             ntype
913                             index
914                             cache))
915              (n-n (&optional cache)
916                (if (consp nindex)
917                    (dfun-update gf #'make-checking-dfun nemf)
918                    (dfun-update gf #'make-n-n-accessor-dfun ntype cache)))
919              (caching () ; because cached accessor emfs are much faster
920                          ; for accessors
921                (dfun-update gf #'make-caching-dfun))
922              (do-fill (update-fn)
923                (let ((ncache (fill-cache cache wrappers nindex)))
924                  (unless (eq ncache cache)
925                    (funcall update-fn ncache)))))
926         (cond ((null ntype)
927                (caching))
928               ((or invalidp
929                    (null nindex)))
930               ((not (pcl-instance-p object))
931                (caching))
932               ((or (neq ntype otype) (listp wrappers))
933                (caching))
934               (t
935                (ecase ostate
936                  (one-class
937                   (setq oindex (dfun-info-index dfun-info))
938                   (setq ow0 (dfun-info-wrapper0 dfun-info))
939                   (unless (eq ow0 wrappers)
940                     (if (eql nindex oindex)
941                         (two-class nindex ow0 wrappers)
942                         (n-n))))
943                  (two-class
944                   (setq oindex (dfun-info-index dfun-info))
945                   (setq ow0 (dfun-info-wrapper0 dfun-info))
946                   (setq ow1 (dfun-info-wrapper1 dfun-info))
947                   (unless (or (eq ow0 wrappers) (eq ow1 wrappers))
948                     (if (eql nindex oindex)
949                         (one-index nindex)
950                         (n-n))))
951                  (one-index
952                   (setq oindex (dfun-info-index dfun-info))
953                   (setq cache (dfun-info-cache dfun-info))
954                   (if (eql nindex oindex)
955                       (do-fill (lambda (ncache)
956                                  (one-index nindex ncache)))
957                       (n-n)))
958                  (n-n
959                   (setq cache (dfun-info-cache dfun-info))
960                   (if (consp nindex)
961                       (caching)
962                       (do-fill #'n-n))))))))))
963
964 (defun checking-miss (generic-function args dfun-info)
965   (let ((oemf (dfun-info-function dfun-info))
966         (cache (dfun-info-cache dfun-info)))
967     (dfun-miss (generic-function args wrappers invalidp nemf)
968       (cond (invalidp)
969             ((eq oemf nemf)
970              ;; The cache of a checking dfun doesn't hold any values,
971              ;; so this NIL appears to be just a dummy-value we use in
972              ;; order to insert the wrappers into the cache.
973              (let ((ncache (fill-cache cache wrappers nil)))
974                (unless (eq ncache cache)
975                  (dfun-update generic-function #'make-checking-dfun
976                               nemf ncache))))
977             (t
978              (dfun-update generic-function #'make-caching-dfun))))))
979
980 (defun caching-miss (generic-function args dfun-info)
981   (let ((ocache (dfun-info-cache dfun-info)))
982     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
983       (cond (invalidp)
984             (t
985              (let ((ncache (fill-cache ocache wrappers emf)))
986                (unless (eq ncache ocache)
987                  (dfun-update generic-function
988                               #'make-caching-dfun ncache))))))))
989
990 (defun constant-value-miss (generic-function args dfun-info)
991   (let ((ocache (dfun-info-cache dfun-info)))
992     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
993       (unless invalidp
994         (let* ((value
995                 (typecase emf
996                   (constant-fast-method-call
997                    (constant-fast-method-call-value emf))
998                   (constant-method-call
999                    (constant-method-call-value emf))
1000                   (t
1001                    (bug "~S with non-constant EMF ~S" 'constant-value-miss emf))))
1002                (ncache (fill-cache ocache wrappers value)))
1003           (unless (eq ncache ocache)
1004             (dfun-update generic-function
1005                          #'make-constant-value-dfun ncache)))))))
1006 \f
1007 ;;; Given a generic function and a set of arguments to that generic
1008 ;;; function, return a mess of values.
1009 ;;;
1010 ;;;  <function>   The compiled effective method function for this set of
1011 ;;;            arguments.
1012 ;;;
1013 ;;;  <applicable> Sorted list of applicable methods.
1014 ;;;
1015 ;;;  <wrappers>   Is a single wrapper if the generic function has only
1016 ;;;            one key, that is arg-info-nkeys of the arg-info is 1.
1017 ;;;            Otherwise a list of the wrappers of the specialized
1018 ;;;            arguments to the generic function.
1019 ;;;
1020 ;;;            Note that all these wrappers are valid. This function
1021 ;;;            does invalid wrapper traps when it finds an invalid
1022 ;;;            wrapper and then returns the new, valid wrapper.
1023 ;;;
1024 ;;;  <invalidp>   True if any of the specialized arguments had an invalid
1025 ;;;            wrapper, false otherwise.
1026 ;;;
1027 ;;;  <type>       READER or WRITER when the only method that would be run
1028 ;;;            is a standard reader or writer method. To be specific,
1029 ;;;            the value is READER when the method combination is eq to
1030 ;;;            *standard-method-combination*; there are no applicable
1031 ;;;            :before, :after or :around methods; and the most specific
1032 ;;;            primary method is a standard reader method.
1033 ;;;
1034 ;;;  <index>      If <type> is READER or WRITER, and the slot accessed is
1035 ;;;            an :instance slot, this is the index number of that slot
1036 ;;;            in the object argument.
1037 (defvar *cache-miss-values-stack* ())
1038
1039 (defun cache-miss-values (gf args state)
1040   (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
1041       (get-generic-fun-info gf)
1042     (declare (ignore nreq applyp nkeys))
1043     (with-dfun-wrappers (args metatypes)
1044       (dfun-wrappers invalid-wrapper-p wrappers classes types)
1045       (error-need-at-least-n-args gf (length metatypes))
1046       (multiple-value-bind (emf methods accessor-type index)
1047           (cache-miss-values-internal
1048            gf arg-info wrappers classes types state)
1049         (values emf methods
1050                 dfun-wrappers
1051                 invalid-wrapper-p
1052                 accessor-type index)))))
1053
1054 (defun cache-miss-values-internal (gf arg-info wrappers classes types state)
1055   (if (and classes (equal classes (cdr (assq gf *cache-miss-values-stack*))))
1056       (break-vicious-metacircle gf classes arg-info)
1057       (let ((*cache-miss-values-stack*
1058              (acons gf classes *cache-miss-values-stack*))
1059             (cam-std-p (or (null arg-info)
1060                            (gf-info-c-a-m-emf-std-p arg-info))))
1061         (multiple-value-bind (methods all-applicable-and-sorted-p)
1062             (if cam-std-p
1063                 (compute-applicable-methods-using-types gf types)
1064                 (compute-applicable-methods-using-classes gf classes))
1065
1066   (let* ((for-accessor-p (eq state 'accessor))
1067          (for-cache-p (or (eq state 'caching) (eq state 'accessor)))
1068          (emf (if (or cam-std-p all-applicable-and-sorted-p)
1069                   (let ((generator
1070                          (get-secondary-dispatch-function1
1071                           gf methods types nil (and for-cache-p wrappers)
1072                           all-applicable-and-sorted-p)))
1073                     (make-callable gf methods generator
1074                                    nil (and for-cache-p wrappers)))
1075                   (default-secondary-dispatch-function gf))))
1076     (multiple-value-bind (index accessor-type)
1077         (and for-accessor-p all-applicable-and-sorted-p methods
1078              (accessor-values gf arg-info classes methods))
1079       (values (if (integerp index) index emf)
1080               methods accessor-type index)))))))
1081
1082 ;;; Try to break a vicious circle while computing a cache miss.
1083 ;;; GF is the generic function, CLASSES are the classes of actual
1084 ;;; arguments, and ARG-INFO is the generic functions' arg-info.
1085 ;;;
1086 ;;; A vicious circle can be entered when the computation of the cache
1087 ;;; miss values itself depends on the values being computed.  For
1088 ;;; instance, adding a method which is an instance of a subclass of
1089 ;;; STANDARD-METHOD leads to cache misses for slot accessors of
1090 ;;; STANDARD-METHOD like METHOD-SPECIALIZERS, and METHOD-SPECIALIZERS
1091 ;;; is itself used while we compute cache miss values.
1092 (defun break-vicious-metacircle (gf classes arg-info)
1093   (when (typep gf 'standard-generic-function)
1094     (multiple-value-bind (class slotd accessor-type)
1095         (accesses-standard-class-slot-p gf)
1096       (when class
1097         (let ((method (find-standard-class-accessor-method
1098                        gf class accessor-type))
1099               (index (standard-slot-value/eslotd slotd 'location))
1100               (type (gf-info-simple-accessor-type arg-info)))
1101           (when (and method
1102                      (subtypep (ecase accessor-type
1103                                  ((reader) (car classes))
1104                                  ((writer) (cadr classes)))
1105                                class))
1106             (return-from break-vicious-metacircle
1107               (values index (list method) type index)))))))
1108   (error "~@<vicious metacircle:  The computation of an ~
1109           effective method of ~s for arguments of types ~s uses ~
1110           the effective method being computed.~@:>"
1111          gf classes))
1112
1113 ;;; Return (CLASS SLOTD ACCESSOR-TYPE) if some method of generic
1114 ;;; function GF accesses a slot of some class in *STANDARD-CLASSES*.
1115 ;;; CLASS is the class accessed, SLOTD is the effective slot definition
1116 ;;; object of the slot accessed, and ACCESSOR-TYPE is one of the symbols
1117 ;;; READER or WRITER describing the slot access.
1118 (defun accesses-standard-class-slot-p (gf)
1119   (labels
1120       ((all-dslotds (class &aux done)
1121          (labels ((all-dslotds-aux (class)
1122                     (if (or (member class done) (not (eq (class-of class) *the-class-standard-class*)))
1123                         nil
1124                         (progn
1125                           (push class done)
1126                           (append (standard-slot-value/class class 'direct-slots)
1127                                   (mapcan #'(lambda (c)
1128                                               (copy-list (all-dslotds-aux c)))
1129                                           (standard-slot-value/class class 'direct-superclasses)))))))
1130            (all-dslotds-aux class)))
1131        (standard-class-slot-access (gf class)
1132
1133          (loop with gf-name = (standard-slot-value/gf gf 'name)
1134             with eslotds = (standard-slot-value/class class 'slots)
1135             with dslotds = (all-dslotds class)
1136             for dslotd in dslotds
1137             as readers = (standard-slot-value/dslotd dslotd 'readers)
1138             as writers = (standard-slot-value/dslotd dslotd 'writers)
1139             as name = (standard-slot-value/dslotd dslotd 'name)
1140             as eslotd = (find name eslotds :key (lambda (x) (standard-slot-value/eslotd x 'name)))
1141             if (member gf-name readers :test #'equal)
1142             return (values eslotd 'reader)
1143             else if (member gf-name writers :test #'equal)
1144             return (values eslotd 'writer))))
1145     (dolist (class-name *standard-classes*)
1146       (let ((class (find-class class-name)))
1147         (multiple-value-bind (slotd accessor-type)
1148             (standard-class-slot-access gf class)
1149           (when slotd
1150             (return (values class slotd accessor-type))))))))
1151
1152 ;;; Find a slot reader/writer method among the methods of generic
1153 ;;; function GF which reads/writes instances of class CLASS.
1154 ;;; TYPE is one of the symbols READER or WRITER.
1155 (defun find-standard-class-accessor-method (gf class type)
1156   (let ((cpl (standard-slot-value/class class '%class-precedence-list))
1157         (found-specializer *the-class-t*)
1158         (found-method nil))
1159     (dolist (method (standard-slot-value/gf gf 'methods) found-method)
1160       (let ((specializers (standard-slot-value/method method 'specializers))
1161             (qualifiers (standard-slot-value/method method 'qualifiers)))
1162         (when (and (null qualifiers)
1163                    (let ((subcpl (member (ecase type
1164                                            (reader (car specializers))
1165                                            (writer (cadr specializers)))
1166                                          cpl :test #'eq)))
1167                      (and subcpl (member found-specializer subcpl :test #'eq))))
1168           (setf found-specializer (ecase type
1169                                     (reader (car specializers))
1170                                     (writer (cadr specializers))))
1171           (setf found-method method))))))
1172
1173 (defun accessor-values (gf arg-info classes methods)
1174   (declare (ignore gf))
1175   (let* ((accessor-type (gf-info-simple-accessor-type arg-info))
1176          (accessor-class (case accessor-type
1177                            ((reader boundp) (car classes))
1178                            (writer (cadr classes)))))
1179     (accessor-values-internal accessor-type accessor-class methods)))
1180
1181 (defun accessor-values1 (gf accessor-type accessor-class)
1182   (let* ((type `(class-eq ,accessor-class))
1183          (types (ecase accessor-type
1184                   ((reader boundp) `(,type))
1185                   (writer `(t ,type))))
1186          (methods (compute-applicable-methods-using-types gf types)))
1187     (accessor-values-internal accessor-type accessor-class methods)))
1188
1189 (defun accessor-values-internal (accessor-type accessor-class methods)
1190   (dolist (meth methods)
1191     (when (if (consp meth)
1192               (early-method-qualifiers meth)
1193               (safe-method-qualifiers meth))
1194       (return-from accessor-values-internal (values nil nil))))
1195   (let* ((meth (car methods))
1196          (early-p (not (eq **boot-state** 'complete)))
1197          (slot-name (when accessor-class
1198                       (if (consp meth)
1199                           (and (early-method-standard-accessor-p meth)
1200                                (early-method-standard-accessor-slot-name meth))
1201                           (and (member *the-class-standard-object*
1202                                        (if early-p
1203                                            (early-class-precedence-list
1204                                             accessor-class)
1205                                            (class-precedence-list
1206                                             accessor-class))
1207                                        :test #'eq)
1208                                (accessor-method-p meth)
1209                                (accessor-method-slot-name meth)))))
1210          (slotd (and accessor-class
1211                      (if early-p
1212                          (dolist (slot (early-class-slotds accessor-class) nil)
1213                            (when (eql slot-name
1214                                       (early-slot-definition-name slot))
1215                              (return slot)))
1216                          (find-slot-definition accessor-class slot-name)))))
1217     (when (and slotd
1218                (or early-p
1219                    (slot-accessor-std-p slotd accessor-type))
1220                (or early-p
1221                    (not (safe-p accessor-class))))
1222       (values (if early-p
1223                   (early-slot-definition-location slotd)
1224                   (slot-definition-location slotd))
1225               accessor-type))))
1226
1227 (defun make-accessor-table (gf type &optional table)
1228   (unless table (setq table (make-hash-table :test 'eq)))
1229   (let ((methods (if (early-gf-p gf)
1230                      (early-gf-methods gf)
1231                      (generic-function-methods gf)))
1232         (all-index nil)
1233         (no-class-slots-p t)
1234         (early-p (not (eq **boot-state** 'complete)))
1235         first second (size 0))
1236     (declare (fixnum size))
1237     ;; class -> {(specl slotd)}
1238     (dolist (method methods)
1239       (let* ((specializers (if (consp method)
1240                                (early-method-specializers method t)
1241                                (method-specializers method)))
1242              (specl (ecase type
1243                       ((reader boundp) (car specializers))
1244                       (writer (cadr specializers))))
1245              (specl-cpl (if early-p
1246                             (early-class-precedence-list specl)
1247                             (when (class-finalized-p specl)
1248                               (class-precedence-list specl))))
1249              (so-p (member *the-class-standard-object* specl-cpl :test #'eq))
1250              (slot-name (if (consp method)
1251                             (and (early-method-standard-accessor-p method)
1252                                  (early-method-standard-accessor-slot-name
1253                                   method))
1254                             (accessor-method-slot-name method))))
1255         (when (or (null specl-cpl)
1256                   (null so-p)
1257                   (member *the-class-structure-object* specl-cpl :test #'eq))
1258           (return-from make-accessor-table nil))
1259         ;; Collect all the slot-definitions for SLOT-NAME from SPECL and
1260         ;; all of its subclasses. If either SPECL or one of the subclasses
1261         ;; is not a standard-class, bail out.
1262         (labels ((aux (class)
1263                    (let ((slotd (find-slot-definition class slot-name)))
1264                      (when slotd
1265                        (unless (or early-p (slot-accessor-std-p slotd type))
1266                          (return-from make-accessor-table nil))
1267                        (push (cons specl slotd) (gethash class table))))
1268                    (dolist (subclass (sb-pcl::class-direct-subclasses class))
1269                      (unless (class-finalized-p subclass)
1270                        (return-from make-accessor-table nil))
1271                      (aux subclass))))
1272           (aux specl))))
1273     (maphash (lambda (class specl+slotd-list)
1274                (dolist (sclass (if early-p
1275                                    (early-class-precedence-list class)
1276                                    (class-precedence-list class))
1277                                (error "This can't happen."))
1278                  (let ((a (assq sclass specl+slotd-list)))
1279                    (when a
1280                      (let* ((slotd (cdr a))
1281                             (index (if early-p
1282                                        (early-slot-definition-location slotd)
1283                                        (slot-definition-location slotd))))
1284                        (unless index (return-from make-accessor-table nil))
1285                        (setf (gethash class table) index)
1286                        (when (consp index) (setq no-class-slots-p nil))
1287                        (setq all-index (if (or (null all-index)
1288                                                (eql all-index index))
1289                                            index t))
1290                        (incf size)
1291                        (cond ((= size 1) (setq first class))
1292                              ((= size 2) (setq second class)))
1293                        (return nil))))))
1294              table)
1295     (values table all-index first second size no-class-slots-p)))
1296
1297 (defun compute-applicable-methods-using-types (generic-function types)
1298   (let ((definite-p t) (possibly-applicable-methods nil))
1299     (dolist (method (if (early-gf-p generic-function)
1300                         (early-gf-methods generic-function)
1301                         (safe-generic-function-methods generic-function)))
1302       (let ((specls (if (consp method)
1303                         (early-method-specializers method t)
1304                         (safe-method-specializers method)))
1305             (types types)
1306             (possibly-applicable-p t) (applicable-p t))
1307         (dolist (specl specls)
1308           (multiple-value-bind (specl-applicable-p specl-possibly-applicable-p)
1309               (specializer-applicable-using-type-p specl (pop types))
1310             (unless specl-applicable-p
1311               (setq applicable-p nil))
1312             (unless specl-possibly-applicable-p
1313               (setq possibly-applicable-p nil)
1314               (return nil))))
1315         (when possibly-applicable-p
1316           (unless applicable-p (setq definite-p nil))
1317           (push method possibly-applicable-methods))))
1318     (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
1319         (get-generic-fun-info generic-function)
1320       (declare (ignore nreq applyp metatypes nkeys))
1321       (let* ((precedence (arg-info-precedence arg-info)))
1322         (values (sort-applicable-methods precedence
1323                                          (nreverse possibly-applicable-methods)
1324                                          types)
1325                 definite-p)))))
1326
1327 (defun sort-applicable-methods (precedence methods types)
1328   (sort-methods methods
1329                 precedence
1330                 (lambda (class1 class2 index)
1331                   (let* ((class (type-class (nth index types)))
1332                          (cpl (if (eq **boot-state** 'complete)
1333                                   (class-precedence-list class)
1334                                   (early-class-precedence-list class))))
1335                     (if (memq class2 (memq class1 cpl))
1336                         class1 class2)))))
1337
1338 (defun sort-methods (methods precedence compare-classes-function)
1339   (flet ((sorter (method1 method2)
1340            (dolist (index precedence)
1341              (let* ((specl1 (nth index (if (listp method1)
1342                                            (early-method-specializers method1
1343                                                                       t)
1344                                            (method-specializers method1))))
1345                     (specl2 (nth index (if (listp method2)
1346                                            (early-method-specializers method2
1347                                                                       t)
1348                                            (method-specializers method2))))
1349                     (order (order-specializers
1350                              specl1 specl2 index compare-classes-function)))
1351                (when order
1352                  (return-from sorter (eq order specl1)))))))
1353     (stable-sort methods #'sorter)))
1354
1355 (defun order-specializers (specl1 specl2 index compare-classes-function)
1356   (let ((type1 (if (eq **boot-state** 'complete)
1357                    (specializer-type specl1)
1358                    (!bootstrap-get-slot 'specializer specl1 '%type)))
1359         (type2 (if (eq **boot-state** 'complete)
1360                    (specializer-type specl2)
1361                    (!bootstrap-get-slot 'specializer specl2 '%type))))
1362     (cond ((eq specl1 specl2)
1363            nil)
1364           ((atom type1)
1365            specl2)
1366           ((atom type2)
1367            specl1)
1368           (t
1369            (case (car type1)
1370              (class    (case (car type2)
1371                          (class (funcall compare-classes-function
1372                                          specl1 specl2 index))
1373                          (t specl2)))
1374              (prototype (case (car type2)
1375                          (class (funcall compare-classes-function
1376                                          specl1 specl2 index))
1377                          (t specl2)))
1378              (class-eq (case (car type2)
1379                          (eql specl2)
1380                          ;; FIXME: This says that all CLASS-EQ
1381                          ;; specializers are equally specific, which
1382                          ;; is fair enough because only one CLASS-EQ
1383                          ;; specializer can ever be appliable.  If
1384                          ;; ORDER-SPECIALIZERS should only ever be
1385                          ;; called on specializers from applicable
1386                          ;; methods, we could replace this with a BUG.
1387                          (class-eq nil)
1388                          (class type1)))
1389              (eql      (case (car type2)
1390                          ;; similarly.
1391                          (eql nil)
1392                          (t specl1))))))))
1393
1394 (defun map-all-orders (methods precedence function)
1395   (let ((choices nil))
1396     (flet ((compare-classes-function (class1 class2 index)
1397              (declare (ignore index))
1398              (let ((choice nil))
1399                (dolist (c choices nil)
1400                  (when (or (and (eq (first c) class1)
1401                                 (eq (second c) class2))
1402                            (and (eq (first c) class2)
1403                                 (eq (second c) class1)))
1404                    (return (setq choice c))))
1405                (unless choice
1406                  (setq choice
1407                        (if (class-might-precede-p class1 class2)
1408                            (if (class-might-precede-p class2 class1)
1409                                (list class1 class2 nil t)
1410                                (list class1 class2 t))
1411                            (if (class-might-precede-p class2 class1)
1412                                (list class2 class1 t)
1413                                (let ((name1 (class-name class1))
1414                                      (name2 (class-name class2)))
1415                                  (if (and name1
1416                                           name2
1417                                           (symbolp name1)
1418                                           (symbolp name2)
1419                                           (string< (symbol-name name1)
1420                                                    (symbol-name name2)))
1421                                      (list class1 class2 t)
1422                                      (list class2 class1 t))))))
1423                  (push choice choices))
1424                (car choice))))
1425       (loop (funcall function
1426                      (sort-methods methods
1427                                    precedence
1428                                    #'compare-classes-function))
1429             (unless (dolist (c choices nil)
1430                       (unless (third c)
1431                         (rotatef (car c) (cadr c))
1432                         (return (setf (third c) t))))
1433               (return nil))))))
1434
1435 ;;; CMUCL comment: used only in map-all-orders
1436 (defun class-might-precede-p (class1 class2)
1437   (not (member class1 (cdr (class-precedence-list class2)) :test #'eq)))
1438
1439 (defun compute-precedence (lambda-list nreq argument-precedence-order)
1440   (if (null argument-precedence-order)
1441       (let ((list nil))
1442         (dotimes-fixnum (i nreq list) (push (- (1- nreq) i) list)))
1443       (mapcar (lambda (x) (position x lambda-list))
1444               argument-precedence-order)))
1445
1446 (defun cpl-or-nil (class)
1447   (if (eq **boot-state** 'complete)
1448       (progn
1449         ;; KLUDGE: why not use (slot-boundp class
1450         ;; 'class-precedence-list)?  Well, unfortunately, CPL-OR-NIL is
1451         ;; used within COMPUTE-APPLICABLE-METHODS, including for
1452         ;; SLOT-BOUNDP-USING-CLASS... and the available mechanism for
1453         ;; breaking such nasty cycles in effective method computation
1454         ;; only works for readers and writers, not boundps.  It might
1455         ;; not be too hard to make it work for BOUNDP accessors, but in
1456         ;; the meantime we use an extra slot for exactly the result of
1457         ;; the SLOT-BOUNDP that we want.  (We cannot use
1458         ;; CLASS-FINALIZED-P, because in the process of class
1459         ;; finalization we need to use the CPL which has been computed
1460         ;; to cache effective methods for slot accessors.) -- CSR,
1461         ;; 2004-09-19.
1462
1463         (when (cpl-available-p class)
1464           (return-from cpl-or-nil (class-precedence-list class)))
1465
1466         ;; if we can finalize an unfinalized class, then do so
1467         (when (and (not (class-finalized-p class))
1468                    (not (class-has-a-forward-referenced-superclass-p class))
1469                    (not (class-has-a-cpl-protocol-violation-p class)))
1470           (finalize-inheritance class)
1471           (class-precedence-list class)))
1472
1473       (early-class-precedence-list class)))
1474
1475 (defun saut-and (specl type)
1476   (let ((applicable nil)
1477         (possibly-applicable t))
1478     (dolist (type (cdr type))
1479       (multiple-value-bind (appl poss-appl)
1480           (specializer-applicable-using-type-p specl type)
1481         (when appl (return (setq applicable t)))
1482         (unless poss-appl (return (setq possibly-applicable nil)))))
1483     (values applicable possibly-applicable)))
1484
1485 (defun saut-not (specl type)
1486   (let ((ntype (cadr type)))
1487     (values nil
1488             (case (car ntype)
1489               (class      (saut-not-class specl ntype))
1490               (class-eq   (saut-not-class-eq specl ntype))
1491               (prototype  (saut-not-prototype specl ntype))
1492               (eql      (saut-not-eql specl ntype))
1493               (t (error "~S cannot handle the second argument ~S"
1494                         'specializer-applicable-using-type-p type))))))
1495
1496 (defun saut-not-class (specl ntype)
1497   (let* ((class (type-class specl))
1498          (cpl (cpl-or-nil class)))
1499     (not (memq (cadr ntype) cpl))))
1500
1501 (defun saut-not-prototype (specl ntype)
1502   (let* ((class (case (car specl)
1503                   (eql       (class-of (cadr specl)))
1504                   (class-eq  (cadr specl))
1505                   (prototype (cadr specl))
1506                   (class     (cadr specl))))
1507          (cpl (cpl-or-nil class)))
1508     (not (memq (cadr ntype) cpl))))
1509
1510 (defun saut-not-class-eq (specl ntype)
1511   (let ((class (case (car specl)
1512                  (eql      (class-of (cadr specl)))
1513                  (class-eq (cadr specl)))))
1514     (not (eq class (cadr ntype)))))
1515
1516 (defun saut-not-eql (specl ntype)
1517   (case (car specl)
1518     (eql (not (eql (cadr specl) (cadr ntype))))
1519     (t   t)))
1520
1521 (defun class-applicable-using-class-p (specl type)
1522   (let ((pred (memq specl (cpl-or-nil type))))
1523     (values pred
1524             (or pred
1525                 (if (not *in-*subtypep*)
1526                     ;; classes might get common subclass
1527                     (superclasses-compatible-p specl type)
1528                     ;; worry only about existing classes
1529                     (classes-have-common-subclass-p specl type))))))
1530
1531 (defun classes-have-common-subclass-p (class1 class2)
1532   (or (eq class1 class2)
1533       (let ((class1-subs (class-direct-subclasses class1)))
1534         (or (memq class2 class1-subs)
1535             (dolist (class1-sub class1-subs nil)
1536               (when (classes-have-common-subclass-p class1-sub class2)
1537                 (return t)))))))
1538
1539 (defun saut-class (specl type)
1540   (case (car specl)
1541     (class (class-applicable-using-class-p (cadr specl) (cadr type)))
1542     (t     (values nil (let ((class (type-class specl)))
1543                          (memq (cadr type)
1544                                (cpl-or-nil class)))))))
1545
1546 (defun saut-class-eq (specl type)
1547   (if (eq (car specl) 'eql)
1548       (values nil (eq (class-of (cadr specl)) (cadr type)))
1549       (let ((pred (case (car specl)
1550                     (class-eq
1551                      (eq (cadr specl) (cadr type)))
1552                     (class
1553                      (or (eq (cadr specl) (cadr type))
1554                          (memq (cadr specl) (cpl-or-nil (cadr type))))))))
1555         (values pred pred))))
1556
1557 (defun saut-prototype (specl type)
1558   (declare (ignore specl type))
1559   (values nil nil)) ; XXX original PCL comment: fix this someday
1560
1561 (defun saut-eql (specl type)
1562   (let ((pred (case (car specl)
1563                 (eql    (eql (cadr specl) (cadr type)))
1564                 (class-eq   (eq (cadr specl) (class-of (cadr type))))
1565                 (class      (memq (cadr specl)
1566                                   (let ((class (class-of (cadr type))))
1567                                     (cpl-or-nil class)))))))
1568     (values pred pred)))
1569
1570 (defun specializer-applicable-using-type-p (specl type)
1571   (setq specl (type-from-specializer specl))
1572   (when (eq specl t)
1573     (return-from specializer-applicable-using-type-p (values t t)))
1574   ;; This is used by C-A-M-U-T and GENERATE-DISCRIMINATION-NET-INTERNAL,
1575   ;; and has only what they need.
1576   (if (or (atom type) (eq (car type) t))
1577       (values nil t)
1578       (case (car type)
1579         (and    (saut-and specl type))
1580         (not    (saut-not specl type))
1581         (class      (saut-class specl type))
1582         (prototype  (saut-prototype specl type))
1583         (class-eq   (saut-class-eq specl type))
1584         (eql    (saut-eql specl type))
1585         (t        (error "~S cannot handle the second argument ~S."
1586                            'specializer-applicable-using-type-p
1587                            type)))))
1588
1589 (defun map-all-classes (fun &optional (root t))
1590   (let ((all-classes (make-hash-table :test 'eq))
1591         (braid-p (or (eq **boot-state** 'braid)
1592                      (eq **boot-state** 'complete))))
1593     (labels ((do-class (class)
1594                (unless (gethash class all-classes)
1595                  (setf (gethash class all-classes) t)
1596                  (funcall fun class)
1597                  (mapc #'do-class
1598                        (if braid-p
1599                            (class-direct-subclasses class)
1600                            (early-class-direct-subclasses class))))))
1601       (do-class (if (symbolp root)
1602                     (find-class root)
1603                     root)))
1604     nil))
1605 \f
1606 ;;; Not synchronized, as all the uses we have for it are multiple ones
1607 ;;; and need WITH-LOCKED-SYSTEM-TABLE in any case.
1608 ;;;
1609 ;;; FIXME: Is it really more efficient to store this stuff in a global
1610 ;;; table instead of having a slot in each method?
1611 ;;;
1612 ;;; FIXME: This table also seems to contain early methods, which should
1613 ;;; presumably be dropped during the bootstrap.
1614 (defvar *effective-method-cache* (make-hash-table :test 'eq))
1615
1616 (defun flush-effective-method-cache (generic-function)
1617   (let ((cache *effective-method-cache*))
1618     (with-locked-system-table (cache)
1619       (dolist (method (generic-function-methods generic-function))
1620         (remhash method cache)))))
1621
1622 (defun get-secondary-dispatch-function (gf methods types
1623                                         &optional method-alist wrappers)
1624   (let ((generator
1625          (get-secondary-dispatch-function1
1626           gf methods types (not (null method-alist)) (not (null wrappers))
1627           (not (methods-contain-eql-specializer-p methods)))))
1628     (make-callable gf methods generator method-alist wrappers)))
1629
1630 (defun get-secondary-dispatch-function1 (gf methods types method-alist-p
1631                                             wrappers-p
1632                                             &optional
1633                                             all-applicable-p
1634                                             (all-sorted-p t)
1635                                             function-p)
1636    (if (null methods)
1637       (lambda (method-alist wrappers)
1638         (declare (ignore method-alist wrappers))
1639         (lambda (&rest args)
1640           (call-no-applicable-method gf args)))
1641       (let* ((key (car methods))
1642              (ht *effective-method-cache*)
1643              (ht-value (with-locked-system-table (ht)
1644                          (or (gethash key ht)
1645                              (setf (gethash key ht) (cons nil nil))))))
1646         (if (and (null (cdr methods)) all-applicable-p ; the most common case
1647                  (null method-alist-p) wrappers-p (not function-p))
1648             (or (car ht-value)
1649                 (setf (car ht-value)
1650                       (get-secondary-dispatch-function2
1651                        gf methods types method-alist-p wrappers-p
1652                        all-applicable-p all-sorted-p function-p)))
1653             (let ((akey (list methods
1654                               (if all-applicable-p 'all-applicable types)
1655                               method-alist-p wrappers-p function-p)))
1656               (or (cdr (assoc akey (cdr ht-value) :test #'equal))
1657                   (let ((value (get-secondary-dispatch-function2
1658                                 gf methods types method-alist-p wrappers-p
1659                                 all-applicable-p all-sorted-p function-p)))
1660                     (push (cons akey value) (cdr ht-value))
1661                     value)))))))
1662
1663 (defun get-secondary-dispatch-function2 (gf methods types method-alist-p
1664                                             wrappers-p all-applicable-p
1665                                             all-sorted-p function-p)
1666   (if (and all-applicable-p all-sorted-p (not function-p))
1667       (if (eq **boot-state** 'complete)
1668           (let* ((combin (generic-function-method-combination gf))
1669                  (effective (compute-effective-method gf combin methods)))
1670             (make-effective-method-function1 gf effective method-alist-p
1671                                              wrappers-p))
1672           (let ((effective (standard-compute-effective-method gf nil methods)))
1673             (make-effective-method-function1 gf effective method-alist-p
1674                                              wrappers-p)))
1675       (let ((net (generate-discrimination-net
1676                   gf methods types all-sorted-p)))
1677         (compute-secondary-dispatch-function1 gf net function-p))))
1678
1679 (defun get-effective-method-function (gf methods
1680                                          &optional method-alist wrappers)
1681   (let ((generator
1682          (get-secondary-dispatch-function1
1683           gf methods nil (not (null method-alist)) (not (null wrappers)) t)))
1684     (make-callable gf methods generator method-alist wrappers)))
1685
1686 (defun get-effective-method-function1 (gf methods &optional (sorted-p t))
1687   (get-secondary-dispatch-function1 gf methods nil nil nil t sorted-p))
1688
1689 (defun methods-contain-eql-specializer-p (methods)
1690   (and (eq **boot-state** 'complete)
1691        (dolist (method methods nil)
1692          (when (dolist (spec (method-specializers method) nil)
1693                  (when (eql-specializer-p spec) (return t)))
1694            (return t)))))
1695 \f
1696 (defun update-dfun (generic-function &optional dfun cache info)
1697   (let ((early-p (early-gf-p generic-function)))
1698     (flet ((update ()
1699              ;; Save DFUN-STATE, so that COMPUTE-DISCRIMINATING-FUNCTION can
1700              ;; access it, and so that it's there for eg. future cache updates.
1701              (set-dfun generic-function dfun cache info)
1702              (let ((dfun (if early-p
1703                              (or dfun (make-initial-dfun generic-function))
1704                              (compute-discriminating-function generic-function))))
1705                (set-funcallable-instance-function generic-function dfun)
1706                (let ((gf-name (if early-p
1707                                   (!early-gf-name generic-function)
1708                                   (generic-function-name generic-function))))
1709                  (set-fun-name generic-function gf-name)
1710                  dfun))))
1711       ;; This needs to be atomic per generic function, consider:
1712       ;;   1. T1 sets dfun-state to S1 and computes discr. fun using S1
1713       ;;   2. T2 sets dfun-state to S2 and computes discr. fun using S2
1714       ;;   3. T2 sets fin
1715       ;;   4. T1 sets fin
1716       ;; Oops: now dfun-state and fin don't match! Since just calling
1717       ;; a generic can cause the dispatch function to be updated we
1718       ;; need a lock here.
1719       ;;
1720       ;; We need to accept recursion, because PCL is nasty and twisty,
1721       ;; and we need to disable interrupts because it would be bad if
1722       ;; we updated the DFUN-STATE but not the dispatch function.
1723       ;;
1724       ;; This is sufficient, because all the other calls to SET-DFUN
1725       ;; are part of this same code path (done while the lock is held),
1726       ;; which we AVER.
1727       ;;
1728       ;; KLUDGE: No need to lock during bootstrap.
1729       (if early-p
1730           (update)
1731           (let ((lock (gf-lock generic-function)))
1732             ;; FIXME: GF-LOCK is a generic function... Are there cases
1733             ;; where we can end up in a metacircular loop here? In
1734             ;; case there are, better fetch it while interrupts are
1735             ;; still enabled...
1736             (sb-thread::call-with-recursive-system-lock #'update lock))))))
1737 \f
1738 (defvar *dfun-count* nil)
1739 (defvar *dfun-list* nil)
1740 (defvar *minimum-cache-size-to-list*)
1741
1742 ;;; These functions aren't used in SBCL, or documented anywhere that
1743 ;;; I'm aware of, but they look like they might be useful for
1744 ;;; debugging or performance tweaking or something, so I've just
1745 ;;; commented them out instead of deleting them. -- WHN 2001-03-28
1746 #||
1747 (defun list-dfun (gf)
1748   (let* ((sym (type-of (gf-dfun-info gf)))
1749          (a (assq sym *dfun-list*)))
1750     (unless a
1751       (push (setq a (list sym)) *dfun-list*))
1752     (push (generic-function-name gf) (cdr a))))
1753
1754 (defun list-all-dfuns ()
1755   (setq *dfun-list* nil)
1756   (map-all-generic-functions #'list-dfun)
1757   *dfun-list*)
1758
1759 (defun list-large-cache (gf)
1760   (let* ((sym (type-of (gf-dfun-info gf)))
1761          (cache (gf-dfun-cache gf)))
1762     (when cache
1763       (let ((size (cache-size cache)))
1764         (when (>= size *minimum-cache-size-to-list*)
1765           (let ((a (assoc size *dfun-list*)))
1766             (unless a
1767               (push (setq a (list size)) *dfun-list*))
1768             (push (let ((name (generic-function-name gf)))
1769                     (if (eq sym 'caching) name (list name sym)))
1770                   (cdr a))))))))
1771
1772 (defun list-large-caches (&optional (*minimum-cache-size-to-list* 130))
1773   (setq *dfun-list* nil)
1774   (map-all-generic-functions #'list-large-cache)
1775   (setq *dfun-list* (sort *dfun-list* #'< :key #'car))
1776   (mapc #'print *dfun-list*)
1777   (values))
1778
1779 (defun count-dfun (gf)
1780   (let* ((sym (type-of (gf-dfun-info gf)))
1781          (cache (gf-dfun-cache gf))
1782          (a (assq sym *dfun-count*)))
1783     (unless a
1784       (push (setq a (list sym 0 nil)) *dfun-count*))
1785     (incf (cadr a))
1786     (when cache
1787       (let* ((size (cache-size cache))
1788              (b (assoc size (third a))))
1789         (unless b
1790           (push (setq b (cons size 0)) (third a)))
1791         (incf (cdr b))))))
1792
1793 (defun count-all-dfuns ()
1794   (setq *dfun-count* (mapcar (lambda (type) (list type 0 nil))
1795                              '(ONE-CLASS TWO-CLASS DEFAULT-METHOD-ONLY
1796                                ONE-INDEX N-N CHECKING CACHING
1797                                DISPATCH)))
1798   (map-all-generic-functions #'count-dfun)
1799   (mapc (lambda (type+count+sizes)
1800           (setf (third type+count+sizes)
1801                 (sort (third type+count+sizes) #'< :key #'car)))
1802         *dfun-count*)
1803   (mapc (lambda (type+count+sizes)
1804           (format t "~&There are ~W dfuns of type ~S."
1805                   (cadr type+count+sizes) (car type+count+sizes))
1806           (format t "~%   ~S~%" (caddr type+count+sizes)))
1807         *dfun-count*)
1808   (values))
1809 ||#
1810
1811 (defun gfs-of-type (type)
1812   (unless (consp type) (setq type (list type)))
1813   (let ((gf-list nil))
1814     (map-all-generic-functions (lambda (gf)
1815                                  (when (memq (type-of (gf-dfun-info gf))
1816                                              type)
1817                                    (push gf gf-list))))
1818     gf-list))