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