403732accab9933750bbab7e649313eebd0fd080
[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                  (handler-bind ((compiler-note #'muffle-warning))
450                    (compile nil `(lambda ,names ,form))))
451                locations))))))
452
453 (defun constructor-function-form (ctor)
454   (let* ((class (ctor-class ctor))
455          (proto (class-prototype class))
456          (make-instance-methods
457           (compute-applicable-methods #'make-instance (list class)))
458          (allocate-instance-methods
459           (compute-applicable-methods #'allocate-instance (list class)))
460          ;; I stared at this in confusion for a while, thinking
461          ;; carefully about the possibility of the class prototype not
462          ;; being of sufficient discrimiating power, given the
463          ;; possibility of EQL-specialized methods on
464          ;; INITIALIZE-INSTANCE or SHARED-INITIALIZE.  However, given
465          ;; that this is a constructor optimization, the user doesn't
466          ;; yet have the instance to create a method with such an EQL
467          ;; specializer.
468          ;;
469          ;; There remains the (theoretical) possibility of someone
470          ;; coming along with code of the form
471          ;;
472          ;; (defmethod initialize-instance :before ((o foo) ...)
473          ;;   (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
474          ;;
475          ;; but probably we can afford not to worry about this too
476          ;; much for now.  -- CSR, 2004-07-12
477          (ii-methods
478           (compute-applicable-methods #'initialize-instance (list proto)))
479          (si-methods
480           (compute-applicable-methods #'shared-initialize (list proto t)))
481          (setf-svuc-slots-methods
482           (loop for slot in (class-slots class)
483                 collect (compute-applicable-methods
484                          #'(setf slot-value-using-class)
485                          (list nil class proto slot))))
486          (sbuc-slots-methods
487           (loop for slot in (class-slots class)
488                 collect (compute-applicable-methods
489                          #'slot-boundp-using-class
490                          (list class proto slot)))))
491     ;; Cannot initialize these variables earlier because the generic
492     ;; functions don't exist when PCL is built.
493     (when (null *the-system-si-method*)
494       (setq *the-system-si-method*
495             (find-method #'shared-initialize
496                          () (list *the-class-slot-object* *the-class-t*)))
497       (setq *the-system-ii-method*
498             (find-method #'initialize-instance
499                          () (list *the-class-slot-object*))))
500     ;; Note that when there are user-defined applicable methods on
501     ;; MAKE-INSTANCE and/or ALLOCATE-INSTANCE, these will show up
502     ;; together with the system-defined ones in what
503     ;; COMPUTE-APPLICABLE-METHODS returns.
504     (let ((maybe-invalid-initargs
505            (check-initargs-1
506             class
507             (append
508              (ctor-default-initkeys
509               (ctor-initargs ctor) (class-default-initargs class))
510              (plist-keys (ctor-initargs ctor)))
511             (append ii-methods si-methods) nil nil))
512           (custom-make-instance
513            (not (null (cdr make-instance-methods)))))
514       (if (and (not (structure-class-p class))
515                (not (condition-class-p class))
516                (not custom-make-instance)
517                (null (cdr allocate-instance-methods))
518                (every (lambda (x)
519                         (member (slot-definition-allocation x)
520                                 '(:instance :class)))
521                       (class-slots class))
522                (not maybe-invalid-initargs)
523                (not (around-or-nonstandard-primary-method-p
524                      ii-methods *the-system-ii-method*))
525                (not (around-or-nonstandard-primary-method-p
526                      si-methods *the-system-si-method*))
527                ;; the instance structure protocol goes through
528                ;; slot-value(-using-class) and friends (actually just
529                ;; (SETF SLOT-VALUE-USING-CLASS) and
530                ;; SLOT-BOUNDP-USING-CLASS), so if there are non-standard
531                ;; applicable methods we can't shortcircuit them.
532                (every (lambda (x) (= (length x) 1)) setf-svuc-slots-methods)
533                (every (lambda (x) (= (length x) 1)) sbuc-slots-methods))
534           (optimizing-generator ctor ii-methods si-methods)
535           (fallback-generator ctor ii-methods si-methods
536                               (or maybe-invalid-initargs custom-make-instance))))))
537
538 (defun around-or-nonstandard-primary-method-p
539     (methods &optional standard-method)
540   (loop with primary-checked-p = nil
541         for method in methods
542         as qualifiers = (if (consp method)
543                             (early-method-qualifiers method)
544                             (safe-method-qualifiers method))
545         when (or (eq :around (car qualifiers))
546                  (and (null qualifiers)
547                       (not primary-checked-p)
548                       (not (null standard-method))
549                       (not (eq standard-method method))))
550           return t
551         when (null qualifiers) do
552           (setq primary-checked-p t)))
553
554 (defun fallback-generator (ctor ii-methods si-methods use-make-instance)
555   (declare (ignore ii-methods si-methods))
556   (let ((class (ctor-class ctor))
557         (lambda-list (make-ctor-parameter-list ctor))
558         (initargs (quote-plist-keys (ctor-initargs ctor))))
559     (if use-make-instance
560         `(lambda ,lambda-list
561            (declare #.*optimize-speed*)
562            ;; The CTOR MAKE-INSTANCE optimization checks for
563            ;; *COMPILING-OPTIMIZED-CONSTRUCTOR* which is bound around compilation of
564            ;; the constructor, hence avoiding the possibility of endless recursion.
565            (make-instance ,class ,@initargs))
566         (let ((defaults (class-default-initargs class)))
567           (when defaults
568             (setf initargs (default-initargs initargs defaults)))
569           `(lambda ,lambda-list
570              (declare #.*optimize-speed*)
571              (fast-make-instance ,class ,@initargs))))))
572
573 ;;; Not as good as the real optimizing generator, but faster than going
574 ;;; via MAKE-INSTANCE: 1 GF call less, and no need to check initargs.
575 (defun fast-make-instance (class &rest initargs)
576   (declare #.*optimize-speed*)
577   (declare (dynamic-extent initargs))
578   (let ((.instance. (apply #'allocate-instance class initargs)))
579     (apply #'initialize-instance .instance. initargs)
580     .instance.))
581
582 (defun optimizing-generator (ctor ii-methods si-methods)
583   (multiple-value-bind (locations names body before-method-p)
584       (fake-initialization-emf ctor ii-methods si-methods)
585     (let ((wrapper (class-wrapper (ctor-class ctor))))
586       (values
587        `(lambda ,(make-ctor-parameter-list ctor)
588          (declare #.*optimize-speed*)
589          (block nil
590            (when (layout-invalid ,wrapper)
591              (install-initial-constructor ,ctor)
592              (return (funcall ,ctor ,@(make-ctor-parameter-list ctor))))
593            ,(wrap-in-allocate-forms ctor body before-method-p)))
594        locations
595        names))))
596
597 ;;; Return a form wrapped around BODY that allocates an instance
598 ;;; constructed by CTOR.  BEFORE-METHOD-P set means we have to run
599 ;;; before-methods, in which case we initialize instance slots to
600 ;;; +SLOT-UNBOUND+.  The resulting form binds the local variables
601 ;;; .INSTANCE. to the instance, and .SLOTS. to the instance's slot
602 ;;; vector around BODY.
603 (defun wrap-in-allocate-forms (ctor body before-method-p)
604   (let* ((class (ctor-class ctor))
605          (wrapper (class-wrapper class))
606          (allocation-function (raw-instance-allocator class))
607          (slots-fetcher (slots-fetcher class)))
608     (if (eq allocation-function 'allocate-standard-instance)
609         `(let ((.instance. (%make-standard-instance nil
610                                                     (get-instance-hash-code)))
611                (.slots. (make-array
612                          ,(layout-length wrapper)
613                          ,@(when before-method-p
614                              '(:initial-element +slot-unbound+)))))
615            (setf (std-instance-wrapper .instance.) ,wrapper)
616            (setf (std-instance-slots .instance.) .slots.)
617            ,body
618            .instance.)
619         `(let* ((.instance. (,allocation-function ,wrapper))
620                 (.slots. (,slots-fetcher .instance.)))
621            (declare (ignorable .slots.))
622            ,body
623            .instance.))))
624
625 ;;; Return a form for invoking METHOD with arguments from ARGS.  As
626 ;;; can be seen in METHOD-FUNCTION-FROM-FAST-FUNCTION, method
627 ;;; functions look like (LAMBDA (ARGS NEXT-METHODS) ...).  We could
628 ;;; call fast method functions directly here, but benchmarks show that
629 ;;; there's no speed to gain, so lets avoid the hair here.
630 (defmacro invoke-method (method args)
631   `(funcall ,(method-function method) ,args ()))
632
633 ;;; Return a form that is sort of an effective method comprising all
634 ;;; calls to INITIALIZE-INSTANCE and SHARED-INITIALIZE that would
635 ;;; normally have taken place when calling MAKE-INSTANCE.
636 (defun fake-initialization-emf (ctor ii-methods si-methods)
637   (multiple-value-bind (ii-around ii-before ii-primary ii-after)
638       (standard-sort-methods ii-methods)
639     (declare (ignore ii-primary))
640     (multiple-value-bind (si-around si-before si-primary si-after)
641         (standard-sort-methods si-methods)
642       (declare (ignore si-primary))
643       (aver (and (null ii-around) (null si-around)))
644       (let ((initargs (ctor-initargs ctor)))
645         (multiple-value-bind (locations names bindings vars defaulting-initargs body)
646             (slot-init-forms ctor (or ii-before si-before))
647         (values
648          locations
649          names
650          `(let ,bindings
651            (declare (ignorable ,@vars))
652            (let (,@(when (or ii-before ii-after)
653                      `((.ii-args.
654                         (list .instance. ,@(quote-plist-keys initargs) ,@defaulting-initargs))))
655                  ,@(when (or si-before si-after)
656                      `((.si-args.
657                         (list .instance. t ,@(quote-plist-keys initargs) ,@defaulting-initargs)))))
658             ,@(loop for method in ii-before
659                     collect `(invoke-method ,method .ii-args.))
660             ,@(loop for method in si-before
661                     collect `(invoke-method ,method .si-args.))
662             ,@body
663             ,@(loop for method in si-after
664                     collect `(invoke-method ,method .si-args.))
665             ,@(loop for method in ii-after
666                     collect `(invoke-method ,method .ii-args.))))
667          (or ii-before si-before)))))))
668
669 ;;; Return four values from APPLICABLE-METHODS: around methods, before
670 ;;; methods, the applicable primary method, and applicable after
671 ;;; methods.  Before and after methods are sorted in the order they
672 ;;; must be called.
673 (defun standard-sort-methods (applicable-methods)
674   (loop for method in applicable-methods
675         as qualifiers = (if (consp method)
676                             (early-method-qualifiers method)
677                             (safe-method-qualifiers method))
678         if (null qualifiers)
679           collect method into primary
680         else if (eq :around (car qualifiers))
681           collect method into around
682         else if (eq :after (car qualifiers))
683           collect method into after
684         else if (eq :before (car qualifiers))
685           collect method into before
686         finally
687           (return (values around before (first primary) (reverse after)))))
688
689 (defmacro with-type-checked ((type safe-p) &body body)
690   (if safe-p
691       ;; To handle FUNCTION types reasonable, we use SAFETY 3 and
692       ;; THE instead of e.g. CHECK-TYPE.
693       `(locally
694            (declare (optimize (safety 3)))
695          (the ,type (progn ,@body)))
696       `(progn ,@body)))
697
698 ;;; Return as multiple values bindings for default initialization
699 ;;; arguments, variable names, defaulting initargs and a body for
700 ;;; initializing instance and class slots of an object costructed by
701 ;;; CTOR.  The variable .SLOTS. is assumed to bound to the instance's
702 ;;; slot vector.  BEFORE-METHOD-P T means before-methods will be
703 ;;; called, which means that 1) other code will initialize instance
704 ;;; slots to +SLOT-UNBOUND+ before the before-methods are run, and
705 ;;; that we have to check if these before-methods have set slots.
706 (defun slot-init-forms (ctor before-method-p)
707   (let* ((class (ctor-class ctor))
708          (initargs (ctor-initargs ctor))
709          (initkeys (plist-keys initargs))
710          (safe-p (ctor-safe-p ctor))
711          (slot-vector
712           (make-array (layout-length (class-wrapper class))
713                       :initial-element nil))
714          (class-inits ())
715          (default-inits ())
716          (defaulting-initargs ())
717          (default-initargs (class-default-initargs class))
718          (initarg-locations
719           (compute-initarg-locations
720            class (append initkeys (mapcar #'car default-initargs)))))
721     (labels ((initarg-locations (initarg)
722                (cdr (assoc initarg initarg-locations :test #'eq)))
723              (initializedp (location)
724                (cond
725                  ((consp location)
726                   (assoc location class-inits :test #'eq))
727                  ((integerp location)
728                   (not (null (aref slot-vector location))))
729                  (t (bug "Weird location in ~S" 'slot-init-forms))))
730              (class-init (location kind val type)
731                (aver (consp location))
732                (unless (initializedp location)
733                  (push (list location kind val type) class-inits)))
734              (instance-init (location kind val type)
735                (aver (integerp location))
736                (unless (initializedp location)
737                  (setf (aref slot-vector location) (list kind val type))))
738              (default-init-var-name (i)
739                (let ((ps #(.d0. .d1. .d2. .d3. .d4. .d5.)))
740                  (if (array-in-bounds-p ps i)
741                      (aref ps i)
742                      (format-symbol *pcl-package* ".D~D." i))))
743              (location-var-name (i)
744                (let ((ls #(.l0. .l1. .l2. .l3. .l4. .l5.)))
745                  (if (array-in-bounds-p ls i)
746                      (aref ls i)
747                      (format-symbol *pcl-package* ".L~D." i)))))
748       ;; Loop over supplied initargs and values and record which
749       ;; instance and class slots they initialize.
750       (loop for (key value) on initargs by #'cddr
751             as kind = (if (constantp value) 'constant 'param)
752             as locations = (initarg-locations key)
753             do (loop for (location . type) in locations
754                      do (if (consp location)
755                             (class-init location kind value type)
756                             (instance-init location kind value type))))
757       ;; Loop over default initargs of the class, recording
758       ;; initializations of slots that have not been initialized
759       ;; above.  Default initargs which are not in the supplied
760       ;; initargs are treated as if they were appended to supplied
761       ;; initargs, that is, their values must be evaluated even
762       ;; if not actually used for initializing a slot.
763       (loop for (key initform initfn) in default-initargs and i from 0
764             unless (member key initkeys :test #'eq)
765             do (let* ((kind (if (constantp initform) 'constant 'var))
766                       (init (if (eq kind 'var) initfn initform)))
767                  (ecase kind
768                    (constant
769                     (push (list 'quote key) defaulting-initargs)
770                     (push initform defaulting-initargs))
771                    (var
772                     (push (list 'quote key) defaulting-initargs)
773                     (push (default-init-var-name i) defaulting-initargs)))
774               (when (eq kind 'var)
775                 (let ((init-var (default-init-var-name i)))
776                   (setq init init-var)
777                   (push (cons init-var initfn) default-inits)))
778               (loop for (location . type) in (initarg-locations key)
779                     do (if (consp location)
780                            (class-init location kind init type)
781                            (instance-init location kind init type)))))
782       ;; Loop over all slots of the class, filling in the rest from
783       ;; slot initforms.
784       (loop for slotd in (class-slots class)
785             as location = (slot-definition-location slotd)
786             as type = (slot-definition-type slotd)
787             as allocation = (slot-definition-allocation slotd)
788             as initfn = (slot-definition-initfunction slotd)
789             as initform = (slot-definition-initform slotd) do
790               (unless (or (eq allocation :class)
791                           (null initfn)
792                           (initializedp location))
793                 (if (constantp initform)
794                     (instance-init location 'initform initform type)
795                     (instance-init location 'initform/initfn initfn type))))
796       ;; Generate the forms for initializing instance and class slots.
797       (let ((instance-init-forms
798              (loop for slot-entry across slot-vector and i from 0
799                    as (kind value type) = slot-entry collect
800                      (ecase kind
801                        ((nil)
802                         (unless before-method-p
803                           `(setf (clos-slots-ref .slots. ,i) +slot-unbound+)))
804                        ((param var)
805                         `(setf (clos-slots-ref .slots. ,i)
806                                (with-type-checked (,type ,safe-p)
807                                    ,value)))
808                        (initfn
809                         `(setf (clos-slots-ref .slots. ,i)
810                                (with-type-checked (,type ,safe-p)
811                                  (funcall ,value))))
812                        (initform/initfn
813                         (if before-method-p
814                             `(when (eq (clos-slots-ref .slots. ,i)
815                                        +slot-unbound+)
816                                (setf (clos-slots-ref .slots. ,i)
817                                      (with-type-checked (,type ,safe-p)
818                                        (funcall ,value))))
819                             `(setf (clos-slots-ref .slots. ,i)
820                                    (with-type-checked (,type ,safe-p)
821                                      (funcall ,value)))))
822                        (initform
823                         (if before-method-p
824                             `(when (eq (clos-slots-ref .slots. ,i)
825                                        +slot-unbound+)
826                                (setf (clos-slots-ref .slots. ,i)
827                                      (with-type-checked (,type ,safe-p)
828                                        ',(constant-form-value value))))
829                             `(setf (clos-slots-ref .slots. ,i)
830                                    (with-type-checked (,type ,safe-p)
831                                      ',(constant-form-value value)))))
832                        (constant
833                         `(setf (clos-slots-ref .slots. ,i)
834                                (with-type-checked (,type ,safe-p)
835                                  ',(constant-form-value value))))))))
836         ;; we are not allowed to modify QUOTEd locations, so we can't
837         ;; generate code like (setf (cdr ',location) arg).  Instead,
838         ;; we have to do (setf (cdr .L0.) arg) and arrange for .L0. to
839         ;; be bound to the location.
840         (multiple-value-bind (names locations class-init-forms)
841             (loop for (location kind value type) in class-inits
842                   for i upfrom 0
843                   for name = (location-var-name i)
844                   collect name into names
845                   collect location into locations
846                   collect `(setf (cdr ,name)
847                                  (with-type-checked (,type ,safe-p)
848                                    ,(case kind
849                                           (constant `',(constant-form-value value))
850                                           ((param var) `,value)
851                                           (initfn `(funcall ,value)))))
852                   into class-init-forms
853                   finally (return (values names locations class-init-forms)))
854           (multiple-value-bind (vars bindings)
855               (loop for (var . initfn) in (nreverse default-inits)
856                     collect var into vars
857                     collect `(,var (funcall ,initfn)) into bindings
858                     finally (return (values vars bindings)))
859             (values locations names
860                     bindings vars
861                     (nreverse defaulting-initargs)
862                     `(,@(delete nil instance-init-forms)
863                       ,@class-init-forms))))))))
864
865 ;;; Return an alist of lists (KEY (LOCATION . TYPE-SPECIFIER) ...)
866 ;;; telling, for each key in INITKEYS, which locations the initarg
867 ;;; initializes and the associated type with the location.  CLASS is
868 ;;; the class of the instance being initialized.
869 (defun compute-initarg-locations (class initkeys)
870   (loop with slots = (class-slots class)
871         for key in initkeys collect
872           (loop for slot in slots
873                 if (memq key (slot-definition-initargs slot))
874                   collect (cons (slot-definition-location slot)
875                                 (slot-definition-type slot))
876                           into locations
877                 else
878                   collect slot into remaining-slots
879                 finally
880                   (setq slots remaining-slots)
881                   (return (cons key locations)))))
882
883 \f
884 ;;; *******************************
885 ;;; External Entry Points  ********
886 ;;; *******************************
887
888 (defun update-ctors (reason &key class name generic-function method)
889   (labels ((reset (class &optional ri-cache-p (ctorsp t))
890              (when ctorsp
891                (dolist (ctor (plist-value class 'ctors))
892                  (install-initial-constructor ctor)))
893              (when ri-cache-p
894                (setf (plist-value class 'ri-initargs) ()))
895              (dolist (subclass (class-direct-subclasses class))
896                (reset subclass ri-cache-p ctorsp))))
897     (ecase reason
898       ;; CLASS must have been specified.
899       (finalize-inheritance
900        (reset class t))
901       ;; NAME must have been specified.
902       (setf-find-class
903        (loop for ctor in *all-ctors*
904              when (eq (ctor-class-or-name ctor) name) do
905              (when (ctor-class ctor)
906                (reset (ctor-class ctor)))
907              (loop-finish)))
908       ;; GENERIC-FUNCTION and METHOD must have been specified.
909       ((add-method remove-method)
910        (flet ((class-of-1st-method-param (method)
911                 (type-class (first (method-specializers method)))))
912          (case (generic-function-name generic-function)
913            ((make-instance allocate-instance
914              initialize-instance shared-initialize)
915             (reset (class-of-1st-method-param method) t t))
916            ((reinitialize-instance)
917             (reset (class-of-1st-method-param method) t nil))
918            (t (when (or (eq (generic-function-name generic-function)
919                             'slot-boundp-using-class)
920                         (equal (generic-function-name generic-function)
921                                '(setf slot-value-using-class)))
922                 ;; this looks awfully expensive, but given that one
923                 ;; can specialize on the SLOTD argument, nothing is
924                 ;; safe.  -- CSR, 2004-07-12
925                 (reset (find-class 'standard-object))))))))))
926
927 (defun precompile-ctors ()
928   (dolist (ctor *all-ctors*)
929     (when (null (ctor-class ctor))
930       (let ((class (find-class (ctor-class-or-name ctor) nil)))
931         (when (and class (class-finalized-p class))
932           (install-optimized-constructor ctor))))))
933
934 (defun check-ri-initargs (instance initargs)
935   (let* ((class (class-of instance))
936          (keys (plist-keys initargs))
937          (cached (assoc keys (plist-value class 'ri-initargs)
938                         :test #'equal))
939          (invalid-keys
940           (if (consp cached)
941               (cdr cached)
942               (let ((invalid
943                      ;; FIXME: give CHECK-INITARGS-1 and friends a
944                      ;; more mnemonic name and (possibly) a nicer,
945                      ;; more orthogonal interface.
946                      (check-initargs-1
947                       class initargs
948                       (list (list* 'reinitialize-instance instance initargs)
949                             (list* 'shared-initialize instance nil initargs))
950                       t nil)))
951                 (setf (plist-value class 'ri-initargs)
952                       (acons keys invalid cached))
953                 invalid))))
954     (when invalid-keys
955       (error 'initarg-error :class class :initargs invalid-keys))))
956
957 ;;; end of ctor.lisp