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