Optimize testing of sealed structures.
[sbcl.git] / src / compiler / typetran.lisp
1 ;;;; This file contains stuff that implements the portable IR1
2 ;;;; semantics of type tests and coercion. The main thing we do is
3 ;;;; convert complex type operations into simpler code that can be
4 ;;;; compiled inline.
5
6 ;;;; This software is part of the SBCL system. See the README file for
7 ;;;; more information.
8 ;;;;
9 ;;;; This software is derived from the CMU CL system, which was
10 ;;;; written at Carnegie Mellon University and released into the
11 ;;;; public domain. The software is in the public domain and is
12 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
13 ;;;; files for more information.
14
15 (in-package "SB!C")
16 \f
17 ;;;; type predicate translation
18 ;;;;
19 ;;;; We maintain a bidirectional association between type predicates
20 ;;;; and the tested type. The presence of a predicate in this
21 ;;;; association implies that it is desirable to implement tests of
22 ;;;; this type using the predicate. These are either predicates that
23 ;;;; the back end is likely to have special knowledge about, or
24 ;;;; predicates so complex that the only reasonable implentation is
25 ;;;; via function call.
26 ;;;;
27 ;;;; Some standard types (such as ATOM) are best tested by letting the
28 ;;;; TYPEP source transform do its thing with the expansion. These
29 ;;;; types (and corresponding predicates) are not maintained in this
30 ;;;; association. In this case, there need not be any predicate
31 ;;;; function unless it is required by the Common Lisp specification.
32 ;;;;
33 ;;;; The mapping between predicates and type structures is considered
34 ;;;; part of the backend; different backends can support different
35 ;;;; sets of predicates.
36
37 ;;; Establish an association between the type predicate NAME and the
38 ;;; corresponding TYPE. This causes the type predicate to be
39 ;;; recognized for purposes of optimization.
40 (defmacro define-type-predicate (name type)
41   `(%define-type-predicate ',name ',type))
42 (defun %define-type-predicate (name specifier)
43   (let ((type (specifier-type specifier)))
44     (setf (gethash name *backend-predicate-types*) type)
45     (setf *backend-type-predicates*
46           (cons (cons type name)
47                 (remove name *backend-type-predicates*
48                         :key #'cdr)))
49     (%deftransform name '(function (t) *) #'fold-type-predicate)
50     name))
51 \f
52 ;;;; IR1 transforms
53
54 ;;; If we discover the type argument is constant during IR1
55 ;;; optimization, then give the source transform another chance. The
56 ;;; source transform can't pass, since we give it an explicit
57 ;;; constant. At worst, it will convert to %TYPEP, which will prevent
58 ;;; spurious attempts at transformation (and possible repeated
59 ;;; warnings.)
60 (deftransform typep ((object type &optional env) * * :node node)
61   (unless (constant-lvar-p type)
62     (give-up-ir1-transform "can't open-code test of non-constant type"))
63   (unless (and (constant-lvar-p env) (null (lvar-value env)))
64     (give-up-ir1-transform "environment argument present and not null"))
65   (multiple-value-bind (expansion fail-p)
66       (source-transform-typep 'object (lvar-value type))
67     (if fail-p
68         (abort-ir1-transform)
69         expansion)))
70
71 ;;; If the lvar OBJECT definitely is or isn't of the specified
72 ;;; type, then return T or NIL as appropriate. Otherwise quietly
73 ;;; GIVE-UP-IR1-TRANSFORM.
74 (defun ir1-transform-type-predicate (object type node)
75   (declare (type lvar object) (type ctype type))
76   (let ((otype (lvar-type object)))
77     (flet ((tricky ()
78              (cond ((typep type 'alien-type-type)
79                     ;; We don't transform alien type tests until here, because
80                     ;; once we do that the rest of the type system can no longer
81                     ;; reason about them properly -- so we'd miss out on type
82                     ;; derivation, etc.
83                     (delay-ir1-transform node :optimize)
84                     (let ((alien-type (alien-type-type-alien-type type)))
85                       ;; If it's a lisp-rep-type, the CTYPE should be one already.
86                       (aver (not (compute-lisp-rep-type alien-type)))
87                       `(sb!alien::alien-value-typep object ',alien-type)))
88                    (t
89                     (give-up-ir1-transform)))))
90       (cond ((not (types-equal-or-intersect otype type))
91             nil)
92            ((csubtypep otype type)
93             t)
94            ((eq type *empty-type*)
95             nil)
96            (t
97             (let ((intersect (type-intersection2 type otype)))
98               (unless intersect
99                 (tricky))
100               (multiple-value-bind (constantp value)
101                   (type-singleton-p intersect)
102                 (if constantp
103                     `(eql object ',value)
104                     (tricky)))))))))
105
106 ;;; Flush %TYPEP tests whose result is known at compile time.
107 (deftransform %typep ((object type) * * :node node)
108   (unless (constant-lvar-p type)
109     (give-up-ir1-transform))
110   (ir1-transform-type-predicate
111    object
112    (ir1-transform-specifier-type (lvar-value type))
113    node))
114
115 ;;; This is the IR1 transform for simple type predicates. It checks
116 ;;; whether the single argument is known to (not) be of the
117 ;;; appropriate type, expanding to T or NIL as appropriate.
118 (deftransform fold-type-predicate ((object) * * :node node :defun-only t)
119   (let ((ctype (gethash (leaf-source-name
120                          (ref-leaf
121                           (lvar-uses
122                            (basic-combination-fun node))))
123                         *backend-predicate-types*)))
124     (aver ctype)
125     (ir1-transform-type-predicate object ctype node)))
126
127 ;;; If FIND-CLASSOID is called on a constant class, locate the
128 ;;; CLASSOID-CELL at load time.
129 (deftransform find-classoid ((name) ((constant-arg symbol)) *)
130   (let* ((name (lvar-value name))
131          (cell (find-classoid-cell name :create t)))
132     `(or (classoid-cell-classoid ',cell)
133          (error "class not yet defined: ~S" name))))
134 \f
135 (defoptimizer (%typep-wrapper constraint-propagate-if)
136     ((test-value variable type) node gen)
137   (aver (constant-lvar-p type))
138   (let ((type (lvar-value type)))
139     (values variable (if (ctype-p type)
140                          type
141                          (handler-case (careful-specifier-type type)
142                            (t () nil))))))
143
144 (deftransform %typep-wrapper ((test-value variable type) * * :node node)
145   (aver (constant-lvar-p type))
146   (if (constant-lvar-p test-value)
147       `',(lvar-value test-value)
148       (let* ((type (lvar-value type))
149              (type (if (ctype-p type)
150                        type
151                        (handler-case (careful-specifier-type type)
152                          (t () nil))))
153              (value-type (lvar-type variable)))
154         (cond ((not type)
155                'test-value)
156               ((csubtypep value-type type)
157                t)
158               ((not (types-equal-or-intersect value-type type))
159                nil)
160               (t
161                (delay-ir1-transform node :constraint)
162                'test-value)))))
163 \f
164 ;;;; standard type predicates, i.e. those defined in package COMMON-LISP,
165 ;;;; plus at least one oddball (%INSTANCEP)
166 ;;;;
167 ;;;; Various other type predicates (e.g. low-level representation
168 ;;;; stuff like SIMPLE-ARRAY-SINGLE-FLOAT-P) are defined elsewhere.
169
170 ;;; FIXME: This function is only called once, at top level. Why not
171 ;;; just expand all its operations into toplevel code?
172 (defun !define-standard-type-predicates ()
173   (define-type-predicate arrayp array)
174   ; (The ATOM predicate is handled separately as (NOT CONS).)
175   (define-type-predicate bit-vector-p bit-vector)
176   (define-type-predicate characterp character)
177   (define-type-predicate compiled-function-p compiled-function)
178   (define-type-predicate complexp complex)
179   (define-type-predicate complex-rational-p (complex rational))
180   (define-type-predicate complex-float-p (complex float))
181   (define-type-predicate consp cons)
182   (define-type-predicate floatp float)
183   (define-type-predicate functionp function)
184   (define-type-predicate integerp integer)
185   (define-type-predicate keywordp keyword)
186   (define-type-predicate listp list)
187   (define-type-predicate null null)
188   (define-type-predicate numberp number)
189   (define-type-predicate rationalp rational)
190   (define-type-predicate realp real)
191   (define-type-predicate sequencep sequence)
192   (define-type-predicate extended-sequence-p extended-sequence)
193   (define-type-predicate simple-bit-vector-p simple-bit-vector)
194   (define-type-predicate simple-string-p simple-string)
195   (define-type-predicate simple-vector-p simple-vector)
196   (define-type-predicate stringp string)
197   (define-type-predicate %instancep instance)
198   (define-type-predicate funcallable-instance-p funcallable-instance)
199   (define-type-predicate symbolp symbol)
200   (define-type-predicate vectorp vector))
201 (!define-standard-type-predicates)
202 \f
203 ;;;; transforms for type predicates not implemented primitively
204 ;;;;
205 ;;;; See also VM dependent transforms.
206
207 (define-source-transform atom (x)
208   `(not (consp ,x)))
209 #!+sb-unicode
210 (define-source-transform base-char-p (x)
211   `(typep ,x 'base-char))
212 \f
213 ;;;; TYPEP source transform
214
215 ;;; Return a form that tests the variable N-OBJECT for being in the
216 ;;; binds specified by TYPE. BASE is the name of the base type, for
217 ;;; declaration. We make SAFETY locally 0 to inhibit any checking of
218 ;;; this assertion.
219 (defun transform-numeric-bound-test (n-object type base)
220   (declare (type numeric-type type))
221   (let ((low (numeric-type-low type))
222         (high (numeric-type-high type)))
223     `(locally
224        (declare (optimize (safety 0)))
225        (and ,@(when low
226                 (if (consp low)
227                     `((> (truly-the ,base ,n-object) ,(car low)))
228                     `((>= (truly-the ,base ,n-object) ,low))))
229             ,@(when high
230                 (if (consp high)
231                     `((< (truly-the ,base ,n-object) ,(car high)))
232                     `((<= (truly-the ,base ,n-object) ,high))))))))
233
234 ;;; Do source transformation of a test of a known numeric type. We can
235 ;;; assume that the type doesn't have a corresponding predicate, since
236 ;;; those types have already been picked off. In particular, CLASS
237 ;;; must be specified, since it is unspecified only in NUMBER and
238 ;;; COMPLEX. Similarly, we assume that COMPLEXP is always specified.
239 ;;;
240 ;;; For non-complex types, we just test that the number belongs to the
241 ;;; base type, and then test that it is in bounds. When CLASS is
242 ;;; INTEGER, we check to see whether the range is no bigger than
243 ;;; FIXNUM. If so, we check for FIXNUM instead of INTEGER. This allows
244 ;;; us to use fixnum comparison to test the bounds.
245 ;;;
246 ;;; For complex types, we must test for complex, then do the above on
247 ;;; both the real and imaginary parts. When CLASS is float, we need
248 ;;; only check the type of the realpart, since the format of the
249 ;;; realpart and the imagpart must be the same.
250 (defun source-transform-numeric-typep (object type)
251   (let* ((class (numeric-type-class type))
252          (base (ecase class
253                  (integer (containing-integer-type
254                            (if (numeric-type-complexp type)
255                                (modified-numeric-type type
256                                                       :complexp :real)
257                                type)))
258                  (rational 'rational)
259                  (float (or (numeric-type-format type) 'float))
260                  ((nil) 'real))))
261     (once-only ((n-object object))
262       (ecase (numeric-type-complexp type)
263         (:real
264          (if (and #!-(or x86 x86-64) ;; Not implemented elsewhere yet
265                   nil
266                   (eql (numeric-type-class type) 'integer)
267                   (eql (numeric-type-low type) 0)
268                   (fixnump (numeric-type-high type)))
269              `(fixnum-mod-p ,n-object ,(numeric-type-high type))
270              `(and (typep ,n-object ',base)
271                    ,(transform-numeric-bound-test n-object type base))))
272         (:complex
273          `(and (complexp ,n-object)
274                ,(once-only ((n-real `(realpart (truly-the complex ,n-object)))
275                             (n-imag `(imagpart (truly-the complex ,n-object))))
276                   `(progn
277                      ,n-imag ; ignorable
278                      (and (typep ,n-real ',base)
279                           ,@(when (eq class 'integer)
280                               `((typep ,n-imag ',base)))
281                           ,(transform-numeric-bound-test n-real type base)
282                           ,(transform-numeric-bound-test n-imag type
283                                                          base))))))))))
284
285 ;;; Do the source transformation for a test of a hairy type. AND,
286 ;;; SATISFIES and NOT are converted into the obvious code. We convert
287 ;;; unknown types to %TYPEP, emitting an efficiency note if
288 ;;; appropriate.
289 (defun source-transform-hairy-typep (object type)
290   (declare (type hairy-type type))
291   (let ((spec (hairy-type-specifier type)))
292     (cond ((unknown-type-p type)
293            (when (policy *lexenv* (> speed inhibit-warnings))
294              (compiler-notify "can't open-code test of unknown type ~S"
295                               (type-specifier type)))
296            `(%typep ,object ',spec))
297           (t
298            (ecase (first spec)
299              (satisfies
300               `(if (funcall (global-function ,(second spec)) ,object) t nil))
301              ((not and)
302               (once-only ((n-obj object))
303                 `(,(first spec) ,@(mapcar (lambda (x)
304                                             `(typep ,n-obj ',x))
305                                           (rest spec))))))))))
306
307 (defun source-transform-negation-typep (object type)
308   (declare (type negation-type type))
309   (let ((spec (type-specifier (negation-type-type type))))
310     `(not (typep ,object ',spec))))
311
312 ;;; Do source transformation for TYPEP of a known union type. If a
313 ;;; union type contains LIST, then we pull that out and make it into a
314 ;;; single LISTP call.  Note that if SYMBOL is in the union, then LIST
315 ;;; will be a subtype even without there being any (member NIL).  We
316 ;;; currently just drop through to the general code in this case,
317 ;;; rather than trying to optimize it (but FIXME CSR 2004-04-05: it
318 ;;; wouldn't be hard to optimize it after all).
319 (defun source-transform-union-typep (object type)
320   (let* ((types (union-type-types type))
321          (type-cons (specifier-type 'cons))
322          (mtype (find-if #'member-type-p types))
323          (members (when mtype (member-type-members mtype))))
324     (if (and mtype
325              (memq nil members)
326              (memq type-cons types))
327         (once-only ((n-obj object))
328           `(or (listp ,n-obj)
329                (typep ,n-obj
330                       '(or ,@(mapcar #'type-specifier
331                                      (remove type-cons
332                                              (remove mtype types)))
333                         (member ,@(remove nil members))))))
334         (once-only ((n-obj object))
335           `(or ,@(mapcar (lambda (x)
336                            `(typep ,n-obj ',(type-specifier x)))
337                          types))))))
338
339 ;;; Do source transformation for TYPEP of a known intersection type.
340 (defun source-transform-intersection-typep (object type)
341   (once-only ((n-obj object))
342     `(and ,@(mapcar (lambda (x)
343                       `(typep ,n-obj ',(type-specifier x)))
344                     (intersection-type-types type)))))
345
346 ;;; If necessary recurse to check the cons type.
347 (defun source-transform-cons-typep (object type)
348   (let* ((car-type (cons-type-car-type type))
349          (cdr-type (cons-type-cdr-type type)))
350     (let ((car-test-p (not (type= car-type *universal-type*)))
351           (cdr-test-p (not (type= cdr-type *universal-type*))))
352       (if (and (not car-test-p) (not cdr-test-p))
353           `(consp ,object)
354           (once-only ((n-obj object))
355             `(and (consp ,n-obj)
356                   ,@(if car-test-p
357                         `((typep (car ,n-obj)
358                                  ',(type-specifier car-type))))
359                   ,@(if cdr-test-p
360                         `((typep (cdr ,n-obj)
361                                  ',(type-specifier cdr-type))))))))))
362
363 (defun source-transform-character-set-typep (object type)
364   (let ((pairs (character-set-type-pairs type)))
365     (if (and (= (length pairs) 1)
366             (= (caar pairs) 0)
367             (= (cdar pairs) (1- sb!xc:char-code-limit)))
368        `(characterp ,object)
369        (once-only ((n-obj object))
370          (let ((n-code (gensym "CODE")))
371            `(and (characterp ,n-obj)
372                  (let ((,n-code (sb!xc:char-code ,n-obj)))
373                    (or
374                     ,@(loop for pair in pairs
375                             collect
376                             `(<= ,(car pair) ,n-code ,(cdr pair)))))))))))
377
378 #!+sb-simd-pack
379 (defun source-transform-simd-pack-typep (object type)
380   (if (type= type (specifier-type 'simd-pack))
381       `(simd-pack-p ,object)
382       (once-only ((n-obj object))
383         (let ((n-tag (gensym "TAG")))
384           `(and
385             (simd-pack-p ,n-obj)
386             (let ((,n-tag (%simd-pack-tag ,n-obj)))
387               (or ,@(loop
388                       for type in (simd-pack-type-element-type type)
389                       for index = (position type *simd-pack-element-types*)
390                       collect `(eql ,n-tag ,index)))))))))
391
392 ;;; Return the predicate and type from the most specific entry in
393 ;;; *TYPE-PREDICATES* that is a supertype of TYPE.
394 (defun find-supertype-predicate (type)
395   (declare (type ctype type))
396   (let ((res nil)
397         (res-type nil))
398     (dolist (x *backend-type-predicates*)
399       (let ((stype (car x)))
400         (when (and (csubtypep type stype)
401                    (or (not res-type)
402                        (csubtypep stype res-type)))
403           (setq res-type stype)
404           (setq res (cdr x)))))
405     (values res res-type)))
406
407 ;;; Return forms to test that OBJ has the rank and dimensions
408 ;;; specified by TYPE, where STYPE is the type we have checked against
409 ;;; (which is the same but for dimensions and element type).
410 ;;;
411 ;;; Secondary return value is true if passing the generated tests implies that
412 ;;; the array has a header.
413 (defun test-array-dimensions (obj type stype)
414   (declare (type array-type type stype))
415   (let ((obj `(truly-the ,(type-specifier stype) ,obj))
416         (dims (array-type-dimensions type)))
417     (unless (or (eq dims '*)
418                 (equal dims (array-type-dimensions stype)))
419       (cond ((cdr dims)
420              (values `((array-header-p ,obj)
421                        ,@(when (eq (array-type-dimensions stype) '*)
422                                `((= (%array-rank ,obj) ,(length dims))))
423                        ,@(loop for d in dims
424                                for i from 0
425                                unless (eq '* d)
426                                collect `(= (%array-dimension ,obj ,i) ,d)))
427                      t))
428             ((not dims)
429              (values `((array-header-p ,obj)
430                        (= (%array-rank ,obj) 0))
431                      t))
432             ((not (array-type-complexp type))
433              (if (csubtypep stype (specifier-type 'vector))
434                  (values (unless (eq '* (car dims))
435                            `((= (vector-length ,obj) ,@dims)))
436                          nil)
437                  (values (if (eq '* (car dims))
438                              `((not (array-header-p ,obj)))
439                              `((not (array-header-p ,obj))
440                                (= (vector-length ,obj) ,@dims)))
441                          nil)))
442             (t
443              (values (unless (eq '* (car dims))
444                        `((if (array-header-p ,obj)
445                              (= (%array-dimension ,obj 0) ,@dims)
446                              (= (vector-length ,obj) ,@dims))))
447                      nil))))))
448
449 ;;; Return forms to test that OBJ has the element-type specified by type
450 ;;; specified by TYPE, where STYPE is the type we have checked against (which
451 ;;; is the same but for dimensions and element type). If HEADERP is true, OBJ
452 ;;; is guaranteed to be an array-header.
453 (defun test-array-element-type (obj type stype headerp)
454   (declare (type array-type type stype))
455   (let ((obj `(truly-the ,(type-specifier stype) ,obj))
456         (eltype (array-type-specialized-element-type type)))
457     (unless (or (type= eltype (array-type-specialized-element-type stype))
458                 (eq eltype *wild-type*))
459       (let ((typecode (sb!vm:saetp-typecode (find-saetp-by-ctype eltype))))
460         (with-unique-names (data)
461          (if (and headerp (not (array-type-complexp stype)))
462              ;; If we know OBJ is an array header, and that the array is
463              ;; simple, we also know there is exactly one indirection to
464              ;; follow.
465              `((eq (%other-pointer-widetag (%array-data-vector ,obj)) ,typecode))
466              `((do ((,data ,(if headerp `(%array-data-vector ,obj) obj)
467                            (%array-data-vector ,data)))
468                    ((not (array-header-p ,data))
469                     (eq (%other-pointer-widetag ,data) ,typecode))))))))))
470
471 ;;; If we can find a type predicate that tests for the type without
472 ;;; dimensions, then use that predicate and test for dimensions.
473 ;;; Otherwise, just do %TYPEP.
474 (defun source-transform-array-typep (obj type)
475   (multiple-value-bind (pred stype) (find-supertype-predicate type)
476     (if (and (array-type-p stype)
477              ;; (If the element type hasn't been defined yet, it's
478              ;; not safe to assume here that it will eventually
479              ;; have (UPGRADED-ARRAY-ELEMENT-TYPE type)=T, so punt.)
480              (not (unknown-type-p (array-type-element-type type)))
481              (or (eq (array-type-complexp stype) (array-type-complexp type))
482                  (and (eql (array-type-complexp stype) :maybe)
483                       (eql (array-type-complexp type) t))))
484         (once-only ((n-obj obj))
485           (multiple-value-bind (tests headerp)
486               (test-array-dimensions n-obj type stype)
487             `(and (,pred ,n-obj)
488                   ,@(when (and (eql (array-type-complexp stype) :maybe)
489                                (eql (array-type-complexp type) t))
490                       ;; KLUDGE: this is a bit lame; if we get here,
491                       ;; we already know that N-OBJ is an array, but
492                       ;; (NOT SIMPLE-ARRAY) doesn't know that.  On the
493                       ;; other hand, this should get compiled down to
494                       ;; two widetag tests, so it's only a bit lame.
495                       `((typep ,n-obj '(not simple-array))))
496                   ,@tests
497                   ,@(test-array-element-type n-obj type stype headerp))))
498         `(%typep ,obj ',(type-specifier type)))))
499
500 ;;; Transform a type test against some instance type. The type test is
501 ;;; flushed if the result is known at compile time. If not properly
502 ;;; named, error. If sealed and has no subclasses, just test for
503 ;;; layout-EQ. If a structure then test for layout-EQ and then a
504 ;;; general test based on layout-inherits. If safety is important,
505 ;;; then we also check whether the layout for the object is invalid
506 ;;; and signal an error if so. Otherwise, look up the indirect
507 ;;; class-cell and call CLASS-CELL-TYPEP at runtime.
508 (deftransform %instance-typep ((object spec) (* *) * :node node)
509   (aver (constant-lvar-p spec))
510   (let* ((spec (lvar-value spec))
511          (class (specifier-type spec))
512          (name (classoid-name class))
513          (otype (lvar-type object))
514          (layout (let ((res (info :type :compiler-layout name)))
515                    (if (and res (not (layout-invalid res)))
516                        res
517                        nil))))
518     (cond
519       ;; Flush tests whose result is known at compile time.
520       ((not (types-equal-or-intersect otype class))
521        nil)
522       ((csubtypep otype class)
523        t)
524       ;; If not properly named, error.
525       ((not (and name (eq (find-classoid name) class)))
526        (compiler-error "can't compile TYPEP of anonymous or undefined ~
527                         class:~%  ~S"
528                        class))
529       (t
530        ;; Delay the type transform to give type propagation a chance.
531        (delay-ir1-transform node :constraint)
532
533        ;; Otherwise transform the type test.
534        (multiple-value-bind (pred get-layout)
535            (cond
536              ((csubtypep class (specifier-type 'funcallable-instance))
537               (values 'funcallable-instance-p '%funcallable-instance-layout))
538              ((csubtypep class (specifier-type 'instance))
539               (values '%instancep '%instance-layout))
540              (t
541               (values '(lambda (x) (declare (ignore x)) t) 'layout-of)))
542          (cond
543            ((and (eq (classoid-state class) :sealed) layout
544                  (not (classoid-subclasses class)))
545             ;; Sealed and has no subclasses.
546             `(and (,pred object)
547                   (eq (,get-layout object) ',layout)))
548            ((and (typep class 'structure-classoid) layout)
549             ;; structure type tests; hierarchical layout depths
550             (let ((depthoid (layout-depthoid layout))
551                   (n-layout (gensym)))
552               `(and (,pred object)
553                     (let ((,n-layout (,get-layout object)))
554                       ;; we used to check for invalid layouts here,
555                       ;; but in fact that's both unnecessary and
556                       ;; wrong; it's unnecessary because structure
557                       ;; classes can't be redefined, and it's wrong
558                       ;; because it is quite legitimate to pass an
559                       ;; object with an invalid layout to a structure
560                       ;; type test.
561                       (if (eq ,n-layout ',layout)
562                           t
563                           (and (> (layout-depthoid ,n-layout)
564                                   ,depthoid)
565                                (locally (declare (optimize (safety 0)))
566                                  ;; Use DATA-VECTOR-REF directly,
567                                  ;; since that's what SVREF in a
568                                  ;; SAFETY 0 lexenv will eventually be
569                                  ;; transformed to. This can give a
570                                  ;; large compilation speedup, since
571                                  ;; %INSTANCE-TYPEPs are frequently
572                                  ;; created during GENERATE-TYPE-CHECKS,
573                                  ;; and the normal aref transformation path
574                                  ;; is pretty heavy.
575                                  (eq (data-vector-ref (layout-inherits ,n-layout)
576                                                       ,depthoid)
577                                      ',layout))))))))
578            ((and layout (>= (layout-depthoid layout) 0))
579             ;; hierarchical layout depths for other things (e.g.
580             ;; CONDITION, STREAM)
581             (let ((depthoid (layout-depthoid layout))
582                   (n-layout (gensym))
583                   (n-inherits (gensym)))
584               `(and (,pred object)
585                     (let ((,n-layout (,get-layout object)))
586                       (when (layout-invalid ,n-layout)
587                         (setq ,n-layout (update-object-layout-or-invalid
588                                          object ',layout)))
589                       (if (eq ,n-layout ',layout)
590                           t
591                           (let ((,n-inherits (layout-inherits ,n-layout)))
592                             (declare (optimize (safety 0)))
593                             (and (> (length ,n-inherits) ,depthoid)
594                                  ;; See above.
595                                  (eq (data-vector-ref ,n-inherits ,depthoid)
596                                      ',layout))))))))
597            (t
598             (/noshow "default case -- ,PRED and CLASS-CELL-TYPEP")
599             `(and (,pred object)
600                   (classoid-cell-typep (,get-layout object)
601                                        ',(find-classoid-cell name :create t)
602                                        object)))))))))
603
604 ;;; If the specifier argument is a quoted constant, then we consider
605 ;;; converting into a simple predicate or other stuff. If the type is
606 ;;; constant, but we can't transform the call, then we convert to
607 ;;; %TYPEP. We only pass when the type is non-constant. This allows us
608 ;;; to recognize between calls that might later be transformed
609 ;;; successfully when a constant type is discovered. We don't give an
610 ;;; efficiency note when we pass, since the IR1 transform will give
611 ;;; one if necessary and appropriate.
612 ;;;
613 ;;; If the type is TYPE= to a type that has a predicate, then expand
614 ;;; to that predicate. Otherwise, we dispatch off of the type's type.
615 ;;; These transformations can increase space, but it is hard to tell
616 ;;; when, so we ignore policy and always do them.
617 (defun %source-transform-typep (object type)
618   (let ((ctype (careful-specifier-type type)))
619     (or (when (not ctype)
620           (compiler-warn "illegal type specifier for TYPEP: ~S" type)
621           (return-from %source-transform-typep (values nil t)))
622         (multiple-value-bind (constantp value) (type-singleton-p ctype)
623           (and constantp
624                `(eql ,object ',value)))
625         (let ((pred (cdr (assoc ctype *backend-type-predicates*
626                                 :test #'type=))))
627           (when pred `(,pred ,object)))
628         (typecase ctype
629           (hairy-type
630            (source-transform-hairy-typep object ctype))
631           (negation-type
632            (source-transform-negation-typep object ctype))
633           (union-type
634            (source-transform-union-typep object ctype))
635           (intersection-type
636            (source-transform-intersection-typep object ctype))
637           (member-type
638            `(if (member ,object ',(member-type-members ctype)) t))
639           (args-type
640            (compiler-warn "illegal type specifier for TYPEP: ~S" type)
641            (return-from %source-transform-typep (values nil t)))
642           (t nil))
643         (typecase ctype
644           (numeric-type
645            (source-transform-numeric-typep object ctype))
646           (classoid
647            `(%instance-typep ,object ',type))
648           (array-type
649            (source-transform-array-typep object ctype))
650           (cons-type
651            (source-transform-cons-typep object ctype))
652           (character-set-type
653            (source-transform-character-set-typep object ctype))
654           #!+sb-simd-pack
655           (simd-pack-type
656            (source-transform-simd-pack-typep object ctype))
657           (t nil))
658         `(%typep ,object ',type))))
659
660 (defun source-transform-typep (object type)
661   (let ((name (gensym "OBJECT")))
662     (multiple-value-bind (transform error)
663         (%source-transform-typep name type)
664       (if error
665           (values nil t)
666           (values `(let ((,name ,object))
667                      (%typep-wrapper ,transform ,name ',type)))))))
668
669 (define-source-transform typep (object spec &optional env)
670   ;; KLUDGE: It looks bad to only do this on explicitly quoted forms,
671   ;; since that would overlook other kinds of constants. But it turns
672   ;; out that the DEFTRANSFORM for TYPEP detects any constant
673   ;; lvar, transforms it into a quoted form, and gives this
674   ;; source transform another chance, so it all works out OK, in a
675   ;; weird roundabout way. -- WHN 2001-03-18
676   (if (and (not env)
677            (consp spec)
678            (eq (car spec) 'quote)
679            (or (not *allow-instrumenting*)
680                (policy *lexenv* (= store-coverage-data 0))))
681       (source-transform-typep object (cadr spec))
682       (values nil t)))
683 \f
684 ;;;; coercion
685
686 ;;; Constant-folding.
687 ;;;
688 #-sb-xc-host
689 (defoptimizer (coerce optimizer) ((x type) node)
690   (when (and (constant-lvar-p x) (constant-lvar-p type))
691     (let ((value (lvar-value x)))
692       (when (or (numberp value) (characterp value))
693         (constant-fold-call node)
694         t))))
695
696 ;;; Drops dimension information from vector types.
697 (defun simplify-vector-type (type)
698   (aver (csubtypep type (specifier-type '(array * (*)))))
699   (let* ((array-type
700           (if (csubtypep type (specifier-type 'simple-array))
701               'simple-array
702               'array))
703          (complexp
704           (not
705            (or (eq 'simple-array array-type)
706                (neq *empty-type*
707                     (type-intersection type (specifier-type 'simple-array)))))))
708     (dolist (etype
709               #+sb-xc-host '(t bit character)
710               #-sb-xc-host sb!kernel::*specialized-array-element-types*
711               #+sb-xc-host (values nil nil nil)
712               #-sb-xc-host (values `(,array-type * (*)) t complexp))
713       (when etype
714         (let ((simplified (specifier-type `(,array-type ,etype (*)))))
715           (when (csubtypep type simplified)
716             (return (values (type-specifier simplified)
717                             etype
718                             complexp))))))))
719
720 (deftransform coerce ((x type) (* *) * :node node)
721   (unless (constant-lvar-p type)
722     (give-up-ir1-transform))
723   (let* ((tval (lvar-value type))
724          (tspec (ir1-transform-specifier-type tval)))
725     (if (csubtypep (lvar-type x) tspec)
726         'x
727         ;; Note: The THE forms we use to wrap the results make sure that
728         ;; specifiers like (SINGLE-FLOAT 0.0 1.0) can raise a TYPE-ERROR.
729         (cond
730           ((csubtypep tspec (specifier-type 'double-float))
731            `(the ,tval (%double-float x)))
732           ;; FIXME: #!+long-float (t ,(error "LONG-FLOAT case needed"))
733           ((csubtypep tspec (specifier-type 'float))
734            `(the ,tval (%single-float x)))
735            ;; Special case STRING and SIMPLE-STRING as they are union types
736            ;; in SBCL.
737            ((member tval '(string simple-string))
738             `(the ,tval
739                (if (typep x ',tval)
740                    x
741                    (replace (make-array (length x) :element-type 'character) x))))
742            ;; Special case VECTOR
743            ((eq tval 'vector)
744             `(the ,tval
745                (if (vectorp x)
746                    x
747                    (replace (make-array (length x)) x))))
748            ;; Handle specialized element types for 1D arrays.
749            ((csubtypep tspec (specifier-type '(array * (*))))
750             ;; Can we avoid checking for dimension issues like (COERCE FOO
751             ;; '(SIMPLE-VECTOR 5)) returning a vector of length 6?
752             ;;
753             ;; CLHS actually allows this for all code with SAFETY < 3,
754             ;; but we're a conservative bunch.
755             (if (or (policy node (zerop safety)) ; no need in unsafe code
756                     (and (array-type-p tspec)    ; no need when no dimensions
757                          (equal (array-type-dimensions tspec) '(*))))
758                 ;; We can!
759                 (multiple-value-bind (vtype etype complexp) (simplify-vector-type tspec)
760                   (unless vtype
761                     (give-up-ir1-transform))
762                   `(the ,vtype
763                      (if (typep x ',vtype)
764                          x
765                          (replace
766                           (make-array (length x) :element-type ',etype
767                                       ,@(when complexp
768                                               (list :fill-pointer t
769                                                     :adjustable t)))
770                           x))))
771                 ;; No, duh. Dimension checking required.
772                 (give-up-ir1-transform
773                  "~@<~S specifies dimensions other than (*) in safe code.~:@>"
774                  tval)))
775            (t
776             (give-up-ir1-transform
777              "~@<open coding coercion to ~S not implemented.~:@>"
778              tval))))))