0.6.9.16:
[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 function-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 (function-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                   (+ (function-cost found) (function-cost 'eq))
53                   nil))))
54       (typecase type
55         (union-type
56          (collect ((res 0 +))
57            (dolist (mem (union-type-types type))
58              (res (type-test-cost mem)))
59            (res)))
60         (member-type
61          (* (length (member-type-members type))
62             (function-cost 'eq)))
63         (numeric-type
64          (* (if (numeric-type-complexp type) 2 1)
65             (function-cost
66              (if (csubtypep type (specifier-type 'fixnum)) 'fixnump 'numberp))
67             (+ 1
68                (if (numeric-type-low type) 1 0)
69                (if (numeric-type-high type) 1 0))))
70         (cons-type
71          (+ (type-test-cost (specifier-type 'cons))
72             (function-cost 'car)
73             (type-test-cost (cons-type-car-type type))
74             (function-cost 'cdr)
75             (type-test-cost (cons-type-cdr-type type))))
76         (t
77          (function-cost 'typep)))))
78 \f
79 ;;;; checking strategy determination
80
81 ;;; Return the type we should test for when we really want to check
82 ;;; for TYPE. If speed, space or compilation speed is more important
83 ;;; than safety, then we return a weaker type if it is easier to
84 ;;; check. First we try the defined type weakenings, then look for any
85 ;;; predicate that is cheaper.
86 ;;;
87 ;;; If the supertype is equal in cost to the type, we prefer the
88 ;;; supertype. This produces a closer approximation of the right thing
89 ;;; in the presence of poor cost info.
90 (defun maybe-weaken-check (type cont)
91   (declare (type ctype type) (type continuation cont))
92   (cond ((policy (continuation-dest cont)
93                  (and (<= speed safety)
94                       (<= space safety)
95                       (<= compilation-speed safety)))
96          type)
97         (t
98          (let ((min-cost (type-test-cost type))
99                (min-type type)
100                (found-super nil))
101            (dolist (x *backend-type-predicates*)
102              (let ((stype (car x)))
103                (when (and (csubtypep type stype)
104                           (not (union-type-p stype)))
105                  (let ((stype-cost (type-test-cost stype)))
106                    (when (or (< stype-cost min-cost)
107                              (type= stype type))
108                      (setq found-super t
109                            min-type stype
110                            min-cost stype-cost))))))
111            (if found-super
112                min-type
113                *universal-type*)))))
114
115 ;;; Like VALUES-TYPES, only mash any complex function types to FUNCTION.
116 (defun no-function-values-types (type)
117   (declare (type ctype type))
118   (multiple-value-bind (res count) (values-types type)
119     (values (mapcar #'(lambda (type)
120                         (if (function-type-p type)
121                             (specifier-type 'function)
122                             type))
123                     res)
124             count)))
125
126 ;;; Switch to disable check complementing, for evaluation.
127 (defvar *complement-type-checks* t)
128
129 ;;; CONT is a continuation we are doing a type check on and TYPES is a
130 ;;; list of types that we are checking its values against. If we have
131 ;;; proven that CONT generates a fixed number of values, then for each
132 ;;; value, we check whether it is cheaper to then difference between
133 ;;; the proven type and the corresponding type in TYPES. If so, we opt
134 ;;; for a :HAIRY check with that test negated. Otherwise, we try to do
135 ;;; a simple test, and if that is impossible, we do a hairy test with
136 ;;; non-negated types. If true, Force-Hairy forces a hairy type check.
137 ;;;
138 ;;; When doing a non-negated check, we call MAYBE-WEAKEN-CHECK to
139 ;;; weaken the test to a convenient supertype (conditional on policy.)
140 ;;; If SPEED is 3, or DEBUG-INFO is not particularly important (DEBUG
141 ;;; <= 1), then we allow weakened checks to be simple, resulting in
142 ;;; less informative error messages, but saving space and possibly
143 ;;; time.
144 ;;;
145 ;;; FIXME: I don't quite understand this, but it looks as though
146 ;;; that means type checks are weakened when SPEED=3 regardless of
147 ;;; the SAFETY level, which is not the right thing to do.
148 (defun maybe-negate-check (cont types force-hairy)
149   (declare (type continuation cont) (list types))
150   (multiple-value-bind (ptypes count)
151       (no-function-values-types (continuation-proven-type cont))
152     (if (eq count :unknown)
153         (if (and (every #'type-check-template types) (not force-hairy))
154             (values :simple types)
155             (values :hairy
156                     (mapcar #'(lambda (x)
157                                 (list nil (maybe-weaken-check x cont) x))
158                             types)))
159         (let ((res (mapcar #'(lambda (p c)
160                                (let ((diff (type-difference p c))
161                                      (weak (maybe-weaken-check c cont)))
162                                  (if (and diff
163                                           (< (type-test-cost diff)
164                                              (type-test-cost weak))
165                                           *complement-type-checks*)
166                                      (list t diff c)
167                                      (list nil weak c))))
168                            ptypes types)))
169           (cond ((or force-hairy (find-if #'first res))
170                  (values :hairy res))
171                 ((every #'type-check-template types)
172                  (values :simple types))
173                 ((policy (continuation-dest cont)
174                          (or (<= debug 1) (and (= speed 3) (/= debug 3))))
175                  (let ((weakened (mapcar #'second res)))
176                    (if (every #'type-check-template weakened)
177                        (values :simple weakened)
178                        (values :hairy res))))
179                 (t
180                  (values :hairy res)))))))
181
182 ;;; Determines whether CONT's assertion is:
183 ;;;  -- checkable by the back end (:SIMPLE), or
184 ;;;  -- not checkable by the back end, but checkable via an explicit 
185 ;;;     test in type check conversion (:HAIRY), or
186 ;;;  -- not reasonably checkable at all (:TOO-HAIRY).
187 ;;;
188 ;;; A type is checkable if it either represents a fixed number of
189 ;;; values (as determined by VALUES-TYPES), or it is the assertion for
190 ;;; an MV-Bind. A type is simply checkable if all the type assertions
191 ;;; have a TYPE-CHECK-TEMPLATE. In this :SIMPLE case, the second value
192 ;;; is a list of the type restrictions specified for the leading
193 ;;; positional values.
194 ;;;
195 ;;; We force a check to be hairy even when there are fixed values if
196 ;;; we are in a context where we may be forced to use the unknown
197 ;;; values convention anyway. This is because IR2tran can't generate
198 ;;; type checks for unknown values continuations but people could
199 ;;; still be depending on the check being done. We only care about
200 ;;; EXIT and RETURN (not MV-COMBINATION) since these are the only
201 ;;; contexts where the ultimate values receiver
202 ;;;
203 ;;; In the :HAIRY case, the second value is a list of triples of
204 ;;; the form:
205 ;;;    (NOT-P TYPE ORIGINAL-TYPE)
206 ;;;
207 ;;; If true, the NOT-P flag indicates a test that the corresponding
208 ;;; value is *not* of the specified TYPE. ORIGINAL-TYPE is the type
209 ;;; asserted on this value in the continuation, for use in error
210 ;;; messages. When NOT-P is true, this will be different from TYPE.
211 ;;;
212 ;;; This allows us to take what has been proven about CONT's type into
213 ;;; consideration. If it is cheaper to test for the difference between
214 ;;; the derived type and the asserted type, then we check for the
215 ;;; negation of this type instead.
216 (defun continuation-check-types (cont)
217   (declare (type continuation cont))
218   (let ((type (continuation-asserted-type cont))
219         (dest (continuation-dest cont)))
220     (assert (not (eq type *wild-type*)))
221     (multiple-value-bind (types count) (no-function-values-types type)
222       (cond ((not (eq count :unknown))
223              (if (or (exit-p dest)
224                      (and (return-p dest)
225                           (multiple-value-bind (ignore count)
226                               (values-types (return-result-type dest))
227                             (declare (ignore ignore))
228                             (eq count :unknown))))
229                  (maybe-negate-check cont types t)
230                  (maybe-negate-check cont types nil)))
231             ((and (mv-combination-p dest)
232                   (eq (basic-combination-kind dest) :local))
233              (assert (values-type-p type))
234              (maybe-negate-check cont (args-type-optional type) nil))
235             (t
236              (values :too-hairy nil))))))
237
238 ;;; Return true if CONT is a continuation whose type the back end is
239 ;;; likely to want to check. Since we don't know what template the
240 ;;; back end is going to choose to implement the continuation's DEST,
241 ;;; we use a heuristic. We always return T unless:
242 ;;;  -- nobody uses the value, or
243 ;;;  -- safety is totally unimportant, or
244 ;;;  -- the continuation is an argument to an unknown function, or
245 ;;;  -- the continuation is an argument to a known function that has 
246 ;;;     no IR2-Convert method or :FAST-SAFE templates that are
247 ;;;     compatible with the call's type.
248 ;;;
249 ;;; We must only return NIL when it is *certain* that a check will not
250 ;;; be done, since if we pass up this chance to do the check, it will
251 ;;; be too late. The penalty for being too conservative is duplicated
252 ;;; type checks. The penalty for erring by being too speculative is
253 ;;; much nastier, e.g. falling through without ever being able to find
254 ;;; an appropriate VOP.
255 ;;;
256 ;;; If there is a compile-time type error, then we always return true
257 ;;; unless the DEST is a full call. With a full call, the theory is
258 ;;; that the type error is probably from a declaration in (or on) the
259 ;;; callee, so the callee should be able to do the check. We want to
260 ;;; let the callee do the check, because it is possible that the error
261 ;;; is really in the callee, not the caller. We don't want to make
262 ;;; people recompile all calls to a function when they were originally
263 ;;; compiled with a bad declaration (or an old type assertion derived
264 ;;; from a definition appearing after the call.)
265 (defun probable-type-check-p (cont)
266   (declare (type continuation cont))
267   (let ((dest (continuation-dest cont)))
268     (cond ((eq (continuation-type-check cont) :error)
269            (if (and (combination-p dest) (eq (combination-kind dest) :error))
270                nil
271                t))
272           ((or (not dest)
273                (policy dest (zerop safety)))
274            nil)
275           ((basic-combination-p dest)
276            (let ((kind (basic-combination-kind dest)))
277              (cond ((eq cont (basic-combination-fun dest)) t)
278                    ((eq kind :local) t)
279                    ((member kind '(:full :error)) nil)
280                    ((function-info-ir2-convert kind) t)
281                    (t
282                     (dolist (template (function-info-templates kind) nil)
283                       (when (eq (template-ltn-policy template) :fast-safe)
284                         (multiple-value-bind (val win)
285                             (valid-function-use dest (template-type template))
286                           (when (or val (not win)) (return t)))))))))
287           (t t))))
288
289 ;;; Return a form that we can convert to do a hairy type check of the
290 ;;; specified TYPES. TYPES is a list of the format returned by
291 ;;; CONTINUATION-CHECK-TYPES in the :HAIRY case. In place of the
292 ;;; actual value(s) we are to check, we use 'DUMMY. This constant
293 ;;; reference is later replaced with the actual values continuation.
294 ;;;
295 ;;; Note that we don't attempt to check for required values being
296 ;;; unsupplied. Such checking is impossible to efficiently do at the
297 ;;; source level because our fixed-values conventions are optimized
298 ;;; for the common MV-BIND case.
299 ;;;
300 ;;; We can always use MULTIPLE-VALUE-BIND, since the macro is clever
301 ;;; about binding a single variable.
302 (defun make-type-check-form (types)
303   (let ((temps (make-gensym-list (length types))))
304     `(multiple-value-bind ,temps 'dummy
305        ,@(mapcar #'(lambda (temp type)
306                      (let* ((spec
307                              (let ((*unparse-function-type-simplify* t))
308                                (type-specifier (second type))))
309                             (test (if (first type) `(not ,spec) spec)))
310                        `(unless (typep ,temp ',test)
311                           (%type-check-error
312                            ,temp
313                            ',(type-specifier (third type))))))
314                  temps
315                  types)
316        (values ,@temps))))
317
318 ;;; Splice in explicit type check code immediately before the node
319 ;;; which is CONT's DEST. This code receives the value(s) that were
320 ;;; being passed to CONT, checks the type(s) of the value(s), then
321 ;;; passes them on to CONT.
322 (defun convert-type-check (cont types)
323   (declare (type continuation cont) (type list types))
324   (with-ir1-environment (continuation-dest cont)
325
326     ;; Ensuring that CONT starts a block lets us freely manipulate its uses.
327     (ensure-block-start cont)
328
329     ;; Make a new continuation and move CONT's uses to it.
330     (let* ((new-start (make-continuation))
331            (dest (continuation-dest cont))
332            (prev (node-prev dest)))
333       (continuation-starts-block new-start)
334       (substitute-continuation-uses new-start cont)
335
336       ;; Setting TYPE-CHECK in CONT to :DELETED indicates that the
337       ;; check has been done.
338       (setf (continuation-%type-check cont) :deleted)
339
340       ;; Make the DEST node start its block so that we can splice in
341       ;; the type check code.
342       (when (continuation-use prev)
343         (node-ends-block (continuation-use prev)))
344
345       (let* ((prev-block (continuation-block prev))
346              (new-block (continuation-block new-start))
347              (dummy (make-continuation)))
348
349         ;; Splice in the new block before DEST, giving the new block
350         ;; all of DEST's predecessors.
351         (dolist (block (block-pred prev-block))
352           (change-block-successor block prev-block new-block))
353
354         ;; Convert the check form, using the new block start as START
355         ;; and a dummy continuation as CONT.
356         (ir1-convert new-start dummy (make-type-check-form types))
357
358         ;; TO DO: Why should this be true? -- WHN 19990601
359         (assert (eq (continuation-block dummy) new-block))
360
361         ;; KLUDGE: Comments at the head of this function in CMU CL
362         ;; said that somewhere in here we
363         ;;   Set the new block's start and end cleanups to the *start*
364         ;;   cleanup of PREV's block. This overrides the incorrect
365         ;;   default from WITH-IR1-ENVIRONMENT.
366         ;; Unfortunately I can't find any code which corresponds to this.
367         ;; Perhaps it was a stale comment? Or perhaps I just don't
368         ;; understand.. -- WHN 19990521
369
370         (let ((node (continuation-use dummy)))
371           (setf (block-last new-block) node)
372           ;; Change the use to a use of CONT. (We need to use the
373           ;; dummy continuation to get the control transfer right,
374           ;; because we want to go to PREV's block, not CONT's.)
375           (delete-continuation-use node)
376           (add-continuation-use node cont))
377         ;; Link the new block to PREV's block.
378         (link-blocks new-block prev-block))
379
380       ;; MAKE-TYPE-CHECK-FORM generated a form which checked the type
381       ;; of 'DUMMY, not a real form. At this point we convert to the
382       ;; real form by finding 'DUMMY and overwriting it with the new
383       ;; continuation. (We can find 'DUMMY because no LET conversion
384       ;; has been done yet.) The [mv-]combination code from the
385       ;; mv-bind in the check form will be the use of the new check
386       ;; continuation. We substitute for the first argument of this
387       ;; node.
388       (let* ((node (continuation-use cont))
389              (args (basic-combination-args node))
390              (victim (first args)))
391         (assert (and (= (length args) 1)
392                      (eq (constant-value
393                           (ref-leaf
394                            (continuation-use victim)))
395                          'dummy)))
396         (substitute-continuation new-start victim)))
397
398     ;; Invoking local call analysis converts this call to a LET.
399     (local-call-analyze *current-component*))
400
401   (values))
402
403 ;;; Emit a type warning for NODE. If the value of NODE is being used
404 ;;; for a variable binding, we figure out which one for source
405 ;;; context. If the value is a constant, we print it specially. We
406 ;;; ignore nodes whose type is NIL, since they are supposed to never
407 ;;; return.
408 (defun do-type-warning (node)
409   (declare (type node node))
410   (let* ((*compiler-error-context* node)
411          (cont (node-cont node))
412          (atype-spec (type-specifier (continuation-asserted-type cont)))
413          (dtype (node-derived-type node))
414          (dest (continuation-dest cont))
415          (what (when (and (combination-p dest)
416                           (eq (combination-kind dest) :local))
417                  (let ((lambda (combination-lambda dest))
418                        (pos (position-or-lose cont (combination-args dest))))
419                    (format nil "~:[A possible~;The~] binding of ~S"
420                            (and (continuation-use cont)
421                                 (eq (functional-kind lambda) :let))
422                            (leaf-name (elt (lambda-vars lambda) pos)))))))
423     (cond ((eq dtype *empty-type*))
424           ((and (ref-p node) (constant-p (ref-leaf node)))
425            (compiler-warning "~:[This~;~:*~A~] is not a ~<~%~9T~:;~S:~>~%  ~S"
426                              what atype-spec (constant-value (ref-leaf node))))
427           (t
428            (compiler-warning
429             "~:[Result~;~:*~A~] is a ~S, ~<~%~9T~:;not a ~S.~>"
430             what (type-specifier dtype) atype-spec))))
431   (values))
432
433 ;;; Mark CONT as being a continuation with a manifest type error. We
434 ;;; set the kind to :ERROR, and clear any FUNCTION-INFO if the
435 ;;; continuation is an argument to a known call. The last is done so
436 ;;; that the back end doesn't have to worry about type errors in
437 ;;; arguments to known functions. This clearing is inhibited for
438 ;;; things with IR2-CONVERT methods, since we can't do a full call to
439 ;;; funny functions.
440 (defun mark-error-continuation (cont)
441   (declare (type continuation cont))
442   (setf (continuation-%type-check cont) :error)
443   (let ((dest (continuation-dest cont)))
444     (when (and (combination-p dest)
445                (let ((kind (basic-combination-kind dest)))
446                  (or (eq kind :full)
447                      (and (function-info-p kind)
448                           (not (function-info-ir2-convert kind))))))
449       (setf (basic-combination-kind dest) :error)))
450   (values))
451
452 ;;; Loop over all blocks in Component that have TYPE-CHECK set,
453 ;;; looking for continuations with TYPE-CHECK T. We do two mostly
454 ;;; unrelated things: detect compile-time type errors and determine if
455 ;;; and how to do run-time type checks.
456 ;;;
457 ;;; If there is a compile-time type error, then we mark the
458 ;;; continuation and emit a warning if appropriate. This part loops
459 ;;; over all the uses of the continuation, since after we convert the
460 ;;; check, the :DELETED kind will inhibit warnings about the types of
461 ;;; other uses.
462 ;;;
463 ;;; If a continuation is too complex to be checked by the back end, or
464 ;;; is better checked with explicit code, then convert to an explicit
465 ;;; test. Assertions that can checked by the back end are passed
466 ;;; through. Assertions that can't be tested are flamed about and
467 ;;; marked as not needing to be checked.
468 ;;;
469 ;;; If we determine that a type check won't be done, then we set
470 ;;; TYPE-CHECK to :NO-CHECK. In the non-hairy cases, this is just to
471 ;;; prevent us from wasting time coming to the same conclusion again
472 ;;; on a later iteration. In the hairy case, we must indicate to LTN
473 ;;; that it must choose a safe implementation, since IR2 conversion
474 ;;; will choke on the check.
475 ;;;
476 ;;; The generation of the type checks is delayed until all the type
477 ;;; check decisions have been made because the generation of the type
478 ;;; checks creates new nodes whose derived types aren't always updated
479 ;;; which may lead to inappropriate template choices due to the
480 ;;; modification of argument types.
481 (defun generate-type-checks (component)
482   (collect ((conts))
483     (do-blocks (block component)
484       (when (block-type-check block)
485         (do-nodes (node cont block)
486           (let ((type-check (continuation-type-check cont)))
487             (unless (member type-check '(nil :error :deleted))
488               (let ((atype (continuation-asserted-type cont)))
489                 (do-uses (use cont)
490                   (unless (values-types-intersect (node-derived-type use)
491                                                   atype)
492                     (mark-error-continuation cont)
493                     (unless (policy node (= inhibit-warnings 3))
494                       (do-type-warning use))))))
495             (when (and (eq type-check t)
496                        (not *byte-compiling*))
497               (cond ((probable-type-check-p cont)
498                      (conts cont))
499                     (t
500                      (setf (continuation-%type-check cont) :no-check))))))
501         (setf (block-type-check block) nil)))
502     (dolist (cont (conts))
503       (multiple-value-bind (check types) (continuation-check-types cont)
504         (ecase check
505           (:simple)
506           (:hairy
507            (convert-type-check cont types))
508           (:too-hairy
509            (let* ((context (continuation-dest cont))
510                   (*compiler-error-context* context))
511              (when (policy context (>= safety inhibit-warnings))
512                (compiler-note
513                 "type assertion too complex to check:~% ~S."
514                 (type-specifier (continuation-asserted-type cont)))))
515            (setf (continuation-%type-check cont) :deleted))))))
516   (values))