1 ;;;; This file implements type check generation. This is a phase that
2 ;;;; runs at the very end of IR1. If a type check is too complex for
3 ;;;; the back end to directly emit in-line, then we transform the check
4 ;;;; into an explicit conditional using TYPEP.
6 ;;;; This software is part of the SBCL system. See the README file for
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.
19 ;;; Return some sort of guess about the cost of a call to a function.
20 ;;; If the function has some templates, we return the cost of the
21 ;;; cheapest one, otherwise we return the cost of CALL-NAMED. Calling
22 ;;; this with functions that have transforms can result in relatively
23 ;;; meaningless results (exaggerated costs.)
25 ;;; We special-case NULL, since it does have a source tranform and is
26 ;;; interesting to us.
27 (defun fun-guessed-cost (name)
28 (declare (symbol name))
29 (let ((info (info :function :info name))
30 (call-cost (template-cost (template-or-lose 'call-named))))
32 (let ((templates (fun-info-templates info)))
34 (template-cost (first templates))
36 (null (template-cost (template-or-lose 'if-eq)))
40 ;;; Return some sort of guess for the cost of doing a test against
41 ;;; TYPE. The result need not be precise as long as it isn't way out
42 ;;; in space. The units are based on the costs specified for various
43 ;;; templates in the VM definition.
44 (defun type-test-cost (type)
45 (declare (type ctype type))
46 (or (when (eq type *universal-type*)
48 (when (eq type *empty-type*)
50 (let ((check (type-check-template type)))
53 (let ((found (cdr (assoc type *backend-type-predicates*
56 (+ (fun-guessed-cost found) (fun-guessed-cost 'eq))
60 (reduce #'+ (compound-type-types type) :key 'type-test-cost))
62 (* (member-type-size type)
63 (fun-guessed-cost 'eq)))
65 (* (if (numeric-type-complexp type) 2 1)
67 (if (csubtypep type (specifier-type 'fixnum)) 'fixnump 'numberp))
69 (if (numeric-type-low type) 1 0)
70 (if (numeric-type-high type) 1 0))))
72 (+ (type-test-cost (specifier-type 'cons))
73 (fun-guessed-cost 'car)
74 (type-test-cost (cons-type-car-type type))
75 (fun-guessed-cost 'cdr)
76 (type-test-cost (cons-type-cdr-type type))))
78 (fun-guessed-cost 'typep)))))
80 (defun weaken-integer-type (type &key range-only)
81 ;; FIXME: Our canonicalization isn't quite ideal for this. We get
84 ;; (OR (AND (SATISFIES FOO) (INTEGER -100 -50))
85 ;; (AND (SATISFIES FOO) (INTEGER 100 200)))
87 ;; here, and weakening that into
89 ;; (AND (SATISFIES FOO) (INTEGER -100 200))
91 ;; is too much work to do here ... but if we canonicalized things
92 ;; differently, we could get it for free with trivial changes here.
93 (labels ((weaken-integer-type-part (type base)
94 (cond ((intersection-type-p type)
95 (let ((new (specifier-type base)))
96 (dolist (part (intersection-type-types type))
99 (not (unknown-type-p part)))
100 (setf new (type-intersection
101 new (weaken-integer-type-part part t)))))
104 (let ((low t) (high t) (rest *empty-type*))
105 (flet ((maximize (bound)
107 (setf high (if (eq t high)
113 (setf low (if (eq t low)
117 (dolist (part (union-type-types type))
118 (let ((weak (weaken-integer-type-part part t)))
119 (cond ((numeric-type-p weak)
120 (minimize (numeric-type-low weak))
121 (maximize (numeric-type-high weak)))
123 (setf rest (type-union rest weak)))))))
128 `(integer ,(or low '*) ,(or high '*)))))))
131 (weaken-integer-type-part type 'integer)))
134 (weaken-type :hash-bits 8
135 :hash-function (lambda (x)
136 (logand (type-hash-value x) #xFF)))
138 (declare (type ctype type))
139 (cond ((named-type-p type)
141 ((csubtypep type (specifier-type 'integer))
142 ;; Simple range checks are not that expensive, and we *don't*
143 ;; want to accidentally lose eg. array bounds checks due to
144 ;; weakening, so for integer types we simply collapse all
146 (weaken-integer-type type))
148 (let ((min-cost (type-test-cost type))
151 (dolist (x *backend-type-predicates*)
152 (let* ((stype (car x))
153 (samep (type= stype type)))
155 (and (csubtypep type stype)
156 (not (union-type-p stype))))
157 (let ((stype-cost (type-test-cost stype)))
158 (when (or (< stype-cost min-cost)
160 ;; If the supertype is equal in cost to the type, we
161 ;; prefer the supertype. This produces a closer
162 ;; approximation of the right thing in the presence of
166 min-cost stype-cost))))))
167 ;; This used to return the *UNIVERSAL-TYPE* if no supertype was found,
168 ;; but that's too liberal: it's far too easy for the user to create
169 ;; a union type (which are excluded above), and then trick the compiler
170 ;; into trusting the union type... and finally ending up corrupting the
171 ;; heap once a bad object sneaks past the missing type check.
176 (defun weaken-values-type (type)
177 (declare (type ctype type))
178 (cond ((eq type *wild-type*) type)
179 ((not (values-type-p type))
182 (make-values-type :required (mapcar #'weaken-type
183 (values-type-required type))
184 :optional (mapcar #'weaken-type
185 (values-type-optional type))
186 :rest (acond ((values-type-rest type)
187 (weaken-type it)))))))
189 ;;;; checking strategy determination
191 ;;; Return the type we should test for when we really want to check
192 ;;; for TYPE. If type checking policy is "fast", then we return a
193 ;;; weaker type if it is easier to check. First we try the defined
194 ;;; type weakenings, then look for any predicate that is cheaper.
195 (defun maybe-weaken-check (type policy)
196 (declare (type ctype type))
197 (ecase (policy policy type-check)
199 (2 (weaken-values-type type))
202 ;;; This is like VALUES-TYPES, only we mash any complex function types
204 (defun no-fun-values-types (type)
205 (declare (type ctype type))
206 (multiple-value-bind (res count) (values-types type)
207 (values (mapcar (lambda (type)
208 (if (fun-type-p type)
209 (specifier-type 'function)
214 ;;; Switch to disable check complementing, for evaluation.
215 (defvar *complement-type-checks* t)
217 ;;; LVAR is an lvar we are doing a type check on and TYPES is a list
218 ;;; of types that we are checking its values against. If we have
219 ;;; proven that LVAR generates a fixed number of values, then for each
220 ;;; value, we check whether it is cheaper to then difference between
221 ;;; the proven type and the corresponding type in TYPES. If so, we opt
222 ;;; for a :HAIRY check with that test negated. Otherwise, we try to do
223 ;;; a simple test, and if that is impossible, we do a hairy test with
224 ;;; non-negated types. If true, FORCE-HAIRY forces a hairy type check.
225 (defun maybe-negate-check (lvar types original-types force-hairy n-required)
226 (declare (type lvar lvar) (list types original-types))
227 (let ((ptypes (values-type-out (lvar-derived-type lvar) (length types))))
228 (multiple-value-bind (hairy-res simple-res)
229 (loop for p in ptypes
231 and a in original-types
233 for cc = (if (>= i n-required)
234 (type-union c (specifier-type 'null))
236 for diff = (type-difference p cc)
237 collect (if (and diff
238 (< (type-test-cost diff)
240 *complement-type-checks*)
244 collect cc into simple-res
245 finally (return (values hairy-res simple-res)))
246 (cond ((or force-hairy (find-if #'first hairy-res))
247 (values :hairy hairy-res))
248 ((every #'type-check-template simple-res)
249 (values :simple simple-res))
251 (values :hairy hairy-res))))))
253 ;;; Determines whether CAST's assertion is:
254 ;;; -- checkable by the back end (:SIMPLE), or
255 ;;; -- not checkable by the back end, but checkable via an explicit
256 ;;; test in type check conversion (:HAIRY), or
257 ;;; -- not reasonably checkable at all (:TOO-HAIRY).
259 ;;; We may check only fixed number of values; in any case the number
260 ;;; of generated values is trusted. If we know the number of produced
261 ;;; values, all of them are checked; otherwise if we know the number
262 ;;; of consumed -- only they are checked; otherwise the check is not
265 ;;; A type is simply checkable if all the type assertions have a
266 ;;; TYPE-CHECK-TEMPLATE. In this :SIMPLE case, the second value is a
267 ;;; list of the type restrictions specified for the leading positional
272 ;;; We force a check to be hairy even when there are fixed values
273 ;;; if we are in a context where we may be forced to use the
274 ;;; unknown values convention anyway. This is because IR2tran can't
275 ;;; generate type checks for unknown values lvars but people could
276 ;;; still be depending on the check being done. We only care about
277 ;;; EXIT and RETURN (not MV-COMBINATION) since these are the only
278 ;;; contexts where the ultimate values receiver
280 ;;; In the :HAIRY case, the second value is a list of triples of
282 ;;; (NOT-P TYPE ORIGINAL-TYPE)
284 ;;; If true, the NOT-P flag indicates a test that the corresponding
285 ;;; value is *not* of the specified TYPE. ORIGINAL-TYPE is the type
286 ;;; asserted on this value in the lvar, for use in error
287 ;;; messages. When NOT-P is true, this will be different from TYPE.
289 ;;; This allows us to take what has been proven about CAST's argument
290 ;;; type into consideration. If it is cheaper to test for the
291 ;;; difference between the derived type and the asserted type, then we
292 ;;; check for the negation of this type instead.
293 (defun cast-check-types (cast force-hairy)
294 (declare (type cast cast))
295 (let* ((ctype (coerce-to-values (cast-type-to-check cast)))
296 (atype (coerce-to-values (cast-asserted-type cast)))
297 (dtype (node-derived-type cast))
298 (value (cast-value cast))
299 (lvar (node-lvar cast))
300 (dest (and lvar (lvar-dest lvar)))
301 (n-consumed (cond ((not lvar)
303 ((lvar-single-value-p lvar)
305 ((and (mv-combination-p dest)
306 (eq (mv-combination-kind dest) :local))
307 (let ((fun-ref (lvar-use (mv-combination-fun dest))))
308 (length (lambda-vars (ref-leaf fun-ref)))))))
309 (n-required (length (values-type-required dtype))))
310 (aver (not (eq ctype *wild-type*)))
311 (cond ((and (null (values-type-optional dtype))
312 (not (values-type-rest dtype)))
313 ;; we [almost] know how many values are produced
314 (maybe-negate-check value
315 (values-type-out ctype n-required)
316 (values-type-out atype n-required)
317 ;; backend checks only consumed values
318 (not (eql n-required n-consumed))
320 ((lvar-single-value-p lvar)
321 ;; exactly one value is consumed
322 (principal-lvar-single-valuify lvar)
323 (flet ((get-type (type)
324 (acond ((args-type-required type)
326 ((args-type-optional type)
328 (t (bug "type ~S is too hairy" type)))))
329 (multiple-value-bind (ctype atype)
330 (values (get-type ctype) (get-type atype))
331 (maybe-negate-check value
332 (list ctype) (list atype)
335 ((and (mv-combination-p dest)
336 (eq (mv-combination-kind dest) :local))
337 ;; we know the number of consumed values
338 (maybe-negate-check value
339 (adjust-list (values-type-types ctype)
342 (adjust-list (values-type-types atype)
348 (values :too-hairy nil)))))
350 ;;; Return T is the cast appears to be from the declaration of the callee,
351 ;;; and should be checked externally -- that is, by the callee and not the caller.
352 (defun cast-externally-checkable-p (cast)
353 (declare (type cast cast))
354 (let* ((lvar (node-lvar cast))
355 (dest (and lvar (lvar-dest lvar))))
356 (and (combination-p dest)
357 ;; The theory is that the type assertion is from a declaration on the
358 ;; callee, so the callee should be able to do the check. We want to
359 ;; let the callee do the check, because it is possible that by the
360 ;; time of call that declaration will be changed and we do not want
361 ;; to make people recompile all calls to a function when they were
362 ;; originally compiled with a bad declaration.
364 ;; ALMOST-IMMEDIATELY-USED-P ensures that we don't delegate casts
365 ;; that occur before nodes that can cause observable side effects --
366 ;; most commonly other non-external casts: so the order in which
367 ;; possible type errors are signalled matches with the evaluation
370 ;; FIXME: We should let more cases be handled by the callee then we
371 ;; currently do, see: https://bugs.launchpad.net/sbcl/+bug/309104
372 ;; This is not fixable quite here, though, because flow-analysis has
373 ;; deleted the LVAR of the cast by the time we get here, so there is
374 ;; no destination. Perhaps we should mark cases inserted by
375 ;; ASSERT-CALL-TYPE explicitly, and delete those whose destination is
376 ;; deemed unreachable?
377 (almost-immediately-used-p lvar cast)
378 (values (values-subtypep (lvar-externally-checkable-type lvar)
379 (cast-type-to-check cast))))))
381 ;;; Return true if CAST's value is an lvar whose type the back end is
382 ;;; likely to be able to check (see GENERATE-TYPE-CHECKS). Since we
383 ;;; don't know what template the back end is going to choose to
384 ;;; implement the continuation's DEST, we use a heuristic.
386 ;;; We always return T unless nobody uses the value (the backend
387 ;;; cannot check unused LVAR chains).
389 ;;; The logic used to be more complex, but most of the cases that used
390 ;;; to be checked here are now dealt with differently . FIXME: but
391 ;;; here's one we used to do, don't anymore, but could still benefit
392 ;;; from, if we reimplemented it (elsewhere):
394 ;;; -- If the lvar is an argument to a known function that has
395 ;;; no IR2-CONVERT method or :FAST-SAFE templates that are
396 ;;; compatible with the call's type: return NIL.
398 ;;; The code used to look like something like this:
401 ;;; (let ((info (basic-combination-fun-info dest)))
402 ;;; (if (fun-info-ir2-convert info)
404 ;;; (dolist (template (fun-info-templates info) nil)
405 ;;; (when (eq (template-ltn-policy template)
407 ;;; (multiple-value-bind (val win)
408 ;;; (valid-fun-use dest (template-type template))
409 ;;; (when (or val (not win)) (return t)))))))))))))
411 ;;; ADP says: It is still interesting. When we have a :SAFE template
412 ;;; and the type assertion is derived from the destination function
413 ;;; type, the check is unneccessary. We cannot return NIL here (the
414 ;;; whole function has changed its meaning, and here NIL *forces*
415 ;;; hairy check), but the functionality is interesting.
416 (defun probable-type-check-p (cast)
417 (declare (type cast cast))
418 (let* ((lvar (node-lvar cast))
419 (dest (and lvar (lvar-dest lvar))))
420 (cond ((not dest) nil)
423 ;;; Return a lambda form that we can convert to do a hairy type check
424 ;;; of the specified TYPES. TYPES is a list of the format returned by
425 ;;; LVAR-CHECK-TYPES in the :HAIRY case.
427 ;;; Note that we don't attempt to check for required values being
428 ;;; unsupplied. Such checking is impossible to efficiently do at the
429 ;;; source level because our fixed-values conventions are optimized
430 ;;; for the common MV-BIND case.
431 (defun make-type-check-form (types)
432 (let ((temps (make-gensym-list (length types))))
433 `(multiple-value-bind ,temps
435 ,@(mapcar (lambda (temp type)
437 (let ((*unparse-fun-type-simplify* t))
438 (type-specifier (second type))))
439 (test (if (first type) `(not ,spec) spec)))
440 `(unless (typep ,temp ',test)
443 ',(type-specifier (third type))))))
448 ;;; Splice in explicit type check code immediately before CAST. This
449 ;;; code receives the value(s) that were being passed to CAST-VALUE,
450 ;;; checks the type(s) of the value(s), then passes them further.
451 (defun convert-type-check (cast types)
452 (declare (type cast cast) (type list types))
453 (let ((value (cast-value cast))
454 (length (length types)))
455 (filter-lvar value (make-type-check-form types))
456 (reoptimize-lvar (cast-value cast))
457 (setf (cast-type-to-check cast) *wild-type*)
458 (setf (cast-%type-check cast) nil)
459 (let* ((atype (cast-asserted-type cast))
460 (atype (cond ((not (values-type-p atype))
463 (single-value-type atype))
466 :required (values-type-out atype length)))))
467 (dtype (node-derived-type cast))
468 (dtype (make-values-type
469 :required (values-type-out dtype length))))
470 (setf (cast-asserted-type cast) atype)
471 (setf (node-derived-type cast) dtype)))
475 ;;; Check all possible arguments of CAST and emit type warnings for
476 ;;; those with type errors. If the value of USE is being used for a
477 ;;; variable binding, we figure out which one for source context. If
478 ;;; the value is a constant, we print it specially.
479 (defun cast-check-uses (cast)
480 (declare (type cast cast))
481 (let* ((lvar (node-lvar cast))
482 (dest (and lvar (lvar-dest lvar)))
483 (value (cast-value cast))
484 (atype (cast-asserted-type cast))
485 (condition 'type-warning)
488 (let ((dtype (node-derived-type use)))
489 (if (values-types-equal-or-intersect dtype atype)
490 (setf condition 'type-style-warning)
491 (push use not-ok-uses))))
492 (dolist (use (nreverse not-ok-uses))
493 (let* ((*compiler-error-context* use)
494 (dtype (node-derived-type use))
495 (atype-spec (type-specifier atype))
496 (what (when (and (combination-p dest)
497 (eq (combination-kind dest) :local))
498 (let ((lambda (combination-lambda dest))
499 (pos (position-or-lose
500 lvar (combination-args dest))))
501 (format nil "~:[A possible~;The~] binding of ~S"
502 (and (lvar-has-single-use-p lvar)
503 (eq (functional-kind lambda) :let))
504 (leaf-source-name (elt (lambda-vars lambda)
506 (cond ((and (ref-p use) (constant-p (ref-leaf use)))
509 "~:[This~;~:*~A~] is not a ~<~%~9T~:;~S:~>~% ~S"
511 (list what atype-spec
512 (constant-value (ref-leaf use)))))
516 "~:[Result~;~:*~A~] is a ~S, ~<~%~9T~:;not a ~S.~>"
518 (list what (type-specifier dtype) atype-spec)))))))
521 ;;; Loop over all blocks in COMPONENT that have TYPE-CHECK set,
522 ;;; looking for CASTs with TYPE-CHECK T. We do two mostly unrelated
523 ;;; things: detect compile-time type errors and determine if and how
524 ;;; to do run-time type checks.
526 ;;; If there is a compile-time type error, then we mark the CAST and
527 ;;; emit a warning if appropriate. This part loops over all the uses
528 ;;; of the continuation, since after we convert the check, the
529 ;;; :DELETED kind will inhibit warnings about the types of other uses.
531 ;;; If the cast is too complex to be checked by the back end, or is
532 ;;; better checked with explicit code, then convert to an explicit
533 ;;; test. Assertions that can checked by the back end are passed
534 ;;; through. Assertions that can't be tested are flamed about and
535 ;;; marked as not needing to be checked.
537 ;;; If we determine that a type check won't be done, then we set
538 ;;; TYPE-CHECK to :NO-CHECK. In the non-hairy cases, this is just to
539 ;;; prevent us from wasting time coming to the same conclusion again
540 ;;; on a later iteration. In the hairy case, we must indicate to LTN
541 ;;; that it must choose a safe implementation, since IR2 conversion
542 ;;; will choke on the check.
544 ;;; The generation of the type checks is delayed until all the type
545 ;;; check decisions have been made because the generation of the type
546 ;;; checks creates new nodes whose derived types aren't always updated
547 ;;; which may lead to inappropriate template choices due to the
548 ;;; modification of argument types.
549 (defun generate-type-checks (component)
551 (do-blocks (block component)
552 (when (block-type-check block)
553 ;; CAST-EXTERNALLY-CHECKABLE-P wants the backward pass
554 (do-nodes-backwards (node nil block)
555 (when (and (cast-p node)
556 (cast-type-check node))
557 (cast-check-uses node)
558 (cond ((cast-externally-checkable-p node)
559 (setf (cast-%type-check node) :external))
561 ;; it is possible that NODE was marked :EXTERNAL by
563 (setf (cast-%type-check node) t)
564 (casts (cons node (not (probable-type-check-p node))))))))
565 (setf (block-type-check block) nil)))
566 (dolist (cast (casts))
567 (destructuring-bind (cast . force-hairy) cast
568 (multiple-value-bind (check types)
569 (cast-check-types cast force-hairy)
573 (convert-type-check cast types))
575 (let ((*compiler-error-context* cast))
576 (when (policy cast (>= safety inhibit-warnings))
578 "type assertion too complex to check:~% ~S."
579 (type-specifier (coerce-to-values (cast-asserted-type cast))))))
580 (setf (cast-type-to-check cast) *wild-type*)
581 (setf (cast-%type-check cast) nil)))))))