*** empty log message ***
[sbcl.git] / src / compiler / ltn.lisp
1 ;;;; This file contains the LTN pass in the compiler. LTN allocates
2 ;;;; expression evaluation TNs, makes nearly all the implementation
3 ;;;; policy decisions, and also does a few other miscellaneous things.
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15 \f
16 ;;;; utilities
17
18 ;;; Return the LTN-POLICY indicated by the node policy.
19 ;;;
20 ;;; FIXME: It would be tidier to use an LTN-POLICY object (an instance
21 ;;; of DEFSTRUCT LTN-POLICY) instead of a keyword, and have queries
22 ;;; like LTN-POLICY-SAFE-P become slot accessors. If we do this,
23 ;;; grep for and carefully review use of literal keywords, so that
24 ;;; things like
25 ;;;   (EQ (TEMPLATE-LTN-POLICY TEMPLATE) :SAFE)
26 ;;; don't get overlooked.
27 ;;;
28 ;;; FIXME: Classic CMU CL went to some trouble to cache LTN-POLICY
29 ;;; values in LTN-ANALYZE so that they didn't have to be recomputed on
30 ;;; every block. I stripped that out (the whole DEFMACRO FROB thing)
31 ;;; because I found it too confusing. Thus, it might be that the 
32 ;;; new uncached code spends an unreasonable amount of time in
33 ;;; this lookup function. This function should be profiled, and if
34 ;;; it's a significant contributor to runtime, we can cache it in
35 ;;; some more local way, e.g. by adding a CACHED-LTN-POLICY slot to
36 ;;; the NODE structure, and doing something like
37 ;;;   (DEFUN NODE-LTN-POLICY (NODE)
38 ;;;     (OR (NODE-CACHED-LTN-POLICY NODE)
39 ;;;         (SETF (NODE-CACHED-LTN-POLICY NODE)
40 ;;;               (NODE-UNCACHED-LTN-POLICY NODE)))
41 (defun node-ltn-policy (node)
42   (declare (type node node))
43   (policy node
44           (let ((eff-space (max space
45                                 ;; on the theory that if the code is
46                                 ;; smaller, it will take less time to
47                                 ;; compile (could lose if the smallest
48                                 ;; case is out of line, and must
49                                 ;; allocate many linkage registers):
50                                 compilation-speed)))
51             (if (zerop safety)
52                 (if (>= speed eff-space) :fast :small)
53                 (if (>= speed eff-space) :fast-safe :safe)))))
54
55 ;;; Return true if LTN-POLICY is a safe policy.
56 (defun ltn-policy-safe-p (ltn-policy)
57   (ecase ltn-policy
58     ((:safe :fast-safe) t)
59     ((:small :fast) nil)))
60
61 ;;; Called when an unsafe policy indicates that no type check should
62 ;;; be done on CONT. We delete the type check unless it is :ERROR
63 ;;; (indicating a compile-time type error.)
64 (defun flush-type-check (cont)
65   (declare (type continuation cont))
66   (when (member (continuation-type-check cont) '(t :no-check))
67     (setf (continuation-%type-check cont) :deleted))
68   (values))
69
70 ;;; an annotated continuation's primitive-type
71 #!-sb-fluid (declaim (inline continuation-ptype))
72 (defun continuation-ptype (cont)
73   (declare (type continuation cont))
74   (ir2-continuation-primitive-type (continuation-info cont)))
75
76 ;;; Return true if a constant LEAF is of a type which we can legally
77 ;;; directly reference in code. Named constants with arbitrary pointer
78 ;;; values cannot, since we must preserve EQLness.
79 (defun legal-immediate-constant-p (leaf)
80   (declare (type constant leaf))
81   (or (not (leaf-has-source-name-p leaf))
82       (typecase (constant-value leaf)
83         ((or number character) t)
84         (symbol (symbol-package (constant-value leaf)))
85         (t nil))))
86
87 ;;; If CONT is used only by a REF to a leaf that can be delayed, then
88 ;;; return the leaf, otherwise return NIL.
89 (defun continuation-delayed-leaf (cont)
90   (declare (type continuation cont))
91   (let ((use (continuation-use cont)))
92     (and (ref-p use)
93          (let ((leaf (ref-leaf use)))
94            (etypecase leaf
95              (lambda-var (if (null (lambda-var-sets leaf)) leaf nil))
96              (constant (if (legal-immediate-constant-p leaf) leaf nil))
97              ((or functional global-var) nil))))))
98
99 ;;; Annotate a normal single-value continuation. If its only use is a
100 ;;; ref that we are allowed to delay the evaluation of, then we mark
101 ;;; the continuation for delayed evaluation, otherwise we assign a TN
102 ;;; to hold the continuation's value. If the continuation has a type
103 ;;; check, we make the TN according to the proven type to ensure that
104 ;;; the possibly erroneous value can be represented.
105 (defun annotate-1-value-continuation (cont)
106   (declare (type continuation cont))
107   (let ((info (continuation-info cont)))
108     (aver (eq (ir2-continuation-kind info) :fixed))
109     (cond
110      ((continuation-delayed-leaf cont)
111       (setf (ir2-continuation-kind info) :delayed))
112      ((member (continuation-type-check cont) '(:deleted nil))
113       (setf (ir2-continuation-locs info)
114             (list (make-normal-tn (ir2-continuation-primitive-type info)))))
115      (t
116       (setf (ir2-continuation-locs info)
117             (list (make-normal-tn
118                    (primitive-type
119                     (single-value-type (continuation-proven-type cont)))))))))
120   (values))
121
122 ;;; Make an IR2-CONTINUATION corresponding to the continuation type
123 ;;; and then do ANNOTATE-1-VALUE-CONTINUATION. If POLICY-KEYWORD isn't
124 ;;; a safe policy keyword, then we clear the TYPE-CHECK flag.
125 (defun annotate-ordinary-continuation (cont ltn-policy)
126   (declare (type continuation cont)
127            (type ltn-policy ltn-policy))
128   (let ((info (make-ir2-continuation
129                (primitive-type (continuation-type cont)))))
130     (setf (continuation-info cont) info)
131     (unless (ltn-policy-safe-p ltn-policy)
132       (flush-type-check cont))
133     (annotate-1-value-continuation cont))
134   (values))
135
136 ;;; Annotate the function continuation for a full call. If the only
137 ;;; reference is to a global function and DELAY is true, then we delay
138 ;;; the reference, otherwise we annotate for a single value.
139 ;;;
140 ;;; Unlike for an argument, we only clear the type check flag when the
141 ;;; LTN-POLICY is unsafe, since the check for a valid function
142 ;;; object must be done before the call.
143 (defun annotate-fun-continuation (cont ltn-policy &optional (delay t))
144   (declare (type continuation cont) (type ltn-policy ltn-policy))
145   (unless (ltn-policy-safe-p ltn-policy)
146     (flush-type-check cont))
147   (let* ((ptype (primitive-type (continuation-type cont)))
148          (tn-ptype (if (member (continuation-type-check cont) '(:deleted nil))
149                        ptype
150                        (primitive-type
151                         (single-value-type
152                          (continuation-proven-type cont)))))
153          (info (make-ir2-continuation ptype)))
154     (setf (continuation-info cont) info)
155     (let ((name (continuation-fun-name cont t)))
156       (if (and delay name)
157           (setf (ir2-continuation-kind info) :delayed)
158           (setf (ir2-continuation-locs info)
159                 (list (make-normal-tn tn-ptype))))))
160   (values))
161
162 ;;; If TAIL-P is true, then we check to see whether the call can really
163 ;;; be a tail call by seeing if this function's return convention is :UNKNOWN.
164 ;;; If so, we move the call block succssor link from the return block to
165 ;;; the component tail (after ensuring that they are in separate blocks.)
166 ;;; This allows the return to be deleted when there are no non-tail uses.
167 (defun flush-full-call-tail-transfer (call)
168   (declare (type basic-combination call))
169   (let ((tails (and (node-tail-p call)
170                     (lambda-tail-set (node-home-lambda call)))))
171     (when tails
172       (cond ((eq (return-info-kind (tail-set-info tails)) :unknown)
173              (node-ends-block call)
174              (let ((block (node-block call)))
175                (unlink-blocks block (first (block-succ block)))
176                (link-blocks block (component-tail (block-component block)))))
177             (t
178              (setf (node-tail-p call) nil)))))
179   (values))
180
181 ;;; We set the kind to :FULL or :FUNNY, depending on whether there is an
182 ;;; IR2-CONVERT method. If a funny function, then we inhibit tail recursion
183 ;;; and type check normally, since the IR2 convert method is going to want to
184 ;;; deliver values normally. We still annotate the function continuation,
185 ;;; since IR2tran might decide to call after all.
186 ;;;
187 ;;; If not funny, we always flush arg type checks, but do it after
188 ;;; annotation when the LTN-POLICY is safe, since we don't want to
189 ;;; choose the TNs according to a type assertions that may not hold.
190 ;;;
191 ;;; Note that args may already be annotated because template selection can
192 ;;; bail out to here.
193 (defun ltn-default-call (call ltn-policy)
194   (declare (type combination call) (type ltn-policy ltn-policy))
195   (let ((kind (basic-combination-kind call)))
196     (annotate-fun-continuation (basic-combination-fun call) ltn-policy)
197
198     (cond
199      ((and (fun-info-p kind)
200            (fun-info-ir2-convert kind))
201       (setf (basic-combination-info call) :funny)
202       (setf (node-tail-p call) nil)
203       (dolist (arg (basic-combination-args call))
204         (unless (continuation-info arg)
205           (setf (continuation-info arg)
206                 (make-ir2-continuation
207                  (primitive-type
208                   (continuation-type arg)))))
209         (annotate-1-value-continuation arg)))
210      (t
211       (let ((safe-p (ltn-policy-safe-p ltn-policy)))
212         (dolist (arg (basic-combination-args call))
213           (unless safe-p (flush-type-check arg))
214           (unless (continuation-info arg)
215             (setf (continuation-info arg)
216                   (make-ir2-continuation
217                    (primitive-type
218                     (continuation-type arg)))))
219           (annotate-1-value-continuation arg)
220           (when safe-p (flush-type-check arg))))
221       (when (eq kind :error)
222         (setf (basic-combination-kind call) :full))
223       (setf (basic-combination-info call) :full)
224       (flush-full-call-tail-transfer call))))
225
226   (values))
227
228 ;;; Annotate a continuation for unknown multiple values:
229 ;;; -- Delete any type check, regardless of LTN-POLICY, since IR2
230 ;;;    conversion isn't prepared to check unknown-values continuations.
231 ;;;    If we delete a type check when the policy is safe, then we emit
232 ;;;    a warning.
233 ;;; -- Add the continuation to the IR2-BLOCK-POPPED if it is used
234 ;;;    across a block boundary.
235 ;;; -- Assign an :UNKNOWN IR2-CONTINUATION.
236 ;;;
237 ;;; Note: it is critical that this be called only during LTN analysis
238 ;;; of CONT's DEST, and called in the order that the continuations are
239 ;;; received. Otherwise the IR2-BLOCK-POPPED and
240 ;;; IR2-COMPONENT-VALUES-FOO would get all messed up.
241 (defun annotate-unknown-values-continuation (cont ltn-policy)
242   (declare (type continuation cont) (type ltn-policy ltn-policy))
243   (when (eq (continuation-type-check cont) t)
244     (let* ((dest (continuation-dest cont))
245            (*compiler-error-context* dest))
246       (when (and (ltn-policy-safe-p ltn-policy)
247                  (policy dest (>= safety inhibit-warnings)))
248         (compiler-note "compiler limitation: ~
249                         unable to check type assertion in ~
250                         unknown-values context:~%  ~S"
251                        (continuation-asserted-type cont))))
252     (setf (continuation-%type-check cont) :deleted))
253
254   (let* ((block (node-block (continuation-dest cont)))
255          (use (continuation-use cont))
256          (2block (block-info block)))
257     (unless (and use (eq (node-block use) block))
258       (setf (ir2-block-popped 2block)
259             (nconc (ir2-block-popped 2block) (list cont)))))
260
261   (let ((2cont (make-ir2-continuation nil)))
262     (setf (ir2-continuation-kind 2cont) :unknown)
263     (setf (ir2-continuation-locs 2cont) (make-unknown-values-locations))
264     (setf (continuation-info cont) 2cont))
265
266   (values))
267
268 ;;; Annotate CONT for a fixed, but arbitrary number of values, of the
269 ;;; specified primitive TYPES. If the continuation has a type check,
270 ;;; we annotate for the number of values indicated by TYPES, but only
271 ;;; use proven type information.
272 (defun annotate-fixed-values-continuation (cont ltn-policy types)
273   (declare (continuation cont) (ltn-policy ltn-policy) (list types))
274   (unless (ltn-policy-safe-p ltn-policy)
275     (flush-type-check cont))
276   (let ((res (make-ir2-continuation nil)))
277     (if (member (continuation-type-check cont) '(:deleted nil))
278         (setf (ir2-continuation-locs res) (mapcar #'make-normal-tn types))
279         (let* ((proven (mapcar (lambda (x)
280                                  (make-normal-tn (primitive-type x)))
281                                (values-types
282                                 (continuation-proven-type cont))))
283                (num-proven (length proven))
284                (num-types (length types)))
285           (setf (ir2-continuation-locs res)
286                 (cond
287                  ((< num-proven num-types)
288                   (append proven
289                           (make-n-tns (- num-types num-proven)
290                                       *backend-t-primitive-type*)))
291                  ((> num-proven num-types)
292                   (subseq proven 0 num-types))
293                  (t
294                   proven)))))
295     (setf (continuation-info cont) res))
296   (values))
297 \f
298 ;;;; node-specific analysis functions
299
300 ;;; Annotate the result continuation for a function. We use the
301 ;;; RETURN-INFO computed by GTN to determine how to represent the
302 ;;; return values within the function:
303 ;;;  * If the TAIL-SET has a fixed values count, then use that
304 ;;;    many values.
305 ;;;  * If the actual uses of the result continuation in this function
306 ;;;    have a fixed number of values (after intersection with the
307 ;;;    assertion), then use that number. We throw out TAIL-P :FULL
308 ;;;    and :LOCAL calls, since we know they will truly end up as TR
309 ;;;    calls. We can use the BASIC-COMBINATION-INFO even though it
310 ;;;    is assigned by this phase, since the initial value NIL doesn't
311 ;;;    look like a TR call.
312 ;;;      If there are *no* non-tail-call uses, then it falls out
313 ;;;    that we annotate for one value (type is NIL), but the return
314 ;;;    will end up being deleted.
315 ;;;      In non-perverse code, the DFO walk will reach all uses of
316 ;;;    the result continuation before it reaches the RETURN. In
317 ;;;    perverse code, we may annotate for unknown values when we
318 ;;;    didn't have to.
319 ;;; * Otherwise, we must annotate the continuation for unknown values.
320 (defun ltn-analyze-return (node ltn-policy)
321   (declare (type creturn node) (type ltn-policy ltn-policy))
322   (let* ((cont (return-result node))
323          (fun (return-lambda node))
324          (returns (tail-set-info (lambda-tail-set fun)))
325          (types (return-info-types returns)))
326     (if (eq (return-info-count returns) :unknown)
327         (collect ((res *empty-type* values-type-union))
328           (do-uses (use (return-result node))
329             (unless (and (node-tail-p use)
330                          (basic-combination-p use)
331                          (member (basic-combination-info use) '(:local :full)))
332               (res (node-derived-type use))))
333
334           (let ((int (values-type-intersection
335                       (res)
336                       (continuation-asserted-type cont))))
337             (multiple-value-bind (types kind)
338                 (values-types (if (eq int *empty-type*) (res) int))
339               (if (eq kind :unknown)
340                   (annotate-unknown-values-continuation cont ltn-policy)
341                   (annotate-fixed-values-continuation
342                    cont ltn-policy (mapcar #'primitive-type types))))))
343         (annotate-fixed-values-continuation cont ltn-policy types)))
344
345   (values))
346
347 ;;; Annotate the single argument continuation as a fixed-values
348 ;;; continuation. We look at the called lambda to determine number and
349 ;;; type of return values desired. It is assumed that only a function
350 ;;; that LOOKS-LIKE-AN-MV-BIND will be converted to a local call.
351 (defun ltn-analyze-mv-bind (call ltn-policy)
352   (declare (type mv-combination call)
353            (type ltn-policy ltn-policy))
354   (setf (basic-combination-kind call) :local)
355   (setf (node-tail-p call) nil)
356   (annotate-fixed-values-continuation
357    (first (basic-combination-args call))
358    ltn-policy
359    (mapcar (lambda (var)
360              (primitive-type (basic-var-type var)))
361            (lambda-vars
362             (ref-leaf
363              (continuation-use
364               (basic-combination-fun call))))))
365   (values))
366
367 ;;; We force all the argument continuations to use the unknown values
368 ;;; convention. The continuations are annotated in reverse order,
369 ;;; since the last argument is on top, thus must be popped first. We
370 ;;; disallow delayed evaluation of the function continuation to
371 ;;; simplify IR2 conversion of MV call.
372 ;;;
373 ;;; We could be cleverer when we know the number of values returned by
374 ;;; the continuations, but optimizations of MV call are probably
375 ;;; unworthwhile.
376 ;;;
377 ;;; We are also responsible for handling THROW, which is represented
378 ;;; in IR1 as an MV call to the %THROW funny function. We annotate the
379 ;;; tag continuation for a single value and the values continuation
380 ;;; for unknown values.
381 (defun ltn-analyze-mv-call (call ltn-policy)
382   (declare (type mv-combination call) (type ltn-policy ltn-policy))
383   (let ((fun (basic-combination-fun call))
384         (args (basic-combination-args call)))
385     (cond ((eq (continuation-fun-name fun) '%throw)
386            (setf (basic-combination-info call) :funny)
387            (annotate-ordinary-continuation (first args) ltn-policy)
388            (annotate-unknown-values-continuation (second args) ltn-policy)
389            (setf (node-tail-p call) nil))
390           (t
391            (setf (basic-combination-info call) :full)
392            (annotate-fun-continuation (basic-combination-fun call)
393                                       ltn-policy
394                                       nil)
395            (dolist (arg (reverse args))
396              (annotate-unknown-values-continuation arg ltn-policy))
397            (flush-full-call-tail-transfer call))))
398
399   (values))
400
401 ;;; Annotate the arguments as ordinary single-value continuations. And
402 ;;; check the successor.
403 (defun ltn-analyze-local-call (call ltn-policy)
404   (declare (type combination call)
405            (type ltn-policy ltn-policy))
406   (setf (basic-combination-info call) :local)
407   (dolist (arg (basic-combination-args call))
408     (when arg
409       (annotate-ordinary-continuation arg ltn-policy)))
410   (when (node-tail-p call)
411     (set-tail-local-call-successor call))
412   (values))
413
414 ;;; Make sure that a tail local call is linked directly to the bind
415 ;;; node. Usually it will be, but calls from XEPs and calls that might have
416 ;;; needed a cleanup after them won't have been swung over yet, since we
417 ;;; weren't sure they would really be TR until now. Also called by byte
418 ;;; compiler.
419 (defun set-tail-local-call-successor (call)
420   (let ((caller (node-home-lambda call))
421         (callee (combination-lambda call)))
422     (aver (eq (lambda-tail-set caller)
423               (lambda-tail-set (lambda-home callee))))
424     (node-ends-block call)
425     (let ((block (node-block call)))
426       (unlink-blocks block (first (block-succ block)))
427       (link-blocks block (lambda-block callee))))
428   (values))
429
430 ;;; Annotate the value continuation.
431 (defun ltn-analyze-set (node ltn-policy)
432   (declare (type cset node) (type ltn-policy ltn-policy))
433   (setf (node-tail-p node) nil)
434   (annotate-ordinary-continuation (set-value node) ltn-policy)
435   (values))
436
437 ;;; If the only use of the TEST continuation is a combination
438 ;;; annotated with a conditional template, then don't annotate the
439 ;;; continuation so that IR2 conversion knows not to emit any code,
440 ;;; otherwise annotate as an ordinary continuation. Since we only use
441 ;;; a conditional template if the call immediately precedes the IF
442 ;;; node in the same block, we know that any predicate will already be
443 ;;; annotated.
444 (defun ltn-analyze-if (node ltn-policy)
445   (declare (type cif node) (type ltn-policy ltn-policy))
446   (setf (node-tail-p node) nil)
447   (let* ((test (if-test node))
448          (use (continuation-use test)))
449     (unless (and (combination-p use)
450                  (let ((info (basic-combination-info use)))
451                    (and (template-p info)
452                         (eq (template-result-types info) :conditional))))
453       (annotate-ordinary-continuation test ltn-policy)))
454   (values))
455
456 ;;; If there is a value continuation, then annotate it for unknown
457 ;;; values. In this case, the exit is non-local, since all other exits
458 ;;; are deleted or degenerate by this point.
459 (defun ltn-analyze-exit (node ltn-policy)
460   (setf (node-tail-p node) nil)
461   (let ((value (exit-value node)))
462     (when value
463       (annotate-unknown-values-continuation value ltn-policy)))
464   (values))
465
466 ;;; We need a special method for %UNWIND-PROTECT that ignores the
467 ;;; cleanup function. We don't annotate either arg, since we don't
468 ;;; need them at run-time.
469 ;;;
470 ;;; (The default is o.k. for %CATCH, since environment analysis
471 ;;; converted the reference to the escape function into a constant
472 ;;; reference to the NLX-INFO.)
473 (defoptimizer (%unwind-protect ltn-annotate) ((escape cleanup)
474                                               node
475                                               ltn-policy)
476   ltn-policy ; a hack to effectively (DECLARE (IGNORE LTN-POLICY))
477   (setf (basic-combination-info node) :funny)
478   (setf (node-tail-p node) nil))
479 \f
480 ;;;; known call annotation
481
482 ;;; Return true if RESTR is satisfied by TYPE. If T-OK is true, then a
483 ;;; T restriction allows any operand type. This is also called by IR2
484 ;;; translation when it determines whether a result temporary needs to
485 ;;; be made, and by representation selection when it is deciding which
486 ;;; move VOP to use. CONT and TN are used to test for constant
487 ;;; arguments.
488 (defun operand-restriction-ok (restr type &key cont tn (t-ok t))
489   (declare (type (or (member *) cons) restr)
490            (type primitive-type type)
491            (type (or continuation null) cont)
492            (type (or tn null) tn))
493   (if (eq restr '*)
494       t
495       (ecase (first restr)
496         (:or
497          (dolist (mem (rest restr) nil)
498            (when (or (and t-ok (eq mem *backend-t-primitive-type*))
499                      (eq mem type))
500              (return t))))
501         (:constant
502          (cond (cont
503                 (and (constant-continuation-p cont)
504                      (funcall (second restr) (continuation-value cont))))
505                (tn
506                 (and (eq (tn-kind tn) :constant)
507                      (funcall (second restr) (tn-value tn))))
508                (t
509                 (error "Neither CONT nor TN supplied.")))))))
510
511 ;;; Check that the argument type restriction for TEMPLATE are
512 ;;; satisfied in call. If an argument's TYPE-CHECK is :NO-CHECK and
513 ;;; our policy is safe, then only :SAFE templates are OK.
514 (defun template-args-ok (template call safe-p)
515   (declare (type template template)
516            (type combination call))
517   (let ((mtype (template-more-args-type template)))
518     (do ((args (basic-combination-args call) (cdr args))
519          (types (template-arg-types template) (cdr types)))
520         ((null types)
521          (cond ((null args) t)
522                ((not mtype) nil)
523                (t
524                 (dolist (arg args t)
525                   (unless (operand-restriction-ok mtype
526                                                   (continuation-ptype arg))
527                     (return nil))))))
528       (when (null args) (return nil))
529       (let ((arg (car args))
530             (type (car types)))
531         (when (and (eq (continuation-type-check arg) :no-check)
532                    safe-p
533                    (not (eq (template-ltn-policy template) :safe)))
534           (return nil))
535         (unless (operand-restriction-ok type (continuation-ptype arg)
536                                         :cont arg)
537           (return nil))))))
538
539 ;;; Check that TEMPLATE can be used with the specifed RESULT-TYPE.
540 ;;; Result type checking is pretty different from argument type
541 ;;; checking due to the relaxed rules for values count. We succeed if
542 ;;; for each required result, there is a positional restriction on the
543 ;;; value that is at least as good. If we run out of result types
544 ;;; before we run out of restrictions, then we only succeed if the
545 ;;; leftover restrictions are *. If we run out of restrictions before
546 ;;; we run out of result types, then we always win.
547 (defun template-results-ok (template result-type)
548   (declare (type template template)
549            (type ctype result-type))
550   (when (template-more-results-type template)
551     (error "~S has :MORE results with :TRANSLATE." (template-name template)))
552   (let ((types (template-result-types template)))
553     (cond
554      ((values-type-p result-type)
555       (do ((ltypes (append (args-type-required result-type)
556                            (args-type-optional result-type))
557                    (rest ltypes))
558            (types types (rest types)))
559           ((null ltypes)
560            (dolist (type types t)
561              (unless (eq type '*)
562                (return nil))))
563         (when (null types) (return t))
564         (let ((type (first types)))
565           (unless (operand-restriction-ok type
566                                           (primitive-type (first ltypes)))
567             (return nil)))))
568      (types
569       (operand-restriction-ok (first types) (primitive-type result-type)))
570      (t t))))
571
572 ;;; Return true if CALL is an ok use of TEMPLATE according to SAFE-P.
573 ;;; -- If the template has a GUARD that isn't true, then we ignore the
574 ;;;    template, not even considering it to be rejected.
575 ;;; -- If the argument type restrictions aren't satisfied, then we
576 ;;;    reject the template.
577 ;;; -- If the template is :CONDITIONAL, then we accept it only when the
578 ;;;    destination of the value is an immediately following IF node.
579 ;;; -- If either the template is safe or the policy is unsafe (i.e. we
580 ;;;    can believe output assertions), then we test against the
581 ;;;    intersection of the node derived type and the continuation
582 ;;;    asserted type. Otherwise, we just use the node type. If
583 ;;;    TYPE-CHECK is null, there is no point in doing the intersection,
584 ;;;    since the node type must be a subtype of the  assertion.
585 ;;;
586 ;;; If the template is *not* ok, then the second value is a keyword
587 ;;; indicating which aspect failed.
588 (defun is-ok-template-use (template call safe-p)
589   (declare (type template template) (type combination call))
590   (let* ((guard (template-guard template))
591          (cont (node-cont call))
592          (atype (continuation-asserted-type cont))
593          (dtype (node-derived-type call)))
594     (cond ((and guard (not (funcall guard)))
595            (values nil :guard))
596           ((not (template-args-ok template call safe-p))
597            (values nil
598                    (if (and safe-p (template-args-ok template call nil))
599                        :arg-check
600                        :arg-types)))
601           ((eq (template-result-types template) :conditional)
602            (let ((dest (continuation-dest cont)))
603              (if (and (if-p dest)
604                       (immediately-used-p (if-test dest) call))
605                  (values t nil)
606                  (values nil :conditional))))
607           ((template-results-ok
608             template
609             (if (and (or (eq (template-ltn-policy template) :safe)
610                          (not safe-p))
611                      (continuation-type-check cont))
612                 (values-type-intersection dtype atype)
613                 dtype))
614            (values t nil))
615           (t
616            (values nil :result-types)))))
617
618 ;;; Use operand type information to choose a template from the list
619 ;;; TEMPLATES for a known CALL. We return three values:
620 ;;; 1. The template we found.
621 ;;; 2. Some template that we rejected due to unsatisfied type restrictions, or
622 ;;;    NIL if none.
623 ;;; 3. The tail of Templates for templates we haven't examined yet.
624 ;;;
625 ;;; We just call IS-OK-TEMPLATE-USE until it returns true.
626 (defun find-template (templates call safe-p)
627   (declare (list templates) (type combination call))
628   (do ((templates templates (rest templates))
629        (rejected nil))
630       ((null templates)
631        (values nil rejected nil))
632     (let ((template (first templates)))
633       (when (is-ok-template-use template call safe-p)
634         (return (values template rejected (rest templates))))
635       (setq rejected template))))
636
637 ;;; Given a partially annotated known call and a translation policy,
638 ;;; return the appropriate template, or NIL if none can be found. We
639 ;;; scan the templates (ordered by increasing cost) looking for a
640 ;;; template whose restrictions are satisfied and that has our policy.
641 ;;;
642 ;;; If we find a template that doesn't have our policy, but has a
643 ;;; legal alternate policy, then we also record that to return as a
644 ;;; last resort. If our policy is safe, then only safe policies are
645 ;;; O.K., otherwise anything goes.
646 ;;;
647 ;;; If we find a template with :SAFE policy, then we return it, or any
648 ;;; cheaper fallback template. The theory behind this is that if it is
649 ;;; cheapest, small and safe, we can't lose. If it is not cheapest,
650 ;;; then we use the fallback, which won't have the desired policy, but
651 ;;; :SAFE isn't desired either, so we might as well go with the
652 ;;; cheaper one. The main reason for doing this is to make sure that
653 ;;; cheap safe templates are used when they apply and the current
654 ;;; policy is something else. This is useful because :SAFE has the
655 ;;; additional semantics of implicit argument type checking, so we may
656 ;;; be forced to define a template with :SAFE policy when it is really
657 ;;; small and fast as well.
658 (defun find-template-for-ltn-policy (call ltn-policy)
659   (declare (type combination call)
660            (type ltn-policy ltn-policy))
661   (let ((safe-p (ltn-policy-safe-p ltn-policy))
662         (current (fun-info-templates (basic-combination-kind call)))
663         (fallback nil)
664         (rejected nil))
665     (loop
666      (multiple-value-bind (template this-reject more)
667          (find-template current call safe-p)
668        (unless rejected
669          (setq rejected this-reject))
670        (setq current more)
671        (unless template
672          (return (values fallback rejected)))
673        (let ((tcpolicy (template-ltn-policy template)))
674          (cond ((eq tcpolicy ltn-policy)
675                 (return (values template rejected)))
676                ((eq tcpolicy :safe)
677                 (return (values (or fallback template) rejected)))
678                ((or (not safe-p) (eq tcpolicy :fast-safe))
679                 (unless fallback
680                   (setq fallback template)))))))))
681
682 (defvar *efficiency-note-limit* 2
683   #!+sb-doc
684   "This is the maximum number of possible optimization alternatives will be
685   mentioned in a particular efficiency note. NIL means no limit.")
686 (declaim (type (or index null) *efficiency-note-limit*))
687
688 (defvar *efficiency-note-cost-threshold* 5
689   #!+sb-doc
690   "This is the minumum cost difference between the chosen implementation and
691   the next alternative that justifies an efficiency note.")
692 (declaim (type index *efficiency-note-cost-threshold*))
693
694 ;;; This function is called by NOTE-REJECTED-TEMPLATES when it can't
695 ;;; figure out any reason why TEMPLATE was rejected. Users should
696 ;;; never see these messages, but they can happen in situations where
697 ;;; the VM definition is messed up somehow.
698 (defun strange-template-failure (template call ltn-policy frob)
699   (declare (type template template) (type combination call)
700            (type ltn-policy ltn-policy) (type function frob))
701   (funcall frob "This shouldn't happen!  Bug?")
702   (multiple-value-bind (win why)
703       (is-ok-template-use template call (ltn-policy-safe-p ltn-policy))
704     (aver (not win))
705     (ecase why
706       (:guard
707        (funcall frob "template guard failed"))
708       (:arg-check
709        (funcall frob "The template isn't safe, yet we were counting on it."))
710       (:arg-types
711        (funcall frob "argument types invalid")
712        (funcall frob "argument primitive types:~%  ~S"
713                 (mapcar (lambda (x)
714                           (primitive-type-name
715                            (continuation-ptype x)))
716                         (combination-args call)))
717        (funcall frob "argument type assertions:~%  ~S"
718                 (mapcar (lambda (x)
719                           (if (atom x)
720                               x
721                               (ecase (car x)
722                                 (:or `(:or .,(mapcar #'primitive-type-name
723                                                      (cdr x))))
724                                 (:constant `(:constant ,(third x))))))
725                         (template-arg-types template))))
726       (:conditional
727        (funcall frob "conditional in a non-conditional context"))
728       (:result-types
729        (funcall frob "result types invalid")))))
730
731 ;;; This function emits efficiency notes describing all of the
732 ;;; templates better (faster) than TEMPLATE that we might have been
733 ;;; able to use if there were better type declarations. Template is
734 ;;; null when we didn't find any template, and thus must do a full
735 ;;; call.
736 ;;;
737 ;;; In order to be worth complaining about, a template must:
738 ;;; -- be allowed by its guard,
739 ;;; -- be safe if the current policy is safe,
740 ;;; -- have argument/result type restrictions consistent with the
741 ;;;    known type information, e.g. we don't consider float templates
742 ;;;    when an operand is known to be an integer,
743 ;;; -- be disallowed by the stricter operand subtype test (which
744 ;;;    resembles, but is not identical to the test done by
745 ;;;    FIND-TEMPLATE.)
746 ;;;
747 ;;; Note that there may not be any possibly applicable templates,
748 ;;; since we are called whenever any template is rejected. That
749 ;;; template might have the wrong policy or be inconsistent with the
750 ;;; known type.
751 ;;;
752 ;;; We go to some trouble to make the whole multi-line output into a
753 ;;; single call to COMPILER-NOTE so that repeat messages are
754 ;;; suppressed, etc.
755 (defun note-rejected-templates (call ltn-policy template)
756   (declare (type combination call) (type ltn-policy ltn-policy)
757            (type (or template null) template))
758
759   (collect ((losers))
760     (let ((safe-p (ltn-policy-safe-p ltn-policy))
761           (verbose-p (policy call (= inhibit-warnings 0)))
762           (max-cost (- (template-cost
763                         (or template
764                             (template-or-lose 'call-named)))
765                        *efficiency-note-cost-threshold*)))
766       (dolist (try (fun-info-templates (basic-combination-kind call)))
767         (when (> (template-cost try) max-cost) (return)) ; FIXME: UNLESS'd be cleaner.
768         (let ((guard (template-guard try)))
769           (when (and (or (not guard) (funcall guard))
770                      (or (not safe-p)
771                          (ltn-policy-safe-p (template-ltn-policy try)))
772                      (or verbose-p
773                          (and (template-note try)
774                               (valid-fun-use
775                                call (template-type try)
776                                :argument-test #'types-equal-or-intersect
777                                :result-test
778                                #'values-types-equal-or-intersect))))
779             (losers try)))))
780
781     (when (losers)
782       (collect ((messages)
783                 (count 0 +))
784         (flet ((lose1 (string &rest stuff)
785                  (messages string)
786                  (messages stuff)))
787           (dolist (loser (losers))
788             (when (and *efficiency-note-limit*
789                        (>= (count) *efficiency-note-limit*))
790               (lose1 "etc.")
791               (return))
792             (let* ((type (template-type loser))
793                    (valid (valid-fun-use call type))
794                    (strict-valid (valid-fun-use call type
795                                                 :strict-result t)))
796               (lose1 "unable to do ~A (cost ~W) because:"
797                      (or (template-note loser) (template-name loser))
798                      (template-cost loser))
799               (cond
800                ((and valid strict-valid)
801                 (strange-template-failure loser call ltn-policy #'lose1))
802                ((not valid)
803                 (aver (not (valid-fun-use call type
804                                           :lossage-fun #'lose1
805                                           :unwinnage-fun #'lose1))))
806                (t
807                 (aver (ltn-policy-safe-p ltn-policy))
808                 (lose1 "can't trust output type assertion under safe policy")))
809               (count 1))))
810
811         (let ((*compiler-error-context* call))
812           (compiler-note "~{~?~^~&~6T~}"
813                          (if template
814                              `("forced to do ~A (cost ~W)"
815                                (,(or (template-note template)
816                                      (template-name template))
817                                 ,(template-cost template))
818                                . ,(messages))
819                              `("forced to do full call"
820                                nil
821                                . ,(messages))))))))
822   (values))
823
824 ;;; Flush type checks according to policy. If the policy is
825 ;;; unsafe, then we never do any checks. If our policy is safe, and
826 ;;; we are using a safe template, then we can also flush arg and
827 ;;; result type checks. Result type checks are only flushed when the
828 ;;; continuation as a single use. Result type checks are not flush if
829 ;;; the policy is safe because the selection of template for results
830 ;;; readers assumes the type check is done (uses the derived type
831 ;;; which is the intersection of the proven and asserted types).
832 (defun flush-type-checks-according-to-ltn-policy (call ltn-policy template)
833   (declare (type combination call) (type ltn-policy ltn-policy)
834            (type template template))
835   (let ((safe-op (eq (template-ltn-policy template) :safe)))
836     (when (or (not (ltn-policy-safe-p ltn-policy)) safe-op)
837       (dolist (arg (basic-combination-args call))
838         (flush-type-check arg)))
839     (when safe-op
840       (let ((cont (node-cont call)))
841         (when (and (eq (continuation-use cont) call)
842                    (not (ltn-policy-safe-p ltn-policy)))
843           (flush-type-check cont)))))
844
845   (values))
846
847 ;;; If a function has a special-case annotation method use that,
848 ;;; otherwise annotate the argument continuations and try to find a
849 ;;; template corresponding to the type signature. If there is none,
850 ;;; convert a full call.
851 (defun ltn-analyze-known-call (call ltn-policy)
852   (declare (type combination call)
853            (type ltn-policy ltn-policy))
854   (let ((method (fun-info-ltn-annotate (basic-combination-kind call)))
855         (args (basic-combination-args call)))
856     (when method
857       (funcall method call ltn-policy)
858       (return-from ltn-analyze-known-call (values)))
859
860     (dolist (arg args)
861       (setf (continuation-info arg)
862             (make-ir2-continuation (primitive-type (continuation-type arg)))))
863
864     (multiple-value-bind (template rejected)
865         (find-template-for-ltn-policy call ltn-policy)
866       ;; If we are unable to use some templates due to unsatisfied
867       ;; operand type restrictions and our policy enables efficiency
868       ;; notes, then we call NOTE-REJECTED-TEMPLATES.
869       (when (and rejected
870                  (policy call (> speed inhibit-warnings)))
871         (note-rejected-templates call ltn-policy template))
872       ;; If we are forced to do a full call, we check to see whether
873       ;; the function called is the same as the current function. If
874       ;; so, we give a warning, as this is probably a botched attempt
875       ;; to implement an out-of-line version in terms of inline
876       ;; transforms or VOPs or whatever.
877       (unless template
878         (when (let ((funleaf (physenv-lambda (node-physenv call))))
879                 (and (leaf-has-source-name-p funleaf)
880                      (eq (continuation-fun-name (combination-fun call))
881                          (leaf-source-name funleaf))
882                      (let ((info (basic-combination-kind call)))
883                        (not (or (fun-info-ir2-convert info)
884                                 (ir1-attributep (fun-info-attributes info)
885                                                 recursive))))))
886           (let ((*compiler-error-context* call))
887             (compiler-warn "~@<recursion in known function definition~2I ~
888                             ~_policy=~S ~_arg types=~S~:>"
889                            (lexenv-policy (node-lexenv call))
890                            (mapcar (lambda (arg)
891                                      (type-specifier (continuation-type arg)))
892                                    args))))
893         (ltn-default-call call ltn-policy)
894         (return-from ltn-analyze-known-call (values)))
895       (setf (basic-combination-info call) template)
896       (setf (node-tail-p call) nil)
897
898       (flush-type-checks-according-to-ltn-policy call ltn-policy template)
899
900       (dolist (arg args)
901         (annotate-1-value-continuation arg))))
902
903   (values))
904 \f
905 ;;;; interfaces
906
907 ;;; most of the guts of the two interface functions: Compute the
908 ;;; policy and dispatch to the appropriate node-specific function.
909 ;;;
910 ;;; Note: we deliberately don't use the DO-NODES macro, since the
911 ;;; block can be split out from underneath us, and DO-NODES would scan
912 ;;; past the block end in that case.
913 (defun ltn-analyze-block (block)
914   (do* ((node (continuation-next (block-start block))
915               (continuation-next cont))
916         (cont (node-cont node) (node-cont node))
917         (ltn-policy (node-ltn-policy node) (node-ltn-policy node)))
918       (nil)
919     (etypecase node
920       (ref)
921       (combination
922        (case (basic-combination-kind node)
923          (:local (ltn-analyze-local-call node ltn-policy))
924          ((:full :error) (ltn-default-call node ltn-policy))
925          (t
926           (ltn-analyze-known-call node ltn-policy))))
927       (cif
928        (ltn-analyze-if node ltn-policy))
929       (creturn
930        (ltn-analyze-return node ltn-policy))
931       ((or bind entry))
932       (exit
933        (ltn-analyze-exit node ltn-policy))
934       (cset (ltn-analyze-set node ltn-policy))
935       (mv-combination
936        (ecase (basic-combination-kind node)
937          (:local
938           (ltn-analyze-mv-bind node ltn-policy))
939          ((:full :error)
940           (ltn-analyze-mv-call node ltn-policy)))))
941     (when (eq node (block-last block))
942       (return))))
943
944 ;;; Loop over the blocks in COMPONENT, doing stuff to nodes that
945 ;;; receive values. In addition to the stuff done by FROB, we also see
946 ;;; whether there are any unknown values receivers, making notations
947 ;;; in the components' GENERATORS and RECEIVERS as appropriate.
948 ;;;
949 ;;; If any unknown-values continations are received by this block (as
950 ;;; indicated by IR2-BLOCK-POPPED), then we add the block to the
951 ;;; IR2-COMPONENT-VALUES-RECEIVERS.
952 ;;;
953 ;;; This is where we allocate IR2 blocks because it is the first place
954 ;;; we need them.
955 (defun ltn-analyze (component)
956   (declare (type component component))
957   (let ((2comp (component-info component)))
958     (do-blocks (block component)
959       ;; This assertion seems to protect us from compiling a component
960       ;; twice. As noted above, "this is where we allocate IR2-BLOCKS
961       ;; because it is the first place we need them", so if one is
962       ;; already allocated here, something is wrong. -- WHN 2001-09-14
963       (aver (not (block-info block)))
964       (let ((2block (make-ir2-block block)))
965         (setf (block-info block) 2block)
966         (ltn-analyze-block block)
967         (let ((popped (ir2-block-popped 2block)))
968           (when popped
969             (push block (ir2-component-values-receivers 2comp)))))))
970   (values))
971
972 ;;; This function is used to analyze blocks that must be added to the
973 ;;; flow graph after the normal LTN phase runs. Such code is
974 ;;; constrained not to use weird unknown values (and probably in lots
975 ;;; of other ways).
976 (defun ltn-analyze-belated-block (block)
977   (declare (type cblock block))
978   (ltn-analyze-block block)
979   (aver (not (ir2-block-popped (block-info block))))
980   (values))
981