More compact type testing of classes.
[sbcl.git] / src / compiler / typetran.lisp
blob90932e43bf258204572808b4ad700026e320cc43
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.
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.
15 (in-package "SB!C")
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.
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))
52 ;;;; IR1 transforms
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 (or (null env)
64 (and (constant-lvar-p env) (null (lvar-value env))))
65 (give-up-ir1-transform "environment argument present and not null"))
66 (multiple-value-bind (expansion fail-p)
67 (source-transform-typep 'object (lvar-value type))
68 (if fail-p
69 (abort-ir1-transform)
70 expansion)))
72 ;;; If the lvar OBJECT definitely is or isn't of the specified
73 ;;; type, then return T or NIL as appropriate. Otherwise quietly
74 ;;; GIVE-UP-IR1-TRANSFORM.
75 (defun ir1-transform-type-predicate (object type node)
76 (declare (type lvar object) (type ctype type))
77 (let ((otype (lvar-type object)))
78 (flet ((tricky ()
79 (cond ((typep type 'alien-type-type)
80 ;; We don't transform alien type tests until here, because
81 ;; once we do that the rest of the type system can no longer
82 ;; reason about them properly -- so we'd miss out on type
83 ;; derivation, etc.
84 (delay-ir1-transform node :optimize)
85 (let ((alien-type (alien-type-type-alien-type type)))
86 ;; If it's a lisp-rep-type, the CTYPE should be one already.
87 (aver (not (compute-lisp-rep-type alien-type)))
88 `(sb!alien::alien-value-typep object ',alien-type)))
90 (give-up-ir1-transform)))))
91 (cond ((not (types-equal-or-intersect otype type))
92 nil)
93 ((csubtypep otype type)
95 ((eq type *empty-type*)
96 nil)
98 (let ((intersect (type-intersection2 type otype)))
99 (unless intersect
100 (tricky))
101 (multiple-value-bind (constantp value)
102 (type-singleton-p intersect)
103 (if constantp
104 `(eql object ',value)
105 (tricky)))))))))
107 ;;; Flush %TYPEP tests whose result is known at compile time.
108 (deftransform %typep ((object type) * * :node node)
109 (unless (constant-lvar-p type)
110 (give-up-ir1-transform))
111 (ir1-transform-type-predicate
112 object
113 (ir1-transform-specifier-type (lvar-value type))
114 node))
116 ;;; This is the IR1 transform for simple type predicates. It checks
117 ;;; whether the single argument is known to (not) be of the
118 ;;; appropriate type, expanding to T or NIL as appropriate.
119 (deftransform fold-type-predicate ((object) * * :node node :defun-only t)
120 (let ((ctype (gethash (leaf-source-name
121 (ref-leaf
122 (lvar-uses
123 (basic-combination-fun node))))
124 *backend-predicate-types*)))
125 (aver ctype)
126 (ir1-transform-type-predicate object ctype node)))
128 ;;; If FIND-CLASSOID is called on a constant class, locate the
129 ;;; CLASSOID-CELL at load time.
130 (deftransform find-classoid ((name) ((constant-arg symbol)) *)
131 (let* ((name (lvar-value name))
132 (cell (find-classoid-cell name :create t)))
133 `(or (classoid-cell-classoid ',cell)
134 (error "class not yet defined: ~S" name))))
136 (defoptimizer (%typep-wrapper constraint-propagate-if)
137 ((test-value variable type) node gen)
138 (declare (ignore test-value gen))
139 (aver (constant-lvar-p type))
140 (let ((type (lvar-value type)))
141 (values variable (if (ctype-p type)
142 type
143 (handler-case (careful-specifier-type type)
144 (t () nil))))))
146 (deftransform %typep-wrapper ((test-value variable type) * * :node node)
147 (aver (constant-lvar-p type))
148 (if (constant-lvar-p test-value)
149 `',(lvar-value test-value)
150 (let* ((type (lvar-value type))
151 (type (if (ctype-p type)
152 type
153 (handler-case (careful-specifier-type type)
154 (t () nil))))
155 (value-type (lvar-type variable)))
156 (cond ((not type)
157 'test-value)
158 ((csubtypep value-type type)
160 ((not (types-equal-or-intersect value-type type))
161 nil)
163 (delay-ir1-transform node :constraint)
164 'test-value)))))
166 ;;;; standard type predicates, i.e. those defined in package COMMON-LISP,
167 ;;;; plus at least one oddball (%INSTANCEP)
168 ;;;;
169 ;;;; Various other type predicates (e.g. low-level representation
170 ;;;; stuff like SIMPLE-ARRAY-SINGLE-FLOAT-P) are defined elsewhere.
172 ;;; FIXME: This function is only called once, at top level. Why not
173 ;;; just expand all its operations into toplevel code?
174 (defun !define-standard-type-predicates ()
175 (define-type-predicate arrayp array)
176 ; (The ATOM predicate is handled separately as (NOT CONS).)
177 (define-type-predicate bit-vector-p bit-vector)
178 (define-type-predicate characterp character)
179 (define-type-predicate compiled-function-p compiled-function)
180 (define-type-predicate complexp complex)
181 (define-type-predicate complex-rational-p (complex rational))
182 (define-type-predicate complex-float-p (complex float))
183 (define-type-predicate consp cons)
184 (define-type-predicate floatp float)
185 (define-type-predicate functionp function)
186 (define-type-predicate integerp integer)
187 (define-type-predicate keywordp keyword)
188 (define-type-predicate listp list)
189 (define-type-predicate null null)
190 (define-type-predicate numberp number)
191 (define-type-predicate rationalp rational)
192 (define-type-predicate realp real)
193 (define-type-predicate sequencep sequence)
194 (define-type-predicate extended-sequence-p extended-sequence)
195 (define-type-predicate simple-bit-vector-p simple-bit-vector)
196 (define-type-predicate simple-string-p simple-string)
197 (define-type-predicate simple-vector-p simple-vector)
198 (define-type-predicate stringp string)
199 (define-type-predicate %instancep instance)
200 (define-type-predicate simple-fun-p simple-fun)
201 (define-type-predicate closurep closure)
202 (define-type-predicate funcallable-instance-p funcallable-instance)
203 (define-type-predicate symbolp symbol)
204 (define-type-predicate vectorp vector))
205 (!define-standard-type-predicates)
207 ;;;; transforms for type predicates not implemented primitively
208 ;;;;
209 ;;;; See also VM dependent transforms.
211 (define-source-transform atom (x)
212 `(not (consp ,x)))
213 #!+sb-unicode
214 (define-source-transform base-char-p (x)
215 `(typep ,x 'base-char))
216 ;; CONS is implemented as (and list (not (eql nil))) where the 'and' is
217 ;; built-in to the consp vop. Reduce to just LISTP if possible.
218 (deftransform consp ((x) ((not null)) * :important nil) '(listp x))
220 ;;;; TYPEP source transform
222 ;;; Return a form that tests the variable N-OBJECT for being in the
223 ;;; binds specified by TYPE. BASE is the name of the base type, for
224 ;;; declaration. We make SAFETY locally 0 to inhibit any checking of
225 ;;; this assertion.
226 (defun transform-numeric-bound-test (n-object type base)
227 (declare (type numeric-type type))
228 (let ((low (numeric-type-low type))
229 (high (numeric-type-high type)))
230 `(locally
231 (declare (optimize (safety 0)))
232 (and ,@(when low
233 (if (consp low)
234 `((> (truly-the ,base ,n-object) ,(car low)))
235 `((>= (truly-the ,base ,n-object) ,low))))
236 ,@(when high
237 (if (consp high)
238 `((< (truly-the ,base ,n-object) ,(car high)))
239 `((<= (truly-the ,base ,n-object) ,high))))))))
241 ;;; Do source transformation of a test of a known numeric type. We can
242 ;;; assume that the type doesn't have a corresponding predicate, since
243 ;;; those types have already been picked off. In particular, CLASS
244 ;;; must be specified, since it is unspecified only in NUMBER and
245 ;;; COMPLEX. Similarly, we assume that COMPLEXP is always specified.
247 ;;; For non-complex types, we just test that the number belongs to the
248 ;;; base type, and then test that it is in bounds. When CLASS is
249 ;;; INTEGER, we check to see whether the range is no bigger than
250 ;;; FIXNUM. If so, we check for FIXNUM instead of INTEGER. This allows
251 ;;; us to use fixnum comparison to test the bounds.
253 ;;; For complex types, we must test for complex, then do the above on
254 ;;; both the real and imaginary parts. When CLASS is float, we need
255 ;;; only check the type of the realpart, since the format of the
256 ;;; realpart and the imagpart must be the same.
257 (defun source-transform-numeric-typep (object type)
258 (let* ((class (numeric-type-class type))
259 (base (ecase class
260 (integer (containing-integer-type
261 (if (numeric-type-complexp type)
262 (modified-numeric-type type
263 :complexp :real)
264 type)))
265 (rational 'rational)
266 (float (or (numeric-type-format type) 'float))
267 ((nil) 'real))))
268 (once-only ((n-object object))
269 (ecase (numeric-type-complexp type)
270 (:real
271 (cond #!+(or x86 x86-64 arm arm64) ;; Not implemented elsewhere yet
272 ((and
273 (eql (numeric-type-class type) 'integer)
274 (eql (numeric-type-low type) 0)
275 (fixnump (numeric-type-high type)))
276 `(fixnum-mod-p ,n-object ,(numeric-type-high type)))
278 `(and (typep ,n-object ',base)
279 ,(transform-numeric-bound-test n-object type base)))))
280 (:complex
281 `(and (complexp ,n-object)
282 ,(once-only ((n-real `(realpart (truly-the complex ,n-object)))
283 (n-imag `(imagpart (truly-the complex ,n-object))))
284 `(progn
285 ,n-imag ; ignorable
286 (and (typep ,n-real ',base)
287 ,@(when (eq class 'integer)
288 `((typep ,n-imag ',base)))
289 ,(transform-numeric-bound-test n-real type base)
290 ,(transform-numeric-bound-test n-imag type
291 base))))))))))
293 ;;; Do the source transformation for a test of a hairy type. AND,
294 ;;; SATISFIES and NOT are converted into the obvious code. We convert
295 ;;; unknown types to %TYPEP, emitting an efficiency note if
296 ;;; appropriate.
297 (defun source-transform-hairy-typep (object type)
298 (declare (type hairy-type type))
299 (let ((spec (hairy-type-specifier type)))
300 (cond ((unknown-type-p type)
301 #+sb-xc-host
302 (warn "can't open-code test of unknown type ~S"
303 (type-specifier type))
304 #-sb-xc-host
305 (when (policy *lexenv* (> speed inhibit-warnings))
306 (compiler-notify "can't open-code test of unknown type ~S"
307 (type-specifier type)))
308 `(%typep ,object ',spec))
310 (ecase (first spec)
311 (satisfies
312 (let* ((name (second spec))
313 (expansion (fun-name-inline-expansion name)))
314 ;; Lambda without lexenv can easily be handled here.
315 ;; This fixes the issue that LEGAL-FUN-NAME-P which is
316 ;; just a renaming of VALID-FUNCTION-NAME-P would not
317 ;; be inlined when testing the FUNCTION-NAME type.
318 `(if ,(if (and (typep expansion '(cons (eql lambda)))
319 (not (fun-lexically-notinline-p name)))
320 `(,expansion ,object)
321 `(funcall (global-function ,name) ,object))
322 t nil)))
323 ((not and)
324 (once-only ((n-obj object))
325 `(,(first spec) ,@(mapcar (lambda (x)
326 `(typep ,n-obj ',x))
327 (rest spec))))))))))
329 (defun source-transform-negation-typep (object type)
330 (declare (type negation-type type))
331 (let ((spec (type-specifier (negation-type-type type))))
332 `(not (typep ,object ',spec))))
334 ;;; Do source transformation for TYPEP of a known union type. If a
335 ;;; union type contains LIST, then we pull that out and make it into a
336 ;;; single LISTP call. Note that if SYMBOL is in the union, then LIST
337 ;;; will be a subtype even without there being any (member NIL). We
338 ;;; currently just drop through to the general code in this case,
339 ;;; rather than trying to optimize it (but FIXME CSR 2004-04-05: it
340 ;;; wouldn't be hard to optimize it after all).
341 ;;; FIXME: if the CONSP|NIL -> LISTP optimization kicks in,
342 ;;; we forgo the array optimizations.
343 (defun source-transform-union-typep (object type)
344 (let* ((types (union-type-types type))
345 (type-cons (specifier-type 'cons))
346 (mtype (find-if #'member-type-p types))
347 (members (when mtype (member-type-members mtype))))
348 (once-only ((n-obj object))
349 (if (and mtype
350 (memq nil members)
351 (memq type-cons types))
352 `(or (listp ,n-obj)
353 (typep ,n-obj
354 '(or ,@(mapcar #'type-specifier
355 (remove type-cons
356 (remove mtype types)))
357 (member ,@(remove nil members)))))
358 (multiple-value-bind (widetags more-types)
359 (sb!kernel::widetags-from-union-type types)
360 `(or ,@(if widetags
361 `((%other-pointer-subtype-p ,n-obj ',widetags)))
362 ,@(mapcar (lambda (x)
363 `(typep ,n-obj ',(type-specifier x)))
364 more-types)))))))
366 ;;; Do source transformation for TYPEP of a known intersection type.
367 (defun source-transform-intersection-typep (object type)
368 (once-only ((n-obj object))
369 `(and ,@(mapcar (lambda (x)
370 `(typep ,n-obj ',(type-specifier x)))
371 (intersection-type-types type)))))
373 ;;; If necessary recurse to check the cons type.
374 (defun source-transform-cons-typep (object type)
375 (let* ((car-type (cons-type-car-type type))
376 (cdr-type (cons-type-cdr-type type))
377 (car-test-p (not (type= car-type *universal-type*)))
378 (cdr-test-p (not (type= cdr-type *universal-type*))))
379 (if (and (not car-test-p) (not cdr-test-p))
380 `(consp ,object)
381 ;; CONSP can be safely weakened to LISTP if either of the CAR
382 ;; or CDR test (or both) can distinguish LIST from CONS
383 ;; by never returning T when given an input of NIL.
384 (labels ((safely-weakened (ctype)
385 (typecase ctype
386 (member-type
387 (not (member nil (member-type-members ctype))))
388 (classoid
389 ;; can't weaken if the specifier is (CONS SYMBOL)
390 (not (ctypep nil ctype)))
391 ;; these are disjoint from NIL
392 ((or cons-type numeric-type array-type character-set-type)
394 (intersection-type
395 ;; at least one of them must not spuriously return T
396 (some #'safely-weakened (compound-type-types ctype)))
397 (union-type
398 ;; require that none spuriously return T
399 (every #'safely-weakened (compound-type-types ctype)))
400 (hairy-type
401 ;; hack - (CONS KEYWORD) is weakenable
402 ;; because NIL is not a keyword.
403 (equal (hairy-type-specifier ctype)
404 '(satisfies keywordp))))))
405 (let* ((n-obj (sb!xc:gensym))
406 (car-test
407 (and car-test-p
408 `((typep (car ,n-obj) ',(type-specifier car-type)))))
409 (cdr-test
410 (and cdr-test-p
411 `((typep (cdr ,n-obj) ',(type-specifier cdr-type))))))
412 `(let ((,n-obj ,object))
413 ;; Being paranoid, perform the safely weakenable test first
414 ;; so that the other part doesn't execute on an object that
415 ;; it would not have gotten, were the CONSP test not weakened.
416 ,(cond ((and car-test-p (safely-weakened car-type))
417 `(and (listp ,n-obj) ,@car-test ,@cdr-test))
418 ((and cdr-test-p (safely-weakened cdr-type))
419 `(and (listp ,n-obj) ,@cdr-test ,@car-test))
421 `(and (consp ,n-obj) ,@car-test ,@cdr-test)))))))))
423 (defun source-transform-character-set-typep (object type)
424 (let ((pairs (character-set-type-pairs type)))
425 (if (and (= (length pairs) 1)
426 (= (caar pairs) 0)
427 (= (cdar pairs) (1- sb!xc:char-code-limit)))
428 `(characterp ,object)
429 (once-only ((n-obj object))
430 (let ((n-code (gensym "CODE")))
431 `(and (characterp ,n-obj)
432 (let ((,n-code (sb!xc:char-code ,n-obj)))
434 ,@(loop for pair in pairs
435 collect
436 `(<= ,(car pair) ,n-code ,(cdr pair)))))))))))
438 #!+sb-simd-pack
439 (defun source-transform-simd-pack-typep (object type)
440 (if (type= type (specifier-type 'simd-pack))
441 `(simd-pack-p ,object)
442 (once-only ((n-obj object))
443 (let ((n-tag (gensym "TAG")))
444 `(and
445 (simd-pack-p ,n-obj)
446 (let ((,n-tag (%simd-pack-tag ,n-obj)))
447 (or ,@(loop
448 for type in (simd-pack-type-element-type type)
449 for index = (position type *simd-pack-element-types*)
450 collect `(eql ,n-tag ,index)))))))))
452 ;;; Return the predicate and type from the most specific entry in
453 ;;; *TYPE-PREDICATES* that is a supertype of TYPE.
454 (defun find-supertype-predicate (type)
455 (declare (type ctype type))
456 (let ((res nil)
457 (res-type nil))
458 (dolist (x *backend-type-predicates*)
459 (let ((stype (car x)))
460 (when (and (csubtypep type stype)
461 (or (not res-type)
462 (csubtypep stype res-type)))
463 (setq res-type stype)
464 (setq res (cdr x)))))
465 (values res res-type)))
467 ;;; Return forms to test that OBJ has the rank and dimensions
468 ;;; specified by TYPE, where STYPE is the type we have checked against
469 ;;; (which is the same but for dimensions and element type).
471 ;;; Secondary return value is true if passing the generated tests implies that
472 ;;; the array has a header.
473 (defun test-array-dimensions (obj type stype)
474 (declare (type array-type type stype))
475 (let ((obj `(truly-the ,(type-specifier stype) ,obj))
476 (dims (array-type-dimensions type)))
477 (unless (or (eq dims '*)
478 (equal dims (array-type-dimensions stype)))
479 (cond ((cdr dims)
480 (values `((array-header-p ,obj)
481 ,@(when (eq (array-type-dimensions stype) '*)
482 `((= (%array-rank ,obj) ,(length dims))))
483 ,@(loop for d in dims
484 for i from 0
485 unless (eq '* d)
486 collect `(= (%array-dimension ,obj ,i) ,d)))
488 ((not dims)
489 (values `((array-header-p ,obj)
490 (= (%array-rank ,obj) 0))
492 ((not (array-type-complexp type))
493 (if (csubtypep stype (specifier-type 'vector))
494 (values (unless (eq '* (car dims))
495 `((= (vector-length ,obj) ,@dims)))
496 nil)
497 (values (if (eq '* (car dims))
498 `((not (array-header-p ,obj)))
499 `((not (array-header-p ,obj))
500 (= (vector-length ,obj) ,@dims)))
501 nil)))
503 (values (unless (eq '* (car dims))
504 `((if (array-header-p ,obj)
505 (= (%array-dimension ,obj 0) ,@dims)
506 (= (vector-length ,obj) ,@dims))))
507 nil))))))
509 ;;; Return forms to test that OBJ has the element-type specified by type
510 ;;; specified by TYPE, where STYPE is the type we have checked against (which
511 ;;; is the same but for dimensions and element type). If HEADERP is true, OBJ
512 ;;; is guaranteed to be an array-header.
513 (defun test-array-element-type (obj type stype headerp)
514 (declare (type array-type type stype))
515 (let ((obj `(truly-the ,(type-specifier stype) ,obj))
516 (eltype (array-type-specialized-element-type type)))
517 (unless (or (type= eltype (array-type-specialized-element-type stype))
518 (eq eltype *wild-type*))
519 (let ((typecode (sb!vm:saetp-typecode (find-saetp-by-ctype eltype))))
520 (with-unique-names (data)
521 (if (and headerp (not (array-type-complexp stype)))
522 ;; If we know OBJ is an array header, and that the array is
523 ;; simple, we also know there is exactly one indirection to
524 ;; follow.
525 `((eq (%other-pointer-widetag (%array-data-vector ,obj)) ,typecode))
526 `((do ((,data ,(if headerp `(%array-data-vector ,obj) obj)
527 (%array-data-vector ,data)))
528 ((not (array-header-p ,data))
529 (eq (%other-pointer-widetag ,data) ,typecode))))))))))
531 ;;; If we can find a type predicate that tests for the type without
532 ;;; dimensions, then use that predicate and test for dimensions.
533 ;;; Otherwise, just do %TYPEP.
534 (defun source-transform-array-typep (obj type)
535 ;; Intercept (SIMPLE-ARRAY * (*)) because otherwise it tests
536 ;; (AND SIMPLE-ARRAY (NOT ARRAY-HEADER)) to weed out rank 0 and >1.
537 ;; By design the simple arrays of of rank 1 occupy a contiguous
538 ;; range of widetags, and unlike the arbitrary-widetags code for unions,
539 ;; this nonstandard predicate can be generically defined for all backends.
540 (if (and (not (array-type-complexp type))
541 (eq (array-type-element-type type) *wild-type*)
542 (equal (array-type-dimensions type) '(*)))
543 (return-from source-transform-array-typep
544 `(simple-rank-1-array-*-p ,obj)))
545 (multiple-value-bind (pred stype) (find-supertype-predicate type)
546 (if (and (array-type-p stype)
547 ;; (If the element type hasn't been defined yet, it's
548 ;; not safe to assume here that it will eventually
549 ;; have (UPGRADED-ARRAY-ELEMENT-TYPE type)=T, so punt.)
550 (not (unknown-type-p (array-type-element-type type)))
551 (or (eq (array-type-complexp stype) (array-type-complexp type))
552 (and (eql (array-type-complexp stype) :maybe)
553 (eql (array-type-complexp type) t))))
554 (once-only ((n-obj obj))
555 (multiple-value-bind (tests headerp)
556 (test-array-dimensions n-obj type stype)
557 `(and (,pred ,n-obj)
558 ,@(when (and (eql (array-type-complexp stype) :maybe)
559 (eql (array-type-complexp type) t))
560 ;; KLUDGE: this is a bit lame; if we get here,
561 ;; we already know that N-OBJ is an array, but
562 ;; (NOT SIMPLE-ARRAY) doesn't know that. On the
563 ;; other hand, this should get compiled down to
564 ;; two widetag tests, so it's only a bit lame.
565 `((typep ,n-obj '(not simple-array))))
566 ,@tests
567 ,@(test-array-element-type n-obj type stype headerp))))
568 `(%typep ,obj ',(type-specifier type)))))
570 ;;; Transform a type test against some instance type. The type test is
571 ;;; flushed if the result is known at compile time. If not properly
572 ;;; named, error. If sealed and has no subclasses, just test for
573 ;;; layout-EQ. If a structure then test for layout-EQ and then a
574 ;;; general test based on layout-inherits. If safety is important,
575 ;;; then we also check whether the layout for the object is invalid
576 ;;; and signal an error if so. Otherwise, look up the indirect
577 ;;; class-cell and call CLASS-CELL-TYPEP at runtime.
578 (deftransform %instance-typep ((object spec) (* *) * :node node)
579 (aver (constant-lvar-p spec))
580 (let* ((spec (lvar-value spec))
581 (class (specifier-type spec))
582 (name (classoid-name class))
583 (otype (lvar-type object))
584 (layout (let ((res (info :type :compiler-layout name)))
585 (if (and res (not (layout-invalid res)))
587 nil))))
588 (cond
589 ;; Flush tests whose result is known at compile time.
590 ((not (types-equal-or-intersect otype class))
591 nil)
592 ((csubtypep otype class)
594 ;; If not properly named, error.
595 ((not (and name (eq (find-classoid name) class)))
596 (compiler-error "can't compile TYPEP of anonymous or undefined ~
597 class:~% ~S"
598 class))
600 ;; Delay the type transform to give type propagation a chance.
601 (delay-ir1-transform node :constraint)
603 ;; FIXME: (TYPEP X 'ERROR) - or any condition - checks whether X
604 ;; has the lowtag of either an ordinary or funcallable instance.
605 ;; But you can not define a class that is both CONDITION and FUNCTION
606 ;; because CONDITION-CLASS and FUNCALLABLE-STANDARD-CLASS are
607 ;; incompatible metaclasses. Thus the type test is less efficient than
608 ;; could be, since fun-pointer-lowtag can not occur in the "true" case.
610 ;; Otherwise transform the type test.
611 (binding* (((pred get-layout)
612 (cond ((csubtypep class (specifier-type 'funcallable-instance))
613 (values '(funcallable-instance-p object)
614 '(%funcallable-instance-layout object)))
615 ((csubtypep class (specifier-type 'instance))
616 (values '(%instancep object)
617 '(%instance-layout object)))))
618 (get-layout-or-return-false
619 (if pred
620 ;; Test just one of %INSTANCEP or %FUNCALLABLE-INSTANCE-P
621 `(if ,pred ,get-layout (return-from typep nil))
622 ;; But if we don't know which is will be, try both.
623 ;; This is less general than LAYOUT-OF,and therefore
624 ;; a little quicker to fail, because objects with
625 ;; {LIST|OTHER}-POINTER-LOWTAG can't possibly pass.
626 `(cond ((%instancep object)
627 (%instance-layout object))
628 ((funcallable-instance-p object)
629 (%funcallable-instance-layout object))
630 (t (return-from typep nil)))))
631 (n-layout (gensym)))
632 (cond
633 ;; It's possible to seal a STANDARD-CLASS, not just a STRUCTURE-CLASS,
634 ;; though probably extremely weird. Also the PRED should be set in
635 ;; that event, but it isn't.
636 ((and (eq (classoid-state class) :sealed) layout
637 (not (classoid-subclasses class)))
638 ;; Sealed and has no subclasses.
639 ;; The crummy dual expressions for the same result are because
640 ;; (BLOCK (RETURN ...)) seems to emit a forward branch in the
641 ;; passing case, but AND emits a forward branch in the failing
642 ;; case which I believe is the better choice.
643 (if pred
644 `(and ,pred (eq ,get-layout ',layout))
645 `(block typep (eq ,get-layout-or-return-false ',layout))))
647 ((and (typep class 'structure-classoid) layout)
648 ;; structure type tests; hierarchical layout depths
649 (let* ((depthoid (layout-depthoid layout))
650 ;; If a structure is apparently an abstract base type,
651 ;; having no constructor, then no instance layout should
652 ;; be EQ to the classoid's layout. It is a slight win
653 ;; to use the depth-based check first, then do the EQ check.
654 ;; There is no loss in the case where both fail, and there
655 ;; is a benefit in a passing case. Always try both though,
656 ;; because (MAKE-INSTANCE 'x) works on any structure class.
657 (abstract-base-p (awhen (layout-info layout)
658 (not (dd-constructors it))))
659 (get-ancestor
660 ;; Use DATA-VECTOR-REF directly, since that's what SVREF in
661 ;; a SAFETY 0 lexenv will eventually be transformed to.
662 ;; This can give a large compilation speedup, since
663 ;; %INSTANCE-TYPEPs are frequently created during
664 ;; GENERATE-TYPE-CHECKS, and the normal aref transformation
665 ;; path is pretty heavy.
666 `(locally (declare (optimize (safety 0)))
667 (data-vector-ref (layout-inherits ,n-layout) ,depthoid)))
668 (deeper-p `(> (layout-depthoid ,n-layout) ,depthoid)))
669 (aver (equal pred '(%instancep object)))
670 `(and ,pred
671 (let ((,n-layout ,get-layout))
672 ;; we used to check for invalid layouts here,
673 ;; but in fact that's both unnecessary and
674 ;; wrong; it's unnecessary because structure
675 ;; classes can't be redefined, and it's wrong
676 ;; because it is quite legitimate to pass an
677 ;; object with an invalid layout to a structure
678 ;; type test.
679 ,(if abstract-base-p
680 `(eq (if ,deeper-p ,get-ancestor ,n-layout) ,layout)
681 `(cond ((eq ,n-layout ,layout) t)
682 (,deeper-p (eq ,get-ancestor ,layout))))))))
683 ((and layout (>= (layout-depthoid layout) 0))
684 ;; hierarchical layout depths for other things (e.g.
685 ;; CONDITION, STREAM)
686 ;; The quasi-hierarchical types are abstract base types,
687 ;; so perform inheritance check first, and EQ second.
688 ;; Actually, since you can't make an abstract STREAM,
689 ;; maybe we should skip the EQ test? But you *can* make
690 ;; an instance of CONDITION for what it's worth.
691 ;; SEQUENCE is special-cased, but could be handled here.
692 (let* ((depthoid (layout-depthoid layout))
693 (n-inherits (gensym))
694 (guts
695 `((when (layout-invalid ,n-layout)
696 (setq ,n-layout (update-object-layout-or-invalid
697 object ',layout)))
698 (let ((,n-inherits (layout-inherits
699 (truly-the layout ,n-layout))))
700 (declare (optimize (safety 0)))
701 (eq (if (> (vector-length ,n-inherits) ,depthoid)
702 (data-vector-ref ,n-inherits ,depthoid)
703 ,n-layout)
704 ,layout)))))
705 (if pred
706 `(and ,pred (let ((,n-layout ,get-layout)) ,@guts))
707 `(block typep
708 (let ((,n-layout ,get-layout-or-return-false)) ,@guts)))))
711 (/noshow "default case -- ,PRED and CLASS-CELL-TYPEP")
712 `(classoid-cell-typep ',(find-classoid-cell name :create t)
713 object))))))))
715 ;;; If the specifier argument is a quoted constant, then we consider
716 ;;; converting into a simple predicate or other stuff. If the type is
717 ;;; constant, but we can't transform the call, then we convert to
718 ;;; %TYPEP. We only pass when the type is non-constant. This allows us
719 ;;; to recognize between calls that might later be transformed
720 ;;; successfully when a constant type is discovered. We don't give an
721 ;;; efficiency note when we pass, since the IR1 transform will give
722 ;;; one if necessary and appropriate.
724 ;;; If the type is TYPE= to a type that has a predicate, then expand
725 ;;; to that predicate. Otherwise, we dispatch off of the type's type.
726 ;;; These transformations can increase space, but it is hard to tell
727 ;;; when, so we ignore policy and always do them.
728 (defun %source-transform-typep (object type)
729 (let ((ctype (careful-specifier-type type)))
730 (or (when (not ctype)
731 (compiler-warn "illegal type specifier for TYPEP: ~S" type)
732 (return-from %source-transform-typep (values nil t)))
733 (multiple-value-bind (constantp value) (type-singleton-p ctype)
734 (and constantp
735 `(eql ,object ',value)))
736 (let ((pred (cdr (assoc ctype *backend-type-predicates*
737 :test #'type=))))
738 (when pred `(,pred ,object)))
739 (typecase ctype
740 (hairy-type
741 (source-transform-hairy-typep object ctype))
742 (negation-type
743 (source-transform-negation-typep object ctype))
744 (union-type
745 (source-transform-union-typep object ctype))
746 (intersection-type
747 (source-transform-intersection-typep object ctype))
748 (member-type
749 `(if (member ,object ',(member-type-members ctype)) t))
750 (args-type
751 (compiler-warn "illegal type specifier for TYPEP: ~S" type)
752 (return-from %source-transform-typep (values nil t)))
753 (t nil))
754 (typecase ctype
755 (numeric-type
756 (source-transform-numeric-typep object ctype))
757 (classoid
758 `(%instance-typep ,object ',type))
759 (array-type
760 (source-transform-array-typep object ctype))
761 (cons-type
762 (source-transform-cons-typep object ctype))
763 (character-set-type
764 (source-transform-character-set-typep object ctype))
765 #!+sb-simd-pack
766 (simd-pack-type
767 (source-transform-simd-pack-typep object ctype))
768 (t nil))
769 `(%typep ,object ',type))))
771 (defun source-transform-typep (object type)
772 (when (typep type 'type-specifier)
773 (check-deprecated-type type))
774 (let ((name (gensym "OBJECT")))
775 (multiple-value-bind (transform error)
776 (%source-transform-typep name type)
777 (if error
778 (values nil t)
779 (values `(let ((,name ,object))
780 (%typep-wrapper ,transform ,name ',type)))))))
782 (define-source-transform typep (object spec &optional env)
783 ;; KLUDGE: It looks bad to only do this on explicitly quoted forms,
784 ;; since that would overlook other kinds of constants. But it turns
785 ;; out that the DEFTRANSFORM for TYPEP detects any constant
786 ;; lvar, transforms it into a quoted form, and gives this
787 ;; source transform another chance, so it all works out OK, in a
788 ;; weird roundabout way. -- WHN 2001-03-18
789 (if (and (not env)
790 (consp spec)
791 (eq (car spec) 'quote))
792 (source-transform-typep object (cadr spec))
793 (values nil t)))
795 ;;;; coercion
797 ;;; Constant-folding.
799 #-sb-xc-host
800 (defoptimizer (coerce optimizer) ((x type) node)
801 (when (and (constant-lvar-p x) (constant-lvar-p type))
802 (let ((value (lvar-value x)))
803 (when (or (numberp value) (characterp value))
804 (constant-fold-call node)
805 t))))
807 ;;; Drops dimension information from vector types.
808 ;;; Returns four values
809 ;;; * vector ctype
810 ;;; * upgraded-element ctype or requsted element
811 ;;; * T if the upgraded-element is upgraded, i.e. it
812 ;;; does not contain any unknown types.
813 ;;; * T if there were any dimensions
814 (defun simplify-vector-type (type)
815 (labels ((process-compound-type (types)
816 (let (array-types
817 element-types
818 (upgraded t)
819 dimensions-removed)
820 (dolist (type types)
821 (unless (or (hairy-type-p type)
822 (sb!kernel::negation-type-p type))
823 (multiple-value-bind (type et upgraded dimensions) (simplify type)
824 (push type array-types)
825 (push et element-types)
826 (when dimensions
827 (setf dimensions-removed t))
828 (unless upgraded
829 (setf upgraded nil)))))
830 (values (apply #'type-union array-types)
831 (if (member *wild-type* element-types)
832 *wild-type*
833 (apply #'type-union element-types))
834 upgraded
835 dimensions-removed)))
836 (simplify (type)
837 (cond ((and (array-type-p type)
838 (singleton-p (array-type-dimensions type)))
839 (let* ((upgraded t)
840 (et (array-type-specialized-element-type type))
841 (et (cond ((neq et *wild-type*)
843 ((eq (array-type-element-type type) *wild-type*)
846 (setf upgraded nil)
847 (array-type-element-type type)))))
848 (values (specifier-type
849 (list (if (array-type-complexp type)
850 'array
851 'simple-array)
852 (type-specifier et)
853 '(*)))
855 upgraded
856 (not (eq (car (array-type-dimensions type)) '*)))))
857 ((union-type-p type)
858 (process-compound-type (union-type-types type)))
859 ((intersection-type-p type)
860 (process-compound-type (intersection-type-types type)))
861 ((member-type-p type)
862 (process-compound-type
863 (mapcar #'ctype-of (member-type-members type))))
865 (error "~a is not a subtype of VECTOR." type)))))
866 (simplify type)))
868 (deftransform coerce ((x type) (* *) * :node node)
869 (unless (constant-lvar-p type)
870 (give-up-ir1-transform))
871 (let* ((tval (lvar-value type))
872 (tspec (ir1-transform-specifier-type tval)))
873 (if (csubtypep (lvar-type x) tspec)
875 ;; Note: The THE forms we use to wrap the results make sure that
876 ;; specifiers like (SINGLE-FLOAT 0.0 1.0) can raise a TYPE-ERROR.
877 (cond
878 ((csubtypep tspec (specifier-type 'double-float))
879 `(the ,tval (%double-float x)))
880 ;; FIXME: #!+long-float (t ,(error "LONG-FLOAT case needed"))
881 ((csubtypep tspec (specifier-type 'float))
882 `(the ,tval (%single-float x)))
883 ((csubtypep tspec (specifier-type 'complex))
884 (multiple-value-bind (part-type result-type)
885 (cond ((and (numeric-type-p tspec)
886 (numeric-type-format tspec))) ; specific FLOAT type
887 ((csubtypep tspec (specifier-type '(complex float)))
888 ;; unspecific FLOAT type
889 'float)
890 ((csubtypep tspec (specifier-type '(complex rational)))
891 (values 'rational `(or ,tval rational)))
893 (values t `(or ,tval rational))))
894 (let ((result-type (or result-type tval)))
895 `(cond
896 ((not (typep x 'complex))
897 (the ,result-type (complex (coerce x ',part-type))))
898 ((typep x ',tval)
900 (t ; X is COMPLEX, but not of the requested type
901 (the ,result-type
902 (complex (coerce (realpart x) ',part-type)
903 (coerce (imagpart x) ',part-type))))))))
904 ;; Special case STRING and SIMPLE-STRING as they are union types
905 ;; in SBCL.
906 ((member tval '(string simple-string))
907 `(the ,tval
908 (if (typep x ',tval)
910 (replace (make-array (length x) :element-type 'character) x))))
911 ((eq tval 'character)
912 `(character x))
913 ;; Special case VECTOR
914 ((eq tval 'vector)
915 `(the ,tval
916 (if (vectorp x)
918 (replace (make-array (length x)) x))))
919 ;; Handle specialized element types for 1D arrays.
920 ((csubtypep tspec (specifier-type '(array * (*))))
921 ;; Can we avoid checking for dimension issues like (COERCE FOO
922 ;; '(SIMPLE-VECTOR 5)) returning a vector of length 6?
924 ;; CLHS actually allows this for all code with SAFETY < 3,
925 ;; but we're a conservative bunch.
926 (if (or (policy node (zerop safety)) ; no need in unsafe code
927 (and (array-type-p tspec) ; no need when no dimensions
928 (equal (array-type-dimensions tspec) '(*))))
929 ;; We can!
930 (multiple-value-bind (vtype etype upgraded) (simplify-vector-type tspec)
931 (unless upgraded
932 (give-up-ir1-transform))
933 (let ((vtype (type-specifier vtype)))
934 `(the ,vtype
935 (if (typep x ',vtype)
937 (replace
938 (make-array (length x)
939 ,@(and (not (eq etype *universal-type*))
940 (not (eq etype *wild-type*))
941 `(:element-type ',(type-specifier etype))))
942 x)))))
943 ;; No, duh. Dimension checking required.
944 (give-up-ir1-transform
945 "~@<~S specifies dimensions other than (*) in safe code.~:@>"
946 tval)))
947 ((type= tspec (specifier-type 'list))
948 `(coerce-to-list x))
949 ((csubtypep tspec (specifier-type 'function))
950 (if (csubtypep (lvar-type x) (specifier-type 'symbol))
951 `(coerce-symbol-to-fun x)
952 ;; if X can later be derived as FUNCTION then we don't want
953 ;; to call COERCE-TO-FUN, because there's no smartness
954 ;; that can undo that and see that it's really (IDENTITY X).
955 (progn (delay-ir1-transform node :constraint)
956 `(coerce-to-fun x))))
958 (give-up-ir1-transform
959 "~@<open coding coercion to ~S not implemented.~:@>"
960 tval))))))