d3308334e83b83991d423bf9e027e8654938e6e9
[sbcl.git] / src / pcl / ctor.lisp
1 ;;;; This file contains the optimization machinery for make-instance.
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5
6 ;;;; This software is derived from software originally released by
7 ;;;; Gerd Moellmann.  Copyright and release statements follow.  Later
8 ;;;; modifications to the software are in the public domain and are
9 ;;;; provided with absolutely no warranty.  See the COPYING and
10 ;;;; CREDITS files for more information.
11
12 ;;; Copyright (C) 2002 Gerd Moellmann <gerd.moellmann@t-online.de>
13 ;;; All rights reserved.
14 ;;;
15 ;;; Redistribution and use in source and binary forms, with or without
16 ;;; modification, are permitted provided that the following conditions
17 ;;; are met:
18 ;;;
19 ;;; 1. Redistributions of source code must retain the above copyright
20 ;;;    notice, this list of conditions and the following disclaimer.
21 ;;; 2. Redistributions in binary form must reproduce the above copyright
22 ;;;    notice, this list of conditions and the following disclaimer in the
23 ;;;    documentation and/or other materials provided with the distribution.
24 ;;; 3. The name of the author may not be used to endorse or promote
25 ;;;    products derived from this software without specific prior written
26 ;;;    permission.
27 ;;;
28 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
29 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
30 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 ;;; ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
32 ;;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
34 ;;; OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35 ;;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
38 ;;; USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
39 ;;; DAMAGE.
40
41 ;;; ***************
42 ;;; Overview  *****
43 ;;; ***************
44 ;;;
45 ;;; Compiler macro for MAKE-INSTANCE, and load-time generation of
46 ;;; optimized instance constructor functions.
47 ;;;
48 ;;; ********************
49 ;;; Entry Points  ******
50 ;;; ********************
51 ;;;
52 ;;; UPDATE-CTORS must be called when methods are added/removed,
53 ;;; classes are changed, etc., which affect instance creation.
54 ;;;
55 ;;; PRECOMPILE-CTORS can be called to precompile constructor functions
56 ;;; for classes whose definitions are known at the time the function
57 ;;; is called.
58
59 (in-package "SB-PCL")
60
61 ;;; ******************
62 ;;; Utilities  *******
63 ;;; ******************
64
65 (defun quote-plist-keys (plist)
66   (loop for (key . more) on plist by #'cddr
67         if (null more) do
68           (error "Not a property list: ~S" plist)
69         else
70           collect `(quote ,key)
71           and collect (car more)))
72
73 (defun plist-keys (plist &key test)
74   (loop for (key . more) on plist by #'cddr
75         if (null more) do
76           (error "Not a property list: ~S" plist)
77         else if (or (null test) (funcall test key))
78           collect key))
79
80 (defun plist-values (plist &key test)
81   (loop for (key . more) on plist by #'cddr
82         if (null more) do
83           (error "Not a property list: ~S" plist)
84         else if (or (null test) (funcall test (car more)))
85           collect (car more)))
86
87 (defun constant-class-arg-p (form)
88   (and (constantp form)
89        (let ((constant (constant-form-value form)))
90          (or (and (symbolp constant)
91                   (not (null (symbol-package constant))))
92              (classp form)))))
93
94 (defun constant-symbol-p (form)
95   (and (constantp form)
96        (let ((constant (constant-form-value form)))
97          (and (symbolp constant)
98               (not (null (symbol-package constant)))))))
99
100 ;;; somewhat akin to DEFAULT-INITARGS (SLOT-CLASS T T), but just
101 ;;; collecting the defaulted initargs for the call.
102 (defun ctor-default-initkeys (supplied-initargs class-default-initargs)
103   (loop for (key) in class-default-initargs
104         when (eq (getf supplied-initargs key '.not-there.) '.not-there.)
105         collect key))
106 \f
107 ;;; *****************
108 ;;; CTORS   *********
109 ;;; *****************
110 ;;;
111 ;;; Ctors are funcallable instances whose initial function is a
112 ;;; function computing an optimized constructor function when called.
113 ;;; When the optimized function is computed, the function of the
114 ;;; funcallable instance is set to it.
115 ;;;
116 (!defstruct-with-alternate-metaclass ctor
117   :slot-names (function-name class-or-name class initargs safe-p)
118   :boa-constructor %make-ctor
119   :superclass-name function
120   :metaclass-name static-classoid
121   :metaclass-constructor make-static-classoid
122   :dd-type funcallable-structure
123   :runtime-type-checks-p nil)
124
125 ;;; List of all defined ctors.
126 (defvar *all-ctors* ())
127
128 (defun make-ctor-parameter-list (ctor)
129   (plist-values (ctor-initargs ctor) :test (complement #'constantp)))
130
131 ;;; Reset CTOR to use a default function that will compute an
132 ;;; optimized constructor function when called.
133 (defun install-initial-constructor (ctor &key force-p)
134   (when (or force-p (ctor-class ctor))
135     (setf (ctor-class ctor) nil)
136     (setf (funcallable-instance-fun ctor)
137           #'(lambda (&rest args)
138               (install-optimized-constructor ctor)
139               (apply ctor args)))
140     (setf (%funcallable-instance-info ctor 1)
141           (ctor-function-name ctor))))
142
143 (defun make-ctor-function-name (class-name initargs safe-code-p)
144   (list* 'ctor class-name safe-code-p initargs))
145
146 ;;; Keep this a separate function for testing.
147 (defun ensure-ctor (function-name class-name initargs safe-code-p)
148   (unless (fboundp function-name)
149     (make-ctor function-name class-name initargs safe-code-p)))
150
151 ;;; Keep this a separate function for testing.
152 (defun make-ctor (function-name class-name initargs safe-p)
153   (without-package-locks ; for (setf symbol-function)
154    (let ((ctor (%make-ctor function-name class-name nil initargs safe-p)))
155      (push ctor *all-ctors*)
156      (setf (fdefinition function-name) ctor)
157      (install-initial-constructor ctor :force-p t)
158      ctor)))
159 \f
160 ;;; *****************
161 ;;; Inline CTOR cache
162 ;;; *****************
163 ;;;
164 ;;; The cache starts out as a list of CTORs, sorted with the most recently
165 ;;; used CTORs near the head. If it expands too much, we switch to a vector
166 ;;; with a simple hashing scheme.
167
168 ;;; Find CTOR for KEY (which is a class or class name) in a list. If the CTOR
169 ;;; is in the list but not one of the 4 first ones, return a new list with the
170 ;;; found CTOR at the head. Thread-safe: the new list shares structure with
171 ;;; the old, but is not desctructively modified. Returning the old list for
172 ;;; hits close to the head reduces ping-ponging with multiple threads seeking
173 ;;; the same list.
174 (defun find-ctor (key list)
175   (labels ((walk (tail from-head depth)
176              (declare (fixnum depth))
177              (if tail
178                  (let ((ctor (car tail)))
179                    (if (eq (ctor-class-or-name ctor) key)
180                        (if (> depth 3)
181                            (values ctor
182                                    (nconc (list ctor) (nreverse from-head) (cdr tail)))
183                            (values ctor
184                                    list))
185                        (walk (cdr tail)
186                              (cons ctor from-head)
187                              (logand #xf (1+ depth)))))
188                  (values nil list))))
189     (walk list nil 0)))
190
191 (declaim (inline sxhash-symbol-or-class))
192 (defun sxhash-symbol-or-class (x)
193   (cond ((symbolp x) (sxhash x))
194         ((std-instance-p x) (std-instance-hash x))
195         ((fsc-instance-p x) (fsc-instance-hash x))
196         (t
197          (bug "Something strange where symbol or class expected."))))
198
199 ;;; Max number of CTORs kept in an inline list cache. Once this is
200 ;;; exceeded we switch to a table.
201 (defconstant +ctor-list-max-size+ 12)
202 ;;; Max table size for CTOR cache. If the table fills up at this size
203 ;;; we keep the same size and drop 50% of the old entries.
204 (defconstant +ctor-table-max-size+ (expt 2 8))
205 ;;; Even if there is space in the cache, if we cannot fit a new entry
206 ;;; with max this number of collisions we expand the table (if possible)
207 ;;; and rehash.
208 (defconstant +ctor-table-max-probe-depth+ 5)
209
210 (defun make-ctor-table (size)
211   (declare (index size))
212   (let ((real-size (power-of-two-ceiling size)))
213     (if (< real-size +ctor-table-max-size+)
214         (values (make-array real-size :initial-element nil) nil)
215         (values (make-array +ctor-table-max-size+ :initial-element nil) t))))
216
217 (declaim (inline mix-ctor-hash))
218 (defun mix-ctor-hash (hash base)
219   (logand most-positive-fixnum (+ hash base 1)))
220
221 (defun put-ctor (ctor table)
222   (cond ((try-put-ctor ctor table)
223          (values ctor table))
224         (t
225          (expand-ctor-table ctor table))))
226
227 ;;; Thread-safe: if two threads write to the same index in parallel, the other
228 ;;; result is just lost. This is not an issue as the CTORs are used as their
229 ;;; own keys. If both were EQ, we're good. If non-EQ, the next time the other
230 ;;; one is needed we just cache it again -- hopefully not getting stomped on
231 ;;; that time.
232 (defun try-put-ctor (ctor table)
233   (declare (simple-vector table) (optimize speed))
234   (let* ((class (ctor-class-or-name ctor))
235          (base (sxhash-symbol-or-class class))
236          (hash base)
237          (mask (1- (length table))))
238     (declare (fixnum base hash mask))
239     (loop repeat +ctor-table-max-probe-depth+
240           do (let* ((index (logand mask hash))
241                     (old (aref table index)))
242                (cond ((and old (neq class (ctor-class-or-name old)))
243                       (setf hash (mix-ctor-hash hash base)))
244                      (t
245                       (setf (aref table index) ctor)
246                       (return-from try-put-ctor t)))))
247     ;; Didn't fit, must expand
248     nil))
249
250 (defun get-ctor (class table)
251   (declare (simple-vector table) (optimize speed))
252   (let* ((base (sxhash-symbol-or-class class))
253          (hash base)
254          (mask (1- (length table))))
255     (declare (fixnum base hash mask))
256     (loop repeat +ctor-table-max-probe-depth+
257           do (let* ((index (logand mask hash))
258                     (old (aref table index)))
259                (if (and old (eq class (ctor-class-or-name old)))
260                    (return-from get-ctor old)
261                    (setf hash (mix-ctor-hash hash base)))))
262     ;; Nothing.
263     nil))
264
265 ;;; Thread safe: the old table is read, but if another thread mutates
266 ;;; it while we're reading we still get a sane result -- either the old
267 ;;; or the new entry. The new table is locally allocated, so that's ok
268 ;;; too.
269 (defun expand-ctor-table (ctor old)
270   (declare (simple-vector old))
271   (let* ((old-size (length old))
272          (new-size (* 2 old-size))
273          (drop-random-entries nil))
274     (tagbody
275      :again
276        (multiple-value-bind (new max-size-p) (make-ctor-table new-size)
277          (let ((action (if drop-random-entries
278                            ;; Same logic as in method caches -- see comment
279                            ;; there.
280                            (randomly-punting-lambda (old-ctor)
281                              (try-put-ctor old-ctor new))
282                            (lambda (old-ctor)
283                              (unless (try-put-ctor old-ctor new)
284                                (if max-size-p
285                                    (setf drop-random-entries t)
286                                    (setf new-size (* 2 new-size)))
287                                (go :again))))))
288            (aver (try-put-ctor ctor new))
289            (dotimes (i old-size)
290              (let ((old-ctor (aref old i)))
291                (when old-ctor
292                  (funcall action old-ctor))))
293            (return-from expand-ctor-table (values ctor new)))))))
294
295 (defun ctor-list-to-table (list)
296   (let ((table (make-ctor-table (length list))))
297     (dolist (ctor list)
298       (setf table (nth-value 1 (put-ctor ctor table))))
299     table))
300
301 (defun ctor-for-caching (class-name initargs safe-code-p)
302   (let ((name (make-ctor-function-name class-name initargs safe-code-p)))
303     (or (ensure-ctor name class-name initargs safe-code-p)
304         (fdefinition name))))
305
306 (defun ensure-cached-ctor (class-name store initargs safe-code-p)
307   (if (listp store)
308       (multiple-value-bind (ctor list) (find-ctor class-name store)
309         (if ctor
310             (values ctor list)
311             (let ((ctor (ctor-for-caching class-name initargs safe-code-p)))
312               (if (< (length list) +ctor-list-max-size+)
313                   (values ctor (cons ctor list))
314                   (values ctor (ctor-list-to-table list))))))
315       (let ((ctor (get-ctor class-name store)))
316         (if ctor
317             (values ctor store)
318             (put-ctor (ctor-for-caching class-name initargs safe-code-p)
319                       store)))))
320 \f
321 ;;; ***********************************************
322 ;;; Compile-Time Expansion of MAKE-INSTANCE *******
323 ;;; ***********************************************
324
325 (defvar *compiling-optimized-constructor* nil)
326
327 (define-compiler-macro make-instance (&whole form &rest args &environment env)
328   (declare (ignore args))
329   ;; Compiling an optimized constructor for a non-standard class means compiling a
330   ;; lambda with (MAKE-INSTANCE #<SOME-CLASS X> ...) in it -- need
331   ;; to make sure we don't recurse there.
332   (or (unless *compiling-optimized-constructor*
333         (make-instance->constructor-call form (safe-code-p env)))
334       form))
335
336 (defun make-instance->constructor-call (form safe-code-p)
337   (destructuring-bind (class-arg &rest args) (cdr form)
338     (flet (;;
339            ;; Return the name of parameter number I of a constructor
340            ;; function.
341            (parameter-name (i)
342              (let ((ps #(.p0. .p1. .p2. .p3. .p4. .p5.)))
343                (if (array-in-bounds-p ps i)
344                    (aref ps i)
345                    (format-symbol *pcl-package* ".P~D." i))))
346            ;; Check if CLASS-ARG is a constant symbol.  Give up if
347            ;; not.
348            (constant-class-p ()
349              (and class-arg (constant-class-arg-p class-arg)))
350            ;; Check if ARGS are suitable for an optimized constructor.
351            ;; Return NIL from the outer function if not.
352            (check-args ()
353              (loop for (key . more) on args by #'cddr do
354                       (when (or (null more)
355                                 (not (constant-symbol-p key))
356                                 (eq :allow-other-keys (constant-form-value key)))
357                         (return-from make-instance->constructor-call nil)))))
358       (check-args)
359       ;; Collect a plist of initargs and constant values/parameter names
360       ;; in INITARGS.  Collect non-constant initialization forms in
361       ;; VALUE-FORMS.
362       (multiple-value-bind (initargs value-forms)
363           (loop for (key value) on args by #'cddr and i from 0
364                 collect (constant-form-value key) into initargs
365                 if (constantp value)
366                 collect value into initargs
367                 else
368                 collect (parameter-name i) into initargs
369                 and collect value into value-forms
370                 finally
371                 (return (values initargs value-forms)))
372         (if (constant-class-p)
373             (let* ((class-or-name (constant-form-value class-arg))
374                    (function-name (make-ctor-function-name class-or-name initargs
375                                                            safe-code-p)))
376               ;; Prevent compiler warnings for calling the ctor.
377               (proclaim-as-fun-name function-name)
378               (note-name-defined function-name :function)
379               (when (eq (info :function :where-from function-name) :assumed)
380                 (setf (info :function :where-from function-name) :defined)
381                 (when (info :function :assumed-type function-name)
382                   (setf (info :function :assumed-type function-name) nil)))
383               ;; Return code constructing a ctor at load time, which, when
384               ;; called, will set its funcallable instance function to an
385               ;; optimized constructor function.
386               `(locally
387                    (declare (disable-package-locks ,function-name))
388                  (let ((.x. (load-time-value
389                              (ensure-ctor ',function-name ',class-or-name ',initargs
390                                           ',safe-code-p))))
391                    (declare (ignore .x.))
392                    ;; ??? check if this is worth it.
393                    (declare
394                     (ftype (or (function ,(make-list (length value-forms)
395                                                      :initial-element t)
396                                          t)
397                                (function (&rest t) t))
398                            ,function-name))
399                    (funcall (function ,function-name) ,@value-forms))))
400             (when class-arg
401               ;; Build an inline cache: a CONS, with the actual cache in the CDR.
402               `(locally (declare (disable-package-locks .cache. .class-arg. .store. .fun.
403                                                         make-instance))
404                  (let* ((.cache. (load-time-value (cons 'ctor-cache nil)))
405                         (.store. (cdr .cache.))
406                         (.class-arg. ,class-arg))
407                    (multiple-value-bind (.fun. .new-store.)
408                        (ensure-cached-ctor .class-arg. .store. ',initargs ',safe-code-p)
409                      ;; Thread safe: if multiple threads hit this in paralle, the update
410                      ;; from the other one is just lost -- no harm done, except for the
411                      ;; need to redo the work next time.
412                      (unless (eq .store. .new-store.)
413                        (setf (cdr .cache.) .new-store.))
414                      (funcall (truly-the function .fun.) ,@value-forms))))))))))
415 \f
416 ;;; **************************************************
417 ;;; Load-Time Constructor Function Generation  *******
418 ;;; **************************************************
419
420 ;;; The system-supplied primary INITIALIZE-INSTANCE and
421 ;;; SHARED-INITIALIZE methods.  One cannot initialize these variables
422 ;;; to the right values here because said functions don't exist yet
423 ;;; when this file is first loaded.
424 (defvar *the-system-ii-method* nil)
425 (defvar *the-system-si-method* nil)
426
427 (defun install-optimized-constructor (ctor)
428   (with-world-lock ()
429     (let* ((class-or-name (ctor-class-or-name ctor))
430            (class (if (symbolp class-or-name)
431                       (find-class class-or-name)
432                       class-or-name)))
433       (unless (class-finalized-p class)
434         (finalize-inheritance class))
435       ;; We can have a class with an invalid layout here.  Such a class
436       ;; cannot have a LAYOUT-INVALID of (:FLUSH ...) or (:OBSOLETE
437       ;; ...), because part of the deal is that those only happen from
438       ;; FORCE-CACHE-FLUSHES, which create a new valid wrapper for the
439       ;; class.  An invalid layout of T needs to be flushed, however.
440       (when (eq (layout-invalid (class-wrapper class)) t)
441         (%force-cache-flushes class))
442       (setf (ctor-class ctor) class)
443       (pushnew ctor (plist-value class 'ctors) :test #'eq)
444       (setf (funcallable-instance-fun ctor)
445             (multiple-value-bind (form locations names)
446                 (constructor-function-form ctor)
447               (apply
448                (let ((*compiling-optimized-constructor* t))
449                  (compile nil `(lambda ,names ,form)))
450                locations))))))
451
452 (defun constructor-function-form (ctor)
453   (let* ((class (ctor-class ctor))
454          (proto (class-prototype class))
455          (make-instance-methods
456           (compute-applicable-methods #'make-instance (list class)))
457          (allocate-instance-methods
458           (compute-applicable-methods #'allocate-instance (list class)))
459          ;; I stared at this in confusion for a while, thinking
460          ;; carefully about the possibility of the class prototype not
461          ;; being of sufficient discrimiating power, given the
462          ;; possibility of EQL-specialized methods on
463          ;; INITIALIZE-INSTANCE or SHARED-INITIALIZE.  However, given
464          ;; that this is a constructor optimization, the user doesn't
465          ;; yet have the instance to create a method with such an EQL
466          ;; specializer.
467          ;;
468          ;; There remains the (theoretical) possibility of someone
469          ;; coming along with code of the form
470          ;;
471          ;; (defmethod initialize-instance :before ((o foo) ...)
472          ;;   (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
473          ;;
474          ;; but probably we can afford not to worry about this too
475          ;; much for now.  -- CSR, 2004-07-12
476          (ii-methods
477           (compute-applicable-methods #'initialize-instance (list proto)))
478          (si-methods
479           (compute-applicable-methods #'shared-initialize (list proto t)))
480          (setf-svuc-slots-methods
481           (loop for slot in (class-slots class)
482                 collect (compute-applicable-methods
483                          #'(setf slot-value-using-class)
484                          (list nil class proto slot))))
485          (sbuc-slots-methods
486           (loop for slot in (class-slots class)
487                 collect (compute-applicable-methods
488                          #'slot-boundp-using-class
489                          (list class proto slot)))))
490     ;; Cannot initialize these variables earlier because the generic
491     ;; functions don't exist when PCL is built.
492     (when (null *the-system-si-method*)
493       (setq *the-system-si-method*
494             (find-method #'shared-initialize
495                          () (list *the-class-slot-object* *the-class-t*)))
496       (setq *the-system-ii-method*
497             (find-method #'initialize-instance
498                          () (list *the-class-slot-object*))))
499     ;; Note that when there are user-defined applicable methods on
500     ;; MAKE-INSTANCE and/or ALLOCATE-INSTANCE, these will show up
501     ;; together with the system-defined ones in what
502     ;; COMPUTE-APPLICABLE-METHODS returns.
503     (let ((maybe-invalid-initargs
504            (check-initargs-1
505             class
506             (append
507              (ctor-default-initkeys
508               (ctor-initargs ctor) (class-default-initargs class))
509              (plist-keys (ctor-initargs ctor)))
510             (append ii-methods si-methods) nil nil))
511           (custom-make-instance
512            (not (null (cdr make-instance-methods)))))
513       (if (and (not (structure-class-p class))
514                (not (condition-class-p class))
515                (not custom-make-instance)
516                (null (cdr allocate-instance-methods))
517                (every (lambda (x)
518                         (member (slot-definition-allocation x)
519                                 '(:instance :class)))
520                       (class-slots class))
521                (not maybe-invalid-initargs)
522                (not (around-or-nonstandard-primary-method-p
523                      ii-methods *the-system-ii-method*))
524                (not (around-or-nonstandard-primary-method-p
525                      si-methods *the-system-si-method*))
526                ;; the instance structure protocol goes through
527                ;; slot-value(-using-class) and friends (actually just
528                ;; (SETF SLOT-VALUE-USING-CLASS) and
529                ;; SLOT-BOUNDP-USING-CLASS), so if there are non-standard
530                ;; applicable methods we can't shortcircuit them.
531                (every (lambda (x) (= (length x) 1)) setf-svuc-slots-methods)
532                (every (lambda (x) (= (length x) 1)) sbuc-slots-methods))
533           (optimizing-generator ctor ii-methods si-methods)
534           (fallback-generator ctor ii-methods si-methods
535                               (or maybe-invalid-initargs custom-make-instance))))))
536
537 (defun around-or-nonstandard-primary-method-p
538     (methods &optional standard-method)
539   (loop with primary-checked-p = nil
540         for method in methods
541         as qualifiers = (if (consp method)
542                             (early-method-qualifiers method)
543                             (safe-method-qualifiers method))
544         when (or (eq :around (car qualifiers))
545                  (and (null qualifiers)
546                       (not primary-checked-p)
547                       (not (null standard-method))
548                       (not (eq standard-method method))))
549           return t
550         when (null qualifiers) do
551           (setq primary-checked-p t)))
552
553 (defun fallback-generator (ctor ii-methods si-methods use-make-instance)
554   (declare (ignore ii-methods si-methods))
555   (let ((class (ctor-class ctor))
556         (lambda-list (make-ctor-parameter-list ctor))
557         (initargs (quote-plist-keys (ctor-initargs ctor))))
558     (if use-make-instance
559         `(lambda ,lambda-list
560            (declare #.*optimize-speed*)
561            ;; The CTOR MAKE-INSTANCE optimization checks for
562            ;; *COMPILING-OPTIMIZED-CONSTRUCTOR* which is bound around compilation of
563            ;; the constructor, hence avoiding the possibility of endless recursion.
564            (make-instance ,class ,@initargs))
565         `(lambda ,lambda-list
566            (declare #.*optimize-speed*)
567            (fast-make-instance ,class ,@initargs)))))
568
569 ;;; Not as good as the real optimizing generator, but faster than going
570 ;;; via MAKE-INSTANCE: 1 GF call less, and no need to check initargs.
571 (defun fast-make-instance (class &rest initargs)
572   (declare #.*optimize-speed*)
573   (declare (dynamic-extent initargs))
574   (let ((.instance. (apply #'allocate-instance class initargs)))
575     (apply #'initialize-instance .instance. initargs)
576     .instance.))
577
578 (defun optimizing-generator (ctor ii-methods si-methods)
579   (multiple-value-bind (locations names body before-method-p)
580       (fake-initialization-emf ctor ii-methods si-methods)
581     (let ((wrapper (class-wrapper (ctor-class ctor))))
582       (values
583        `(lambda ,(make-ctor-parameter-list ctor)
584          (declare #.*optimize-speed*)
585          (block nil
586            (when (layout-invalid ,wrapper)
587              (install-initial-constructor ,ctor)
588              (return (funcall ,ctor ,@(make-ctor-parameter-list ctor))))
589            ,(wrap-in-allocate-forms ctor body before-method-p)))
590        locations
591        names))))
592
593 ;;; Return a form wrapped around BODY that allocates an instance
594 ;;; constructed by CTOR.  BEFORE-METHOD-P set means we have to run
595 ;;; before-methods, in which case we initialize instance slots to
596 ;;; +SLOT-UNBOUND+.  The resulting form binds the local variables
597 ;;; .INSTANCE. to the instance, and .SLOTS. to the instance's slot
598 ;;; vector around BODY.
599 (defun wrap-in-allocate-forms (ctor body before-method-p)
600   (let* ((class (ctor-class ctor))
601          (wrapper (class-wrapper class))
602          (allocation-function (raw-instance-allocator class))
603          (slots-fetcher (slots-fetcher class)))
604     (if (eq allocation-function 'allocate-standard-instance)
605         `(let ((.instance. (%make-standard-instance nil
606                                                     (get-instance-hash-code)))
607                (.slots. (make-array
608                          ,(layout-length wrapper)
609                          ,@(when before-method-p
610                              '(:initial-element +slot-unbound+)))))
611            (setf (std-instance-wrapper .instance.) ,wrapper)
612            (setf (std-instance-slots .instance.) .slots.)
613            ,body
614            .instance.)
615         `(let* ((.instance. (,allocation-function ,wrapper))
616                 (.slots. (,slots-fetcher .instance.)))
617            (declare (ignorable .slots.))
618            ,body
619            .instance.))))
620
621 ;;; Return a form for invoking METHOD with arguments from ARGS.  As
622 ;;; can be seen in METHOD-FUNCTION-FROM-FAST-FUNCTION, method
623 ;;; functions look like (LAMBDA (ARGS NEXT-METHODS) ...).  We could
624 ;;; call fast method functions directly here, but benchmarks show that
625 ;;; there's no speed to gain, so lets avoid the hair here.
626 (defmacro invoke-method (method args)
627   `(funcall ,(method-function method) ,args ()))
628
629 ;;; Return a form that is sort of an effective method comprising all
630 ;;; calls to INITIALIZE-INSTANCE and SHARED-INITIALIZE that would
631 ;;; normally have taken place when calling MAKE-INSTANCE.
632 (defun fake-initialization-emf (ctor ii-methods si-methods)
633   (multiple-value-bind (ii-around ii-before ii-primary ii-after)
634       (standard-sort-methods ii-methods)
635     (declare (ignore ii-primary))
636     (multiple-value-bind (si-around si-before si-primary si-after)
637         (standard-sort-methods si-methods)
638       (declare (ignore si-primary))
639       (aver (and (null ii-around) (null si-around)))
640       (let ((initargs (ctor-initargs ctor)))
641         (multiple-value-bind (locations names bindings vars defaulting-initargs body)
642             (slot-init-forms ctor (or ii-before si-before))
643         (values
644          locations
645          names
646          `(let ,bindings
647            (declare (ignorable ,@vars))
648            (let (,@(when (or ii-before ii-after)
649                      `((.ii-args.
650                         (list .instance. ,@(quote-plist-keys initargs) ,@defaulting-initargs))))
651                  ,@(when (or si-before si-after)
652                      `((.si-args.
653                         (list .instance. t ,@(quote-plist-keys initargs) ,@defaulting-initargs)))))
654             ,@(loop for method in ii-before
655                     collect `(invoke-method ,method .ii-args.))
656             ,@(loop for method in si-before
657                     collect `(invoke-method ,method .si-args.))
658             ,@body
659             ,@(loop for method in si-after
660                     collect `(invoke-method ,method .si-args.))
661             ,@(loop for method in ii-after
662                     collect `(invoke-method ,method .ii-args.))))
663          (or ii-before si-before)))))))
664
665 ;;; Return four values from APPLICABLE-METHODS: around methods, before
666 ;;; methods, the applicable primary method, and applicable after
667 ;;; methods.  Before and after methods are sorted in the order they
668 ;;; must be called.
669 (defun standard-sort-methods (applicable-methods)
670   (loop for method in applicable-methods
671         as qualifiers = (if (consp method)
672                             (early-method-qualifiers method)
673                             (safe-method-qualifiers method))
674         if (null qualifiers)
675           collect method into primary
676         else if (eq :around (car qualifiers))
677           collect method into around
678         else if (eq :after (car qualifiers))
679           collect method into after
680         else if (eq :before (car qualifiers))
681           collect method into before
682         finally
683           (return (values around before (first primary) (reverse after)))))
684
685 (defmacro with-type-checked ((type safe-p) &body body)
686   (if safe-p
687       ;; To handle FUNCTION types reasonable, we use SAFETY 3 and
688       ;; THE instead of e.g. CHECK-TYPE.
689       `(locally
690            (declare (optimize (safety 3)))
691          (the ,type (progn ,@body)))
692       `(progn ,@body)))
693
694 ;;; Return as multiple values bindings for default initialization
695 ;;; arguments, variable names, defaulting initargs and a body for
696 ;;; initializing instance and class slots of an object costructed by
697 ;;; CTOR.  The variable .SLOTS. is assumed to bound to the instance's
698 ;;; slot vector.  BEFORE-METHOD-P T means before-methods will be
699 ;;; called, which means that 1) other code will initialize instance
700 ;;; slots to +SLOT-UNBOUND+ before the before-methods are run, and
701 ;;; that we have to check if these before-methods have set slots.
702 (defun slot-init-forms (ctor before-method-p)
703   (let* ((class (ctor-class ctor))
704          (initargs (ctor-initargs ctor))
705          (initkeys (plist-keys initargs))
706          (safe-p (ctor-safe-p ctor))
707          (slot-vector
708           (make-array (layout-length (class-wrapper class))
709                       :initial-element nil))
710          (class-inits ())
711          (default-inits ())
712          (defaulting-initargs ())
713          (default-initargs (class-default-initargs class))
714          (initarg-locations
715           (compute-initarg-locations
716            class (append initkeys (mapcar #'car default-initargs)))))
717     (labels ((initarg-locations (initarg)
718                (cdr (assoc initarg initarg-locations :test #'eq)))
719              (initializedp (location)
720                (cond
721                  ((consp location)
722                   (assoc location class-inits :test #'eq))
723                  ((integerp location)
724                   (not (null (aref slot-vector location))))
725                  (t (bug "Weird location in ~S" 'slot-init-forms))))
726              (class-init (location kind val type)
727                (aver (consp location))
728                (unless (initializedp location)
729                  (push (list location kind val type) class-inits)))
730              (instance-init (location kind val type)
731                (aver (integerp location))
732                (unless (initializedp location)
733                  (setf (aref slot-vector location) (list kind val type))))
734              (default-init-var-name (i)
735                (let ((ps #(.d0. .d1. .d2. .d3. .d4. .d5.)))
736                  (if (array-in-bounds-p ps i)
737                      (aref ps i)
738                      (format-symbol *pcl-package* ".D~D." i))))
739              (location-var-name (i)
740                (let ((ls #(.l0. .l1. .l2. .l3. .l4. .l5.)))
741                  (if (array-in-bounds-p ls i)
742                      (aref ls i)
743                      (format-symbol *pcl-package* ".L~D." i)))))
744       ;; Loop over supplied initargs and values and record which
745       ;; instance and class slots they initialize.
746       (loop for (key value) on initargs by #'cddr
747             as kind = (if (constantp value) 'constant 'param)
748             as locations = (initarg-locations key)
749             do (loop for (location . type) in locations
750                      do (if (consp location)
751                             (class-init location kind value type)
752                             (instance-init location kind value type))))
753       ;; Loop over default initargs of the class, recording
754       ;; initializations of slots that have not been initialized
755       ;; above.  Default initargs which are not in the supplied
756       ;; initargs are treated as if they were appended to supplied
757       ;; initargs, that is, their values must be evaluated even
758       ;; if not actually used for initializing a slot.
759       (loop for (key initform initfn) in default-initargs and i from 0
760             unless (member key initkeys :test #'eq)
761             do (let* ((kind (if (constantp initform) 'constant 'var))
762                       (init (if (eq kind 'var) initfn initform)))
763                  (ecase kind
764                    (constant
765                     (push (list 'quote key) defaulting-initargs)
766                     (push initform defaulting-initargs))
767                    (var
768                     (push (list 'quote key) defaulting-initargs)
769                     (push (default-init-var-name i) defaulting-initargs)))
770               (when (eq kind 'var)
771                 (let ((init-var (default-init-var-name i)))
772                   (setq init init-var)
773                   (push (cons init-var initfn) default-inits)))
774               (loop for (location . type) in (initarg-locations key)
775                     do (if (consp location)
776                            (class-init location kind init type)
777                            (instance-init location kind init type)))))
778       ;; Loop over all slots of the class, filling in the rest from
779       ;; slot initforms.
780       (loop for slotd in (class-slots class)
781             as location = (slot-definition-location slotd)
782             as type = (slot-definition-type slotd)
783             as allocation = (slot-definition-allocation slotd)
784             as initfn = (slot-definition-initfunction slotd)
785             as initform = (slot-definition-initform slotd) do
786               (unless (or (eq allocation :class)
787                           (null initfn)
788                           (initializedp location))
789                 (if (constantp initform)
790                     (instance-init location 'initform initform type)
791                     (instance-init location 'initform/initfn initfn type))))
792       ;; Generate the forms for initializing instance and class slots.
793       (let ((instance-init-forms
794              (loop for slot-entry across slot-vector and i from 0
795                    as (kind value type) = slot-entry collect
796                      (ecase kind
797                        ((nil)
798                         (unless before-method-p
799                           `(setf (clos-slots-ref .slots. ,i) +slot-unbound+)))
800                        ((param var)
801                         `(setf (clos-slots-ref .slots. ,i)
802                                (with-type-checked (,type ,safe-p)
803                                    ,value)))
804                        (initfn
805                         `(setf (clos-slots-ref .slots. ,i)
806                                (with-type-checked (,type ,safe-p)
807                                  (funcall ,value))))
808                        (initform/initfn
809                         (if before-method-p
810                             `(when (eq (clos-slots-ref .slots. ,i)
811                                        +slot-unbound+)
812                                (setf (clos-slots-ref .slots. ,i)
813                                      (with-type-checked (,type ,safe-p)
814                                        (funcall ,value))))
815                             `(setf (clos-slots-ref .slots. ,i)
816                                    (with-type-checked (,type ,safe-p)
817                                      (funcall ,value)))))
818                        (initform
819                         (if before-method-p
820                             `(when (eq (clos-slots-ref .slots. ,i)
821                                        +slot-unbound+)
822                                (setf (clos-slots-ref .slots. ,i)
823                                      (with-type-checked (,type ,safe-p)
824                                        ',(constant-form-value value))))
825                             `(setf (clos-slots-ref .slots. ,i)
826                                    (with-type-checked (,type ,safe-p)
827                                      ',(constant-form-value value)))))
828                        (constant
829                         `(setf (clos-slots-ref .slots. ,i)
830                                (with-type-checked (,type ,safe-p)
831                                  ',(constant-form-value value))))))))
832         ;; we are not allowed to modify QUOTEd locations, so we can't
833         ;; generate code like (setf (cdr ',location) arg).  Instead,
834         ;; we have to do (setf (cdr .L0.) arg) and arrange for .L0. to
835         ;; be bound to the location.
836         (multiple-value-bind (names locations class-init-forms)
837             (loop for (location kind value type) in class-inits
838                   for i upfrom 0
839                   for name = (location-var-name i)
840                   collect name into names
841                   collect location into locations
842                   collect `(setf (cdr ,name)
843                                  (with-type-checked (,type ,safe-p)
844                                    ,(case kind
845                                           (constant `',(constant-form-value value))
846                                           ((param var) `,value)
847                                           (initfn `(funcall ,value)))))
848                   into class-init-forms
849                   finally (return (values names locations class-init-forms)))
850           (multiple-value-bind (vars bindings)
851               (loop for (var . initfn) in (nreverse default-inits)
852                     collect var into vars
853                     collect `(,var (funcall ,initfn)) into bindings
854                     finally (return (values vars bindings)))
855             (values locations names
856                     bindings vars
857                     (nreverse defaulting-initargs)
858                     `(,@(delete nil instance-init-forms)
859                       ,@class-init-forms))))))))
860
861 ;;; Return an alist of lists (KEY (LOCATION . TYPE-SPECIFIER) ...)
862 ;;; telling, for each key in INITKEYS, which locations the initarg
863 ;;; initializes and the associated type with the location.  CLASS is
864 ;;; the class of the instance being initialized.
865 (defun compute-initarg-locations (class initkeys)
866   (loop with slots = (class-slots class)
867         for key in initkeys collect
868           (loop for slot in slots
869                 if (memq key (slot-definition-initargs slot))
870                   collect (cons (slot-definition-location slot)
871                                 (slot-definition-type slot))
872                           into locations
873                 else
874                   collect slot into remaining-slots
875                 finally
876                   (setq slots remaining-slots)
877                   (return (cons key locations)))))
878
879 \f
880 ;;; *******************************
881 ;;; External Entry Points  ********
882 ;;; *******************************
883
884 (defun update-ctors (reason &key class name generic-function method)
885   (labels ((reset (class &optional ri-cache-p (ctorsp t))
886              (when ctorsp
887                (dolist (ctor (plist-value class 'ctors))
888                  (install-initial-constructor ctor)))
889              (when ri-cache-p
890                (setf (plist-value class 'ri-initargs) ()))
891              (dolist (subclass (class-direct-subclasses class))
892                (reset subclass ri-cache-p ctorsp))))
893     (ecase reason
894       ;; CLASS must have been specified.
895       (finalize-inheritance
896        (reset class t))
897       ;; NAME must have been specified.
898       (setf-find-class
899        (loop for ctor in *all-ctors*
900              when (eq (ctor-class-or-name ctor) name) do
901              (when (ctor-class ctor)
902                (reset (ctor-class ctor)))
903              (loop-finish)))
904       ;; GENERIC-FUNCTION and METHOD must have been specified.
905       ((add-method remove-method)
906        (flet ((class-of-1st-method-param (method)
907                 (type-class (first (method-specializers method)))))
908          (case (generic-function-name generic-function)
909            ((make-instance allocate-instance
910              initialize-instance shared-initialize)
911             (reset (class-of-1st-method-param method) t t))
912            ((reinitialize-instance)
913             (reset (class-of-1st-method-param method) t nil))
914            (t (when (or (eq (generic-function-name generic-function)
915                             'slot-boundp-using-class)
916                         (equal (generic-function-name generic-function)
917                                '(setf slot-value-using-class)))
918                 ;; this looks awfully expensive, but given that one
919                 ;; can specialize on the SLOTD argument, nothing is
920                 ;; safe.  -- CSR, 2004-07-12
921                 (reset (find-class 'standard-object))))))))))
922
923 (defun precompile-ctors ()
924   (dolist (ctor *all-ctors*)
925     (when (null (ctor-class ctor))
926       (let ((class (find-class (ctor-class-or-name ctor) nil)))
927         (when (and class (class-finalized-p class))
928           (install-optimized-constructor ctor))))))
929
930 (defun check-ri-initargs (instance initargs)
931   (let* ((class (class-of instance))
932          (keys (plist-keys initargs))
933          (cached (assoc keys (plist-value class 'ri-initargs)
934                         :test #'equal))
935          (invalid-keys
936           (if (consp cached)
937               (cdr cached)
938               (let ((invalid
939                      ;; FIXME: give CHECK-INITARGS-1 and friends a
940                      ;; more mnemonic name and (possibly) a nicer,
941                      ;; more orthogonal interface.
942                      (check-initargs-1
943                       class initargs
944                       (list (list* 'reinitialize-instance instance initargs)
945                             (list* 'shared-initialize instance nil initargs))
946                       t nil)))
947                 (setf (plist-value class 'ri-initargs)
948                       (acons keys invalid cached))
949                 invalid))))
950     (when invalid-keys
951       (error 'initarg-error :class class :initargs invalid-keys))))
952
953 ;;; end of ctor.lisp