1.0.46.11: faster slot-accesses in the presence of SLOT-VALUE-USING-CLASS &co
[sbcl.git] / src / pcl / low.lisp
1 ;;;; This file contains portable versions of low-level functions and macros
2 ;;;; which are ripe for implementation specific customization. None of the code
3 ;;;; in this file *has* to be customized for a particular Common Lisp
4 ;;;; implementation. Moreover, in some implementations it may not make any
5 ;;;; sense to customize some of this code.
6 ;;;;
7 ;;;; The original version was intended to support portable customization to
8 ;;;; lotso different Lisp implementations. This functionality is gone in the
9 ;;;; current version, and it now runs only under SBCL. (Now that ANSI Common
10 ;;;; Lisp has mixed CLOS into the insides of the system (e.g. error handling
11 ;;;; and printing) so deeply that it's not very meaningful to bootstrap Common
12 ;;;; Lisp without CLOS, the old functionality is of dubious use. -- WHN
13 ;;;; 19981108)
14
15 ;;;; This software is part of the SBCL system. See the README file for more
16 ;;;; information.
17
18 ;;;; This software is derived from software originally released by Xerox
19 ;;;; Corporation. Copyright and release statements follow. Later modifications
20 ;;;; to the software are in the public domain and are provided with
21 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
22 ;;;; information.
23
24 ;;;; copyright information from original PCL sources:
25 ;;;;
26 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
27 ;;;; All rights reserved.
28 ;;;;
29 ;;;; Use and copying of this software and preparation of derivative works based
30 ;;;; upon this software are permitted. Any distribution of this software or
31 ;;;; derivative works must comply with all applicable United States export
32 ;;;; control laws.
33 ;;;;
34 ;;;; This software is made available AS IS, and Xerox Corporation makes no
35 ;;;; warranty about the software, its performance or its conformity to any
36 ;;;; specification.
37
38 (in-package "SB-PCL")
39 \f
40 (eval-when (:compile-toplevel :load-toplevel :execute)
41 (defvar *optimize-speed*
42   '(optimize (speed 3) (safety 0)))
43 ) ; EVAL-WHEN
44
45 (defmacro dotimes-fixnum ((var count &optional (result nil)) &body body)
46   `(dotimes (,var (the fixnum ,count) ,result)
47      (declare (fixnum ,var))
48      ,@body))
49
50 (declaim (inline random-fixnum))
51 (defun random-fixnum ()
52   (random (1+ most-positive-fixnum)))
53
54 (defconstant n-fixnum-bits #.(integer-length most-positive-fixnum))
55
56 ;;; Lambda which executes its body (or not) randomly. Used to drop
57 ;;; random cache entries.
58 (defmacro randomly-punting-lambda (lambda-list &body body)
59   (with-unique-names (drops drop-pos)
60     `(let ((,drops (random-fixnum))
61            (,drop-pos n-fixnum-bits))
62        (declare (fixnum ,drops)
63                 (type (integer 0 #.n-fixnum-bits) ,drop-pos))
64        (lambda ,lambda-list
65          (when (logbitp (the unsigned-byte (decf ,drop-pos)) ,drops)
66            (locally ,@body))
67          (when (zerop ,drop-pos)
68            (setf ,drops (random-fixnum)
69                  ,drop-pos n-fixnum-bits))))))
70 \f
71 ;;;; early definition of WRAPPER
72 ;;;;
73 ;;;; Most WRAPPER stuff is defined later, but the DEFSTRUCT itself
74 ;;;; is here early so that things like (TYPEP .. 'WRAPPER) can be
75 ;;;; compiled efficiently.
76
77 ;;; Note that for SBCL, as for CMU CL, the WRAPPER of a built-in or
78 ;;; structure class will be some other kind of SB-KERNEL:LAYOUT, but
79 ;;; this shouldn't matter, since the only two slots that WRAPPER adds
80 ;;; are meaningless in those cases.
81 (defstruct (wrapper
82             (:include layout
83                       ;; KLUDGE: In CMU CL, the initialization default
84                       ;; for LAYOUT-INVALID was NIL. In SBCL, that has
85                       ;; changed to :UNINITIALIZED, but PCL code might
86                       ;; still expect NIL for the initialization
87                       ;; default of WRAPPER-INVALID. Instead of trying
88                       ;; to find out, I just overrode the LAYOUT
89                       ;; default here. -- WHN 19991204
90                       (invalid nil)
91                       ;; This allows quick testing of wrapperness.
92                       (for-std-class-p t))
93             (:constructor make-wrapper-internal)
94             (:copier nil))
95   (instance-slots-layout nil :type list)
96   (class-slots nil :type list))
97 #-sb-fluid (declaim (sb-ext:freeze-type wrapper))
98 \f
99 ;;;; PCL's view of funcallable instances
100
101 (!defstruct-with-alternate-metaclass standard-funcallable-instance
102   ;; KLUDGE: Note that neither of these slots is ever accessed by its
103   ;; accessor name as of sbcl-0.pre7.63. Presumably everything works
104   ;; by puns based on absolute locations. Fun fun fun.. -- WHN 2001-10-30
105   :slot-names (clos-slots name hash-code)
106   :boa-constructor %make-standard-funcallable-instance
107   :superclass-name function
108   :metaclass-name standard-classoid
109   :metaclass-constructor make-standard-classoid
110   :dd-type funcallable-structure
111   ;; Only internal implementation code will access these, and these
112   ;; accesses (slot readers in particular) could easily be a
113   ;; bottleneck, so it seems reasonable to suppress runtime type
114   ;; checks.
115   ;;
116   ;; (Except note KLUDGE above that these accessors aren't used at all
117   ;; (!) as of sbcl-0.pre7.63, so for now it's academic.)
118   :runtime-type-checks-p nil)
119
120 (import 'sb-kernel:funcallable-instance-p)
121
122 (defun set-funcallable-instance-function (fin new-value)
123   (declare (type function new-value))
124   (aver (funcallable-instance-p fin))
125   (setf (funcallable-instance-fun fin) new-value))
126
127 ;;; FIXME: these macros should just go away.  It's not clear whether
128 ;;; the inline functions defined by
129 ;;; !DEFSTRUCT-WITH-ALTERNATE-METACLASS are as efficient as they could
130 ;;; be; ordinary defstruct accessors are defined as source transforms.
131 (defun fsc-instance-p (fin)
132   (funcallable-instance-p fin))
133 (define-compiler-macro fsc-instance-p (fin)
134   `(funcallable-instance-p ,fin))
135 (defmacro fsc-instance-wrapper (fin)
136   `(%funcallable-instance-layout ,fin))
137 (defmacro fsc-instance-slots (fin)
138   `(%funcallable-instance-info ,fin 1))
139 (defmacro fsc-instance-hash (fin)
140   `(%funcallable-instance-info ,fin 3))
141 \f
142 (declaim (inline clos-slots-ref (setf clos-slots-ref)))
143 (declaim (ftype (function (simple-vector index) t) clos-slots-ref))
144 (defun clos-slots-ref (slots index)
145   (svref slots index))
146 (declaim (ftype (function (t simple-vector index) t) (setf clos-slots-ref)))
147 (defun (setf clos-slots-ref) (new-value slots index)
148   (setf (svref slots index) new-value))
149
150 ;;; Note on implementation under CMU CL >=17 and SBCL: STD-INSTANCE-P
151 ;;; is only used to discriminate between functions (including FINs)
152 ;;; and normal instances, so we can return true on structures also. A
153 ;;; few uses of (OR STD-INSTANCE-P FSC-INSTANCE-P) are changed to
154 ;;; PCL-INSTANCE-P.
155 (defun std-instance-p (x)
156   (%instancep x))
157 (define-compiler-macro std-instance-p (x)
158   `(%instancep ,x))
159
160 ;; a temporary definition used for debugging the bootstrap
161 #+sb-show
162 (defun print-std-instance (instance stream depth)
163   (declare (ignore depth))
164   (print-unreadable-object (instance stream :type t :identity t)
165     (let ((class (class-of instance)))
166       (when (or (eq class (find-class 'standard-class nil))
167                 (eq class (find-class 'funcallable-standard-class nil))
168                 (eq class (find-class 'built-in-class nil)))
169         (princ (early-class-name instance) stream)))))
170
171 ;;; This is the value that we stick into a slot to tell us that it is
172 ;;; unbound. It may seem gross, but for performance reasons, we make
173 ;;; this an interned symbol. That means that the fast check to see
174 ;;; whether a slot is unbound is to say (EQ <val> '..SLOT-UNBOUND..).
175 ;;; That is considerably faster than looking at the value of a special
176 ;;; variable.
177 ;;;
178 ;;; It seems only reasonable to also export this for users, since
179 ;;; otherwise dealing with STANDARD-INSTANCE-ACCESS becomes harder
180 ;;; -- and slower -- than it needs to be.
181 (defconstant +slot-unbound+ '..slot-unbound..
182   "SBCL specific extentions to MOP: if this value is read from an
183 instance using STANDARD-INSTANCE-ACCESS, the slot is unbound.
184 Similarly, an :INSTANCE allocated slot can be made unbound by
185 assigning this to it using (SETF STANDARD-INSTANCE-ACCESS).
186
187 Value of +SLOT-UNBOUND+ is unspecified, and should not be relied to be
188 of any particular type, but it is guaranteed to be suitable for EQ
189 comparison.")
190
191 (defmacro %allocate-static-slot-storage--class (no-of-slots)
192   `(make-array ,no-of-slots :initial-element +slot-unbound+))
193
194 (defmacro std-instance-class (instance)
195   `(wrapper-class* (std-instance-wrapper ,instance)))
196 \f
197 ;;; When given a funcallable instance, SET-FUN-NAME *must* side-effect
198 ;;; that FIN to give it the name. When given any other kind of
199 ;;; function SET-FUN-NAME is allowed to return a new function which is
200 ;;; "the same" except that it has the name.
201 ;;;
202 ;;; In all cases, SET-FUN-NAME must return the new (or same)
203 ;;; function. (Unlike other functions to set stuff, it does not return
204 ;;; the new value.)
205 (defun set-fun-name (fun new-name)
206   #+sb-doc
207   "Set the name of a compiled function object. Return the function."
208   (when (valid-function-name-p fun)
209     (setq fun (fdefinition fun)))
210   (typecase fun
211     (%method-function (setf (%method-function-name fun) new-name))
212     #+sb-eval
213     (sb-eval:interpreted-function
214      (setf (sb-eval:interpreted-function-name fun) new-name))
215     (funcallable-instance ;; KLUDGE: probably a generic function...
216      (cond ((if (eq **boot-state** 'complete)
217                 (typep fun 'generic-function)
218                 (eq (class-of fun) *the-class-standard-generic-function*))
219             (setf (%funcallable-instance-info fun 2) new-name))
220            (t
221             (bug "unanticipated function type")))))
222   ;; Fixup name-to-function mappings in cases where the function
223   ;; hasn't been defined by DEFUN.  (FIXME: is this right?  This logic
224   ;; comes from CMUCL).  -- CSR, 2004-12-31
225   (when (and (consp new-name)
226              (member (car new-name) '(slow-method fast-method slot-accessor)))
227     (setf (fdefinition new-name) fun))
228   fun)
229 \f
230 ;;; FIXME: probably no longer needed after init
231 (defmacro precompile-random-code-segments (&optional system)
232   `(progn
233      (eval-when (:compile-toplevel)
234        (update-dispatch-dfuns))
235      (precompile-function-generators ,system)
236      (precompile-dfun-constructors ,system)
237      (precompile-ctors)))
238 \f
239 ;;; This definition is for interpreted code.
240 (defun pcl-instance-p (x)
241   (typep (layout-of x) 'wrapper))
242
243 ;;; CMU CL comment:
244 ;;;   We define this as STANDARD-INSTANCE, since we're going to
245 ;;;   clobber the layout with some standard-instance layout as soon as
246 ;;;   we make it, and we want the accessor to still be type-correct.
247 #|
248 (defstruct (standard-instance
249             (:predicate nil)
250             (:constructor %%allocate-instance--class ())
251             (:copier nil)
252             (:alternate-metaclass instance
253                                   cl:standard-class
254                                   make-standard-class))
255   (slots nil))
256 |#
257 (!defstruct-with-alternate-metaclass standard-instance
258   :slot-names (slots hash-code)
259   :boa-constructor %make-standard-instance
260   :superclass-name t
261   :metaclass-name standard-classoid
262   :metaclass-constructor make-standard-classoid
263   :dd-type structure
264   :runtime-type-checks-p nil)
265
266 ;;; Both of these operations "work" on structures, which allows the above
267 ;;; weakening of STD-INSTANCE-P.
268 (defmacro std-instance-slots (x) `(%instance-ref ,x 1))
269 (defmacro std-instance-wrapper (x) `(%instance-layout ,x))
270 ;;; KLUDGE: This one doesn't "work" on structures.  However, we
271 ;;; ensure, in SXHASH and friends, never to call it on structures.
272 (defmacro std-instance-hash (x) `(%instance-ref ,x 2))
273
274 ;;; FIXME: These functions are called every place we do a
275 ;;; CALL-NEXT-METHOD, and probably other places too. It's likely worth
276 ;;; selectively optimizing them with DEFTRANSFORMs and stuff, rather
277 ;;; than just indiscriminately expanding them inline everywhere.
278 (declaim (inline get-slots get-slots-or-nil))
279 (declaim (ftype (function (t) simple-vector) get-slots))
280 (declaim (ftype (function (t) (or simple-vector null)) get-slots-or-nil))
281 (defun get-slots (instance)
282   (if (std-instance-p instance)
283       (std-instance-slots instance)
284       (fsc-instance-slots instance)))
285 (defun get-slots-or-nil (instance)
286   ;; Suppress a code-deletion note.  FIXME: doing the FIXME above,
287   ;; integrating PCL more with the compiler, would remove the need for
288   ;; this icky stuff.
289   (declare (optimize (inhibit-warnings 3)))
290   (when (pcl-instance-p instance)
291     (get-slots instance)))
292
293 (defmacro get-wrapper (inst)
294   (once-only ((wrapper `(wrapper-of ,inst)))
295     `(progn
296        (aver (typep ,wrapper 'wrapper))
297        ,wrapper)))
298
299 ;;; FIXME: could be an inline function or ordinary function (like many
300 ;;; other things around here)
301 (defmacro get-instance-wrapper-or-nil (inst)
302   (once-only ((wrapper `(wrapper-of ,inst)))
303     `(if (typep ,wrapper 'wrapper)
304          ,wrapper
305          nil)))
306 \f
307 ;;;; support for useful hashing of PCL instances
308
309 (defvar *instance-hash-code-random-state* (make-random-state))
310 (defun get-instance-hash-code ()
311   ;; ANSI SXHASH wants us to make a good-faith effort to produce
312   ;; hash-codes that are well distributed within the range of
313   ;; non-negative fixnums, and this RANDOM operation does that, unlike
314   ;; the sbcl<=0.8.16 implementation of this operation as
315   ;; (INCF COUNTER).
316   ;;
317   ;; Hopefully there was no virtue to the old counter implementation
318   ;; that I am insufficiently insightful to insee. -- WHN 2004-10-28
319   (random most-positive-fixnum
320           *instance-hash-code-random-state*))
321
322 (defun sb-impl::sxhash-instance (x)
323   (cond
324     ((std-instance-p x) (std-instance-hash x))
325     ((fsc-instance-p x) (fsc-instance-hash x))
326     (t (bug "SXHASH-INSTANCE called on some weird thing: ~S" x))))
327 \f
328 ;;;; structure-instance stuff
329 ;;;;
330 ;;;; FIXME: Now that the code is SBCL-only, this extra layer of
331 ;;;; abstraction around our native structure representation doesn't
332 ;;;; seem to add anything useful, and could probably go away.
333
334 ;;; The definition of STRUCTURE-TYPE-P was moved to early-low.lisp.
335
336 (defun structure-type-slot-description-list (type)
337   (let* ((dd (find-defstruct-description type))
338          (include (dd-include dd))
339          (all-slots (dd-slots dd)))
340     (multiple-value-bind (super slot-overrides)
341         (if (consp include)
342             (values (car include) (mapcar #'car (cdr include)))
343             (values include nil))
344       (let ((included-slots
345              (when super
346                (dd-slots (find-defstruct-description super)))))
347         (loop for slot = (pop all-slots)
348               for included-slot = (pop included-slots)
349               while slot
350               when (or (not included-slot)
351                        (member (dsd-name included-slot) slot-overrides :test #'eq))
352               collect slot)))))
353
354 (defun uninitialized-accessor-function (type slotd)
355   (lambda (&rest args)
356     (declare (ignore args))
357     (error "~:(~A~) function~@[ for ~S ~] not yet initialized."
358            type slotd)))
359
360 (defun structure-slotd-name (slotd)
361   (dsd-name slotd))
362
363 (defun structure-slotd-accessor-symbol (slotd)
364   (dsd-accessor-name slotd))
365
366 (defun structure-slotd-reader-function (slotd)
367   (let ((name (dsd-accessor-name slotd)))
368     (if (fboundp name)
369         (fdefinition name)
370         (uninitialized-accessor-function :reader slotd))))
371
372 (defun structure-slotd-writer-function (type slotd)
373   (if (dsd-read-only slotd)
374       (let ((dd (find-defstruct-description type)))
375         (coerce (slot-setter-lambda-form dd slotd) 'function))
376       (let ((name `(setf ,(dsd-accessor-name slotd))))
377         (if (fboundp name)
378             (fdefinition name)
379             (uninitialized-accessor-function :writer slotd)))))
380
381 (defun structure-slotd-type (slotd)
382   (dsd-type slotd))
383
384 (defun structure-slotd-init-form (slotd)
385   (dsd-default slotd))
386 \f
387 ;;; method function stuff.
388 ;;;
389 ;;; PCL historically included a so-called method-fast-function, which
390 ;;; is essentially a method function but with (a) a precomputed
391 ;;; continuation for CALL-NEXT-METHOD and (b) a permutation vector for
392 ;;; slot access.  [ FIXME: see if we can understand these two
393 ;;; optimizations before commit. ]  However, the presence of the
394 ;;; fast-function meant that we violated AMOP and the effect of the
395 ;;; :FUNCTION initarg, and furthermore got to potentially confusing
396 ;;; situations where the function and the fast-function got out of
397 ;;; sync, so that calling (method-function method) with the defined
398 ;;; protocol would do different things from (call-method method) in
399 ;;; method combination.
400 ;;;
401 ;;; So we define this internal method function structure, which we use
402 ;;; when we create a method function ourselves.  This means that we
403 ;;; can hang the various bits of information that we want off the
404 ;;; method function itself, and also that if a user overrides method
405 ;;; function creation there is no danger of having the system get
406 ;;; confused.
407 (!defstruct-with-alternate-metaclass %method-function
408   :slot-names (fast-function name)
409   :boa-constructor %make-method-function
410   :superclass-name function
411   :metaclass-name static-classoid
412   :metaclass-constructor make-static-classoid
413   :dd-type funcallable-structure)
414