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