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