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