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