1 ;;;; This file contains the optimization machinery for make-instance.
3 ;;;; This software is part of the SBCL system. See the README file for
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.
12 ;;; Copyright (C) 2002 Gerd Moellmann <gerd.moellmann@t-online.de>
13 ;;; All rights reserved.
15 ;;; Redistribution and use in source and binary forms, with or without
16 ;;; modification, are permitted provided that the following conditions
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
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
45 ;;; Compiler macro for MAKE-INSTANCE, and load-time generation of
46 ;;; optimized instance constructor functions.
48 ;;; ********************
49 ;;; Entry Points ******
50 ;;; ********************
52 ;;; UPDATE-CTORS must be called when methods are added/removed,
53 ;;; classes are changed, etc., which affect instance creation.
55 ;;; PRECOMPILE-CTORS can be called to precompile constructor functions
56 ;;; for classes whose definitions are known at the time the function
61 ;;; ******************
63 ;;; ******************
65 (defun quote-plist-keys (plist)
66 (loop for (key . more) on plist by #'cddr
68 (error "Not a property list: ~S" plist)
71 and collect (car more)))
73 (defun plist-keys (plist &key test)
74 (loop for (key . more) on plist by #'cddr
76 (error "Not a property list: ~S" plist)
77 else if (or (null test) (funcall test key))
80 (defun plist-values (plist &key test)
81 (loop for (key . more) on plist by #'cddr
83 (error "Not a property list: ~S" plist)
84 else if (or (null test) (funcall test (car more)))
87 (defun constant-class-arg-p (form)
89 (let ((constant (constant-form-value form)))
90 (or (and (symbolp constant)
91 (not (null (symbol-package constant))))
94 (defun constant-symbol-p (form)
96 (let ((constant (constant-form-value form)))
97 (and (symbolp constant)
98 (not (null (symbol-package constant)))))))
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.)
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
115 (return (append supplied-initargs default-initargs))))
117 ;;; *****************
119 ;;; *****************
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.
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)
135 ;;; List of all defined ctors.
136 (defvar *all-ctors* ())
138 (defun make-ctor-parameter-list (ctor)
139 (plist-values (ctor-initargs ctor) :test (complement #'constantp)))
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)
150 (setf (%funcallable-instance-info ctor 1)
151 (ctor-function-name ctor))))
153 (defun make-ctor-function-name (class-name initargs safe-code-p)
154 (list* 'ctor class-name safe-code-p initargs))
156 ;;; Keep this a separate function for testing.
157 (defun ensure-ctor (function-name class-name initargs safe-code-p)
159 (if (fboundp function-name)
160 (the ctor (fdefinition function-name))
161 (make-ctor function-name class-name initargs safe-code-p))))
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)
172 ;;; *****************
173 ;;; Inline CTOR cache
174 ;;; *****************
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.
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
186 (defun find-ctor (key list)
187 (labels ((walk (tail from-head depth)
188 (declare (fixnum depth))
190 (let ((ctor (car tail)))
191 (if (eq (ctor-class-or-name ctor) key)
194 (nconc (list ctor) (nreverse from-head) (cdr tail)))
198 (cons ctor from-head)
199 (logand #xf (1+ depth)))))
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))
209 (bug "Something strange where symbol or class expected."))))
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)
220 (defconstant +ctor-table-max-probe-depth+ 5)
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))))
229 (declaim (inline mix-ctor-hash))
230 (defun mix-ctor-hash (hash base)
231 (logand most-positive-fixnum (+ hash base 1)))
233 (defun put-ctor (ctor table)
234 (cond ((try-put-ctor ctor table)
237 (expand-ctor-table ctor table))))
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
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))
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)))
257 (setf (aref table index) ctor)
258 (return-from try-put-ctor t)))))
259 ;; Didn't fit, must expand
262 (defun get-ctor (class table)
263 (declare (simple-vector table) (optimize speed))
264 (let* ((base (sxhash-symbol-or-class class))
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)))))
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
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))
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
292 (randomly-punting-lambda (old-ctor)
293 (try-put-ctor old-ctor new))
295 (unless (try-put-ctor old-ctor new)
297 (setf drop-random-entries t)
298 (setf new-size (* 2 new-size)))
300 (aver (try-put-ctor ctor new))
301 (dotimes (i old-size)
302 (let ((old-ctor (aref old i)))
304 (funcall action old-ctor))))
305 (return-from expand-ctor-table (values ctor new)))))))
307 (defun ctor-list-to-table (list)
308 (let ((table (make-ctor-table (length list))))
310 (setf table (nth-value 1 (put-ctor ctor table))))
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)
322 (doplist (key value) initargs
323 (push key mi-initargs)
324 (push (if (constantp value)
326 (pop ctor-parameters))
328 (apply #'make-instance class-name (nreverse mi-initargs))))
331 (multiple-value-bind (ctor list) (find-ctor class-name store)
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)))
341 (put-ctor (maybe-ctor-for-caching) store))))))
343 ;;; ***********************************************
344 ;;; Compile-Time Expansion of MAKE-INSTANCE *******
345 ;;; ***********************************************
347 (defvar *compiling-optimized-constructor* nil)
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)))
358 (defun make-instance->constructor-call (form safe-code-p)
359 (destructuring-bind (class-arg &rest args) (cdr form)
361 ;; Return the name of parameter number I of a constructor
364 (let ((ps #(.p0. .p1. .p2. .p3. .p4. .p5.)))
365 (if (array-in-bounds-p ps i)
367 (format-symbol *pcl-package* ".P~D." i))))
368 ;; Check if CLASS-ARG is a constant symbol. Give up if
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.
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)))))
381 ;; Collect a plist of initargs and constant values/parameter names
382 ;; in INITARGS. Collect non-constant initialization forms in
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
388 collect value into initargs
390 collect (parameter-name i) into initargs
391 and collect value into value-forms
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
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.
409 (declare (disable-package-locks ,function-name))
410 (let ((.x. (load-time-value
411 (ensure-ctor ',function-name ',class-or-name ',initargs
413 (declare (ignore .x.))
414 ;; ??? check if this is worth it.
416 (ftype (or (function ,(make-list (length value-forms)
419 (function (&rest t) t))
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.
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))))))))))
438 ;;; **************************************************
439 ;;; Load-Time Constructor Function Generation *******
440 ;;; **************************************************
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)
449 (defun install-optimized-constructor (ctor)
451 (let* ((class-or-name (ctor-class-or-name ctor))
452 (class (if (symbolp class-or-name)
453 (find-class 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)
470 (let ((*compiling-optimized-constructor* t))
471 (handler-bind ((compiler-note #'muffle-warning))
472 (compile nil `(lambda ,names ,form))))
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
491 ;; There remains the (theoretical) possibility of someone
492 ;; coming along with code of the form
494 ;; (defmethod initialize-instance :before ((o foo) ...)
495 ;; (eval `(defmethod shared-initialize :before ((o foo) ...) ...)))
497 ;; but probably we can afford not to worry about this too
498 ;; much for now. -- CSR, 2004-07-12
500 (compute-applicable-methods #'initialize-instance (list proto)))
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))))
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
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))
541 (member (slot-definition-allocation x)
542 '(:instance :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))))))
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))))
573 when (null qualifiers) do
574 (setq primary-checked-p t)))
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)))
590 (setf initargs (ctor-default-initargs initargs defaults)))
591 `(lambda ,lambda-list
592 (declare #.*optimize-speed*)
593 (fast-make-instance ,class ,@initargs))))))
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)
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))))
609 `(lambda ,(make-ctor-parameter-list ctor)
610 (declare #.*optimize-speed*)
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)))
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)))
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.)
641 `(let* ((.instance. (,allocation-function ,wrapper))
642 (.slots. (,slots-fetcher .instance.)))
643 (declare (ignorable .slots.))
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 ()))
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))
673 (declare (ignorable ,@vars))
674 (let (,@(when (or ii-before ii-after)
676 (list .instance. ,@(quote-plist-keys initargs) ,@defaulting-initargs))))
677 ,@(when (or si-before si-after)
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.))
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)))))))
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
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))
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
709 (return (values around before (first primary) (reverse after)))))
711 (defmacro with-type-checked ((type safe-p) &body body)
713 ;; To handle FUNCTION types reasonable, we use SAFETY 3 and
714 ;; THE instead of e.g. CHECK-TYPE.
716 (declare (optimize (safety 3)))
717 (the ,type (progn ,@body)))
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))
734 (make-array (layout-length (class-wrapper class))
735 :initial-element nil))
738 (defaulting-initargs ())
739 (default-initargs (class-default-initargs class))
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)
748 (assoc location class-inits :test #'eq))
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)
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)
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)))
791 (push (list 'quote key) defaulting-initargs)
792 (push initform defaulting-initargs))
794 (push (list 'quote key) defaulting-initargs)
795 (push (default-init-var-name i) defaulting-initargs)))
797 (let ((init-var (default-init-var-name i)))
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
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)
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
824 (unless before-method-p
825 `(setf (clos-slots-ref .slots. ,i) +slot-unbound+)))
827 `(setf (clos-slots-ref .slots. ,i)
828 (with-type-checked (,type ,safe-p)
831 `(setf (clos-slots-ref .slots. ,i)
832 (with-type-checked (,type ,safe-p)
836 `(when (eq (clos-slots-ref .slots. ,i)
838 (setf (clos-slots-ref .slots. ,i)
839 (with-type-checked (,type ,safe-p)
841 `(setf (clos-slots-ref .slots. ,i)
842 (with-type-checked (,type ,safe-p)
846 `(when (eq (clos-slots-ref .slots. ,i)
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)))))
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
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)
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
883 (nreverse defaulting-initargs)
884 `(,@(delete nil instance-init-forms)
885 ,@class-init-forms))))))))
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))
900 collect slot into remaining-slots
902 (setq slots remaining-slots)
903 (return (cons key locations)))))
906 ;;; *******************************
907 ;;; External Entry Points ********
908 ;;; *******************************
910 (defun update-ctors (reason &key class name generic-function method)
911 (labels ((reset (class &optional ri-cache-p (ctorsp t))
913 (dolist (ctor (plist-value class 'ctors))
914 (install-initial-constructor ctor)))
916 (setf (plist-value class 'ri-initargs) ()))
917 (dolist (subclass (class-direct-subclasses class))
918 (reset subclass ri-cache-p ctorsp))))
920 ;; CLASS must have been specified.
921 (finalize-inheritance
923 ;; NAME must have been specified.
925 (loop for ctor in *all-ctors*
926 when (eq (ctor-class-or-name ctor) name) do
927 (when (ctor-class ctor)
928 (reset (ctor-class ctor)))
930 ;; GENERIC-FUNCTION and METHOD must have been specified.
931 ((add-method remove-method)
932 (flet ((class-of-1st-method-param (method)
933 (type-class (first (method-specializers method)))))
934 (case (generic-function-name generic-function)
935 ((make-instance allocate-instance
936 initialize-instance shared-initialize)
937 (reset (class-of-1st-method-param method) t t))
938 ((reinitialize-instance)
939 (reset (class-of-1st-method-param method) t nil))
940 (t (when (or (eq (generic-function-name generic-function)
941 'slot-boundp-using-class)
942 (equal (generic-function-name generic-function)
943 '(setf slot-value-using-class)))
944 ;; this looks awfully expensive, but given that one
945 ;; can specialize on the SLOTD argument, nothing is
946 ;; safe. -- CSR, 2004-07-12
947 (reset (find-class 'standard-object))))))))))
949 (defun precompile-ctors ()
950 (dolist (ctor *all-ctors*)
951 (when (null (ctor-class ctor))
952 (let ((class (find-class (ctor-class-or-name ctor) nil)))
953 (when (and class (class-finalized-p class))
954 (install-optimized-constructor ctor))))))
956 (defun check-ri-initargs (instance initargs)
957 (let* ((class (class-of instance))
958 (keys (plist-keys initargs))
959 (cached (assoc keys (plist-value class 'ri-initargs)
965 ;; FIXME: give CHECK-INITARGS-1 and friends a
966 ;; more mnemonic name and (possibly) a nicer,
967 ;; more orthogonal interface.
970 (list (list* 'reinitialize-instance instance initargs)
971 (list* 'shared-initialize instance nil initargs))
973 (setf (plist-value class 'ri-initargs)
974 (acons keys invalid cached))
977 (error 'initarg-error :class class :initargs invalid-keys))))