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