0.7.13.pcl-class.2
[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 |#
79 \f
80 ;;; an alist in which each entry is of the form
81 ;;;   (<generator> . (<subentry> ...)).
82 ;;; Each subentry is of the form
83 ;;;   (<args> <constructor> <system>).
84 (defvar *dfun-constructors* ())                 
85
86 ;;; If this is NIL, then the whole mechanism for caching dfun constructors is
87 ;;; turned off. The only time that makes sense is when debugging LAP code.
88 (defvar *enable-dfun-constructor-caching* t)    
89
90 (defun show-dfun-constructors ()
91   (format t "~&DFUN constructor caching is ~A."
92           (if *enable-dfun-constructor-caching*
93               "enabled" "disabled"))
94   (dolist (generator-entry *dfun-constructors*)
95     (dolist (args-entry (cdr generator-entry))
96       (format t "~&~S ~S"
97               (cons (car generator-entry) (caar args-entry))
98               (caddr args-entry)))))
99
100 (defvar *raise-metatypes-to-class-p* t)
101
102 (defun get-dfun-constructor (generator &rest args)
103   (when (and *raise-metatypes-to-class-p*
104              (member generator '(emit-checking emit-caching
105                                  emit-in-checking-cache-p emit-constant-value)))
106     (setq args (cons (mapcar (lambda (mt)
107                                (if (eq mt t)
108                                    mt
109                                    'class))
110                              (car args))
111                      (cdr args))))
112   (let* ((generator-entry (assq generator *dfun-constructors*))
113          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
114     (if (null *enable-dfun-constructor-caching*)
115         (apply (fdefinition generator) args)
116         (or (cadr args-entry)
117             (multiple-value-bind (new not-best-p)
118                 (apply (symbol-function generator) args)
119               (let ((entry (list (copy-list args) new (unless not-best-p 'pcl)
120                                  not-best-p)))
121                 (if generator-entry
122                     (push entry (cdr generator-entry))
123                     (push (list generator entry)
124                           *dfun-constructors*)))
125               (values new not-best-p))))))
126
127 (defun load-precompiled-dfun-constructor (generator args system constructor)
128   (let* ((generator-entry (assq generator *dfun-constructors*))
129          (args-entry (assoc args (cdr generator-entry) :test #'equal)))
130     (if args-entry
131         (when (fourth args-entry)
132           (let* ((dfun-type (case generator
133                               (emit-checking 'checking)
134                               (emit-caching 'caching)
135                               (emit-constant-value 'constant-value)
136                               (emit-default-only 'default-method-only)))
137                  (metatypes (car args))
138                  (gfs (when dfun-type (gfs-of-type dfun-type))))
139             (dolist (gf gfs)
140               (when (and (equal metatypes
141                                 (arg-info-metatypes (gf-arg-info gf)))
142                          (let ((gf-name (generic-function-name gf)))
143                            (and (not (eq gf-name 'slot-value-using-class))
144                                 (not (equal gf-name
145                                             '(setf slot-value-using-class)))
146                                 (not (eq gf-name 'slot-boundp-using-class)))))
147                 (update-dfun gf)))
148             (setf (second args-entry) constructor)
149             (setf (third args-entry) system)
150             (setf (fourth args-entry) nil)))
151         (let ((entry (list args constructor system nil)))
152           (if generator-entry
153               (push entry (cdr generator-entry))
154               (push (list generator entry) *dfun-constructors*))))))
155
156 (defmacro precompile-dfun-constructors (&optional system)
157   (let ((*precompiling-lap* t))
158     `(progn
159        ,@(let (collect)
160            (dolist (generator-entry *dfun-constructors*)
161              (dolist (args-entry (cdr generator-entry))
162                (when (or (null (caddr args-entry))
163                          (eq (caddr args-entry) system))
164                  (when system (setf (caddr args-entry) system))
165                  (push `(load-precompiled-dfun-constructor
166                          ',(car generator-entry)
167                          ',(car args-entry)
168                          ',system
169                          ,(apply (fdefinition (car generator-entry))
170                                  (car args-entry)))
171                        collect))))
172            (nreverse collect)))))
173 \f
174 ;;; When all the methods of a generic function are automatically
175 ;;; generated reader or writer methods a number of special
176 ;;; optimizations are possible. These are important because of the
177 ;;; large number of generic functions of this type.
178 ;;;
179 ;;; There are a number of cases:
180 ;;;
181 ;;;   ONE-CLASS-ACCESSOR
182 ;;;     In this case, the accessor generic function has only been
183 ;;;     called with one class of argument. There is no cache vector,
184 ;;;     the wrapper of the one class, and the slot index are stored
185 ;;;     directly as closure variables of the discriminating function.
186 ;;;     This case can convert to either of the next kind.
187 ;;;
188 ;;;   TWO-CLASS-ACCESSOR
189 ;;;     Like above, but two classes. This is common enough to do
190 ;;;     specially. There is no cache vector. The two classes are
191 ;;;     stored a separate closure variables.
192 ;;;
193 ;;;   ONE-INDEX-ACCESSOR
194 ;;;     In this case, the accessor generic function has seen more than
195 ;;;     one class of argument, but the index of the slot is the same
196 ;;;     for all the classes that have been seen. A cache vector is
197 ;;;     used to store the wrappers that have been seen, the slot index
198 ;;;     is stored directly as a closure variable of the discriminating
199 ;;;     function. This case can convert to the next kind.
200 ;;;
201 ;;;   N-N-ACCESSOR
202 ;;;     This is the most general case. In this case, the accessor
203 ;;;     generic function has seen more than one class of argument and
204 ;;;     more than one slot index. A cache vector stores the wrappers
205 ;;;     and corresponding slot indexes. Because each cache line is
206 ;;;     more than one element long, a cache lock count is used.
207 (defstruct (dfun-info (:constructor nil)
208                       (:copier nil))
209   (cache nil))
210
211 (defstruct (no-methods (:constructor no-methods-dfun-info ())
212                        (:include dfun-info)
213                        (:copier nil)))
214
215 (defstruct (initial (:constructor initial-dfun-info ())
216                     (:include dfun-info)
217                     (:copier nil)))
218
219 (defstruct (initial-dispatch (:constructor initial-dispatch-dfun-info ())
220                              (:include dfun-info)
221                              (:copier nil)))
222
223 (defstruct (dispatch (:constructor dispatch-dfun-info ())
224                      (:include dfun-info)
225                      (:copier nil)))
226
227 (defstruct (default-method-only (:constructor default-method-only-dfun-info ())
228                                 (:include dfun-info)
229                                 (:copier nil)))
230
231 ;without caching:
232 ;  dispatch one-class two-class default-method-only
233
234 ;with caching:
235 ;  one-index n-n checking caching
236
237 ;accessor:
238 ;  one-class two-class one-index n-n
239 (defstruct (accessor-dfun-info (:constructor nil)
240                                (:include dfun-info)
241                                (:copier nil))
242   accessor-type) ; (member reader writer)
243
244 (defmacro dfun-info-accessor-type (di)
245   `(accessor-dfun-info-accessor-type ,di))
246
247 (defstruct (one-index-dfun-info (:constructor nil)
248                                 (:include accessor-dfun-info)
249                                 (:copier nil))
250   index)
251
252 (defmacro dfun-info-index (di)
253   `(one-index-dfun-info-index ,di))
254
255 (defstruct (n-n (:constructor n-n-dfun-info (accessor-type cache))
256                 (:include accessor-dfun-info)
257                 (:copier nil)))
258
259 (defstruct (one-class (:constructor one-class-dfun-info
260                                     (accessor-type index wrapper0))
261                       (:include one-index-dfun-info)
262                       (:copier nil))
263   wrapper0)
264
265 (defmacro dfun-info-wrapper0 (di)
266   `(one-class-wrapper0 ,di))
267
268 (defstruct (two-class (:constructor two-class-dfun-info
269                                     (accessor-type index wrapper0 wrapper1))
270                       (:include one-class)
271                       (:copier nil))
272   wrapper1)
273
274 (defmacro dfun-info-wrapper1 (di)
275   `(two-class-wrapper1 ,di))
276
277 (defstruct (one-index (:constructor one-index-dfun-info
278                                     (accessor-type index cache))
279                       (:include one-index-dfun-info)
280                       (:copier nil)))
281
282 (defstruct (checking (:constructor checking-dfun-info (function cache))
283                      (:include dfun-info)
284                      (:copier nil))
285   function)
286
287 (defmacro dfun-info-function (di)
288   `(checking-function ,di))
289
290 (defstruct (caching (:constructor caching-dfun-info (cache))
291                     (:include dfun-info)
292                     (:copier nil)))
293
294 (defstruct (constant-value (:constructor constant-value-dfun-info (cache))
295                            (:include dfun-info)
296                            (:copier nil)))
297
298 (defmacro dfun-update (generic-function function &rest args)
299   `(multiple-value-bind (dfun cache info)
300        (funcall ,function ,generic-function ,@args)
301      (update-dfun ,generic-function dfun cache info)))
302
303 (defun accessor-miss-function (gf dfun-info)
304   (ecase (dfun-info-accessor-type dfun-info)
305     ((reader boundp)
306      (lambda (arg)
307        (accessor-miss gf nil arg dfun-info)))
308     (writer
309      (lambda (new arg)
310        (accessor-miss gf new arg dfun-info)))))
311
312 #-sb-fluid (declaim (sb-ext:freeze-type dfun-info))
313 \f
314 (defun make-one-class-accessor-dfun (gf type wrapper index)
315   (let ((emit (ecase type
316                 (reader 'emit-one-class-reader)
317                 (boundp 'emit-one-class-boundp)
318                 (writer 'emit-one-class-writer)))
319         (dfun-info (one-class-dfun-info type index wrapper)))
320     (values
321      (funcall (get-dfun-constructor emit (consp index))
322               wrapper index
323               (accessor-miss-function gf dfun-info))
324      nil
325      dfun-info)))
326
327 (defun make-two-class-accessor-dfun (gf type w0 w1 index)
328   (let ((emit (ecase type
329                 (reader 'emit-two-class-reader)
330                 (boundp 'emit-two-class-boundp)
331                 (writer 'emit-two-class-writer)))
332         (dfun-info (two-class-dfun-info type index w0 w1)))
333     (values
334      (funcall (get-dfun-constructor emit (consp index))
335               w0 w1 index
336               (accessor-miss-function gf dfun-info))
337      nil
338      dfun-info)))
339
340 ;;; std accessors same index dfun
341 (defun make-one-index-accessor-dfun (gf type index &optional cache)
342   (let* ((emit (ecase type
343                  (reader 'emit-one-index-readers)
344                  (boundp 'emit-one-index-boundps)
345                  (writer 'emit-one-index-writers)))
346          (cache (or cache (get-cache 1 nil #'one-index-limit-fn 4)))
347          (dfun-info (one-index-dfun-info type index cache)))
348     (declare (type cache cache))
349     (values
350      (funcall (get-dfun-constructor emit (consp index))
351               cache
352               index
353               (accessor-miss-function gf dfun-info))
354      cache
355      dfun-info)))
356
357 (defun make-final-one-index-accessor-dfun (gf type index table)
358   (let ((cache (fill-dfun-cache table nil 1 #'one-index-limit-fn)))
359     (make-one-index-accessor-dfun gf type index cache)))
360
361 (defun one-index-limit-fn (nlines)
362   (default-limit-fn nlines))
363
364 (defun make-n-n-accessor-dfun (gf type &optional cache)
365   (let* ((emit (ecase type
366                  (reader 'emit-n-n-readers)
367                  (boundp 'emit-n-n-boundps)
368                  (writer 'emit-n-n-writers)))
369          (cache (or cache (get-cache 1 t #'n-n-accessors-limit-fn 2)))
370          (dfun-info (n-n-dfun-info type cache)))
371     (declare (type cache cache))
372     (values
373      (funcall (get-dfun-constructor emit)
374               cache
375               (accessor-miss-function gf dfun-info))
376      cache
377      dfun-info)))
378
379 (defun make-final-n-n-accessor-dfun (gf type table)
380   (let ((cache (fill-dfun-cache table t 1 #'n-n-accessors-limit-fn)))
381     (make-n-n-accessor-dfun gf type cache)))
382
383 (defun n-n-accessors-limit-fn (nlines)
384   (default-limit-fn nlines))
385
386 (defun make-checking-dfun (generic-function function &optional cache)
387   (unless cache
388     (when (use-caching-dfun-p generic-function)
389       (return-from make-checking-dfun (make-caching-dfun generic-function)))
390     (when (use-dispatch-dfun-p generic-function)
391       (return-from make-checking-dfun (make-dispatch-dfun generic-function))))
392   (multiple-value-bind (nreq applyp metatypes nkeys)
393       (get-generic-fun-info generic-function)
394     (declare (ignore nreq))
395     (if (every (lambda (mt) (eq mt t)) metatypes)
396         (let ((dfun-info (default-method-only-dfun-info)))
397           (values
398            (funcall (get-dfun-constructor 'emit-default-only metatypes applyp)
399                     function)
400            nil
401            dfun-info))
402         (let* ((cache (or cache (get-cache nkeys nil #'checking-limit-fn 2)))
403                (dfun-info (checking-dfun-info function cache)))
404           (values
405            (funcall (get-dfun-constructor 'emit-checking metatypes applyp)
406                     cache
407                     function
408                     (lambda (&rest args)
409                       (checking-miss generic-function args dfun-info)))
410            cache
411            dfun-info)))))
412
413 (defun make-final-checking-dfun (generic-function function
414                                                   classes-list new-class)
415   (let ((metatypes (arg-info-metatypes (gf-arg-info generic-function))))
416     (if (every (lambda (mt) (eq mt t)) metatypes)
417         (values (lambda (&rest args)
418                   (invoke-emf function args))
419                 nil (default-method-only-dfun-info))
420         (let ((cache (make-final-ordinary-dfun-internal
421                       generic-function nil #'checking-limit-fn
422                       classes-list new-class)))
423           (make-checking-dfun generic-function function cache)))))
424
425 (defun use-default-method-only-dfun-p (generic-function)
426   (multiple-value-bind (nreq applyp metatypes nkeys)
427       (get-generic-fun-info generic-function)
428     (declare (ignore nreq applyp nkeys))
429     (every (lambda (mt) (eq mt t)) metatypes)))
430
431 (defun use-caching-dfun-p (generic-function)
432   (some (lambda (method)
433           (let ((fmf (if (listp method)
434                          (third method)
435                          (method-fast-function method))))
436             (method-function-get fmf :slot-name-lists)))
437         ;; KLUDGE: As of sbcl-0.6.4, it's very important for
438         ;; efficiency to know the type of the sequence argument to
439         ;; quantifiers (SOME/NOTANY/etc.) at compile time, but
440         ;; the compiler isn't smart enough to understand the :TYPE
441         ;; slot option for DEFCLASS, so we just tell
442         ;; it the type by hand here.
443         (the list 
444              (if (early-gf-p generic-function)
445                  (early-gf-methods generic-function)
446                  (generic-function-methods generic-function)))))
447
448 (defun checking-limit-fn (nlines)
449   (default-limit-fn nlines))
450 \f
451 (defun make-caching-dfun (generic-function &optional cache)
452   (unless cache
453     (when (use-constant-value-dfun-p generic-function)
454       (return-from make-caching-dfun
455         (make-constant-value-dfun generic-function)))
456     (when (use-dispatch-dfun-p generic-function)
457       (return-from make-caching-dfun
458         (make-dispatch-dfun generic-function))))
459   (multiple-value-bind (nreq applyp metatypes nkeys)
460       (get-generic-fun-info generic-function)
461     (declare (ignore nreq))
462     (let* ((cache (or cache (get-cache nkeys t #'caching-limit-fn 2)))
463            (dfun-info (caching-dfun-info cache)))
464       (values
465        (funcall (get-dfun-constructor 'emit-caching metatypes applyp)
466                 cache
467                 (lambda (&rest args)
468                   (caching-miss generic-function args dfun-info)))
469        cache
470        dfun-info))))
471
472 (defun make-final-caching-dfun (generic-function classes-list new-class)
473   (let ((cache (make-final-ordinary-dfun-internal
474                 generic-function t #'caching-limit-fn
475                 classes-list new-class)))
476     (make-caching-dfun generic-function cache)))
477
478 (defun caching-limit-fn (nlines)
479   (default-limit-fn nlines))
480
481 (defun insure-caching-dfun (gf)
482   (multiple-value-bind (nreq applyp metatypes nkeys)
483       (get-generic-fun-info gf)
484     (declare (ignore nreq nkeys))
485     (when (and metatypes
486                (not (null (car metatypes)))
487                (dolist (mt metatypes nil)
488                  (unless (eq mt t) (return t))))
489       (get-dfun-constructor 'emit-caching metatypes applyp))))
490
491 (defun use-constant-value-dfun-p (gf &optional boolean-values-p)
492   (multiple-value-bind (nreq applyp metatypes nkeys)
493       (get-generic-fun-info gf)
494     (declare (ignore nreq metatypes nkeys))
495     (let* ((early-p (early-gf-p gf))
496            (methods (if early-p
497                         (early-gf-methods gf)
498                         (generic-function-methods gf)))
499            (default '(unknown)))
500       (and (null applyp)
501            (or (not (eq *boot-state* 'complete))
502                (compute-applicable-methods-emf-std-p gf))
503            (notany (lambda (method)
504                      (or (and (eq *boot-state* 'complete)
505                               (some #'eql-specializer-p
506                                     (method-specializers method)))
507                          (let ((value (method-function-get
508                                        (if early-p
509                                            (or (third method) (second method))
510                                            (or (method-fast-function method)
511                                                (method-function method)))
512                                        :constant-value default)))
513                            (if boolean-values-p
514                                (not (or (eq value t) (eq value nil)))
515                                (eq value default)))))
516                    methods)))))
517
518 (defun make-constant-value-dfun (generic-function &optional cache)
519   (multiple-value-bind (nreq applyp metatypes nkeys)
520       (get-generic-fun-info generic-function)
521     (declare (ignore nreq applyp))
522     (let* ((cache (or cache (get-cache nkeys t #'caching-limit-fn 2)))
523            (dfun-info (constant-value-dfun-info cache)))
524       (values
525        (funcall (get-dfun-constructor 'emit-constant-value metatypes)
526                 cache
527                 (lambda (&rest args)
528                   (constant-value-miss generic-function args dfun-info)))
529        cache
530        dfun-info))))
531
532 (defun make-final-constant-value-dfun (generic-function classes-list new-class)
533   (let ((cache (make-final-ordinary-dfun-internal
534                 generic-function :constant-value #'caching-limit-fn
535                 classes-list new-class)))
536     (make-constant-value-dfun generic-function cache)))
537
538 (defun use-dispatch-dfun-p (gf &optional (caching-p (use-caching-dfun-p gf)))
539   (when (eq *boot-state* 'complete)
540     (unless caching-p
541       ;; This should return T when almost all dispatching is by
542       ;; eql specializers or built-in classes. In other words,
543       ;; return NIL if we might ever need to do more than
544       ;; one (non built-in) typep.
545       ;; Otherwise, it is probably at least as fast to use
546       ;; a caching dfun first, possibly followed by secondary dispatching.
547
548       #||;;; Original found in cmu 17f -- S L O W
549       (< (dispatch-dfun-cost gf) (caching-dfun-cost gf))
550       ||#
551       ;; This uses improved dispatch-dfun-cost below
552       (let ((cdc  (caching-dfun-cost gf))) ; fast
553         (> cdc (dispatch-dfun-cost gf cdc))))))
554
555 (defparameter *non-built-in-typep-cost* 1)
556 (defparameter *structure-typep-cost* 1)
557 (defparameter *built-in-typep-cost* 0)
558
559 ;;; According to comments in the original CMU CL version of PCL,
560 ;;; the cost LIMIT is important to cut off exponential growth for
561 ;;; large numbers of gf methods and argument lists.
562 (defun dispatch-dfun-cost (gf &optional limit)
563   (generate-discrimination-net-internal
564    gf (generic-function-methods gf) nil
565    (lambda (methods known-types)
566      (declare (ignore methods known-types))
567      0)
568    (lambda (position type true-value false-value)
569      (declare (ignore position))
570      (let* ((type-test-cost
571              (if (eq 'class (car type))
572                  (let* ((metaclass (class-of (cadr type)))
573                         (mcpl (class-precedence-list metaclass)))
574                    (cond ((memq *the-class-built-in-class* mcpl)
575                           *built-in-typep-cost*)
576                          ((memq *the-class-structure-class* mcpl)
577                           *structure-typep-cost*)
578                          (t
579                           *non-built-in-typep-cost*)))
580                  0))
581             (max-cost-so-far
582              (+ (max true-value false-value) type-test-cost)))
583        (when (and limit (<= limit max-cost-so-far))
584          (return-from dispatch-dfun-cost max-cost-so-far))
585        max-cost-so-far))
586    #'identity))
587
588 (defparameter *cache-lookup-cost* 1)
589 (defparameter *wrapper-of-cost* 0)
590 (defparameter *secondary-dfun-call-cost* 1)
591
592 (defun caching-dfun-cost (gf)
593   (let* ((arg-info (gf-arg-info gf))
594          (nreq (length (arg-info-metatypes arg-info))))
595     (+ *cache-lookup-cost*
596        (* *wrapper-of-cost* nreq)
597        (if (methods-contain-eql-specializer-p
598             (generic-function-methods gf))
599            *secondary-dfun-call-cost*
600            0))))
601
602 (setq *non-built-in-typep-cost* 100)
603 (setq *structure-typep-cost* 15)
604 (setq *built-in-typep-cost* 5)
605 (setq *cache-lookup-cost* 30)
606 (setq *wrapper-of-cost* 15)
607 (setq *secondary-dfun-call-cost* 30)
608
609 (defun make-dispatch-dfun (gf)
610   (values (get-dispatch-function gf) nil (dispatch-dfun-info)))
611
612 (defun get-dispatch-function (gf)
613   (let ((methods (generic-function-methods gf)))
614     (function-funcall (get-secondary-dispatch-function1 gf methods nil nil nil
615                                                         nil nil t)
616                       nil nil)))
617
618 (defun make-final-dispatch-dfun (gf)
619   (make-dispatch-dfun gf))
620
621 (defun update-dispatch-dfuns ()
622   (dolist (gf (gfs-of-type '(dispatch initial-dispatch)))
623     (dfun-update gf #'make-dispatch-dfun)))
624
625 (defun fill-dfun-cache (table valuep nkeys limit-fn &optional cache)
626   (let ((cache (or cache (get-cache nkeys valuep limit-fn
627                                     (+ (hash-table-count table) 3)))))
628     (maphash (lambda (classes value)
629                (setq cache (fill-cache cache
630                                        (class-wrapper classes)
631                                        value
632                                        t)))
633              table)
634     cache))
635
636 (defun make-final-ordinary-dfun-internal (generic-function valuep limit-fn
637                                                            classes-list new-class)
638   (let* ((arg-info (gf-arg-info generic-function))
639          (nkeys (arg-info-nkeys arg-info))
640          (new-class (and new-class
641                          (equal (type-of (gf-dfun-info generic-function))
642                                 (cond ((eq valuep t) 'caching)
643                                       ((eq valuep :constant-value) 'constant-value)
644                                       ((null valuep) 'checking)))
645                          new-class))
646          (cache (if new-class
647                     (copy-cache (gf-dfun-cache generic-function))
648                     (get-cache nkeys (not (null valuep)) limit-fn 4))))
649       (make-emf-cache generic-function valuep cache classes-list new-class)))
650 \f
651 (defvar *dfun-miss-gfs-on-stack* ())
652
653 (defmacro dfun-miss ((gf args wrappers invalidp nemf
654                       &optional type index caching-p applicable)
655                      &body body)
656   (unless applicable (setq applicable (gensym)))
657   `(multiple-value-bind (,nemf ,applicable ,wrappers ,invalidp
658                          ,@(when type `(,type ,index)))
659        (cache-miss-values ,gf ,args ',(cond (caching-p 'caching)
660                                             (type 'accessor)
661                                             (t 'checking)))
662     (when (and ,applicable (not (memq ,gf *dfun-miss-gfs-on-stack*)))
663       (let ((*dfun-miss-gfs-on-stack* (cons ,gf *dfun-miss-gfs-on-stack*)))
664         ,@body))
665     ;; Create a FAST-INSTANCE-BOUNDP structure instance for a cached
666     ;; SLOT-BOUNDP so that INVOKE-EMF does the right thing, that is,
667     ;; does not signal a SLOT-UNBOUND error for a boundp test.
668     ,@(if type
669           ;; FIXME: could the NEMF not be a CONS (for :CLASS-allocated
670           ;; slots?)
671           `((if (and (eq ,type 'boundp) (integerp ,nemf))
672                 (invoke-emf (make-fast-instance-boundp :index ,nemf) ,args)
673                 (invoke-emf ,nemf ,args)))
674           `((invoke-emf ,nemf ,args)))))
675
676 ;;; The dynamically adaptive method lookup algorithm is implemented is
677 ;;; implemented as a kind of state machine. The kinds of
678 ;;; discriminating function is the state, the various kinds of reasons
679 ;;; for a cache miss are the state transitions.
680 ;;;
681 ;;; The code which implements the transitions is all in the miss
682 ;;; handlers for each kind of dfun. Those appear here.
683 ;;;
684 ;;; Note that within the states that cache, there are dfun updates
685 ;;; which simply select a new cache or cache field. Those are not
686 ;;; considered as state transitions.
687 (defvar *lazy-dfun-compute-p* t)
688 (defvar *early-p* nil)
689
690 (defun make-initial-dfun (gf)
691   (let ((initial-dfun
692          #'(instance-lambda (&rest args)
693              (initial-dfun gf args))))
694     (multiple-value-bind (dfun cache info)
695         (if (and (eq *boot-state* 'complete)
696                  (compute-applicable-methods-emf-std-p gf))
697             (let* ((caching-p (use-caching-dfun-p gf))
698                    (classes-list (precompute-effective-methods
699                                   gf caching-p
700                                   (not *lazy-dfun-compute-p*))))
701               (if *lazy-dfun-compute-p*
702                   (cond ((use-dispatch-dfun-p gf caching-p)
703                          (values initial-dfun
704                                  nil
705                                  (initial-dispatch-dfun-info)))
706                         (caching-p
707                          (insure-caching-dfun gf)
708                          (values initial-dfun nil (initial-dfun-info)))
709                         (t
710                          (values initial-dfun nil (initial-dfun-info))))
711                   (make-final-dfun-internal gf classes-list)))
712             (let ((arg-info (if (early-gf-p gf)
713                                 (early-gf-arg-info gf)
714                                 (gf-arg-info gf)))
715                   (type nil))
716               (if (and (gf-precompute-dfun-and-emf-p arg-info)
717                        (setq type (final-accessor-dfun-type gf)))
718                   (if *early-p*
719                       (values (make-early-accessor gf type) nil nil)
720                       (make-final-accessor-dfun gf type))
721                   (values initial-dfun nil (initial-dfun-info)))))
722       (set-dfun gf dfun cache info))))
723
724 (defun make-early-accessor (gf type)
725   (let* ((methods (early-gf-methods gf))
726          (slot-name (early-method-standard-accessor-slot-name (car methods))))
727     (ecase type
728       (reader #'(instance-lambda (instance)
729                   (let* ((class (class-of instance))
730                          (class-name (!bootstrap-get-slot 'class class 'name)))
731                     (!bootstrap-get-slot class-name instance slot-name))))
732       (boundp #'(instance-lambda (instance)
733                   (let* ((class (class-of instance))
734                          (class-name (!bootstrap-get-slot 'class class 'name)))
735                     (not (eq +slot-unbound+
736                              (!bootstrap-get-slot class-name
737                                                   instance slot-name))))))
738       (writer #'(instance-lambda (new-value instance)
739                   (let* ((class (class-of instance))
740                          (class-name (!bootstrap-get-slot 'class class 'name)))
741                     (!bootstrap-set-slot class-name instance slot-name new-value)))))))
742
743 (defun initial-dfun (gf args)
744   (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
745     (cond (invalidp)
746           ((and ntype nindex)
747            (dfun-update
748             gf #'make-one-class-accessor-dfun ntype wrappers nindex))
749           ((use-caching-dfun-p gf)
750            (dfun-update gf #'make-caching-dfun))
751           (t
752            (dfun-update
753             gf #'make-checking-dfun
754             ;; nemf is suitable only for caching, have to do this:
755             (cache-miss-values gf args 'checking))))))
756
757 (defun make-final-dfun (gf &optional classes-list)
758   (multiple-value-bind (dfun cache info)
759       (make-final-dfun-internal gf classes-list)
760     (set-dfun gf dfun cache info)))
761
762 (defvar *new-class* nil)
763
764 (defvar *free-hash-tables* (mapcar #'list '(eq equal eql)))
765
766 (defmacro with-hash-table ((table test) &body forms)
767   `(let* ((.free. (assoc ',test *free-hash-tables*))
768           (,table (if (cdr .free.)
769                       (pop (cdr .free.))
770                       (make-hash-table :test ',test))))
771      (multiple-value-prog1
772          (progn ,@forms)
773        (clrhash ,table)
774        (push ,table (cdr .free.)))))
775
776 (defmacro with-eq-hash-table ((table) &body forms)
777   `(with-hash-table (,table eq) ,@forms))
778
779 (defun final-accessor-dfun-type (gf)
780   (let ((methods (if (early-gf-p gf)
781                      (early-gf-methods gf)
782                      (generic-function-methods gf))))
783     (cond ((every (lambda (method)
784                     (if (consp method)
785                         (eq *the-class-standard-reader-method*
786                             (early-method-class method))
787                         (standard-reader-method-p method)))
788                   methods)
789            'reader)
790           ((every (lambda (method)
791                     (if (consp method)
792                         (eq *the-class-standard-boundp-method*
793                             (early-method-class method))
794                         (standard-boundp-method-p method)))
795                   methods)
796            'boundp)
797           ((every (lambda (method)
798                     (if (consp method)
799                         (eq *the-class-standard-writer-method*
800                             (early-method-class method))
801                         (standard-writer-method-p method)))
802                   methods)
803            'writer))))
804
805 (defun make-final-accessor-dfun (gf type &optional classes-list new-class)
806   (with-eq-hash-table (table)
807     (multiple-value-bind (table all-index first second size no-class-slots-p)
808         (make-accessor-table gf type table)
809       (if table
810           (cond ((= size 1)
811                  (let ((w (class-wrapper first)))
812                    (make-one-class-accessor-dfun gf type w all-index)))
813                 ((and (= size 2) (or (integerp all-index) (consp all-index)))
814                  (let ((w0 (class-wrapper first))
815                        (w1 (class-wrapper second)))
816                    (make-two-class-accessor-dfun gf type w0 w1 all-index)))
817                 ((or (integerp all-index) (consp all-index))
818                  (make-final-one-index-accessor-dfun
819                   gf type all-index table))
820                 (no-class-slots-p
821                  (make-final-n-n-accessor-dfun gf type table))
822                 (t
823                  (make-final-caching-dfun gf classes-list new-class)))
824           (make-final-caching-dfun gf classes-list new-class)))))
825
826 (defun make-final-dfun-internal (gf &optional classes-list)
827   (let ((methods (generic-function-methods gf)) type
828         (new-class *new-class*) (*new-class* nil)
829         specls all-same-p)
830     (cond ((null methods)
831            (values
832             #'(instance-lambda (&rest args)
833                 (apply #'no-applicable-method gf args))
834             nil
835             (no-methods-dfun-info)))
836           ((setq type (final-accessor-dfun-type gf))
837            (make-final-accessor-dfun gf type classes-list new-class))
838           ((and (not (and (every (lambda (specl) (eq specl *the-class-t*))
839                                  (setq specls
840                                        (method-specializers (car methods))))
841                           (setq all-same-p
842                                 (every (lambda (method)
843                                          (and (equal specls
844                                                      (method-specializers
845                                                       method))))
846                                        methods))))
847                 (use-constant-value-dfun-p gf))
848            (make-final-constant-value-dfun gf classes-list new-class))
849           ((use-dispatch-dfun-p gf)
850            (make-final-dispatch-dfun gf))
851           ((and all-same-p (not (use-caching-dfun-p gf)))
852            (let ((emf (get-secondary-dispatch-function gf methods nil)))
853              (make-final-checking-dfun gf emf classes-list new-class)))
854           (t
855            (make-final-caching-dfun gf classes-list new-class)))))
856
857 (defun accessor-miss (gf new object dfun-info)
858   (let* ((ostate (type-of dfun-info))
859          (otype (dfun-info-accessor-type dfun-info))
860          oindex ow0 ow1 cache
861          (args (ecase otype
862                  ;; The congruence rules ensure that this is safe
863                  ;; despite not knowing the new type yet.
864                  ((reader boundp) (list object))
865                  (writer (list new object)))))  
866     (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
867
868       ;; The following lexical functions change the state of the
869       ;; dfun to that which is their name. They accept arguments
870       ;; which are the parameters of the new state, and get other
871       ;; information from the lexical variables bound above.
872       (flet ((two-class (index w0 w1)
873                (when (zerop (random 2)) (psetf w0 w1 w1 w0))
874                (dfun-update gf
875                             #'make-two-class-accessor-dfun
876                             ntype
877                             w0
878                             w1
879                             index))
880              (one-index (index &optional cache)
881                (dfun-update gf
882                             #'make-one-index-accessor-dfun
883                             ntype
884                             index
885                             cache))
886              (n-n (&optional cache)
887                (if (consp nindex)
888                    (dfun-update gf #'make-checking-dfun nemf)
889                    (dfun-update gf #'make-n-n-accessor-dfun ntype cache)))
890              (caching () ; because cached accessor emfs are much faster
891                          ; for accessors
892                (dfun-update gf #'make-caching-dfun))
893              (do-fill (update-fn)
894                (let ((ncache (fill-cache cache wrappers nindex)))
895                  (unless (eq ncache cache)
896                    (funcall update-fn ncache)))))
897
898         (cond ((null ntype)
899                (caching))
900               ((or invalidp
901                    (null nindex)))
902               ((not (pcl-instance-p object))
903                (caching))
904               ((or (neq ntype otype) (listp wrappers))
905                (caching))
906               (t
907                (ecase ostate
908                  (one-class
909                   (setq oindex (dfun-info-index dfun-info))
910                   (setq ow0 (dfun-info-wrapper0 dfun-info))
911                   (unless (eq ow0 wrappers)
912                     (if (eql nindex oindex)
913                         (two-class nindex ow0 wrappers)
914                         (n-n))))
915                  (two-class
916                   (setq oindex (dfun-info-index dfun-info))
917                   (setq ow0 (dfun-info-wrapper0 dfun-info))
918                   (setq ow1 (dfun-info-wrapper1 dfun-info))
919                   (unless (or (eq ow0 wrappers) (eq ow1 wrappers))
920                     (if (eql nindex oindex)
921                         (one-index nindex)
922                         (n-n))))
923                  (one-index
924                   (setq oindex (dfun-info-index dfun-info))
925                   (setq cache (dfun-info-cache dfun-info))
926                   (if (eql nindex oindex)
927                       (do-fill (lambda (ncache)
928                                  (one-index nindex ncache)))
929                       (n-n)))
930                  (n-n
931                   (setq cache (dfun-info-cache dfun-info))
932                   (if (consp nindex)
933                       (caching)
934                       (do-fill #'n-n))))))))))
935
936 (defun checking-miss (generic-function args dfun-info)
937   (let ((oemf (dfun-info-function dfun-info))
938         (cache (dfun-info-cache dfun-info)))
939     (dfun-miss (generic-function args wrappers invalidp nemf)
940       (cond (invalidp)
941             ((eq oemf nemf)
942              (let ((ncache (fill-cache cache wrappers nil)))
943                (unless (eq ncache cache)
944                  (dfun-update generic-function #'make-checking-dfun
945                               nemf ncache))))
946             (t
947              (dfun-update generic-function #'make-caching-dfun))))))
948
949 (defun caching-miss (generic-function args dfun-info)
950   (let ((ocache (dfun-info-cache dfun-info)))
951     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
952       (cond (invalidp)
953             (t
954              (let ((ncache (fill-cache ocache wrappers emf)))
955                (unless (eq ncache ocache)
956                  (dfun-update generic-function
957                               #'make-caching-dfun ncache))))))))
958
959 (defun constant-value-miss (generic-function args dfun-info)
960   (let ((ocache (dfun-info-cache dfun-info)))
961     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
962       (cond (invalidp)
963             (t
964              (let* ((function (typecase emf
965                                 (fast-method-call (fast-method-call-function
966                                                    emf))
967                                 (method-call (method-call-function emf))))
968                     (value (method-function-get function :constant-value))
969                     (ncache (fill-cache ocache wrappers value)))
970                (unless (eq ncache ocache)
971                  (dfun-update generic-function
972                               #'make-constant-value-dfun ncache))))))))
973 \f
974 ;;; Given a generic function and a set of arguments to that generic
975 ;;; function, return a mess of values.
976 ;;;
977 ;;;  <function>   The compiled effective method function for this set of
978 ;;;            arguments.
979 ;;;
980 ;;;  <applicable> Sorted list of applicable methods.
981 ;;;
982 ;;;  <wrappers>   Is a single wrapper if the generic function has only
983 ;;;            one key, that is arg-info-nkeys of the arg-info is 1.
984 ;;;            Otherwise a list of the wrappers of the specialized
985 ;;;            arguments to the generic function.
986 ;;;
987 ;;;            Note that all these wrappers are valid. This function
988 ;;;            does invalid wrapper traps when it finds an invalid
989 ;;;            wrapper and then returns the new, valid wrapper.
990 ;;;
991 ;;;  <invalidp>   True if any of the specialized arguments had an invalid
992 ;;;            wrapper, false otherwise.
993 ;;;
994 ;;;  <type>       READER or WRITER when the only method that would be run
995 ;;;            is a standard reader or writer method. To be specific,
996 ;;;            the value is READER when the method combination is eq to
997 ;;;            *standard-method-combination*; there are no applicable
998 ;;;            :before, :after or :around methods; and the most specific
999 ;;;            primary method is a standard reader method.
1000 ;;;
1001 ;;;  <index>      If <type> is READER or WRITER, and the slot accessed is
1002 ;;;            an :instance slot, this is the index number of that slot
1003 ;;;            in the object argument.
1004 (defun cache-miss-values (gf args state)
1005   (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
1006       (get-generic-fun-info gf)
1007     (declare (ignore nreq applyp nkeys))
1008     (with-dfun-wrappers (args metatypes)
1009       (dfun-wrappers invalid-wrapper-p wrappers classes types)
1010       (error-need-at-least-n-args gf (length metatypes))
1011       (multiple-value-bind (emf methods accessor-type index)
1012           (cache-miss-values-internal
1013            gf arg-info wrappers classes types state)
1014         (values emf methods
1015                 dfun-wrappers
1016                 invalid-wrapper-p
1017                 accessor-type index)))))
1018
1019 (defun cache-miss-values-internal (gf arg-info wrappers classes types state)
1020   (let* ((for-accessor-p (eq state 'accessor))
1021          (for-cache-p (or (eq state 'caching) (eq state 'accessor)))
1022          (cam-std-p (or (null arg-info)
1023                         (gf-info-c-a-m-emf-std-p arg-info))))
1024     (multiple-value-bind (methods all-applicable-and-sorted-p)
1025         (if cam-std-p
1026             (compute-applicable-methods-using-types gf types)
1027             (compute-applicable-methods-using-classes gf classes))
1028       (let ((emf (if (or cam-std-p all-applicable-and-sorted-p)
1029                      (function-funcall (get-secondary-dispatch-function1
1030                                         gf methods types nil (and for-cache-p
1031                                                                   wrappers)
1032                                         all-applicable-and-sorted-p)
1033                                        nil (and for-cache-p wrappers))
1034                      (default-secondary-dispatch-function gf))))
1035         (multiple-value-bind (index accessor-type)
1036             (and for-accessor-p all-applicable-and-sorted-p methods
1037                  (accessor-values gf arg-info classes methods))
1038           (values (if (integerp index) index emf)
1039                   methods accessor-type index))))))
1040
1041 (defun accessor-values (gf arg-info classes methods)
1042   (declare (ignore gf))
1043   (let* ((accessor-type (gf-info-simple-accessor-type arg-info))
1044          (accessor-class (case accessor-type
1045                            ((reader boundp) (car classes))
1046                            (writer (cadr classes)))))
1047     (accessor-values-internal accessor-type accessor-class methods)))
1048
1049 (defun accessor-values1 (gf accessor-type accessor-class)
1050   (let* ((type `(class-eq ,accessor-class))
1051          (types (ecase accessor-type
1052                   ((reader boundp) `(,type))
1053                   (writer `(t ,type))))
1054          (methods (compute-applicable-methods-using-types gf types)))
1055     (accessor-values-internal accessor-type accessor-class methods)))
1056
1057 (defun accessor-values-internal (accessor-type accessor-class methods)
1058   (dolist (meth methods)
1059     (when (if (consp meth)
1060               (early-method-qualifiers meth)
1061               (method-qualifiers meth))
1062       (return-from accessor-values-internal (values nil nil))))
1063   (let* ((meth (car methods))
1064          (early-p (not (eq *boot-state* 'complete)))
1065          (slot-name (when accessor-class
1066                       (if (consp meth)
1067                           (and (early-method-standard-accessor-p meth)
1068                                (early-method-standard-accessor-slot-name meth))
1069                           (and (member *the-class-std-object*
1070                                        (if early-p
1071                                            (early-class-precedence-list
1072                                             accessor-class)
1073                                            (class-precedence-list
1074                                             accessor-class)))
1075                                (if early-p
1076                                    (not (eq *the-class-standard-method*
1077                                             (early-method-class meth)))
1078                                    (standard-accessor-method-p meth))
1079                                (if early-p
1080                                    (early-accessor-method-slot-name meth)
1081                                    (accessor-method-slot-name meth))))))
1082          (slotd (and accessor-class
1083                      (if early-p
1084                          (dolist (slot (early-class-slotds accessor-class) nil)
1085                            (when (eql slot-name
1086                                       (early-slot-definition-name slot))
1087                              (return slot)))
1088                          (find-slot-definition accessor-class slot-name)))))
1089     (when (and slotd
1090                (or early-p
1091                    (slot-accessor-std-p slotd accessor-type)))
1092       (values (if early-p
1093                   (early-slot-definition-location slotd)
1094                   (slot-definition-location slotd))
1095               accessor-type))))
1096
1097 (defun make-accessor-table (gf type &optional table)
1098   (unless table (setq table (make-hash-table :test 'eq)))
1099   (let ((methods (if (early-gf-p gf)
1100                      (early-gf-methods gf)
1101                      (generic-function-methods gf)))
1102         (all-index nil)
1103         (no-class-slots-p t)
1104         (early-p (not (eq *boot-state* 'complete)))
1105         first second (size 0))
1106     (declare (fixnum size))
1107     ;; class -> {(specl slotd)}
1108     (dolist (method methods)
1109       (let* ((specializers (if (consp method)
1110                                (early-method-specializers method t)
1111                                (method-specializers method)))
1112              (specl (ecase type
1113                       ((reader boundp) (car specializers))
1114                       (writer (cadr specializers))))
1115              (specl-cpl (if early-p
1116                             (early-class-precedence-list specl)
1117                             (and (class-finalized-p specl)
1118                                  (class-precedence-list specl))))
1119              (so-p (member *the-class-std-object* specl-cpl))
1120              (slot-name (if (consp method)
1121                             (and (early-method-standard-accessor-p method)
1122                                  (early-method-standard-accessor-slot-name
1123                                   method))
1124                             (accessor-method-slot-name method))))
1125         (when (or (null specl-cpl)
1126                   (member *the-class-structure-object* specl-cpl))
1127           (return-from make-accessor-table nil))
1128         (maphash (lambda (class slotd)
1129                    (let ((cpl (if early-p
1130                                   (early-class-precedence-list class)
1131                                   (class-precedence-list class))))
1132                      (when (memq specl cpl)
1133                        (unless (and (or so-p
1134                                         (member *the-class-std-object* cpl))
1135                                     (or early-p
1136                                         (slot-accessor-std-p slotd type)))
1137                          (return-from make-accessor-table nil))
1138                        (push (cons specl slotd) (gethash class table)))))
1139                  (gethash slot-name *name->class->slotd-table*))))
1140     (maphash (lambda (class specl+slotd-list)
1141                (dolist (sclass (if early-p
1142                                    (early-class-precedence-list class)
1143                                    (class-precedence-list class))
1144                                (error "This can't happen."))
1145                  (let ((a (assq sclass specl+slotd-list)))
1146                    (when a
1147                      (let* ((slotd (cdr a))
1148                             (index (if early-p
1149                                        (early-slot-definition-location slotd)
1150                                        (slot-definition-location slotd))))
1151                        (unless index (return-from make-accessor-table nil))
1152                        (setf (gethash class table) index)
1153                        (when (consp index) (setq no-class-slots-p nil))
1154                        (setq all-index (if (or (null all-index)
1155                                                (eql all-index index))
1156                                            index t))
1157                        (incf size)
1158                        (cond ((= size 1) (setq first class))
1159                              ((= size 2) (setq second class)))
1160                        (return nil))))))
1161              table)
1162     (values table all-index first second size no-class-slots-p)))
1163
1164 (defun compute-applicable-methods-using-types (generic-function types)
1165   (let ((definite-p t) (possibly-applicable-methods nil))
1166     (dolist (method (if (early-gf-p generic-function)
1167                         (early-gf-methods generic-function)
1168                         (generic-function-methods generic-function)))
1169       (let ((specls (if (consp method)
1170                         (early-method-specializers method t)
1171                         (method-specializers method)))
1172             (types types)
1173             (possibly-applicable-p t) (applicable-p t))
1174         (dolist (specl specls)
1175           (multiple-value-bind (specl-applicable-p specl-possibly-applicable-p)
1176               (specializer-applicable-using-type-p specl (pop types))
1177             (unless specl-applicable-p
1178               (setq applicable-p nil))
1179             (unless specl-possibly-applicable-p
1180               (setq possibly-applicable-p nil)
1181               (return nil))))
1182         (when possibly-applicable-p
1183           (unless applicable-p (setq definite-p nil))
1184           (push method possibly-applicable-methods))))
1185     (let ((precedence (arg-info-precedence (if (early-gf-p generic-function)
1186                                                (early-gf-arg-info
1187                                                 generic-function)
1188                                                (gf-arg-info
1189                                                 generic-function)))))
1190       (values (sort-applicable-methods precedence
1191                                        (nreverse possibly-applicable-methods)
1192                                        types)
1193               definite-p))))
1194
1195 (defun sort-applicable-methods (precedence methods types)
1196   (sort-methods methods
1197                 precedence
1198                 (lambda (class1 class2 index)
1199                   (let* ((class (type-class (nth index types)))
1200                          (cpl (if (eq *boot-state* 'complete)
1201                                   (class-precedence-list class)
1202                                   (early-class-precedence-list class))))
1203                     (if (memq class2 (memq class1 cpl))
1204                         class1 class2)))))
1205
1206 (defun sort-methods (methods precedence compare-classes-function)
1207   (flet ((sorter (method1 method2)
1208            (dolist (index precedence)
1209              (let* ((specl1 (nth index (if (listp method1)
1210                                            (early-method-specializers method1
1211                                                                       t)
1212                                            (method-specializers method1))))
1213                     (specl2 (nth index (if (listp method2)
1214                                            (early-method-specializers method2
1215                                                                       t)
1216                                            (method-specializers method2))))
1217                     (order (order-specializers
1218                              specl1 specl2 index compare-classes-function)))
1219                (when order
1220                  (return-from sorter (eq order specl1)))))))
1221     (stable-sort methods #'sorter)))
1222
1223 (defun order-specializers (specl1 specl2 index compare-classes-function)
1224   (let ((type1 (if (eq *boot-state* 'complete)
1225                    (specializer-type specl1)
1226                    (!bootstrap-get-slot 'specializer specl1 'type)))
1227         (type2 (if (eq *boot-state* 'complete)
1228                    (specializer-type specl2)
1229                    (!bootstrap-get-slot 'specializer specl2 'type))))
1230     (cond ((eq specl1 specl2)
1231            nil)
1232           ((atom type1)
1233            specl2)
1234           ((atom type2)
1235            specl1)
1236           (t
1237            (case (car type1)
1238              (class    (case (car type2)
1239                          (class (funcall compare-classes-function
1240                                          specl1 specl2 index))
1241                          (t specl2)))
1242              (prototype (case (car type2)
1243                          (class (funcall compare-classes-function
1244                                          specl1 specl2 index))
1245                          (t specl2)))
1246              (class-eq (case (car type2)
1247                          (eql specl2)
1248                          (class-eq nil)
1249                          (class type1)))
1250              (eql      (case (car type2)
1251                          (eql nil)
1252                          (t specl1))))))))
1253
1254 (defun map-all-orders (methods precedence function)
1255   (let ((choices nil))
1256     (flet ((compare-classes-function (class1 class2 index)
1257              (declare (ignore index))
1258              (let ((choice nil))
1259                (dolist (c choices nil)
1260                  (when (or (and (eq (first c) class1)
1261                                 (eq (second c) class2))
1262                            (and (eq (first c) class2)
1263                                 (eq (second c) class1)))
1264                    (return (setq choice c))))
1265                (unless choice
1266                  (setq choice
1267                        (if (class-might-precede-p class1 class2)
1268                            (if (class-might-precede-p class2 class1)
1269                                (list class1 class2 nil t)
1270                                (list class1 class2 t))
1271                            (if (class-might-precede-p class2 class1)
1272                                (list class2 class1 t)
1273                                (let ((name1 (class-name class1))
1274                                      (name2 (class-name class2)))
1275                                  (if (and name1
1276                                           name2
1277                                           (symbolp name1)
1278                                           (symbolp name2)
1279                                           (string< (symbol-name name1)
1280                                                    (symbol-name name2)))
1281                                      (list class1 class2 t)
1282                                      (list class2 class1 t))))))
1283                  (push choice choices))
1284                (car choice))))
1285       (loop (funcall function
1286                      (sort-methods methods
1287                                    precedence
1288                                    #'compare-classes-function))
1289             (unless (dolist (c choices nil)
1290                       (unless (third c)
1291                         (rotatef (car c) (cadr c))
1292                         (return (setf (third c) t))))
1293               (return nil))))))
1294
1295 (defvar *in-precompute-effective-methods-p* nil)
1296
1297 ;used only in map-all-orders
1298 (defun class-might-precede-p (class1 class2)
1299   (if (not *in-precompute-effective-methods-p*)
1300       (not (member class1 (cdr (class-precedence-list class2))))
1301       (class-can-precede-p class1 class2)))
1302
1303 (defun compute-precedence (lambda-list nreq argument-precedence-order)
1304   (if (null argument-precedence-order)
1305       (let ((list nil))
1306         (dotimes-fixnum (i nreq list) (push (- (1- nreq) i) list)))
1307       (mapcar (lambda (x) (position x lambda-list))
1308               argument-precedence-order)))
1309
1310 (defun saut-and (specl type)
1311   (let ((applicable nil)
1312         (possibly-applicable t))
1313     (dolist (type (cdr type))
1314       (multiple-value-bind (appl poss-appl)
1315           (specializer-applicable-using-type-p specl type)
1316         (when appl (return (setq applicable t)))
1317         (unless poss-appl (return (setq possibly-applicable nil)))))
1318     (values applicable possibly-applicable)))
1319
1320 (defun saut-not (specl type)
1321   (let ((ntype (cadr type)))
1322     (values nil
1323             (case (car ntype)
1324               (class      (saut-not-class specl ntype))
1325               (class-eq   (saut-not-class-eq specl ntype))
1326               (prototype  (saut-not-prototype specl ntype))
1327               (eql      (saut-not-eql specl ntype))
1328               (t (error "~S cannot handle the second argument ~S"
1329                         'specializer-applicable-using-type-p type))))))
1330
1331 (defun saut-not-class (specl ntype)
1332   (let* ((class (type-class specl))
1333          (cpl (class-precedence-list class)))
1334      (not (memq (cadr ntype) cpl))))
1335
1336 (defun saut-not-prototype (specl ntype)
1337   (let* ((class (case (car specl)
1338                   (eql       (class-of (cadr specl)))
1339                   (class-eq  (cadr specl))
1340                   (prototype (cadr specl))
1341                   (class     (cadr specl))))
1342          (cpl (class-precedence-list class)))
1343      (not (memq (cadr ntype) cpl))))
1344
1345 (defun saut-not-class-eq (specl ntype)
1346   (let ((class (case (car specl)
1347                  (eql      (class-of (cadr specl)))
1348                  (class-eq (cadr specl)))))
1349     (not (eq class (cadr ntype)))))
1350
1351 (defun saut-not-eql (specl ntype)
1352   (case (car specl)
1353     (eql (not (eql (cadr specl) (cadr ntype))))
1354     (t   t)))
1355
1356 (defun class-applicable-using-class-p (specl type)
1357   (let ((pred (memq specl (if (eq *boot-state* 'complete)
1358                               (class-precedence-list type)
1359                               (early-class-precedence-list type)))))
1360     (values pred
1361             (or pred
1362                 (if (not *in-precompute-effective-methods-p*)
1363                     ;; classes might get common subclass
1364                     (superclasses-compatible-p specl type)
1365                     ;; worry only about existing classes
1366                     (classes-have-common-subclass-p specl type))))))
1367
1368 (defun classes-have-common-subclass-p (class1 class2)
1369   (or (eq class1 class2)
1370       (let ((class1-subs (class-direct-subclasses class1)))
1371         (or (memq class2 class1-subs)
1372             (dolist (class1-sub class1-subs nil)
1373               (when (classes-have-common-subclass-p class1-sub class2)
1374                 (return t)))))))
1375
1376 (defun saut-class (specl type)
1377   (case (car specl)
1378     (class (class-applicable-using-class-p (cadr specl) (cadr type)))
1379     (t     (values nil (let ((class (type-class specl)))
1380                          (memq (cadr type)
1381                                (class-precedence-list class)))))))
1382
1383 (defun saut-class-eq (specl type)
1384   (if (eq (car specl) 'eql)
1385       (values nil (eq (class-of (cadr specl)) (cadr type)))
1386       (let ((pred (case (car specl)
1387                     (class-eq
1388                      (eq (cadr specl) (cadr type)))
1389                     (class
1390                      (or (eq (cadr specl) (cadr type))
1391                          (memq (cadr specl)
1392                                (if (eq *boot-state* 'complete)
1393                                    (class-precedence-list (cadr type))
1394                                    (early-class-precedence-list
1395                                     (cadr type)))))))))
1396         (values pred pred))))
1397
1398 (defun saut-prototype (specl type)
1399   (declare (ignore specl type))
1400   (values nil nil)) ; XXX original PCL comment: fix this someday
1401
1402 (defun saut-eql (specl type)
1403   (let ((pred (case (car specl)
1404                 (eql    (eql (cadr specl) (cadr type)))
1405                 (class-eq   (eq (cadr specl) (class-of (cadr type))))
1406                 (class      (memq (cadr specl)
1407                                   (let ((class (class-of (cadr type))))
1408                                     (if (eq *boot-state* 'complete)
1409                                         (class-precedence-list class)
1410                                         (early-class-precedence-list
1411                                          class))))))))
1412     (values pred pred)))
1413
1414 (defun specializer-applicable-using-type-p (specl type)
1415   (setq specl (type-from-specializer specl))
1416   (when (eq specl t)
1417     (return-from specializer-applicable-using-type-p (values t t)))
1418   ;; This is used by C-A-M-U-T and GENERATE-DISCRIMINATION-NET-INTERNAL,
1419   ;; and has only what they need.
1420   (if (or (atom type) (eq (car type) t))
1421       (values nil t)
1422       (case (car type)
1423         (and    (saut-and specl type))
1424         (not    (saut-not specl type))
1425         (class      (saut-class specl type))
1426         (prototype  (saut-prototype specl type))
1427         (class-eq   (saut-class-eq specl type))
1428         (eql    (saut-eql specl type))
1429         (t        (error "~S cannot handle the second argument ~S."
1430                            'specializer-applicable-using-type-p
1431                            type)))))
1432
1433 (defun map-all-classes (function &optional (root t))
1434   (let ((braid-p (or (eq *boot-state* 'braid)
1435                      (eq *boot-state* 'complete))))
1436     (labels ((do-class (class)
1437                (mapc #'do-class
1438                      (if braid-p
1439                          (class-direct-subclasses class)
1440                          (early-class-direct-subclasses class)))
1441                (funcall function class)))
1442       (do-class (if (symbolp root)
1443                     (find-class root)
1444                     root)))))
1445 \f
1446 ;;; NOTE: We are assuming a restriction on user code that the method
1447 ;;;       combination must not change once it is connected to the
1448 ;;;       generic function.
1449 ;;;
1450 ;;;       This has to be legal, because otherwise any kind of method
1451 ;;;       lookup caching couldn't work. See this by saying that this
1452 ;;;       cache, is just a backing cache for the fast cache. If that
1453 ;;;       cache is legal, this one must be too.
1454 ;;;
1455 ;;; Don't clear this table!
1456 (defvar *effective-method-table* (make-hash-table :test 'eq))
1457
1458 (defun get-secondary-dispatch-function (gf methods types &optional
1459                                                          method-alist wrappers)
1460   (function-funcall (get-secondary-dispatch-function1
1461                      gf methods types
1462                      (not (null method-alist))
1463                      (not (null wrappers))
1464                      (not (methods-contain-eql-specializer-p methods)))
1465                     method-alist wrappers))
1466
1467 (defun get-secondary-dispatch-function1 (gf methods types method-alist-p
1468                                             wrappers-p
1469                                             &optional
1470                                             all-applicable-p
1471                                             (all-sorted-p t)
1472                                             function-p)
1473   (if (null methods)
1474       (if function-p
1475           (lambda (method-alist wrappers)
1476             (declare (ignore method-alist wrappers))
1477             #'(instance-lambda (&rest args)
1478                 (apply #'no-applicable-method gf args)))
1479           (lambda (method-alist wrappers)
1480             (declare (ignore method-alist wrappers))
1481             (lambda (&rest args)
1482               (apply #'no-applicable-method gf args))))
1483       (let* ((key (car methods))
1484              (ht-value (or (gethash key *effective-method-table*)
1485                            (setf (gethash key *effective-method-table*)
1486                                  (cons nil nil)))))
1487         (if (and (null (cdr methods)) all-applicable-p ; the most common case
1488                  (null method-alist-p) wrappers-p (not function-p))
1489             (or (car ht-value)
1490                 (setf (car ht-value)
1491                       (get-secondary-dispatch-function2
1492                        gf methods types method-alist-p wrappers-p
1493                        all-applicable-p all-sorted-p function-p)))
1494             (let ((akey (list methods
1495                               (if all-applicable-p 'all-applicable types)
1496                               method-alist-p wrappers-p function-p)))
1497               (or (cdr (assoc akey (cdr ht-value) :test #'equal))
1498                   (let ((value (get-secondary-dispatch-function2
1499                                 gf methods types method-alist-p wrappers-p
1500                                 all-applicable-p all-sorted-p function-p)))
1501                     (push (cons akey value) (cdr ht-value))
1502                     value)))))))
1503
1504 (defun get-secondary-dispatch-function2 (gf methods types method-alist-p
1505                                             wrappers-p all-applicable-p
1506                                             all-sorted-p function-p)
1507   (if (and all-applicable-p all-sorted-p (not function-p))
1508       (if (eq *boot-state* 'complete)
1509           (let* ((combin (generic-function-method-combination gf))
1510                  (effective (compute-effective-method gf combin methods)))
1511             (make-effective-method-function1 gf effective method-alist-p
1512                                              wrappers-p))
1513           (let ((effective (standard-compute-effective-method gf nil methods)))
1514             (make-effective-method-function1 gf effective method-alist-p
1515                                              wrappers-p)))
1516       (let ((net (generate-discrimination-net
1517                   gf methods types all-sorted-p)))
1518         (compute-secondary-dispatch-function1 gf net function-p))))
1519
1520 (defun get-effective-method-function (gf methods
1521                                          &optional method-alist wrappers)
1522   (function-funcall (get-secondary-dispatch-function1 gf methods nil
1523                                                       (not (null method-alist))
1524                                                       (not (null wrappers))
1525                                                       t)
1526                     method-alist wrappers))
1527
1528 (defun get-effective-method-function1 (gf methods &optional (sorted-p t))
1529   (get-secondary-dispatch-function1 gf methods nil nil nil t sorted-p))
1530
1531 (defun methods-contain-eql-specializer-p (methods)
1532   (and (eq *boot-state* 'complete)
1533        (dolist (method methods nil)
1534          (when (dolist (spec (method-specializers method) nil)
1535                  (when (eql-specializer-p spec) (return t)))
1536            (return t)))))
1537 \f
1538 (defun update-dfun (generic-function &optional dfun cache info)
1539   (let* ((early-p (early-gf-p generic-function))
1540          (gf-name (if early-p
1541                       (!early-gf-name generic-function)
1542                       (generic-function-name generic-function)))
1543          (ocache (gf-dfun-cache generic-function)))
1544     (set-dfun generic-function dfun cache info)
1545     (let ((dfun (if early-p
1546                     (or dfun (make-initial-dfun generic-function))
1547                     (compute-discriminating-function generic-function))))
1548       (set-funcallable-instance-fun generic-function dfun)
1549       (set-fun-name generic-function gf-name)
1550       (when (and ocache (not (eq ocache cache))) (free-cache ocache))
1551       dfun)))
1552 \f
1553 (defvar *dfun-count* nil)
1554 (defvar *dfun-list* nil)
1555 (defvar *minimum-cache-size-to-list*)
1556
1557 ;;; These functions aren't used in SBCL, or documented anywhere that
1558 ;;; I'm aware of, but they look like they might be useful for
1559 ;;; debugging or performance tweaking or something, so I've just
1560 ;;; commented them out instead of deleting them. -- WHN 2001-03-28
1561 #|
1562 (defun list-dfun (gf)
1563   (let* ((sym (type-of (gf-dfun-info gf)))
1564          (a (assq sym *dfun-list*)))
1565     (unless a
1566       (push (setq a (list sym)) *dfun-list*))
1567     (push (generic-function-name gf) (cdr a))))
1568
1569 (defun list-all-dfuns ()
1570   (setq *dfun-list* nil)
1571   (map-all-generic-functions #'list-dfun)
1572   *dfun-list*)
1573
1574 (defun list-large-cache (gf)
1575   (let* ((sym (type-of (gf-dfun-info gf)))
1576          (cache (gf-dfun-cache gf)))
1577     (when cache
1578       (let ((size (cache-size cache)))
1579         (when (>= size *minimum-cache-size-to-list*)
1580           (let ((a (assoc size *dfun-list*)))
1581             (unless a
1582               (push (setq a (list size)) *dfun-list*))
1583             (push (let ((name (generic-function-name gf)))
1584                     (if (eq sym 'caching) name (list name sym)))
1585                   (cdr a))))))))
1586
1587 (defun list-large-caches (&optional (*minimum-cache-size-to-list* 130))
1588   (setq *dfun-list* nil)
1589   (map-all-generic-functions #'list-large-cache)
1590   (setq *dfun-list* (sort *dfun-list* #'< :key #'car))
1591   (mapc #'print *dfun-list*)
1592   (values))
1593
1594 (defun count-dfun (gf)
1595   (let* ((sym (type-of (gf-dfun-info gf)))
1596          (cache (gf-dfun-cache gf))
1597          (a (assq sym *dfun-count*)))
1598     (unless a
1599       (push (setq a (list sym 0 nil)) *dfun-count*))
1600     (incf (cadr a))
1601     (when cache
1602       (let* ((size (cache-size cache))
1603              (b (assoc size (third a))))
1604         (unless b
1605           (push (setq b (cons size 0)) (third a)))
1606         (incf (cdr b))))))
1607
1608 (defun count-all-dfuns ()
1609   (setq *dfun-count* (mapcar (lambda (type) (list type 0 nil))
1610                              '(ONE-CLASS TWO-CLASS DEFAULT-METHOD-ONLY
1611                                ONE-INDEX N-N CHECKING CACHING
1612                                DISPATCH)))
1613   (map-all-generic-functions #'count-dfun)
1614   (mapc (lambda (type+count+sizes)
1615           (setf (third type+count+sizes)
1616                 (sort (third type+count+sizes) #'< :key #'car)))
1617         *dfun-count*)
1618   (mapc (lambda (type+count+sizes)
1619           (format t "~&There are ~W dfuns of type ~S."
1620                   (cadr type+count+sizes) (car type+count+sizes))
1621           (format t "~%   ~S~%" (caddr type+count+sizes)))
1622         *dfun-count*)
1623   (values))
1624 |#
1625
1626 (defun gfs-of-type (type)
1627   (unless (consp type) (setq type (list type)))
1628   (let ((gf-list nil))
1629     (map-all-generic-functions (lambda (gf)
1630                                  (when (memq (type-of (gf-dfun-info gf))
1631                                              type)
1632                                    (push gf gf-list))))
1633     gf-list))