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