0.7.7.33:
[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 SEQUENCE) are best tested by letting
28 ;;;; the 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))
61   (unless (constant-continuation-p type)
62     (give-up-ir1-transform "can't open-code test of non-constant type"))
63   `(typep object ',(continuation-value type)))
64
65 ;;; If the continuation OBJECT definitely is or isn't of the specified
66 ;;; type, then return T or NIL as appropriate. Otherwise quietly
67 ;;; GIVE-UP-IR1-TRANSFORM.
68 (defun ir1-transform-type-predicate (object type)
69   (declare (type continuation object) (type ctype type))
70   (let ((otype (continuation-type object)))
71     (cond ((not (types-equal-or-intersect otype type))
72            nil)
73           ((csubtypep otype type)
74            t)
75           (t
76            (give-up-ir1-transform)))))
77
78 ;;; Flush %TYPEP tests whose result is known at compile time.
79 (deftransform %typep ((object type))
80   (unless (constant-continuation-p type)
81     (give-up-ir1-transform))
82   (ir1-transform-type-predicate
83    object
84    (specifier-type (continuation-value type))))
85
86 ;;; This is the IR1 transform for simple type predicates. It checks
87 ;;; whether the single argument is known to (not) be of the
88 ;;; appropriate type, expanding to T or NIL as appropriate.
89 (deftransform fold-type-predicate ((object) * * :node node :defun-only t)
90   (let ((ctype (gethash (leaf-source-name
91                          (ref-leaf
92                           (continuation-use
93                            (basic-combination-fun node))))
94                         *backend-predicate-types*)))
95     (aver ctype)
96     (ir1-transform-type-predicate object ctype)))
97
98 ;;; If FIND-CLASS is called on a constant class, locate the CLASS-CELL
99 ;;; at load time.
100 (deftransform find-class ((name) ((constant-arg symbol)) *)
101   (let* ((name (continuation-value name))
102          (cell (find-class-cell name)))
103     `(or (class-cell-class ',cell)
104          (error "class not yet defined: ~S" name))))
105 \f
106 ;;;; standard type predicates, i.e. those defined in package COMMON-LISP,
107 ;;;; plus at least one oddball (%INSTANCEP)
108 ;;;;
109 ;;;; Various other type predicates (e.g. low-level representation
110 ;;;; stuff like SIMPLE-ARRAY-SINGLE-FLOAT-P) are defined elsewhere.
111
112 ;;; FIXME: This function is only called once, at top level. Why not
113 ;;; just expand all its operations into toplevel code?
114 (defun !define-standard-type-predicates ()
115   (define-type-predicate arrayp array)
116   ; (The ATOM predicate is handled separately as (NOT CONS).)
117   (define-type-predicate bit-vector-p bit-vector)
118   (define-type-predicate characterp character)
119   (define-type-predicate compiled-function-p compiled-function)
120   (define-type-predicate complexp complex)
121   (define-type-predicate complex-rational-p (complex rational))
122   (define-type-predicate complex-float-p (complex float))
123   (define-type-predicate consp cons)
124   (define-type-predicate floatp float)
125   (define-type-predicate functionp function)
126   (define-type-predicate integerp integer)
127   (define-type-predicate keywordp keyword)
128   (define-type-predicate listp list)
129   (define-type-predicate null null)
130   (define-type-predicate numberp number)
131   (define-type-predicate rationalp rational)
132   (define-type-predicate realp real)
133   (define-type-predicate simple-bit-vector-p simple-bit-vector)
134   (define-type-predicate simple-string-p simple-string)
135   (define-type-predicate simple-vector-p simple-vector)
136   (define-type-predicate stringp string)
137   (define-type-predicate %instancep instance)
138   (define-type-predicate funcallable-instance-p funcallable-instance)
139   (define-type-predicate symbolp symbol)
140   (define-type-predicate vectorp vector))
141 (!define-standard-type-predicates)
142 \f
143 ;;;; transforms for type predicates not implemented primitively
144 ;;;;
145 ;;;; See also VM dependent transforms.
146
147 (define-source-transform atom (x)
148   `(not (consp ,x)))
149 \f
150 ;;;; TYPEP source transform
151
152 ;;; Return a form that tests the variable N-OBJECT for being in the
153 ;;; binds specified by TYPE. BASE is the name of the base type, for
154 ;;; declaration. We make SAFETY locally 0 to inhibit any checking of
155 ;;; this assertion.
156 #!-negative-zero-is-not-zero
157 (defun transform-numeric-bound-test (n-object type base)
158   (declare (type numeric-type type))
159   (let ((low (numeric-type-low type))
160         (high (numeric-type-high type)))
161     `(locally
162        (declare (optimize (safety 0)))
163        (and ,@(when low
164                 (if (consp low)
165                     `((> (the ,base ,n-object) ,(car low)))
166                     `((>= (the ,base ,n-object) ,low))))
167             ,@(when high
168                 (if (consp high)
169                     `((< (the ,base ,n-object) ,(car high)))
170                     `((<= (the ,base ,n-object) ,high))))))))
171
172 #!+negative-zero-is-not-zero
173 (defun transform-numeric-bound-test (n-object type base)
174   (declare (type numeric-type type))
175   (let ((low (numeric-type-low type))
176         (high (numeric-type-high type))
177         (float-type-p (csubtypep type (specifier-type 'float)))
178         (x (gensym))
179         (y (gensym)))
180     `(locally
181        (declare (optimize (safety 0)))
182        (and ,@(when low
183                 (if (consp low)
184                     `((let ((,x (the ,base ,n-object))
185                             (,y ,(car low)))
186                         ,(if (not float-type-p)
187                             `(> ,x ,y)
188                             `(if (and (zerop ,x) (zerop ,y))
189                                  (> (float-sign ,x) (float-sign ,y))
190                                  (> ,x ,y)))))
191                     `((let ((,x (the ,base ,n-object))
192                             (,y ,low))
193                         ,(if (not float-type-p)
194                             `(>= ,x ,y)
195                             `(if (and (zerop ,x) (zerop ,y))
196                                  (>= (float-sign ,x) (float-sign ,y))
197                                  (>= ,x ,y)))))))
198             ,@(when high
199                 (if (consp high)
200                     `((let ((,x (the ,base ,n-object))
201                             (,y ,(car high)))
202                         ,(if (not float-type-p)
203                              `(< ,x ,y)
204                              `(if (and (zerop ,x) (zerop ,y))
205                                   (< (float-sign ,x) (float-sign ,y))
206                                   (< ,x ,y)))))
207                     `((let ((,x (the ,base ,n-object))
208                             (,y ,high))
209                         ,(if (not float-type-p)
210                              `(<= ,x ,y)
211                              `(if (and (zerop ,x) (zerop ,y))
212                                   (<= (float-sign ,x) (float-sign ,y))
213                                   (<= ,x ,y)))))))))))
214
215 ;;; Do source transformation of a test of a known numeric type. We can
216 ;;; assume that the type doesn't have a corresponding predicate, since
217 ;;; those types have already been picked off. In particular, CLASS
218 ;;; must be specified, since it is unspecified only in NUMBER and
219 ;;; COMPLEX. Similarly, we assume that COMPLEXP is always specified.
220 ;;;
221 ;;; For non-complex types, we just test that the number belongs to the
222 ;;; base type, and then test that it is in bounds. When CLASS is
223 ;;; INTEGER, we check to see whether the range is no bigger than
224 ;;; FIXNUM. If so, we check for FIXNUM instead of INTEGER. This allows
225 ;;; us to use fixnum comparison to test the bounds.
226 ;;;
227 ;;; For complex types, we must test for complex, then do the above on
228 ;;; both the real and imaginary parts. When CLASS is float, we need
229 ;;; only check the type of the realpart, since the format of the
230 ;;; realpart and the imagpart must be the same.
231 (defun source-transform-numeric-typep (object type)
232   (let* ((class (numeric-type-class type))
233          (base (ecase class
234                  (integer (containing-integer-type type))
235                  (rational 'rational)
236                  (float (or (numeric-type-format type) 'float))
237                  ((nil) 'real))))
238     (once-only ((n-object object))
239       (ecase (numeric-type-complexp type)
240         (:real
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 (the complex ,n-object)))
246                             (n-imag `(imagpart (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-note "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 `(if (funcall #',(second spec) ,object) t nil))
271              ((not and)
272               (once-only ((n-obj object))
273                 `(,(first spec) ,@(mapcar (lambda (x)
274                                             `(typep ,n-obj ',x))
275                                           (rest spec))))))))))
276
277 ;;; Do source transformation for TYPEP of a known union type. If a
278 ;;; union type contains LIST, then we pull that out and make it into a
279 ;;; single LISTP call. Note that if SYMBOL is in the union, then LIST
280 ;;; will be a subtype even without there being any (member NIL). We
281 ;;; just drop through to the general code in this case, rather than
282 ;;; trying to optimize it.
283 (defun source-transform-union-typep (object type)
284   (let* ((types (union-type-types type))
285          (ltype (specifier-type 'list))
286          (mtype (find-if #'member-type-p types)))
287     (if (and mtype (csubtypep ltype type))
288         (let ((members (member-type-members mtype)))
289           (once-only ((n-obj object))
290             `(or (listp ,n-obj)
291                  (typep ,n-obj
292                         '(or ,@(mapcar #'type-specifier
293                                        (remove (specifier-type 'cons)
294                                                (remove mtype types)))
295                              (member ,@(remove nil members)))))))
296         (once-only ((n-obj object))
297           `(or ,@(mapcar (lambda (x)
298                            `(typep ,n-obj ',(type-specifier x)))
299                          types))))))
300
301 ;;; Do source transformation for TYPEP of a known intersection type.
302 (defun source-transform-intersection-typep (object type)
303   (once-only ((n-obj object))
304     `(and ,@(mapcar (lambda (x)
305                       `(typep ,n-obj ',(type-specifier x)))
306                     (intersection-type-types type)))))
307
308 ;;; If necessary recurse to check the cons type.
309 (defun source-transform-cons-typep (object type)
310   (let* ((car-type (cons-type-car-type type))
311          (cdr-type (cons-type-cdr-type type)))
312     (let ((car-test-p (not (or (type= car-type *wild-type*)
313                                (type= car-type (specifier-type t)))))
314           (cdr-test-p (not (or (type= cdr-type *wild-type*)
315                                (type= cdr-type (specifier-type t))))))
316       (if (and (not car-test-p) (not cdr-test-p))
317           `(consp ,object)
318           (once-only ((n-obj object))
319             `(and (consp ,n-obj)
320                   ,@(if car-test-p
321                         `((typep (car ,n-obj)
322                                  ',(type-specifier car-type))))
323                   ,@(if cdr-test-p
324                         `((typep (cdr ,n-obj)
325                                  ',(type-specifier cdr-type))))))))))
326  
327 ;;; Return the predicate and type from the most specific entry in
328 ;;; *TYPE-PREDICATES* that is a supertype of TYPE.
329 (defun find-supertype-predicate (type)
330   (declare (type ctype type))
331   (let ((res nil)
332         (res-type nil))
333     (dolist (x *backend-type-predicates*)
334       (let ((stype (car x)))
335         (when (and (csubtypep type stype)
336                    (or (not res-type)
337                        (csubtypep stype res-type)))
338           (setq res-type stype)
339           (setq res (cdr x)))))
340     (values res res-type)))
341
342 ;;; Return forms to test that OBJ has the rank and dimensions
343 ;;; specified by TYPE, where STYPE is the type we have checked against
344 ;;; (which is the same but for dimensions.)
345 (defun test-array-dimensions (obj type stype)
346   (declare (type array-type type stype))
347   (let ((obj `(truly-the ,(type-specifier stype) ,obj))
348         (dims (array-type-dimensions type)))
349     (unless (eq dims '*)
350       (collect ((res))
351         (when (eq (array-type-dimensions stype) '*)
352           (res `(= (array-rank ,obj) ,(length dims))))
353         (do ((i 0 (1+ i))
354              (dim dims (cdr dim)))
355             ((null dim))
356           (let ((dim (car dim)))
357             (unless (eq dim '*)
358               (res `(= (array-dimension ,obj ,i) ,dim)))))
359         (res)))))
360
361 ;;; If we can find a type predicate that tests for the type without
362 ;;; dimensions, then use that predicate and test for dimensions.
363 ;;; Otherwise, just do %TYPEP.
364 (defun source-transform-array-typep (obj type)
365   (multiple-value-bind (pred stype) (find-supertype-predicate type)
366     (if (and (array-type-p stype)
367              ;; (If the element type hasn't been defined yet, it's
368              ;; not safe to assume here that it will eventually
369              ;; have (UPGRADED-ARRAY-ELEMENT-TYPE type)=T, so punt.)
370              (not (unknown-type-p (array-type-element-type type)))
371              (type= (array-type-specialized-element-type stype)
372                     (array-type-specialized-element-type type))
373              (eq (array-type-complexp stype) (array-type-complexp type)))
374         (once-only ((n-obj obj))
375           `(and (,pred ,n-obj)
376                 ,@(test-array-dimensions n-obj type stype)))
377         `(%typep ,obj ',(type-specifier type)))))
378
379 ;;; Transform a type test against some instance type. The type test is
380 ;;; flushed if the result is known at compile time. If not properly
381 ;;; named, error. If sealed and has no subclasses, just test for
382 ;;; layout-EQ. If a structure then test for layout-EQ and then a
383 ;;; general test based on layout-inherits. If safety is important,
384 ;;; then we also check whether the layout for the object is invalid
385 ;;; and signal an error if so. Otherwise, look up the indirect
386 ;;; class-cell and call CLASS-CELL-TYPEP at runtime.
387 (deftransform %instance-typep ((object spec) (* *) * :node node)
388   (aver (constant-continuation-p spec))
389   (let* ((spec (continuation-value spec))
390          (class (specifier-type spec))
391          (name (sb!xc:class-name class))
392          (otype (continuation-type object))
393          (layout (let ((res (info :type :compiler-layout name)))
394                    (if (and res (not (layout-invalid res)))
395                        res
396                        nil))))
397     (cond
398       ;; Flush tests whose result is known at compile time.
399       ((not (types-equal-or-intersect otype class))
400        nil)
401       ((csubtypep otype class)
402        t)
403       ;; If not properly named, error.
404       ((not (and name (eq (sb!xc:find-class name) class)))
405        (compiler-error "can't compile TYPEP of anonymous or undefined ~
406                         class:~%  ~S"
407                        class))
408       (t
409         ;; Delay the type transform to give type propagation a chance.
410         (delay-ir1-transform node :constraint)
411
412        ;; Otherwise transform the type test.
413        (multiple-value-bind (pred get-layout)
414            (cond
415              ((csubtypep class (specifier-type 'funcallable-instance))
416               (values 'funcallable-instance-p '%funcallable-instance-layout))
417              ((csubtypep class (specifier-type 'instance))
418               (values '%instancep '%instance-layout))
419              (t
420               (values '(lambda (x) (declare (ignore x)) t) 'layout-of)))
421          (cond
422            ((and (eq (class-state class) :sealed) layout
423                  (not (class-subclasses class)))
424             ;; Sealed and has no subclasses.
425             (let ((n-layout (gensym)))
426               `(and (,pred object)
427                     (let ((,n-layout (,get-layout object)))
428                       ,@(when (policy *lexenv* (>= safety speed))
429                               `((when (layout-invalid ,n-layout)
430                                   (%layout-invalid-error object ',layout))))
431                       (eq ,n-layout ',layout)))))
432            ((and (typep class 'basic-structure-class) layout)
433             ;; structure type tests; hierarchical layout depths
434             (let ((depthoid (layout-depthoid layout))
435                   (n-layout (gensym)))
436               `(and (,pred object)
437                     (let ((,n-layout (,get-layout object)))
438                       ,@(when (policy *lexenv* (>= safety speed))
439                               `((when (layout-invalid ,n-layout)
440                                   (%layout-invalid-error object ',layout))))
441                       (if (eq ,n-layout ',layout)
442                           t
443                           (and (> (layout-depthoid ,n-layout)
444                                   ,depthoid)
445                                (locally (declare (optimize (safety 0)))
446                                  (eq (svref (layout-inherits ,n-layout)
447                                             ,depthoid)
448                                      ',layout))))))))
449            ((and layout (>= (layout-depthoid layout) 0))
450             ;; hierarchical layout depths for other things (e.g.
451             ;; CONDITIONs)
452             (let ((depthoid (layout-depthoid layout))
453                   (n-layout (gensym))
454                   (n-inherits (gensym)))
455               `(and (,pred object)
456                     (let ((,n-layout (,get-layout object)))
457                       ,@(when (policy *lexenv* (>= safety speed))
458                           `((when (layout-invalid ,n-layout)
459                               (%layout-invalid-error object ',layout))))
460                       (if (eq ,n-layout ',layout)
461                           t
462                           (let ((,n-inherits (layout-inherits ,n-layout)))
463                             (declare (optimize (safety 0)))
464                             (and (> (length ,n-inherits) ,depthoid)
465                                  (eq (svref ,n-inherits ,depthoid)
466                                      ',layout))))))))
467            (t
468             (/noshow "default case -- ,PRED and CLASS-CELL-TYPEP")
469             `(and (,pred object)
470                   (class-cell-typep (,get-layout object)
471                                     ',(find-class-cell name)
472                                     object)))))))))
473
474 ;;; If the specifier argument is a quoted constant, then we consider
475 ;;; converting into a simple predicate or other stuff. If the type is
476 ;;; constant, but we can't transform the call, then we convert to
477 ;;; %TYPEP. We only pass when the type is non-constant. This allows us
478 ;;; to recognize between calls that might later be transformed
479 ;;; successfully when a constant type is discovered. We don't give an
480 ;;; efficiency note when we pass, since the IR1 transform will give
481 ;;; one if necessary and appropriate.
482 ;;;
483 ;;; If the type is TYPE= to a type that has a predicate, then expand
484 ;;; to that predicate. Otherwise, we dispatch off of the type's type.
485 ;;; These transformations can increase space, but it is hard to tell
486 ;;; when, so we ignore policy and always do them. 
487 (define-source-transform typep (object spec)
488   ;; KLUDGE: It looks bad to only do this on explicitly quoted forms,
489   ;; since that would overlook other kinds of constants. But it turns
490   ;; out that the DEFTRANSFORM for TYPEP detects any constant
491   ;; continuation, transforms it into a quoted form, and gives this
492   ;; source transform another chance, so it all works out OK, in a
493   ;; weird roundabout way. -- WHN 2001-03-18
494   (if (and (consp spec) (eq (car spec) 'quote))
495       (let ((type (specifier-type (cadr spec))))
496         (or (let ((pred (cdr (assoc type *backend-type-predicates*
497                                     :test #'type=))))
498               (when pred `(,pred ,object)))
499             (typecase type
500               (hairy-type
501                (source-transform-hairy-typep object type))
502               (union-type
503                (source-transform-union-typep object type))
504               (intersection-type
505                (source-transform-intersection-typep object type))
506               (member-type
507                `(member ,object ',(member-type-members type)))
508               (args-type
509                (compiler-warn "illegal type specifier for TYPEP: ~S"
510                               (cadr spec))
511                `(%typep ,object ,spec))
512               (t nil))
513             (typecase type
514               (numeric-type
515                (source-transform-numeric-typep object type))
516               (sb!xc:class
517                `(%instance-typep ,object ,spec))
518               (array-type
519                (source-transform-array-typep object type))
520               (cons-type
521                (source-transform-cons-typep object type))
522               (t nil))
523             `(%typep ,object ,spec)))
524       (values nil t)))
525 \f
526 ;;;; coercion
527
528 (deftransform coerce ((x type) (* *) *)
529   (unless (constant-continuation-p type)
530     (give-up-ir1-transform))
531   (let ((tspec (specifier-type (continuation-value type))))
532     (if (csubtypep (continuation-type x) tspec)
533         'x
534         ;; Note: The THE here makes sure that specifiers like
535         ;; (SINGLE-FLOAT 0.0 1.0) can raise a TYPE-ERROR.
536         `(the ,(continuation-value type)
537            ,(cond
538              ((csubtypep tspec (specifier-type 'double-float))
539               '(%double-float x))       
540              ;; FIXME: #!+long-float (t ,(error "LONG-FLOAT case needed"))
541              ((csubtypep tspec (specifier-type 'float))
542               '(%single-float x))
543              ;; FIXME: VECTOR types?
544              (t
545               (give-up-ir1-transform)))))))
546