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