0.8.0.74:
[sbcl.git] / src / compiler / checkgen.lisp
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.
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 ;;;; cost estimation
18
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.)
24 ;;;
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))))
31     (if info
32         (let ((templates (fun-info-templates info)))
33           (if templates
34               (template-cost (first templates))
35               (case name
36                 (null (template-cost (template-or-lose 'if-eq)))
37                 (t call-cost))))
38         call-cost)))
39
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 (let ((check (type-check-template type)))
47         (if check
48             (template-cost check)
49             (let ((found (cdr (assoc type *backend-type-predicates*
50                                      :test #'type=))))
51               (if found
52                   (+ (fun-guessed-cost found) (fun-guessed-cost 'eq))
53                   nil))))
54       (typecase type
55         (compound-type
56          (reduce #'+ (compound-type-types type) :key 'type-test-cost))
57         (member-type
58          (* (length (member-type-members type))
59             (fun-guessed-cost 'eq)))
60         (numeric-type
61          (* (if (numeric-type-complexp type) 2 1)
62             (fun-guessed-cost
63              (if (csubtypep type (specifier-type 'fixnum)) 'fixnump 'numberp))
64             (+ 1
65                (if (numeric-type-low type) 1 0)
66                (if (numeric-type-high type) 1 0))))
67         (cons-type
68          (+ (type-test-cost (specifier-type 'cons))
69             (fun-guessed-cost 'car)
70             (type-test-cost (cons-type-car-type type))
71             (fun-guessed-cost 'cdr)
72             (type-test-cost (cons-type-cdr-type type))))
73         (t
74          (fun-guessed-cost 'typep)))))
75
76 (defun-cached
77     (weaken-type :hash-bits 8
78                  :hash-function (lambda (x)
79                                   (logand (type-hash-value x) #xFF)))
80     ((type eq))
81   (declare (type ctype type))
82   (let ((min-cost (type-test-cost type))
83         (min-type type)
84         (found-super nil))
85     (dolist (x *backend-type-predicates*)
86       (let ((stype (car x)))
87         (when (and (csubtypep type stype)
88                    (not (union-type-p stype)))
89           (let ((stype-cost (type-test-cost stype)))
90             (when (or (< stype-cost min-cost)
91                       (type= stype type))
92               ;; If the supertype is equal in cost to the type, we
93               ;; prefer the supertype. This produces a closer
94               ;; approximation of the right thing in the presence of
95               ;; poor cost info.
96               (setq found-super t
97                     min-type stype
98                     min-cost stype-cost))))))
99     (if found-super
100         min-type
101         *universal-type*)))
102
103 (defun weaken-values-type (type)
104   (declare (type ctype type))
105   (cond ((eq type *wild-type*) type)
106         ((not (values-type-p type))
107          (weaken-type type))
108         (t
109          (make-values-type :required (mapcar #'weaken-type
110                                              (values-type-required type))
111                            :optional (mapcar #'weaken-type
112                                              (values-type-optional type))
113                            :rest (acond ((values-type-rest type)
114                                          (weaken-type it)))))))
115 \f
116 ;;;; checking strategy determination
117
118 ;;; Return the type we should test for when we really want to check
119 ;;; for TYPE. If type checking policy is "fast", then we return a
120 ;;; weaker type if it is easier to check. First we try the defined
121 ;;; type weakenings, then look for any predicate that is cheaper.
122 (defun maybe-weaken-check (type policy)
123   (declare (type ctype type))
124   (ecase (policy policy type-check)
125     (0 *wild-type*)
126     (2 (weaken-values-type type))
127     (3 type)))
128
129 ;;; This is like VALUES-TYPES, only we mash any complex function types
130 ;;; to FUNCTION.
131 (defun no-fun-values-types (type)
132   (declare (type ctype type))
133   (multiple-value-bind (res count) (values-types type)
134     (values (mapcar (lambda (type)
135                       (if (fun-type-p type)
136                           (specifier-type 'function)
137                           type))
138                     res)
139             count)))
140
141 ;;; Switch to disable check complementing, for evaluation.
142 (defvar *complement-type-checks* t)
143
144 ;;; CONT is a continuation we are doing a type check on and TYPES is a
145 ;;; list of types that we are checking its values against. If we have
146 ;;; proven that CONT generates a fixed number of values, then for each
147 ;;; value, we check whether it is cheaper to then difference between
148 ;;; the proven type and the corresponding type in TYPES. If so, we opt
149 ;;; for a :HAIRY check with that test negated. Otherwise, we try to do
150 ;;; a simple test, and if that is impossible, we do a hairy test with
151 ;;; non-negated types. If true, FORCE-HAIRY forces a hairy type check.
152 ;;;
153 ;;; When doing a non-negated check, we call MAYBE-WEAKEN-CHECK to
154 ;;; weaken the test to a convenient supertype (conditional on policy.)
155 ;;; If SPEED is 3, or DEBUG-INFO is not particularly important (DEBUG
156 ;;; <= 1), then we allow weakened checks to be simple, resulting in
157 ;;; less informative error messages, but saving space and possibly
158 ;;; time.
159 ;;;
160 ;;; FIXME: I don't quite understand this, but it looks as though
161 ;;; that means type checks are weakened when SPEED=3 regardless of
162 ;;; the SAFETY level, which is not the right thing to do.
163 (defun maybe-negate-check (cont types original-types force-hairy)
164   (declare (type continuation cont) (list types))
165   (multiple-value-bind (ptypes count)
166       (no-fun-values-types (continuation-derived-type cont))
167     (if (eq count :unknown)
168         (if (and (every #'type-check-template types) (not force-hairy))
169             (values :simple types)
170             (values :hairy (mapcar (lambda (x) (list nil x x)) types)))
171         (let ((res (mapcar (lambda (p c a)
172                              (let ((diff (type-difference p c)))
173                                (if (and diff
174                                         (< (type-test-cost diff)
175                                            (type-test-cost c))
176                                         *complement-type-checks*)
177                                    (list t diff a)
178                                    (list nil c a))))
179                            ptypes types original-types)))
180           (cond ((or force-hairy (find-if #'first res))
181                  (values :hairy res))
182                 ((every #'type-check-template types)
183                  (values :simple types))
184                 (t
185                  (values :hairy res)))))))
186
187 ;;; Determines whether CONT's assertion is:
188 ;;;  -- checkable by the back end (:SIMPLE), or
189 ;;;  -- not checkable by the back end, but checkable via an explicit 
190 ;;;     test in type check conversion (:HAIRY), or
191 ;;;  -- not reasonably checkable at all (:TOO-HAIRY).
192 ;;;
193 ;;; A type is checkable if it either represents a fixed number of
194 ;;; values (as determined by VALUES-TYPES), or it is the assertion for
195 ;;; an MV-BIND. A type is simply checkable if all the type assertions
196 ;;; have a TYPE-CHECK-TEMPLATE. In this :SIMPLE case, the second value
197 ;;; is a list of the type restrictions specified for the leading
198 ;;; positional values.
199 ;;;
200 ;;; We force a check to be hairy even when there are fixed values if
201 ;;; we are in a context where we may be forced to use the unknown
202 ;;; values convention anyway. This is because IR2tran can't generate
203 ;;; type checks for unknown values continuations but people could
204 ;;; still be depending on the check being done. We only care about
205 ;;; EXIT and RETURN (not MV-COMBINATION) since these are the only
206 ;;; contexts where the ultimate values receiver
207 ;;;
208 ;;; In the :HAIRY case, the second value is a list of triples of
209 ;;; the form:
210 ;;;    (NOT-P TYPE ORIGINAL-TYPE)
211 ;;;
212 ;;; If true, the NOT-P flag indicates a test that the corresponding
213 ;;; value is *not* of the specified TYPE. ORIGINAL-TYPE is the type
214 ;;; asserted on this value in the continuation, for use in error
215 ;;; messages. When NOT-P is true, this will be different from TYPE.
216 ;;;
217 ;;; This allows us to take what has been proven about CONT's type into
218 ;;; consideration. If it is cheaper to test for the difference between
219 ;;; the derived type and the asserted type, then we check for the
220 ;;; negation of this type instead.
221 (defun cast-check-types (cast force-hairy)
222   (declare (type cast cast))
223   (let* ((cont (node-cont cast))
224          (ctype (coerce-to-values (cast-type-to-check cast)))
225          (atype (coerce-to-values (cast-asserted-type cast)))
226          (value (cast-value cast))
227          (vtype (continuation-derived-type value))
228          (dest (continuation-dest cont)))
229     (aver (not (eq ctype *wild-type*)))
230     (multiple-value-bind (ctypes count) (no-fun-values-types ctype)
231       (multiple-value-bind (atypes acount) (no-fun-values-types atype)
232         (multiple-value-bind (vtypes vcount) (values-types vtype)
233           (declare (ignore vtypes))
234           (aver (eq count acount))
235           (cond ((not (eq count :unknown))
236                  (if (or (exit-p dest)
237                          (and (return-p dest)
238                               (multiple-value-bind (ignore count)
239                                   (values-types (return-result-type dest))
240                                 (declare (ignore ignore))
241                                 (eq count :unknown))))
242                      (maybe-negate-check value ctypes atypes t)
243                      (maybe-negate-check value ctypes atypes force-hairy)))
244                 ((and (continuation-single-value-p cont)
245                       (or (not (args-type-rest ctype))
246                           (eq (args-type-rest ctype) *universal-type*)))
247                  (principal-continuation-single-valuify cont)
248                  (let ((creq (car (args-type-required ctype))))
249                    (multiple-value-setq (ctype atype)
250                      (if creq
251                          (values creq (car (args-type-required atype)))
252                          (values (car (args-type-optional ctype))
253                                  (car (args-type-optional atype)))))
254                    (maybe-negate-check value
255                                        (list ctype) (list atype)
256                                        force-hairy)))
257                 ((and (mv-combination-p dest)
258                       (eq (mv-combination-kind dest) :local))
259                  (let* ((fun-ref (continuation-use (mv-combination-fun dest)))
260                         (length (length (lambda-vars (ref-leaf fun-ref)))))
261                    (maybe-negate-check value
262                                        ;; FIXME
263                                        (adjust-list (values-type-types ctype)
264                                                     length
265                                                     *universal-type*)
266                                        (adjust-list (values-type-types atype)
267                                                     length
268                                                     *universal-type*)
269                                        force-hairy)))
270                 ((not (eq vcount :unknown))
271                  (maybe-negate-check value
272                                      (values-type-start ctype vcount)
273                                      (values-type-start atype vcount)
274                                      t))
275                 (t
276                  (values :too-hairy nil))))))))
277
278 ;;; Do we want to do a type check?
279 (defun worth-type-check-p (cast)
280   (declare (type cast cast))
281   (let* ((cont (node-cont cast))
282          (dest (continuation-dest cont)))
283     (not (or (not (cast-type-check cast))
284              (and (combination-p dest)
285                   (let ((kind (combination-kind dest)))
286                     (or (eq kind :full)
287                         ;; The theory is that the type assertion is
288                         ;; from a declaration in (or on) the callee,
289                         ;; so the callee should be able to do the
290                         ;; check. We want to let the callee do the
291                         ;; check, because it is possible that by the
292                         ;; time of call that declaration will be
293                         ;; changed and we do not want to make people
294                         ;; recompile all calls to a function when they
295                         ;; were originally compiled with a bad
296                         ;; declaration. (See also bug 35.)
297                         (and (fun-info-p kind)
298                              (null (fun-info-templates kind))
299                              (not (fun-info-ir2-convert kind)))))
300                   (and
301                    (immediately-used-p cont cast)
302                    (values-subtypep (continuation-externally-checkable-type cont)
303                                    (cast-type-to-check cast))))))))
304
305 ;;; Return true if CONT is a continuation whose type the back end is
306 ;;; likely to want to check. Since we don't know what template the
307 ;;; back end is going to choose to implement the continuation's DEST,
308 ;;; we use a heuristic. We always return T unless:
309 ;;;  -- nobody uses the value, or
310 ;;;  -- safety is totally unimportant, or
311 ;;;  -- the continuation is an argument to an unknown function, or
312 ;;;  -- the continuation is an argument to a known function that has
313 ;;;     no IR2-CONVERT method or :FAST-SAFE templates that are
314 ;;;     compatible with the call's type.
315 (defun probable-type-check-p (cast)
316   (declare (type cast cast))
317   (let* ((cont (node-cont cast))
318          (dest (continuation-dest cont)))
319     (cond ((not dest) nil)
320           (t t))
321     #+nil
322     (cond ((or (not dest)
323                (policy dest (zerop safety)))
324            nil)
325           ((basic-combination-p dest)
326            (let ((kind (basic-combination-kind dest)))
327              (cond ((eq cont (basic-combination-fun dest)) t)
328                    ((eq kind :local) t)
329                    ((eq kind :full)
330                     (and (combination-p dest)
331                          (not (values-subtypep ; explicit THE
332                                (continuation-externally-checkable-type cont)
333                                (continuation-type-to-check cont)))))
334
335                    ((eq kind :error) nil)
336                    ;; :ERROR means that we have an invalid syntax of
337                    ;; the call and the callee will detect it before
338                    ;; thinking about types.
339
340                    ((fun-info-ir2-convert kind) t)
341                    (t
342                     (dolist (template (fun-info-templates kind) nil)
343                       (when (eq (template-ltn-policy template) :fast-safe)
344                         (multiple-value-bind (val win)
345                             (valid-fun-use dest (template-type template))
346                           (when (or val (not win)) (return t)))))))))
347           (t t))))
348
349 ;;; Return a lambda form that we can convert to do a hairy type check
350 ;;; of the specified TYPES. TYPES is a list of the format returned by
351 ;;; CONTINUATION-CHECK-TYPES in the :HAIRY case.
352 ;;;
353 ;;; Note that we don't attempt to check for required values being
354 ;;; unsupplied. Such checking is impossible to efficiently do at the
355 ;;; source level because our fixed-values conventions are optimized
356 ;;; for the common MV-BIND case.
357 (defun make-type-check-form (types)
358   (let ((temps (make-gensym-list (length types))))
359     `(multiple-value-bind ,temps
360          'dummy
361        ,@(mapcar (lambda (temp type)
362                    (let* ((spec
363                            (let ((*unparse-fun-type-simplify* t))
364                              (type-specifier (second type))))
365                           (test (if (first type) `(not ,spec) spec)))
366                      `(unless (typep ,temp ',test)
367                         (%type-check-error
368                          ,temp
369                          ',(type-specifier (third type))))))
370                  temps
371                  types)
372        (values ,@temps))))
373
374 ;;; Splice in explicit type check code immediately before the node
375 ;;; which is CONT's DEST. This code receives the value(s) that were
376 ;;; being passed to CONT, checks the type(s) of the value(s), then
377 ;;; passes them on to CONT.
378 (defun convert-type-check (cast types)
379   (declare (type cast cast) (type list types))
380   (let ((cont (cast-value cast))
381         (length (length types)))
382     (filter-continuation cont (make-type-check-form types))
383     (reoptimize-continuation (cast-value cast))
384     (setf (cast-type-to-check cast) *wild-type*)
385     (setf (cast-%type-check cast) nil)
386     (let* ((atype (cast-asserted-type cast))
387            (atype (cond ((not (values-type-p atype))
388                          atype)
389                         ((= length 1)
390                          (single-value-type atype))
391                         (t
392                          (make-values-type :required 
393                                            (values-type-start atype length)))))
394            (dtype (node-derived-type cast))
395            (dtype (make-values-type :required 
396                                     (values-type-start dtype length))))
397       (setf (cast-asserted-type cast) atype)
398       (setf (node-derived-type cast) dtype)))
399
400   (values))
401
402 ;;; Check all possible arguments of CAST and emit type warnings for
403 ;;; those with type errors. If the value of USE is being used for a
404 ;;; variable binding, we figure out which one for source context. If
405 ;;; the value is a constant, we print it specially.
406 (defun cast-check-uses (cast)
407   (declare (type cast cast))
408   (let* ((cont (node-cont cast))
409          (dest (continuation-dest cont))
410          (value (cast-value cast))
411          (atype (cast-asserted-type cast)))
412     (do-uses (use value)
413       (let ((dtype (node-derived-type use)))
414         (unless (values-types-equal-or-intersect dtype atype)
415           (let* ((*compiler-error-context* use)
416                  (atype-spec (type-specifier atype))
417                  (what (when (and (combination-p dest)
418                                   (eq (combination-kind dest) :local))
419                          (let ((lambda (combination-lambda dest))
420                                (pos (position-or-lose
421                                      cont (combination-args dest))))
422                            (format nil "~:[A possible~;The~] binding of ~S"
423                                    (and (continuation-use cont)
424                                         (eq (functional-kind lambda) :let))
425                                    (leaf-source-name (elt (lambda-vars lambda)
426                                                           pos)))))))
427             (cond ((and (ref-p use) (constant-p (ref-leaf use)))
428                    (compiler-warn "~:[This~;~:*~A~] is not a ~<~%~9T~:;~S:~>~%  ~S"
429                                   what atype-spec (constant-value (ref-leaf use))))
430                   (t
431                    (compiler-warn
432                     "~:[Result~;~:*~A~] is a ~S, ~<~%~9T~:;not a ~S.~>"
433                     what (type-specifier dtype) atype-spec))))))))
434   (values))
435
436 ;;; Loop over all blocks in COMPONENT that have TYPE-CHECK set,
437 ;;; looking for continuations with TYPE-CHECK T. We do two mostly
438 ;;; unrelated things: detect compile-time type errors and determine if
439 ;;; and how to do run-time type checks.
440 ;;;
441 ;;; If there is a compile-time type error, then we mark the
442 ;;; continuation and emit a warning if appropriate. This part loops
443 ;;; over all the uses of the continuation, since after we convert the
444 ;;; check, the :DELETED kind will inhibit warnings about the types of
445 ;;; other uses.
446 ;;;
447 ;;; If a continuation is too complex to be checked by the back end, or
448 ;;; is better checked with explicit code, then convert to an explicit
449 ;;; test. Assertions that can checked by the back end are passed
450 ;;; through. Assertions that can't be tested are flamed about and
451 ;;; marked as not needing to be checked.
452 ;;;
453 ;;; If we determine that a type check won't be done, then we set
454 ;;; TYPE-CHECK to :NO-CHECK. In the non-hairy cases, this is just to
455 ;;; prevent us from wasting time coming to the same conclusion again
456 ;;; on a later iteration. In the hairy case, we must indicate to LTN
457 ;;; that it must choose a safe implementation, since IR2 conversion
458 ;;; will choke on the check.
459 ;;;
460 ;;; The generation of the type checks is delayed until all the type
461 ;;; check decisions have been made because the generation of the type
462 ;;; checks creates new nodes whose derived types aren't always updated
463 ;;; which may lead to inappropriate template choices due to the
464 ;;; modification of argument types.
465 (defun generate-type-checks (component)
466   (collect ((casts))
467     (do-blocks (block component)
468       (when (block-type-check block)
469         (do-nodes (node cont block)
470           (when (cast-p node)
471             (when (cast-type-check node)
472               (cast-check-uses node))
473             (cond ((worth-type-check-p node)
474                    (casts (cons node (not (probable-type-check-p node)))))
475                   (t
476                    (setf (cast-%type-check node) nil)
477                    (setf (cast-type-to-check node) *wild-type*)))))
478         (setf (block-type-check block) nil)))
479     (dolist (cast (casts))
480       (destructuring-bind (cast . force-hairy) cast
481         (multiple-value-bind (check types)
482             (cast-check-types cast force-hairy)
483           (ecase check
484             (:simple)
485             (:hairy
486              (convert-type-check cast types))
487             (:too-hairy
488              (let ((*compiler-error-context* cast))
489                (when (policy cast (>= safety inhibit-warnings))
490                  (compiler-notify
491                   "type assertion too complex to check:~% ~S."
492                   (type-specifier (coerce-to-values (cast-asserted-type cast))))))
493              (setf (cast-type-to-check cast) *wild-type*)
494              (setf (cast-%type-check cast) nil)))))))
495   (values))