0.pre8.9:
[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                   ;; KLUDGE: the only effect of this (when
713                   ;; *LAZY-DFUN-COMPUTE-P* is true, as it usually is)
714                   ;; is to signal an error when we try to add methods
715                   ;; with the wrong qualifiers to a generic function.
716                   (classes-list (precompute-effective-methods
717                                  gf caching-p
718                                  (not *lazy-dfun-compute-p*))))
719              (if *lazy-dfun-compute-p*
720                  (cond ((use-dispatch-dfun-p gf caching-p)
721                         (values initial-dfun
722                                 nil
723                                 (initial-dispatch-dfun-info)))
724                        (caching-p
725                         (insure-caching-dfun gf)
726                         (values initial-dfun nil (initial-dfun-info)))
727                        (t
728                         (values initial-dfun nil (initial-dfun-info))))
729                  (make-final-dfun-internal gf classes-list))))
730           (t
731            (let ((arg-info (if (early-gf-p gf)
732                                (early-gf-arg-info gf)
733                                (gf-arg-info gf)))
734                  (type nil))
735              (if (and (gf-precompute-dfun-and-emf-p arg-info)
736                       (setq type (final-accessor-dfun-type gf)))
737                  (if *early-p*
738                      (values (make-early-accessor gf type) nil nil)
739                      (make-final-accessor-dfun gf type))
740                  (values initial-dfun nil (initial-dfun-info))))))
741       (set-dfun gf dfun cache info))))
742
743 (defun make-early-accessor (gf type)
744   (let* ((methods (early-gf-methods gf))
745          (slot-name (early-method-standard-accessor-slot-name (car methods))))
746     (ecase type
747       (reader #'(instance-lambda (instance)
748                   (let* ((class (class-of instance))
749                          (class-name (!bootstrap-get-slot 'class class 'name)))
750                     (!bootstrap-get-slot class-name instance slot-name))))
751       (boundp #'(instance-lambda (instance)
752                   (let* ((class (class-of instance))
753                          (class-name (!bootstrap-get-slot 'class class 'name)))
754                     (not (eq +slot-unbound+
755                              (!bootstrap-get-slot class-name
756                                                   instance slot-name))))))
757       (writer #'(instance-lambda (new-value instance)
758                   (let* ((class (class-of instance))
759                          (class-name (!bootstrap-get-slot 'class class 'name)))
760                     (!bootstrap-set-slot class-name instance slot-name new-value)))))))
761
762 (defun initial-dfun (gf args)
763   (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
764     (cond (invalidp)
765           ((and ntype nindex)
766            (dfun-update
767             gf #'make-one-class-accessor-dfun ntype wrappers nindex))
768           ((use-caching-dfun-p gf)
769            (dfun-update gf #'make-caching-dfun))
770           (t
771            (dfun-update
772             gf #'make-checking-dfun
773             ;; nemf is suitable only for caching, have to do this:
774             (cache-miss-values gf args 'checking))))))
775
776 (defun make-final-dfun (gf &optional classes-list)
777   (multiple-value-bind (dfun cache info)
778       (make-final-dfun-internal gf classes-list)
779     (set-dfun gf dfun cache info)))
780
781 (defvar *new-class* nil)
782
783 (defvar *free-hash-tables* (mapcar #'list '(eq equal eql)))
784
785 (defmacro with-hash-table ((table test) &body forms)
786   `(let* ((.free. (assoc ',test *free-hash-tables*))
787           (,table (if (cdr .free.)
788                       (pop (cdr .free.))
789                       (make-hash-table :test ',test))))
790      (multiple-value-prog1
791          (progn ,@forms)
792        (clrhash ,table)
793        (push ,table (cdr .free.)))))
794
795 (defmacro with-eq-hash-table ((table) &body forms)
796   `(with-hash-table (,table eq) ,@forms))
797
798 (defun final-accessor-dfun-type (gf)
799   (let ((methods (if (early-gf-p gf)
800                      (early-gf-methods gf)
801                      (generic-function-methods gf))))
802     (cond ((every (lambda (method)
803                     (if (consp method)
804                         (eq *the-class-standard-reader-method*
805                             (early-method-class method))
806                         (standard-reader-method-p method)))
807                   methods)
808            'reader)
809           ((every (lambda (method)
810                     (if (consp method)
811                         (eq *the-class-standard-boundp-method*
812                             (early-method-class method))
813                         (standard-boundp-method-p method)))
814                   methods)
815            'boundp)
816           ((every (lambda (method)
817                     (if (consp method)
818                         (eq *the-class-standard-writer-method*
819                             (early-method-class method))
820                         (standard-writer-method-p method)))
821                   methods)
822            'writer))))
823
824 (defun make-final-accessor-dfun (gf type &optional classes-list new-class)
825   (with-eq-hash-table (table)
826     (multiple-value-bind (table all-index first second size no-class-slots-p)
827         (make-accessor-table gf type table)
828       (if table
829           (cond ((= size 1)
830                  (let ((w (class-wrapper first)))
831                    (make-one-class-accessor-dfun gf type w all-index)))
832                 ((and (= size 2) (or (integerp all-index) (consp all-index)))
833                  (let ((w0 (class-wrapper first))
834                        (w1 (class-wrapper second)))
835                    (make-two-class-accessor-dfun gf type w0 w1 all-index)))
836                 ((or (integerp all-index) (consp all-index))
837                  (make-final-one-index-accessor-dfun
838                   gf type all-index table))
839                 (no-class-slots-p
840                  (make-final-n-n-accessor-dfun gf type table))
841                 (t
842                  (make-final-caching-dfun gf classes-list new-class)))
843           (make-final-caching-dfun gf classes-list new-class)))))
844
845 (defun make-final-dfun-internal (gf &optional classes-list)
846   (let ((methods (generic-function-methods gf)) type
847         (new-class *new-class*) (*new-class* nil)
848         specls all-same-p)
849     (cond ((null methods)
850            (values
851             #'(instance-lambda (&rest args)
852                 (apply #'no-applicable-method gf args))
853             nil
854             (no-methods-dfun-info)))
855           ((setq type (final-accessor-dfun-type gf))
856            (make-final-accessor-dfun gf type classes-list new-class))
857           ((and (not (and (every (lambda (specl) (eq specl *the-class-t*))
858                                  (setq specls
859                                        (method-specializers (car methods))))
860                           (setq all-same-p
861                                 (every (lambda (method)
862                                          (and (equal specls
863                                                      (method-specializers
864                                                       method))))
865                                        methods))))
866                 (use-constant-value-dfun-p gf))
867            (make-final-constant-value-dfun gf classes-list new-class))
868           ((use-dispatch-dfun-p gf)
869            (make-final-dispatch-dfun gf))
870           ((and all-same-p (not (use-caching-dfun-p gf)))
871            (let ((emf (get-secondary-dispatch-function gf methods nil)))
872              (make-final-checking-dfun gf emf classes-list new-class)))
873           (t
874            (make-final-caching-dfun gf classes-list new-class)))))
875
876 (defun accessor-miss (gf new object dfun-info)
877   (let* ((ostate (type-of dfun-info))
878          (otype (dfun-info-accessor-type dfun-info))
879          oindex ow0 ow1 cache
880          (args (ecase otype
881                  ;; The congruence rules ensure that this is safe
882                  ;; despite not knowing the new type yet.
883                  ((reader boundp) (list object))
884                  (writer (list new object)))))  
885     (dfun-miss (gf args wrappers invalidp nemf ntype nindex)
886
887       ;; The following lexical functions change the state of the
888       ;; dfun to that which is their name. They accept arguments
889       ;; which are the parameters of the new state, and get other
890       ;; information from the lexical variables bound above.
891       (flet ((two-class (index w0 w1)
892                (when (zerop (random 2)) (psetf w0 w1 w1 w0))
893                (dfun-update gf
894                             #'make-two-class-accessor-dfun
895                             ntype
896                             w0
897                             w1
898                             index))
899              (one-index (index &optional cache)
900                (dfun-update gf
901                             #'make-one-index-accessor-dfun
902                             ntype
903                             index
904                             cache))
905              (n-n (&optional cache)
906                (if (consp nindex)
907                    (dfun-update gf #'make-checking-dfun nemf)
908                    (dfun-update gf #'make-n-n-accessor-dfun ntype cache)))
909              (caching () ; because cached accessor emfs are much faster
910                          ; for accessors
911                (dfun-update gf #'make-caching-dfun))
912              (do-fill (update-fn)
913                (let ((ncache (fill-cache cache wrappers nindex)))
914                  (unless (eq ncache cache)
915                    (funcall update-fn ncache)))))
916
917         (cond ((null ntype)
918                (caching))
919               ((or invalidp
920                    (null nindex)))
921               ((not (pcl-instance-p object))
922                (caching))
923               ((or (neq ntype otype) (listp wrappers))
924                (caching))
925               (t
926                (ecase ostate
927                  (one-class
928                   (setq oindex (dfun-info-index dfun-info))
929                   (setq ow0 (dfun-info-wrapper0 dfun-info))
930                   (unless (eq ow0 wrappers)
931                     (if (eql nindex oindex)
932                         (two-class nindex ow0 wrappers)
933                         (n-n))))
934                  (two-class
935                   (setq oindex (dfun-info-index dfun-info))
936                   (setq ow0 (dfun-info-wrapper0 dfun-info))
937                   (setq ow1 (dfun-info-wrapper1 dfun-info))
938                   (unless (or (eq ow0 wrappers) (eq ow1 wrappers))
939                     (if (eql nindex oindex)
940                         (one-index nindex)
941                         (n-n))))
942                  (one-index
943                   (setq oindex (dfun-info-index dfun-info))
944                   (setq cache (dfun-info-cache dfun-info))
945                   (if (eql nindex oindex)
946                       (do-fill (lambda (ncache)
947                                  (one-index nindex ncache)))
948                       (n-n)))
949                  (n-n
950                   (setq cache (dfun-info-cache dfun-info))
951                   (if (consp nindex)
952                       (caching)
953                       (do-fill #'n-n))))))))))
954
955 (defun checking-miss (generic-function args dfun-info)
956   (let ((oemf (dfun-info-function dfun-info))
957         (cache (dfun-info-cache dfun-info)))
958     (dfun-miss (generic-function args wrappers invalidp nemf)
959       (cond (invalidp)
960             ((eq oemf nemf)
961              (let ((ncache (fill-cache cache wrappers nil)))
962                (unless (eq ncache cache)
963                  (dfun-update generic-function #'make-checking-dfun
964                               nemf ncache))))
965             (t
966              (dfun-update generic-function #'make-caching-dfun))))))
967
968 (defun caching-miss (generic-function args dfun-info)
969   (let ((ocache (dfun-info-cache dfun-info)))
970     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
971       (cond (invalidp)
972             (t
973              (let ((ncache (fill-cache ocache wrappers emf)))
974                (unless (eq ncache ocache)
975                  (dfun-update generic-function
976                               #'make-caching-dfun ncache))))))))
977
978 (defun constant-value-miss (generic-function args dfun-info)
979   (let ((ocache (dfun-info-cache dfun-info)))
980     (dfun-miss (generic-function args wrappers invalidp emf nil nil t)
981       (cond (invalidp)
982             (t
983              (let* ((function (typecase emf
984                                 (fast-method-call (fast-method-call-function
985                                                    emf))
986                                 (method-call (method-call-function emf))))
987                     (value (method-function-get function :constant-value))
988                     (ncache (fill-cache ocache wrappers value)))
989                (unless (eq ncache ocache)
990                  (dfun-update generic-function
991                               #'make-constant-value-dfun ncache))))))))
992 \f
993 ;;; Given a generic function and a set of arguments to that generic
994 ;;; function, return a mess of values.
995 ;;;
996 ;;;  <function>   The compiled effective method function for this set of
997 ;;;            arguments.
998 ;;;
999 ;;;  <applicable> Sorted list of applicable methods.
1000 ;;;
1001 ;;;  <wrappers>   Is a single wrapper if the generic function has only
1002 ;;;            one key, that is arg-info-nkeys of the arg-info is 1.
1003 ;;;            Otherwise a list of the wrappers of the specialized
1004 ;;;            arguments to the generic function.
1005 ;;;
1006 ;;;            Note that all these wrappers are valid. This function
1007 ;;;            does invalid wrapper traps when it finds an invalid
1008 ;;;            wrapper and then returns the new, valid wrapper.
1009 ;;;
1010 ;;;  <invalidp>   True if any of the specialized arguments had an invalid
1011 ;;;            wrapper, false otherwise.
1012 ;;;
1013 ;;;  <type>       READER or WRITER when the only method that would be run
1014 ;;;            is a standard reader or writer method. To be specific,
1015 ;;;            the value is READER when the method combination is eq to
1016 ;;;            *standard-method-combination*; there are no applicable
1017 ;;;            :before, :after or :around methods; and the most specific
1018 ;;;            primary method is a standard reader method.
1019 ;;;
1020 ;;;  <index>      If <type> is READER or WRITER, and the slot accessed is
1021 ;;;            an :instance slot, this is the index number of that slot
1022 ;;;            in the object argument.
1023 (defun cache-miss-values (gf args state)
1024   (multiple-value-bind (nreq applyp metatypes nkeys arg-info)
1025       (get-generic-fun-info gf)
1026     (declare (ignore nreq applyp nkeys))
1027     (with-dfun-wrappers (args metatypes)
1028       (dfun-wrappers invalid-wrapper-p wrappers classes types)
1029       (error-need-at-least-n-args gf (length metatypes))
1030       (multiple-value-bind (emf methods accessor-type index)
1031           (cache-miss-values-internal
1032            gf arg-info wrappers classes types state)
1033         (values emf methods
1034                 dfun-wrappers
1035                 invalid-wrapper-p
1036                 accessor-type index)))))
1037
1038 (defun cache-miss-values-internal (gf arg-info wrappers classes types state)
1039   (let* ((for-accessor-p (eq state 'accessor))
1040          (for-cache-p (or (eq state 'caching) (eq state 'accessor)))
1041          (cam-std-p (or (null arg-info)
1042                         (gf-info-c-a-m-emf-std-p arg-info))))
1043     (multiple-value-bind (methods all-applicable-and-sorted-p)
1044         (if cam-std-p
1045             (compute-applicable-methods-using-types gf types)
1046             (compute-applicable-methods-using-classes gf classes))
1047       (let ((emf (if (or cam-std-p all-applicable-and-sorted-p)
1048                      (function-funcall (get-secondary-dispatch-function1
1049                                         gf methods types nil (and for-cache-p
1050                                                                   wrappers)
1051                                         all-applicable-and-sorted-p)
1052                                        nil (and for-cache-p wrappers))
1053                      (default-secondary-dispatch-function gf))))
1054         (multiple-value-bind (index accessor-type)
1055             (and for-accessor-p all-applicable-and-sorted-p methods
1056                  (accessor-values gf arg-info classes methods))
1057           (values (if (integerp index) index emf)
1058                   methods accessor-type index))))))
1059
1060 (defun accessor-values (gf arg-info classes methods)
1061   (declare (ignore gf))
1062   (let* ((accessor-type (gf-info-simple-accessor-type arg-info))
1063          (accessor-class (case accessor-type
1064                            ((reader boundp) (car classes))
1065                            (writer (cadr classes)))))
1066     (accessor-values-internal accessor-type accessor-class methods)))
1067
1068 (defun accessor-values1 (gf accessor-type accessor-class)
1069   (let* ((type `(class-eq ,accessor-class))
1070          (types (ecase accessor-type
1071                   ((reader boundp) `(,type))
1072                   (writer `(t ,type))))
1073          (methods (compute-applicable-methods-using-types gf types)))
1074     (accessor-values-internal accessor-type accessor-class methods)))
1075
1076 (defun accessor-values-internal (accessor-type accessor-class methods)
1077   (dolist (meth methods)
1078     (when (if (consp meth)
1079               (early-method-qualifiers meth)
1080               (method-qualifiers meth))
1081       (return-from accessor-values-internal (values nil nil))))
1082   (let* ((meth (car methods))
1083          (early-p (not (eq *boot-state* 'complete)))
1084          (slot-name (when accessor-class
1085                       (if (consp meth)
1086                           (and (early-method-standard-accessor-p meth)
1087                                (early-method-standard-accessor-slot-name meth))
1088                           (and (member *the-class-std-object*
1089                                        (if early-p
1090                                            (early-class-precedence-list
1091                                             accessor-class)
1092                                            (class-precedence-list
1093                                             accessor-class)))
1094                                (if early-p
1095                                    (not (eq *the-class-standard-method*
1096                                             (early-method-class meth)))
1097                                    (standard-accessor-method-p meth))
1098                                (if early-p
1099                                    (early-accessor-method-slot-name meth)
1100                                    (accessor-method-slot-name meth))))))
1101          (slotd (and accessor-class
1102                      (if early-p
1103                          (dolist (slot (early-class-slotds accessor-class) nil)
1104                            (when (eql slot-name
1105                                       (early-slot-definition-name slot))
1106                              (return slot)))
1107                          (find-slot-definition accessor-class slot-name)))))
1108     (when (and slotd
1109                (or early-p
1110                    (slot-accessor-std-p slotd accessor-type)))
1111       (values (if early-p
1112                   (early-slot-definition-location slotd)
1113                   (slot-definition-location slotd))
1114               accessor-type))))
1115
1116 (defun make-accessor-table (gf type &optional table)
1117   (unless table (setq table (make-hash-table :test 'eq)))
1118   (let ((methods (if (early-gf-p gf)
1119                      (early-gf-methods gf)
1120                      (generic-function-methods gf)))
1121         (all-index nil)
1122         (no-class-slots-p t)
1123         (early-p (not (eq *boot-state* 'complete)))
1124         first second (size 0))
1125     (declare (fixnum size))
1126     ;; class -> {(specl slotd)}
1127     (dolist (method methods)
1128       (let* ((specializers (if (consp method)
1129                                (early-method-specializers method t)
1130                                (method-specializers method)))
1131              (specl (ecase type
1132                       ((reader boundp) (car specializers))
1133                       (writer (cadr specializers))))
1134              (specl-cpl (if early-p
1135                             (early-class-precedence-list specl)
1136                             (and (class-finalized-p specl)
1137                                  (class-precedence-list specl))))
1138              (so-p (member *the-class-std-object* specl-cpl))
1139              (slot-name (if (consp method)
1140                             (and (early-method-standard-accessor-p method)
1141                                  (early-method-standard-accessor-slot-name
1142                                   method))
1143                             (accessor-method-slot-name method))))
1144         (when (or (null specl-cpl)
1145                   (member *the-class-structure-object* specl-cpl))
1146           (return-from make-accessor-table nil))
1147         (maphash (lambda (class slotd)
1148                    (let ((cpl (if early-p
1149                                   (early-class-precedence-list class)
1150                                   (class-precedence-list class))))
1151                      (when (memq specl cpl)
1152                        (unless (and (or so-p
1153                                         (member *the-class-std-object* cpl))
1154                                     (or early-p
1155                                         (slot-accessor-std-p slotd type)))
1156                          (return-from make-accessor-table nil))
1157                        (push (cons specl slotd) (gethash class table)))))
1158                  (gethash slot-name *name->class->slotd-table*))))
1159     (maphash (lambda (class specl+slotd-list)
1160                (dolist (sclass (if early-p
1161                                    (early-class-precedence-list class)
1162                                    (class-precedence-list class))
1163                                (error "This can't happen."))
1164                  (let ((a (assq sclass specl+slotd-list)))
1165                    (when a
1166                      (let* ((slotd (cdr a))
1167                             (index (if early-p
1168                                        (early-slot-definition-location slotd)
1169                                        (slot-definition-location slotd))))
1170                        (unless index (return-from make-accessor-table nil))
1171                        (setf (gethash class table) index)
1172                        (when (consp index) (setq no-class-slots-p nil))
1173                        (setq all-index (if (or (null all-index)
1174                                                (eql all-index index))
1175                                            index t))
1176                        (incf size)
1177                        (cond ((= size 1) (setq first class))
1178                              ((= size 2) (setq second class)))
1179                        (return nil))))))
1180              table)
1181     (values table all-index first second size no-class-slots-p)))
1182
1183 (defun compute-applicable-methods-using-types (generic-function types)
1184   (let ((definite-p t) (possibly-applicable-methods nil))
1185     (dolist (method (if (early-gf-p generic-function)
1186                         (early-gf-methods generic-function)
1187                         (generic-function-methods generic-function)))
1188       (let ((specls (if (consp method)
1189                         (early-method-specializers method t)
1190                         (method-specializers method)))
1191             (types types)
1192             (possibly-applicable-p t) (applicable-p t))
1193         (dolist (specl specls)
1194           (multiple-value-bind (specl-applicable-p specl-possibly-applicable-p)
1195               (specializer-applicable-using-type-p specl (pop types))
1196             (unless specl-applicable-p
1197               (setq applicable-p nil))
1198             (unless specl-possibly-applicable-p
1199               (setq possibly-applicable-p nil)
1200               (return nil))))
1201         (when possibly-applicable-p
1202           (unless applicable-p (setq definite-p nil))
1203           (push method possibly-applicable-methods))))
1204     (let ((precedence (arg-info-precedence (if (early-gf-p generic-function)
1205                                                (early-gf-arg-info
1206                                                 generic-function)
1207                                                (gf-arg-info
1208                                                 generic-function)))))
1209       (values (sort-applicable-methods precedence
1210                                        (nreverse possibly-applicable-methods)
1211                                        types)
1212               definite-p))))
1213
1214 (defun sort-applicable-methods (precedence methods types)
1215   (sort-methods methods
1216                 precedence
1217                 (lambda (class1 class2 index)
1218                   (let* ((class (type-class (nth index types)))
1219                          (cpl (if (eq *boot-state* 'complete)
1220                                   (class-precedence-list class)
1221                                   (early-class-precedence-list class))))
1222                     (if (memq class2 (memq class1 cpl))
1223                         class1 class2)))))
1224
1225 (defun sort-methods (methods precedence compare-classes-function)
1226   (flet ((sorter (method1 method2)
1227            (dolist (index precedence)
1228              (let* ((specl1 (nth index (if (listp method1)
1229                                            (early-method-specializers method1
1230                                                                       t)
1231                                            (method-specializers method1))))
1232                     (specl2 (nth index (if (listp method2)
1233                                            (early-method-specializers method2
1234                                                                       t)
1235                                            (method-specializers method2))))
1236                     (order (order-specializers
1237                              specl1 specl2 index compare-classes-function)))
1238                (when order
1239                  (return-from sorter (eq order specl1)))))))
1240     (stable-sort methods #'sorter)))
1241
1242 (defun order-specializers (specl1 specl2 index compare-classes-function)
1243   (let ((type1 (if (eq *boot-state* 'complete)
1244                    (specializer-type specl1)
1245                    (!bootstrap-get-slot 'specializer specl1 'type)))
1246         (type2 (if (eq *boot-state* 'complete)
1247                    (specializer-type specl2)
1248                    (!bootstrap-get-slot 'specializer specl2 'type))))
1249     (cond ((eq specl1 specl2)
1250            nil)
1251           ((atom type1)
1252            specl2)
1253           ((atom type2)
1254            specl1)
1255           (t
1256            (case (car type1)
1257              (class    (case (car type2)
1258                          (class (funcall compare-classes-function
1259                                          specl1 specl2 index))
1260                          (t specl2)))
1261              (prototype (case (car type2)
1262                          (class (funcall compare-classes-function
1263                                          specl1 specl2 index))
1264                          (t specl2)))
1265              (class-eq (case (car type2)
1266                          (eql specl2)
1267                          (class-eq nil)
1268                          (class type1)))
1269              (eql      (case (car type2)
1270                          (eql nil)
1271                          (t specl1))))))))
1272
1273 (defun map-all-orders (methods precedence function)
1274   (let ((choices nil))
1275     (flet ((compare-classes-function (class1 class2 index)
1276              (declare (ignore index))
1277              (let ((choice nil))
1278                (dolist (c choices nil)
1279                  (when (or (and (eq (first c) class1)
1280                                 (eq (second c) class2))
1281                            (and (eq (first c) class2)
1282                                 (eq (second c) class1)))
1283                    (return (setq choice c))))
1284                (unless choice
1285                  (setq choice
1286                        (if (class-might-precede-p class1 class2)
1287                            (if (class-might-precede-p class2 class1)
1288                                (list class1 class2 nil t)
1289                                (list class1 class2 t))
1290                            (if (class-might-precede-p class2 class1)
1291                                (list class2 class1 t)
1292                                (let ((name1 (class-name class1))
1293                                      (name2 (class-name class2)))
1294                                  (if (and name1
1295                                           name2
1296                                           (symbolp name1)
1297                                           (symbolp name2)
1298                                           (string< (symbol-name name1)
1299                                                    (symbol-name name2)))
1300                                      (list class1 class2 t)
1301                                      (list class2 class1 t))))))
1302                  (push choice choices))
1303                (car choice))))
1304       (loop (funcall function
1305                      (sort-methods methods
1306                                    precedence
1307                                    #'compare-classes-function))
1308             (unless (dolist (c choices nil)
1309                       (unless (third c)
1310                         (rotatef (car c) (cadr c))
1311                         (return (setf (third c) t))))
1312               (return nil))))))
1313
1314 (defvar *in-precompute-effective-methods-p* nil)
1315
1316 ;used only in map-all-orders
1317 (defun class-might-precede-p (class1 class2)
1318   (if (not *in-precompute-effective-methods-p*)
1319       (not (member class1 (cdr (class-precedence-list class2))))
1320       (class-can-precede-p class1 class2)))
1321
1322 (defun compute-precedence (lambda-list nreq argument-precedence-order)
1323   (if (null argument-precedence-order)
1324       (let ((list nil))
1325         (dotimes-fixnum (i nreq list) (push (- (1- nreq) i) list)))
1326       (mapcar (lambda (x) (position x lambda-list))
1327               argument-precedence-order)))
1328
1329 (defun cpl-or-nil (class)
1330   (if (eq *boot-state* 'complete)
1331       (when (class-finalized-p class)
1332         (class-precedence-list class))
1333       (early-class-precedence-list class)))
1334
1335 (defun saut-and (specl type)
1336   (let ((applicable nil)
1337         (possibly-applicable t))
1338     (dolist (type (cdr type))
1339       (multiple-value-bind (appl poss-appl)
1340           (specializer-applicable-using-type-p specl type)
1341         (when appl (return (setq applicable t)))
1342         (unless poss-appl (return (setq possibly-applicable nil)))))
1343     (values applicable possibly-applicable)))
1344
1345 (defun saut-not (specl type)
1346   (let ((ntype (cadr type)))
1347     (values nil
1348             (case (car ntype)
1349               (class      (saut-not-class specl ntype))
1350               (class-eq   (saut-not-class-eq specl ntype))
1351               (prototype  (saut-not-prototype specl ntype))
1352               (eql      (saut-not-eql specl ntype))
1353               (t (error "~S cannot handle the second argument ~S"
1354                         'specializer-applicable-using-type-p type))))))
1355
1356 (defun saut-not-class (specl ntype)
1357   (let* ((class (type-class specl))
1358          (cpl (cpl-or-nil class)))
1359     (not (memq (cadr ntype) cpl))))
1360
1361 (defun saut-not-prototype (specl ntype)
1362   (let* ((class (case (car specl)
1363                   (eql       (class-of (cadr specl)))
1364                   (class-eq  (cadr specl))
1365                   (prototype (cadr specl))
1366                   (class     (cadr specl))))
1367          (cpl (cpl-or-nil class)))
1368     (not (memq (cadr ntype) cpl))))
1369
1370 (defun saut-not-class-eq (specl ntype)
1371   (let ((class (case (car specl)
1372                  (eql      (class-of (cadr specl)))
1373                  (class-eq (cadr specl)))))
1374     (not (eq class (cadr ntype)))))
1375
1376 (defun saut-not-eql (specl ntype)
1377   (case (car specl)
1378     (eql (not (eql (cadr specl) (cadr ntype))))
1379     (t   t)))
1380
1381 (defun class-applicable-using-class-p (specl type)
1382   (let ((pred (memq specl (cpl-or-nil type))))
1383     (values pred
1384             (or pred
1385                 (if (not *in-precompute-effective-methods-p*)
1386                     ;; classes might get common subclass
1387                     (superclasses-compatible-p specl type)
1388                     ;; worry only about existing classes
1389                     (classes-have-common-subclass-p specl type))))))
1390
1391 (defun classes-have-common-subclass-p (class1 class2)
1392   (or (eq class1 class2)
1393       (let ((class1-subs (class-direct-subclasses class1)))
1394         (or (memq class2 class1-subs)
1395             (dolist (class1-sub class1-subs nil)
1396               (when (classes-have-common-subclass-p class1-sub class2)
1397                 (return t)))))))
1398
1399 (defun saut-class (specl type)
1400   (case (car specl)
1401     (class (class-applicable-using-class-p (cadr specl) (cadr type)))
1402     (t     (values nil (let ((class (type-class specl)))
1403                          (memq (cadr type)
1404                                (cpl-or-nil class)))))))
1405
1406 (defun saut-class-eq (specl type)
1407   (if (eq (car specl) 'eql)
1408       (values nil (eq (class-of (cadr specl)) (cadr type)))
1409       (let ((pred (case (car specl)
1410                     (class-eq
1411                      (eq (cadr specl) (cadr type)))
1412                     (class
1413                      (or (eq (cadr specl) (cadr type))
1414                          (memq (cadr specl)
1415                                (if (eq *boot-state* 'complete)
1416                                    (class-precedence-list (cadr type))
1417                                    (early-class-precedence-list
1418                                     (cadr type)))))))))
1419         (values pred pred))))
1420
1421 (defun saut-prototype (specl type)
1422   (declare (ignore specl type))
1423   (values nil nil)) ; XXX original PCL comment: fix this someday
1424
1425 (defun saut-eql (specl type)
1426   (let ((pred (case (car specl)
1427                 (eql    (eql (cadr specl) (cadr type)))
1428                 (class-eq   (eq (cadr specl) (class-of (cadr type))))
1429                 (class      (memq (cadr specl)
1430                                   (let ((class (class-of (cadr type))))
1431                                     (if (eq *boot-state* 'complete)
1432                                         (class-precedence-list class)
1433                                         (early-class-precedence-list
1434                                          class))))))))
1435     (values pred pred)))
1436
1437 (defun specializer-applicable-using-type-p (specl type)
1438   (setq specl (type-from-specializer specl))
1439   (when (eq specl t)
1440     (return-from specializer-applicable-using-type-p (values t t)))
1441   ;; This is used by C-A-M-U-T and GENERATE-DISCRIMINATION-NET-INTERNAL,
1442   ;; and has only what they need.
1443   (if (or (atom type) (eq (car type) t))
1444       (values nil t)
1445       (case (car type)
1446         (and    (saut-and specl type))
1447         (not    (saut-not specl type))
1448         (class      (saut-class specl type))
1449         (prototype  (saut-prototype specl type))
1450         (class-eq   (saut-class-eq specl type))
1451         (eql    (saut-eql specl type))
1452         (t        (error "~S cannot handle the second argument ~S."
1453                            'specializer-applicable-using-type-p
1454                            type)))))
1455
1456 (defun map-all-classes (function &optional (root t))
1457   (let ((braid-p (or (eq *boot-state* 'braid)
1458                      (eq *boot-state* 'complete))))
1459     (labels ((do-class (class)
1460                (mapc #'do-class
1461                      (if braid-p
1462                          (class-direct-subclasses class)
1463                          (early-class-direct-subclasses class)))
1464                (funcall function class)))
1465       (do-class (if (symbolp root)
1466                     (find-class root)
1467                     root)))))
1468 \f
1469 ;;; NOTE: We are assuming a restriction on user code that the method
1470 ;;;       combination must not change once it is connected to the
1471 ;;;       generic function.
1472 ;;;
1473 ;;;       This has to be legal, because otherwise any kind of method
1474 ;;;       lookup caching couldn't work. See this by saying that this
1475 ;;;       cache, is just a backing cache for the fast cache. If that
1476 ;;;       cache is legal, this one must be too.
1477 ;;;
1478 ;;; Don't clear this table!
1479 (defvar *effective-method-table* (make-hash-table :test 'eq))
1480
1481 (defun get-secondary-dispatch-function (gf methods types &optional
1482                                                          method-alist wrappers)
1483   (function-funcall (get-secondary-dispatch-function1
1484                      gf methods types
1485                      (not (null method-alist))
1486                      (not (null wrappers))
1487                      (not (methods-contain-eql-specializer-p methods)))
1488                     method-alist wrappers))
1489
1490 (defun get-secondary-dispatch-function1 (gf methods types method-alist-p
1491                                             wrappers-p
1492                                             &optional
1493                                             all-applicable-p
1494                                             (all-sorted-p t)
1495                                             function-p)
1496   (if (null methods)
1497       (if function-p
1498           (lambda (method-alist wrappers)
1499             (declare (ignore method-alist wrappers))
1500             #'(instance-lambda (&rest args)
1501                 (apply #'no-applicable-method gf args)))
1502           (lambda (method-alist wrappers)
1503             (declare (ignore method-alist wrappers))
1504             (lambda (&rest args)
1505               (apply #'no-applicable-method gf args))))
1506       (let* ((key (car methods))
1507              (ht-value (or (gethash key *effective-method-table*)
1508                            (setf (gethash key *effective-method-table*)
1509                                  (cons nil nil)))))
1510         (if (and (null (cdr methods)) all-applicable-p ; the most common case
1511                  (null method-alist-p) wrappers-p (not function-p))
1512             (or (car ht-value)
1513                 (setf (car ht-value)
1514                       (get-secondary-dispatch-function2
1515                        gf methods types method-alist-p wrappers-p
1516                        all-applicable-p all-sorted-p function-p)))
1517             (let ((akey (list methods
1518                               (if all-applicable-p 'all-applicable types)
1519                               method-alist-p wrappers-p function-p)))
1520               (or (cdr (assoc akey (cdr ht-value) :test #'equal))
1521                   (let ((value (get-secondary-dispatch-function2
1522                                 gf methods types method-alist-p wrappers-p
1523                                 all-applicable-p all-sorted-p function-p)))
1524                     (push (cons akey value) (cdr ht-value))
1525                     value)))))))
1526
1527 (defun get-secondary-dispatch-function2 (gf methods types method-alist-p
1528                                             wrappers-p all-applicable-p
1529                                             all-sorted-p function-p)
1530   (if (and all-applicable-p all-sorted-p (not function-p))
1531       (if (eq *boot-state* 'complete)
1532           (let* ((combin (generic-function-method-combination gf))
1533                  (effective (compute-effective-method gf combin methods)))
1534             (make-effective-method-function1 gf effective method-alist-p
1535                                              wrappers-p))
1536           (let ((effective (standard-compute-effective-method gf nil methods)))
1537             (make-effective-method-function1 gf effective method-alist-p
1538                                              wrappers-p)))
1539       (let ((net (generate-discrimination-net
1540                   gf methods types all-sorted-p)))
1541         (compute-secondary-dispatch-function1 gf net function-p))))
1542
1543 (defun get-effective-method-function (gf methods
1544                                          &optional method-alist wrappers)
1545   (function-funcall (get-secondary-dispatch-function1 gf methods nil
1546                                                       (not (null method-alist))
1547                                                       (not (null wrappers))
1548                                                       t)
1549                     method-alist wrappers))
1550
1551 (defun get-effective-method-function1 (gf methods &optional (sorted-p t))
1552   (get-secondary-dispatch-function1 gf methods nil nil nil t sorted-p))
1553
1554 (defun methods-contain-eql-specializer-p (methods)
1555   (and (eq *boot-state* 'complete)
1556        (dolist (method methods nil)
1557          (when (dolist (spec (method-specializers method) nil)
1558                  (when (eql-specializer-p spec) (return t)))
1559            (return t)))))
1560 \f
1561 (defun update-dfun (generic-function &optional dfun cache info)
1562   (let* ((early-p (early-gf-p generic-function))
1563          (gf-name (if early-p
1564                       (!early-gf-name generic-function)
1565                       (generic-function-name generic-function))))
1566     (set-dfun generic-function dfun cache info)
1567     (let ((dfun (if early-p
1568                     (or dfun (make-initial-dfun generic-function))
1569                     (compute-discriminating-function generic-function))))
1570       (set-funcallable-instance-function generic-function dfun)
1571       (set-fun-name generic-function gf-name)
1572       dfun)))
1573 \f
1574 (defvar *dfun-count* nil)
1575 (defvar *dfun-list* nil)
1576 (defvar *minimum-cache-size-to-list*)
1577
1578 ;;; These functions aren't used in SBCL, or documented anywhere that
1579 ;;; I'm aware of, but they look like they might be useful for
1580 ;;; debugging or performance tweaking or something, so I've just
1581 ;;; commented them out instead of deleting them. -- WHN 2001-03-28
1582 #|
1583 (defun list-dfun (gf)
1584   (let* ((sym (type-of (gf-dfun-info gf)))
1585          (a (assq sym *dfun-list*)))
1586     (unless a
1587       (push (setq a (list sym)) *dfun-list*))
1588     (push (generic-function-name gf) (cdr a))))
1589
1590 (defun list-all-dfuns ()
1591   (setq *dfun-list* nil)
1592   (map-all-generic-functions #'list-dfun)
1593   *dfun-list*)
1594
1595 (defun list-large-cache (gf)
1596   (let* ((sym (type-of (gf-dfun-info gf)))
1597          (cache (gf-dfun-cache gf)))
1598     (when cache
1599       (let ((size (cache-size cache)))
1600         (when (>= size *minimum-cache-size-to-list*)
1601           (let ((a (assoc size *dfun-list*)))
1602             (unless a
1603               (push (setq a (list size)) *dfun-list*))
1604             (push (let ((name (generic-function-name gf)))
1605                     (if (eq sym 'caching) name (list name sym)))
1606                   (cdr a))))))))
1607
1608 (defun list-large-caches (&optional (*minimum-cache-size-to-list* 130))
1609   (setq *dfun-list* nil)
1610   (map-all-generic-functions #'list-large-cache)
1611   (setq *dfun-list* (sort *dfun-list* #'< :key #'car))
1612   (mapc #'print *dfun-list*)
1613   (values))
1614
1615 (defun count-dfun (gf)
1616   (let* ((sym (type-of (gf-dfun-info gf)))
1617          (cache (gf-dfun-cache gf))
1618          (a (assq sym *dfun-count*)))
1619     (unless a
1620       (push (setq a (list sym 0 nil)) *dfun-count*))
1621     (incf (cadr a))
1622     (when cache
1623       (let* ((size (cache-size cache))
1624              (b (assoc size (third a))))
1625         (unless b
1626           (push (setq b (cons size 0)) (third a)))
1627         (incf (cdr b))))))
1628
1629 (defun count-all-dfuns ()
1630   (setq *dfun-count* (mapcar (lambda (type) (list type 0 nil))
1631                              '(ONE-CLASS TWO-CLASS DEFAULT-METHOD-ONLY
1632                                ONE-INDEX N-N CHECKING CACHING
1633                                DISPATCH)))
1634   (map-all-generic-functions #'count-dfun)
1635   (mapc (lambda (type+count+sizes)
1636           (setf (third type+count+sizes)
1637                 (sort (third type+count+sizes) #'< :key #'car)))
1638         *dfun-count*)
1639   (mapc (lambda (type+count+sizes)
1640           (format t "~&There are ~W dfuns of type ~S."
1641                   (cadr type+count+sizes) (car type+count+sizes))
1642           (format t "~%   ~S~%" (caddr type+count+sizes)))
1643         *dfun-count*)
1644   (values))
1645 |#
1646
1647 (defun gfs-of-type (type)
1648   (unless (consp type) (setq type (list type)))
1649   (let ((gf-list nil))
1650     (map-all-generic-functions (lambda (gf)
1651                                  (when (memq (type-of (gf-dfun-info gf))
1652                                              type)
1653                                    (push gf gf-list))))
1654     gf-list))