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