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