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