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