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