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)))))
81 (weaken-type :hash-bits 8
82 :hash-function (lambda (x)
83 (logand (type-hash-value x) #xFF)))
85 (declare (type ctype type))
86 (let ((min-cost (type-test-cost type))
89 (dolist (x *backend-type-predicates*)
90 (let* ((stype (car x))
91 (samep (type= stype type)))
93 (and (csubtypep type stype)
94 (not (union-type-p stype))))
95 (let ((stype-cost (type-test-cost stype)))
96 (when (or (< stype-cost min-cost)
98 ;; If the supertype is equal in cost to the type, we
99 ;; prefer the supertype. This produces a closer
100 ;; approximation of the right thing in the presence of
104 min-cost stype-cost))))))
105 ;; This used to return the *UNIVERSAL-TYPE* if no supertype was found,
106 ;; but that's too liberal: it's far too easy for the user to create
107 ;; a union type (which are excluded above), and then trick the compiler
108 ;; into trusting the union type... and finally ending up corrupting the
109 ;; heap once a bad object sneaks past the missing type check.
114 (defun weaken-values-type (type)
115 (declare (type ctype type))
116 (cond ((eq type *wild-type*) type)
117 ((not (values-type-p type))
120 (make-values-type :required (mapcar #'weaken-type
121 (values-type-required type))
122 :optional (mapcar #'weaken-type
123 (values-type-optional type))
124 :rest (acond ((values-type-rest type)
125 (weaken-type it)))))))
127 ;;;; checking strategy determination
129 ;;; Return the type we should test for when we really want to check
130 ;;; for TYPE. If type checking policy is "fast", then we return a
131 ;;; weaker type if it is easier to check. First we try the defined
132 ;;; type weakenings, then look for any predicate that is cheaper.
133 (defun maybe-weaken-check (type policy)
134 (declare (type ctype type))
135 (ecase (policy policy type-check)
137 (2 (weaken-values-type type))
140 ;;; This is like VALUES-TYPES, only we mash any complex function types
142 (defun no-fun-values-types (type)
143 (declare (type ctype type))
144 (multiple-value-bind (res count) (values-types type)
145 (values (mapcar (lambda (type)
146 (if (fun-type-p type)
147 (specifier-type 'function)
152 ;;; Switch to disable check complementing, for evaluation.
153 (defvar *complement-type-checks* t)
155 ;;; LVAR is an lvar we are doing a type check on and TYPES is a list
156 ;;; of types that we are checking its values against. If we have
157 ;;; proven that LVAR generates a fixed number of values, then for each
158 ;;; value, we check whether it is cheaper to then difference between
159 ;;; the proven type and the corresponding type in TYPES. If so, we opt
160 ;;; for a :HAIRY check with that test negated. Otherwise, we try to do
161 ;;; a simple test, and if that is impossible, we do a hairy test with
162 ;;; non-negated types. If true, FORCE-HAIRY forces a hairy type check.
163 (defun maybe-negate-check (lvar types original-types force-hairy n-required)
164 (declare (type lvar lvar) (list types original-types))
165 (let ((ptypes (values-type-out (lvar-derived-type lvar) (length types))))
166 (multiple-value-bind (hairy-res simple-res)
167 (loop for p in ptypes
169 and a in original-types
171 for cc = (if (>= i n-required)
172 (type-union c (specifier-type 'null))
174 for diff = (type-difference p cc)
175 collect (if (and diff
176 (< (type-test-cost diff)
178 *complement-type-checks*)
182 collect cc into simple-res
183 finally (return (values hairy-res simple-res)))
184 (cond ((or force-hairy (find-if #'first hairy-res))
185 (values :hairy hairy-res))
186 ((every #'type-check-template simple-res)
187 (values :simple simple-res))
189 (values :hairy hairy-res))))))
191 ;;; Determines whether CAST's assertion is:
192 ;;; -- checkable by the back end (:SIMPLE), or
193 ;;; -- not checkable by the back end, but checkable via an explicit
194 ;;; test in type check conversion (:HAIRY), or
195 ;;; -- not reasonably checkable at all (:TOO-HAIRY).
197 ;;; We may check only fixed number of values; in any case the number
198 ;;; of generated values is trusted. If we know the number of produced
199 ;;; values, all of them are checked; otherwise if we know the number
200 ;;; of consumed -- only they are checked; otherwise the check is not
203 ;;; A type is simply checkable if all the type assertions have a
204 ;;; TYPE-CHECK-TEMPLATE. In this :SIMPLE case, the second value is a
205 ;;; list of the type restrictions specified for the leading positional
210 ;;; We force a check to be hairy even when there are fixed values
211 ;;; if we are in a context where we may be forced to use the
212 ;;; unknown values convention anyway. This is because IR2tran can't
213 ;;; generate type checks for unknown values lvars but people could
214 ;;; still be depending on the check being done. We only care about
215 ;;; EXIT and RETURN (not MV-COMBINATION) since these are the only
216 ;;; contexts where the ultimate values receiver
218 ;;; In the :HAIRY case, the second value is a list of triples of
220 ;;; (NOT-P TYPE ORIGINAL-TYPE)
222 ;;; If true, the NOT-P flag indicates a test that the corresponding
223 ;;; value is *not* of the specified TYPE. ORIGINAL-TYPE is the type
224 ;;; asserted on this value in the lvar, for use in error
225 ;;; messages. When NOT-P is true, this will be different from TYPE.
227 ;;; This allows us to take what has been proven about CAST's argument
228 ;;; type into consideration. If it is cheaper to test for the
229 ;;; difference between the derived type and the asserted type, then we
230 ;;; check for the negation of this type instead.
231 (defun cast-check-types (cast force-hairy)
232 (declare (type cast cast))
233 (let* ((ctype (coerce-to-values (cast-type-to-check cast)))
234 (atype (coerce-to-values (cast-asserted-type cast)))
235 (dtype (node-derived-type cast))
236 (value (cast-value cast))
237 (lvar (node-lvar cast))
238 (dest (and lvar (lvar-dest lvar)))
239 (n-consumed (cond ((not lvar)
241 ((lvar-single-value-p lvar)
243 ((and (mv-combination-p dest)
244 (eq (mv-combination-kind dest) :local))
245 (let ((fun-ref (lvar-use (mv-combination-fun dest))))
246 (length (lambda-vars (ref-leaf fun-ref)))))))
247 (n-required (length (values-type-required dtype))))
248 (aver (not (eq ctype *wild-type*)))
249 (cond ((and (null (values-type-optional dtype))
250 (not (values-type-rest dtype)))
251 ;; we [almost] know how many values are produced
252 (maybe-negate-check value
253 (values-type-out ctype n-required)
254 (values-type-out atype n-required)
255 ;; backend checks only consumed values
256 (not (eql n-required n-consumed))
258 ((lvar-single-value-p lvar)
259 ;; exactly one value is consumed
260 (principal-lvar-single-valuify lvar)
261 (flet ((get-type (type)
262 (acond ((args-type-required type)
264 ((args-type-optional type)
266 (t (bug "type ~S is too hairy" type)))))
267 (multiple-value-bind (ctype atype)
268 (values (get-type ctype) (get-type atype))
269 (maybe-negate-check value
270 (list ctype) (list atype)
273 ((and (mv-combination-p dest)
274 (eq (mv-combination-kind dest) :local))
275 ;; we know the number of consumed values
276 (maybe-negate-check value
277 (adjust-list (values-type-types ctype)
280 (adjust-list (values-type-types atype)
286 (values :too-hairy nil)))))
288 ;;; Do we want to do a type check?
289 (defun cast-externally-checkable-p (cast)
290 (declare (type cast cast))
291 (let* ((lvar (node-lvar cast))
292 (dest (and lvar (lvar-dest lvar))))
293 (and (combination-p dest)
294 ;; The theory is that the type assertion is from a
295 ;; declaration in (or on) the callee, so the callee should be
296 ;; able to do the check. We want to let the callee do the
297 ;; check, because it is possible that by the time of call
298 ;; that declaration will be changed and we do not want to
299 ;; make people recompile all calls to a function when they
300 ;; were originally compiled with a bad declaration. (See also
302 (or (immediately-used-p lvar cast)
303 (binding* ((ctran (node-next cast) :exit-if-null)
304 (next (ctran-next ctran)))
306 (eq (node-dest next) dest)
307 (eq (cast-type-check next) :external))))
308 (values-subtypep (lvar-externally-checkable-type lvar)
309 (cast-type-to-check cast)))))
311 ;;; Return true if CAST's value is an lvar whose type the back end is
312 ;;; likely to be able to check (see GENERATE-TYPE-CHECKS). Since we
313 ;;; don't know what template the back end is going to choose to
314 ;;; implement the continuation's DEST, we use a heuristic.
316 ;;; We always return T unless nobody uses the value (the backend
317 ;;; cannot check unused LVAR chains).
319 ;;; The logic used to be more complex, but most of the cases that used
320 ;;; to be checked here are now dealt with differently . FIXME: but
321 ;;; here's one we used to do, don't anymore, but could still benefit
322 ;;; from, if we reimplemented it (elsewhere):
324 ;;; -- If the lvar is an argument to a known function that has
325 ;;; no IR2-CONVERT method or :FAST-SAFE templates that are
326 ;;; compatible with the call's type: return NIL.
328 ;;; The code used to look like something like this:
331 ;;; (let ((info (basic-combination-fun-info dest)))
332 ;;; (if (fun-info-ir2-convert info)
334 ;;; (dolist (template (fun-info-templates info) nil)
335 ;;; (when (eq (template-ltn-policy template)
337 ;;; (multiple-value-bind (val win)
338 ;;; (valid-fun-use dest (template-type template))
339 ;;; (when (or val (not win)) (return t)))))))))))))
341 ;;; ADP says: It is still interesting. When we have a :SAFE template
342 ;;; and the type assertion is derived from the destination function
343 ;;; type, the check is unneccessary. We cannot return NIL here (the
344 ;;; whole function has changed its meaning, and here NIL *forces*
345 ;;; hairy check), but the functionality is interesting.
346 (defun probable-type-check-p (cast)
347 (declare (type cast cast))
348 (let* ((lvar (node-lvar cast))
349 (dest (and lvar (lvar-dest lvar))))
350 (cond ((not dest) nil)
353 ;;; Return a lambda form that we can convert to do a hairy type check
354 ;;; of the specified TYPES. TYPES is a list of the format returned by
355 ;;; LVAR-CHECK-TYPES in the :HAIRY case.
357 ;;; Note that we don't attempt to check for required values being
358 ;;; unsupplied. Such checking is impossible to efficiently do at the
359 ;;; source level because our fixed-values conventions are optimized
360 ;;; for the common MV-BIND case.
361 (defun make-type-check-form (types)
362 (let ((temps (make-gensym-list (length types))))
363 `(multiple-value-bind ,temps
365 ,@(mapcar (lambda (temp type)
367 (let ((*unparse-fun-type-simplify* t))
368 (type-specifier (second type))))
369 (test (if (first type) `(not ,spec) spec)))
370 `(unless (typep ,temp ',test)
373 ',(type-specifier (third type))))))
378 ;;; Splice in explicit type check code immediately before CAST. This
379 ;;; code receives the value(s) that were being passed to CAST-VALUE,
380 ;;; checks the type(s) of the value(s), then passes them further.
381 (defun convert-type-check (cast types)
382 (declare (type cast cast) (type list types))
383 (let ((value (cast-value cast))
384 (length (length types)))
385 (filter-lvar value (make-type-check-form types))
386 (reoptimize-lvar (cast-value cast))
387 (setf (cast-type-to-check cast) *wild-type*)
388 (setf (cast-%type-check cast) nil)
389 (let* ((atype (cast-asserted-type cast))
390 (atype (cond ((not (values-type-p atype))
393 (single-value-type atype))
396 :required (values-type-out atype length)))))
397 (dtype (node-derived-type cast))
398 (dtype (make-values-type
399 :required (values-type-out dtype length))))
400 (setf (cast-asserted-type cast) atype)
401 (setf (node-derived-type cast) dtype)))
405 ;;; Check all possible arguments of CAST and emit type warnings for
406 ;;; those with type errors. If the value of USE is being used for a
407 ;;; variable binding, we figure out which one for source context. If
408 ;;; the value is a constant, we print it specially.
409 (defun cast-check-uses (cast)
410 (declare (type cast cast))
411 (let* ((lvar (node-lvar cast))
412 (dest (and lvar (lvar-dest lvar)))
413 (value (cast-value cast))
414 (atype (cast-asserted-type cast)))
416 (let ((dtype (node-derived-type use)))
417 (unless (values-types-equal-or-intersect dtype atype)
418 (let* ((*compiler-error-context* use)
419 (atype-spec (type-specifier atype))
420 (what (when (and (combination-p dest)
421 (eq (combination-kind dest) :local))
422 (let ((lambda (combination-lambda dest))
423 (pos (position-or-lose
424 lvar (combination-args dest))))
425 (format nil "~:[A possible~;The~] binding of ~S"
426 (and (lvar-has-single-use-p lvar)
427 (eq (functional-kind lambda) :let))
428 (leaf-source-name (elt (lambda-vars lambda)
430 (cond ((and (ref-p use) (constant-p (ref-leaf use)))
433 "~:[This~;~:*~A~] is not a ~<~%~9T~:;~S:~>~% ~S"
435 (list what atype-spec
436 (constant-value (ref-leaf use)))))
440 "~:[Result~;~:*~A~] is a ~S, ~<~%~9T~:;not a ~S.~>"
442 (list what (type-specifier dtype) atype-spec)))))))))
445 ;;; Loop over all blocks in COMPONENT that have TYPE-CHECK set,
446 ;;; looking for CASTs with TYPE-CHECK T. We do two mostly unrelated
447 ;;; things: detect compile-time type errors and determine if and how
448 ;;; to do run-time type checks.
450 ;;; If there is a compile-time type error, then we mark the CAST and
451 ;;; emit a warning if appropriate. This part loops over all the uses
452 ;;; of the continuation, since after we convert the check, the
453 ;;; :DELETED kind will inhibit warnings about the types of other uses.
455 ;;; If the cast is too complex to be checked by the back end, or is
456 ;;; better checked with explicit code, then convert to an explicit
457 ;;; test. Assertions that can checked by the back end are passed
458 ;;; through. Assertions that can't be tested are flamed about and
459 ;;; marked as not needing to be checked.
461 ;;; If we determine that a type check won't be done, then we set
462 ;;; TYPE-CHECK to :NO-CHECK. In the non-hairy cases, this is just to
463 ;;; prevent us from wasting time coming to the same conclusion again
464 ;;; on a later iteration. In the hairy case, we must indicate to LTN
465 ;;; that it must choose a safe implementation, since IR2 conversion
466 ;;; will choke on the check.
468 ;;; The generation of the type checks is delayed until all the type
469 ;;; check decisions have been made because the generation of the type
470 ;;; checks creates new nodes whose derived types aren't always updated
471 ;;; which may lead to inappropriate template choices due to the
472 ;;; modification of argument types.
473 (defun generate-type-checks (component)
475 (do-blocks (block component)
476 (when (block-type-check block)
477 ;; CAST-EXTERNALLY-CHECKABLE-P wants the backward pass
478 (do-nodes-backwards (node nil block)
479 (when (and (cast-p node)
480 (cast-type-check node))
481 (cast-check-uses node)
482 (cond ((cast-externally-checkable-p node)
483 (setf (cast-%type-check node) :external))
485 ;; it is possible that NODE was marked :EXTERNAL by
487 (setf (cast-%type-check node) t)
488 (casts (cons node (not (probable-type-check-p node))))))))
489 (setf (block-type-check block) nil)))
490 (dolist (cast (casts))
491 (destructuring-bind (cast . force-hairy) cast
492 (multiple-value-bind (check types)
493 (cast-check-types cast force-hairy)
497 (convert-type-check cast types))
499 (let ((*compiler-error-context* cast))
500 (when (policy cast (>= safety inhibit-warnings))
502 "type assertion too complex to check:~% ~S."
503 (type-specifier (coerce-to-values (cast-asserted-type cast))))))
504 (setf (cast-type-to-check cast) *wild-type*)
505 (setf (cast-%type-check cast) nil)))))))