1.0.48.21: explicitly indefinite-extent leaves, safer dynamic-extent &REST
[sbcl.git] / src / compiler / locall.lisp
1 ;;;; This file implements local call analysis. A local call is a
2 ;;;; function call between functions being compiled at the same time.
3 ;;;; If we can tell at compile time that such a call is legal, then we
4 ;;;; change the combination to call the correct lambda, mark it as
5 ;;;; local, and add this link to our call graph. Once a call is local,
6 ;;;; it is then eligible for let conversion, which places the body of
7 ;;;; the function inline.
8 ;;;;
9 ;;;; We cannot always do a local call even when we do have the
10 ;;;; function being called. Calls that cannot be shown to have legal
11 ;;;; arg counts are not converted.
12
13 ;;;; This software is part of the SBCL system. See the README file for
14 ;;;; more information.
15 ;;;;
16 ;;;; This software is derived from the CMU CL system, which was
17 ;;;; written at Carnegie Mellon University and released into the
18 ;;;; public domain. The software is in the public domain and is
19 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
20 ;;;; files for more information.
21
22 (in-package "SB!C")
23
24 ;;; This function propagates information from the variables in the
25 ;;; function FUN to the actual arguments in CALL. This is also called
26 ;;; by the VALUES IR1 optimizer when it sleazily converts MV-BINDs to
27 ;;; LETs.
28 ;;;
29 ;;; We flush all arguments to CALL that correspond to unreferenced
30 ;;; variables in FUN. We leave NILs in the COMBINATION-ARGS so that
31 ;;; the remaining args still match up with their vars.
32 ;;;
33 ;;; We also apply the declared variable type assertion to the argument
34 ;;; lvars.
35 (defun propagate-to-args (call fun)
36   (declare (type combination call) (type clambda fun))
37   (loop with policy = (lexenv-policy (node-lexenv call))
38         for args on (basic-combination-args call)
39         and var in (lambda-vars fun)
40         do (assert-lvar-type (car args) (leaf-type var) policy)
41         do (unless (leaf-refs var)
42              (flush-dest (car args))
43              (setf (car args) nil)))
44   (values))
45
46 (defun recognize-dynamic-extent-lvars (call fun)
47   (declare (type combination call) (type clambda fun))
48   (loop for arg in (basic-combination-args call)
49         for var in (lambda-vars fun)
50         for dx = (leaf-dynamic-extent var)
51         when (and dx arg (not (lvar-dynamic-extent arg)))
52         append (handle-nested-dynamic-extent-lvars dx arg) into dx-lvars
53         finally (when dx-lvars
54                   ;; Stack analysis requires that the CALL ends the block, so
55                   ;; that MAP-BLOCK-NLXES sees the cleanup we insert here.
56                   (node-ends-block call)
57                   (let* ((entry (with-ir1-environment-from-node call
58                                   (make-entry)))
59                          (cleanup (make-cleanup :kind :dynamic-extent
60                                                 :mess-up entry
61                                                 :info dx-lvars)))
62                     (setf (entry-cleanup entry) cleanup)
63                     (insert-node-before call entry)
64                     (setf (node-lexenv call)
65                           (make-lexenv :default (node-lexenv call)
66                                        :cleanup cleanup))
67                     (push entry (lambda-entries (node-home-lambda entry)))
68                     (dolist (cell dx-lvars)
69                       (setf (lvar-dynamic-extent (cdr cell)) cleanup)))))
70   (values))
71
72 ;;; This function handles merging the tail sets if CALL is potentially
73 ;;; tail-recursive, and is a call to a function with a different
74 ;;; TAIL-SET than CALL's FUN. This must be called whenever we alter
75 ;;; IR1 so as to place a local call in what might be a tail-recursive
76 ;;; context. Note that any call which returns its value to a RETURN is
77 ;;; considered potentially tail-recursive, since any implicit MV-PROG1
78 ;;; might be optimized away.
79 ;;;
80 ;;; We destructively modify the set for the calling function to
81 ;;; represent both, and then change all the functions in callee's set
82 ;;; to reference the first. If we do merge, we reoptimize the
83 ;;; RETURN-RESULT lvar to cause IR1-OPTIMIZE-RETURN to recompute the
84 ;;; tail set type.
85 (defun merge-tail-sets (call &optional (new-fun (combination-lambda call)))
86   (declare (type basic-combination call) (type clambda new-fun))
87   (let ((return (node-dest call)))
88     (when (return-p return)
89       (let ((call-set (lambda-tail-set (node-home-lambda call)))
90             (fun-set (lambda-tail-set new-fun)))
91         (unless (eq call-set fun-set)
92           (let ((funs (tail-set-funs fun-set)))
93             (dolist (fun funs)
94               (setf (lambda-tail-set fun) call-set))
95             (setf (tail-set-funs call-set)
96                   (nconc (tail-set-funs call-set) funs)))
97           (reoptimize-lvar (return-result return))
98           t)))))
99
100 ;;; Convert a combination into a local call. We PROPAGATE-TO-ARGS, set
101 ;;; the combination kind to :LOCAL, add FUN to the CALLS of the
102 ;;; function that the call is in, call MERGE-TAIL-SETS, then replace
103 ;;; the function in the REF node with the new function.
104 ;;;
105 ;;; We change the REF last, since changing the reference can trigger
106 ;;; LET conversion of the new function, but will only do so if the
107 ;;; call is local. Note that the replacement may trigger LET
108 ;;; conversion or other changes in IR1. We must call MERGE-TAIL-SETS
109 ;;; with NEW-FUN before the substitution, since after the substitution
110 ;;; (and LET conversion), the call may no longer be recognizable as
111 ;;; tail-recursive.
112 (defun convert-call (ref call fun)
113   (declare (type ref ref) (type combination call) (type clambda fun))
114   (propagate-to-args call fun)
115   (setf (basic-combination-kind call) :local)
116   (unless (call-full-like-p call)
117     (dolist (arg (basic-combination-args call))
118       (when arg
119         (flush-lvar-externally-checkable-type arg))))
120   (sset-adjoin fun (lambda-calls-or-closes (node-home-lambda call)))
121   (recognize-dynamic-extent-lvars call fun)
122   (merge-tail-sets call fun)
123   (change-ref-leaf ref fun)
124   (values))
125 \f
126 ;;;; external entry point creation
127
128 ;;; Return a LAMBDA form that can be used as the definition of the XEP
129 ;;; for FUN.
130 ;;;
131 ;;; If FUN is a LAMBDA, then we check the number of arguments
132 ;;; (conditional on policy) and call FUN with all the arguments.
133 ;;;
134 ;;; If FUN is an OPTIONAL-DISPATCH, then we dispatch off of the number
135 ;;; of supplied arguments by doing do an = test for each entry-point,
136 ;;; calling the entry with the appropriate prefix of the passed
137 ;;; arguments.
138 ;;;
139 ;;; If there is a &MORE arg, then there are a couple of optimizations
140 ;;; that we make (more for space than anything else):
141 ;;; -- If MIN-ARGS is 0, then we make the more entry a T clause, since
142 ;;;    no argument count error is possible.
143 ;;; -- We can omit the = clause for the last entry-point, allowing the
144 ;;;    case of 0 more args to fall through to the more entry.
145 ;;;
146 ;;; We don't bother to policy conditionalize wrong arg errors in
147 ;;; optional dispatches, since the additional overhead is negligible
148 ;;; compared to the cost of everything else going on.
149 ;;;
150 ;;; Note that if policy indicates it, argument type declarations in
151 ;;; FUN will be verified. Since nothing is known about the type of the
152 ;;; XEP arg vars, type checks will be emitted when the XEP's arg vars
153 ;;; are passed to the actual function.
154 (defun make-xep-lambda-expression (fun)
155   (declare (type functional fun))
156   (etypecase fun
157     (clambda
158      (let ((nargs (length (lambda-vars fun)))
159            (n-supplied (gensym))
160            (temps (make-gensym-list (length (lambda-vars fun)))))
161        `(lambda (,n-supplied ,@temps)
162           (declare (type index ,n-supplied))
163           ,(if (policy *lexenv* (zerop verify-arg-count))
164                `(declare (ignore ,n-supplied))
165                `(%verify-arg-count ,n-supplied ,nargs))
166           (locally
167             (declare (optimize (merge-tail-calls 3)))
168             (%funcall ,fun ,@temps)))))
169     (optional-dispatch
170      (let* ((min (optional-dispatch-min-args fun))
171             (max (optional-dispatch-max-args fun))
172             (more (optional-dispatch-more-entry fun))
173             (n-supplied (gensym))
174             (temps (make-gensym-list max)))
175        (collect ((entries))
176          ;; Force convertion of all entries
177          (optional-dispatch-entry-point-fun fun 0)
178          (loop for ep in (optional-dispatch-entry-points fun)
179                and n from min
180                do (entries `((eql ,n-supplied ,n)
181                              (%funcall ,(force ep) ,@(subseq temps 0 n)))))
182          `(lambda (,n-supplied ,@temps)
183             (declare (type index ,n-supplied))
184             (cond
185              ,@(if more (butlast (entries)) (entries))
186              ,@(when more
187                  ;; KLUDGE: (NOT (< ...)) instead of >= avoids one round of
188                  ;; deftransforms and lambda-conversion.
189                  `((,(if (zerop min) t `(not (< ,n-supplied ,max)))
190                     ,(with-unique-names (n-context n-count)
191                        `(multiple-value-bind (,n-context ,n-count)
192                             (%more-arg-context ,n-supplied ,max)
193                           (locally
194                             (declare (optimize (merge-tail-calls 3)))
195                             (%funcall ,more ,@temps ,n-context ,n-count)))))))
196              (t
197               (%arg-count-error ,n-supplied)))))))))
198
199 ;;; Make an external entry point (XEP) for FUN and return it. We
200 ;;; convert the result of MAKE-XEP-LAMBDA in the correct environment,
201 ;;; then associate this lambda with FUN as its XEP. After the
202 ;;; conversion, we iterate over the function's associated lambdas,
203 ;;; redoing local call analysis so that the XEP calls will get
204 ;;; converted.
205 ;;;
206 ;;; We set REANALYZE and REOPTIMIZE in the component, just in case we
207 ;;; discover an XEP after the initial local call analyze pass.
208 (defun make-xep (fun)
209   (declare (type functional fun))
210   (aver (null (functional-entry-fun fun)))
211   (with-ir1-environment-from-node (lambda-bind (main-entry fun))
212     (let ((xep (ir1-convert-lambda (make-xep-lambda-expression fun)
213                                    :debug-name (debug-name
214                                                 'xep (leaf-debug-name fun))
215                                    :system-lambda t)))
216       (setf (functional-kind xep) :external
217             (leaf-ever-used xep) t
218             (functional-entry-fun xep) fun
219             (functional-entry-fun fun) xep
220             (component-reanalyze *current-component*) t)
221       (reoptimize-component *current-component* :maybe)
222       (locall-analyze-xep-entry-point fun)
223       xep)))
224
225 (defun locall-analyze-xep-entry-point (fun)
226   (declare (type functional fun))
227   (etypecase fun
228     (clambda
229      (locall-analyze-fun-1 fun))
230     (optional-dispatch
231      (dolist (ep (optional-dispatch-entry-points fun))
232        (locall-analyze-fun-1 (force ep)))
233      (when (optional-dispatch-more-entry fun)
234        (locall-analyze-fun-1 (optional-dispatch-more-entry fun))))))
235
236 ;;; Notice a REF that is not in a local-call context. If the REF is
237 ;;; already to an XEP, then do nothing, otherwise change it to the
238 ;;; XEP, making an XEP if necessary.
239 ;;;
240 ;;; If REF is to a special :CLEANUP or :ESCAPE function, then we treat
241 ;;; it as though it was not an XEP reference (i.e. leave it alone).
242 (defun reference-entry-point (ref)
243   (declare (type ref ref))
244   (let ((fun (ref-leaf ref)))
245     (unless (or (xep-p fun)
246                 (member (functional-kind fun) '(:escape :cleanup)))
247       (change-ref-leaf ref (or (functional-entry-fun fun)
248                                (make-xep fun))))))
249 \f
250 ;;; Attempt to convert all references to FUN to local calls. The
251 ;;; reference must be the function for a call, and the function lvar
252 ;;; must be used only once, since otherwise we cannot be sure what
253 ;;; function is to be called. The call lvar would be multiply used if
254 ;;; there is hairy stuff such as conditionals in the expression that
255 ;;; computes the function.
256 ;;;
257 ;;; If we cannot convert a reference, then we mark the referenced
258 ;;; function as an entry-point, creating a new XEP if necessary. We
259 ;;; don't try to convert calls that are in error (:ERROR kind.)
260 ;;;
261 ;;; This is broken off from LOCALL-ANALYZE-COMPONENT so that people
262 ;;; can force analysis of newly introduced calls. Note that we don't
263 ;;; do LET conversion here.
264 (defun locall-analyze-fun-1 (fun)
265   (declare (type functional fun))
266   (let ((refs (leaf-refs fun))
267         (local-p t))
268     (dolist (ref refs)
269       (let* ((lvar (node-lvar ref))
270              (dest (when lvar (lvar-dest lvar))))
271         (unless (node-to-be-deleted-p ref)
272           (cond ((and (basic-combination-p dest)
273                       (eq (basic-combination-fun dest) lvar)
274                       (eq (lvar-uses lvar) ref))
275
276                  (convert-call-if-possible ref dest)
277
278                  (unless (eq (basic-combination-kind dest) :local)
279                    (reference-entry-point ref)
280                    (setq local-p nil)))
281                 (t
282                  (reference-entry-point ref)
283                  (setq local-p nil))))))
284     (when local-p (note-local-functional fun)))
285
286   (values))
287
288 ;;; We examine all NEW-FUNCTIONALS in COMPONENT, attempting to convert
289 ;;; calls into local calls when it is legal. We also attempt to
290 ;;; convert each LAMBDA to a LET. LET conversion is also triggered by
291 ;;; deletion of a function reference, but functions that start out
292 ;;; eligible for conversion must be noticed sometime.
293 ;;;
294 ;;; Note that there is a lot of action going on behind the scenes
295 ;;; here, triggered by reference deletion. In particular, the
296 ;;; COMPONENT-LAMBDAS are being hacked to remove newly deleted and LET
297 ;;; converted LAMBDAs, so it is important that the LAMBDA is added to
298 ;;; the COMPONENT-LAMBDAS when it is. Also, the
299 ;;; COMPONENT-NEW-FUNCTIONALS may contain all sorts of drivel, since
300 ;;; it is not updated when we delete functions, etc. Only
301 ;;; COMPONENT-LAMBDAS is updated.
302 ;;;
303 ;;; COMPONENT-REANALYZE-FUNCTIONALS is treated similarly to
304 ;;; COMPONENT-NEW-FUNCTIONALS, but we don't add lambdas to the
305 ;;; LAMBDAS.
306 (defun locall-analyze-component (component)
307   (declare (type component component))
308   (aver-live-component component)
309   (loop
310     (let* ((new-functional (pop (component-new-functionals component)))
311            (functional (or new-functional
312                            (pop (component-reanalyze-functionals component)))))
313       (unless functional
314         (return))
315       (let ((kind (functional-kind functional)))
316         (cond ((or (functional-somewhat-letlike-p functional)
317                    (memq kind '(:deleted :zombie)))
318                (values)) ; nothing to do
319               ((and (null (leaf-refs functional)) (eq kind nil)
320                     (not (functional-entry-fun functional)))
321                (delete-functional functional))
322               (t
323                ;; Fix/check FUNCTIONAL's relationship to COMPONENT-LAMDBAS.
324                (cond ((not (lambda-p functional))
325                       ;; Since FUNCTIONAL isn't a LAMBDA, this doesn't
326                       ;; apply: no-op.
327                       (values))
328                      (new-functional ; FUNCTIONAL came from
329                                      ; NEW-FUNCTIONALS, hence is new.
330                       ;; FUNCTIONAL becomes part of COMPONENT-LAMBDAS now.
331                       (aver (not (member functional
332                                          (component-lambdas component))))
333                       (push functional (component-lambdas component)))
334                      (t ; FUNCTIONAL is old.
335                       ;; FUNCTIONAL should be in COMPONENT-LAMBDAS already.
336                       (aver (member functional (component-lambdas
337                                                 component)))))
338                (locall-analyze-fun-1 functional)
339                (when (lambda-p functional)
340                  (maybe-let-convert functional)))))))
341   (values))
342
343 (defun locall-analyze-clambdas-until-done (clambdas)
344   (loop
345    (let ((did-something nil))
346      (dolist (clambda clambdas)
347        (let ((component (lambda-component clambda)))
348          ;; The original CMU CL code seemed to implicitly assume that
349          ;; COMPONENT is the only one here. Let's make that explicit.
350          (aver (= 1 (length (functional-components clambda))))
351          (aver (eql component (first (functional-components clambda))))
352          (when (or (component-new-functionals component)
353                    (component-reanalyze-functionals component))
354            (setf did-something t)
355            (locall-analyze-component component))))
356      (unless did-something
357        (return))))
358   (values))
359
360 ;;; If policy is auspicious and CALL is not in an XEP and we don't seem
361 ;;; to be in an infinite recursive loop, then change the reference to
362 ;;; reference a fresh copy. We return whichever function we decide to
363 ;;; reference.
364 (defun maybe-expand-local-inline (original-functional ref call)
365   (if (and (policy call
366                    (and (>= speed space)
367                         (>= speed compilation-speed)))
368            (not (eq (functional-kind (node-home-lambda call)) :external))
369            (inline-expansion-ok call))
370       (let* ((end (component-last-block (node-component call)))
371              (pred (block-prev end)))
372         (multiple-value-bind (losing-local-object converted-lambda)
373             (catch 'locall-already-let-converted
374               (with-ir1-environment-from-node call
375                 (let ((*lexenv* (functional-lexenv original-functional)))
376                   (values nil
377                           (ir1-convert-lambda
378                            (functional-inline-expansion original-functional)
379                            :debug-name (debug-name 'local-inline
380                                                    (leaf-debug-name
381                                                     original-functional)))))))
382           (cond (losing-local-object
383                  (if (functional-p losing-local-object)
384                      (let ((*compiler-error-context* call))
385                        (compiler-notify "couldn't inline expand because expansion ~
386                                          calls this LET-converted local function:~
387                                          ~%  ~S"
388                                         (leaf-debug-name losing-local-object)))
389                      (let ((*compiler-error-context* call))
390                        (compiler-notify "implementation limitation: couldn't inline ~
391                                          expand because expansion refers to ~
392                                          the optimized away object ~S."
393                                         losing-local-object)))
394                  (loop for block = (block-next pred) then (block-next block)
395                        until (eq block end)
396                        do (setf (block-delete-p block) t))
397                  (loop for block = (block-next pred) then (block-next block)
398                        until (eq block end)
399                        do (delete-block block t))
400                  original-functional)
401                 (t
402                  (change-ref-leaf ref converted-lambda)
403                  converted-lambda))))
404       original-functional))
405
406 ;;; Dispatch to the appropriate function to attempt to convert a call.
407 ;;; REF must be a reference to a FUNCTIONAL. This is called in IR1
408 ;;; optimization as well as in local call analysis. If the call is is
409 ;;; already :LOCAL, we do nothing. If the call is already scheduled
410 ;;; for deletion, also do nothing (in addition to saving time, this
411 ;;; also avoids some problems with optimizing collections of functions
412 ;;; that are partially deleted.)
413 ;;;
414 ;;; This is called both before and after FIND-INITIAL-DFO runs. When
415 ;;; called on a :INITIAL component, we don't care whether the caller
416 ;;; and callee are in the same component. Afterward, we must stick
417 ;;; with whatever component division we have chosen.
418 ;;;
419 ;;; Before attempting to convert a call, we see whether the function
420 ;;; is supposed to be inline expanded. Call conversion proceeds as
421 ;;; before after any expansion.
422 ;;;
423 ;;; We bind *COMPILER-ERROR-CONTEXT* to the node for the call so that
424 ;;; warnings will get the right context.
425 (defun convert-call-if-possible (ref call)
426   (declare (type ref ref) (type basic-combination call))
427   (let* ((block (node-block call))
428          (component (block-component block))
429          (original-fun (ref-leaf ref)))
430     (aver (functional-p original-fun))
431     (unless (or (member (basic-combination-kind call) '(:local :error))
432                 (node-to-be-deleted-p call)
433                 (member (functional-kind original-fun)
434                         '(:toplevel-xep :deleted))
435                 (not (or (eq (component-kind component) :initial)
436                          (eq (block-component
437                               (node-block
438                                (lambda-bind (main-entry original-fun))))
439                              component))))
440       (let ((fun (if (xep-p original-fun)
441                      (functional-entry-fun original-fun)
442                      original-fun))
443             (*compiler-error-context* call))
444
445         (when (and (eq (functional-inlinep fun) :inline)
446                    (rest (leaf-refs original-fun)))
447           (setq fun (maybe-expand-local-inline fun ref call)))
448
449         (aver (member (functional-kind fun)
450                       '(nil :escape :cleanup :optional)))
451         (cond ((mv-combination-p call)
452                (convert-mv-call ref call fun))
453               ((lambda-p fun)
454                (convert-lambda-call ref call fun))
455               (t
456                (convert-hairy-call ref call fun))))))
457
458   (values))
459
460 ;;; Attempt to convert a multiple-value call. The only interesting
461 ;;; case is a call to a function that LOOKS-LIKE-AN-MV-BIND, has
462 ;;; exactly one reference and no XEP, and is called with one values
463 ;;; lvar.
464 ;;;
465 ;;; We change the call to be to the last optional entry point and
466 ;;; change the call to be local. Due to our preconditions, the call
467 ;;; should eventually be converted to a let, but we can't do that now,
468 ;;; since there may be stray references to the e-p lambda due to
469 ;;; optional defaulting code.
470 ;;;
471 ;;; We also use variable types for the called function to construct an
472 ;;; assertion for the values lvar.
473 ;;;
474 ;;; See CONVERT-CALL for additional notes on MERGE-TAIL-SETS, etc.
475 (defun convert-mv-call (ref call fun)
476   (declare (type ref ref) (type mv-combination call) (type functional fun))
477   (when (and (looks-like-an-mv-bind fun)
478              (singleton-p (leaf-refs fun))
479              (singleton-p (basic-combination-args call))
480              (not (functional-entry-fun fun)))
481     (let* ((*current-component* (node-component ref))
482            (ep (optional-dispatch-entry-point-fun
483                 fun (optional-dispatch-max-args fun))))
484       (when (null (leaf-refs ep))
485         (aver (= (optional-dispatch-min-args fun) 0))
486         (setf (basic-combination-kind call) :local)
487         (sset-adjoin ep (lambda-calls-or-closes (node-home-lambda call)))
488         (merge-tail-sets call ep)
489         (change-ref-leaf ref ep)
490
491         (assert-lvar-type
492          (first (basic-combination-args call))
493          (make-short-values-type (mapcar #'leaf-type (lambda-vars ep)))
494          (lexenv-policy (node-lexenv call))))))
495   (values))
496
497 ;;; Attempt to convert a call to a lambda. If the number of args is
498 ;;; wrong, we give a warning and mark the call as :ERROR to remove it
499 ;;; from future consideration. If the argcount is O.K. then we just
500 ;;; convert it.
501 (defun convert-lambda-call (ref call fun)
502   (declare (type ref ref) (type combination call) (type clambda fun))
503   (let ((nargs (length (lambda-vars fun)))
504         (n-call-args (length (combination-args call))))
505     (cond ((= n-call-args nargs)
506            (convert-call ref call fun))
507           (t
508            (warn
509             'local-argument-mismatch
510             :format-control
511             "function called with ~R argument~:P, but wants exactly ~R"
512             :format-arguments (list n-call-args nargs))
513            (setf (basic-combination-kind call) :error)))))
514 \f
515 ;;;; &OPTIONAL, &MORE and &KEYWORD calls
516
517 ;;; This is similar to CONVERT-LAMBDA-CALL, but deals with
518 ;;; OPTIONAL-DISPATCHes. If only fixed args are supplied, then convert
519 ;;; a call to the correct entry point. If &KEY args are supplied, then
520 ;;; dispatch to a subfunction. We don't convert calls to functions
521 ;;; that have a &MORE (or &REST) arg.
522 (defun convert-hairy-call (ref call fun)
523   (declare (type ref ref) (type combination call)
524            (type optional-dispatch fun))
525   (let ((min-args (optional-dispatch-min-args fun))
526         (max-args (optional-dispatch-max-args fun))
527         (call-args (length (combination-args call))))
528     (cond ((< call-args min-args)
529            (warn
530             'local-argument-mismatch
531             :format-control
532             "function called with ~R argument~:P, but wants at least ~R"
533             :format-arguments (list call-args min-args))
534            (setf (basic-combination-kind call) :error))
535           ((<= call-args max-args)
536            (convert-call ref call
537                          (let ((*current-component* (node-component ref)))
538                            (optional-dispatch-entry-point-fun
539                             fun (- call-args min-args)))))
540           ((optional-dispatch-more-entry fun)
541            (convert-more-call ref call fun))
542           (t
543            (warn
544             'local-argument-mismatch
545             :format-control
546             "function called with ~R argument~:P, but wants at most ~R"
547             :format-arguments
548             (list call-args max-args))
549            (setf (basic-combination-kind call) :error))))
550   (values))
551
552 ;;; This function is used to convert a call to an entry point when
553 ;;; complex transformations need to be done on the original arguments.
554 ;;; ENTRY is the entry point function that we are calling. VARS is a
555 ;;; list of variable names which are bound to the original call
556 ;;; arguments. IGNORES is the subset of VARS which are ignored. ARGS
557 ;;; is the list of arguments to the entry point function.
558 ;;;
559 ;;; In order to avoid gruesome graph grovelling, we introduce a new
560 ;;; function that rearranges the arguments and calls the entry point.
561 ;;; We analyze the new function and the entry point immediately so
562 ;;; that everything gets converted during the single pass.
563 (defun convert-hairy-fun-entry (ref call entry vars ignores args indef)
564   (declare (list vars ignores args) (type ref ref) (type combination call)
565            (type clambda entry))
566   (let ((new-fun
567          (with-ir1-environment-from-node call
568            (ir1-convert-lambda
569             `(lambda ,vars
570                (declare (ignorable ,@ignores)
571                         (indefinite-extent ,@indef))
572                (%funcall ,entry ,@args))
573             :debug-name (debug-name 'hairy-function-entry
574                                     (lvar-fun-debug-name
575                                      (basic-combination-fun call)))
576             :system-lambda t))))
577     (convert-call ref call new-fun)
578     (dolist (ref (leaf-refs entry))
579       (convert-call-if-possible ref (lvar-dest (node-lvar ref))))))
580
581 ;;; Use CONVERT-HAIRY-FUN-ENTRY to convert a &MORE-arg call to a known
582 ;;; function into a local call to the MAIN-ENTRY.
583 ;;;
584 ;;; First we verify that all keywords are constant and legal. If there
585 ;;; aren't, then we warn the user and don't attempt to convert the call.
586 ;;;
587 ;;; We massage the supplied &KEY arguments into the order expected
588 ;;; by the main entry. This is done by binding all the arguments to
589 ;;; the keyword call to variables in the introduced lambda, then
590 ;;; passing these values variables in the correct order when calling
591 ;;; the main entry. Unused arguments (such as the keywords themselves)
592 ;;; are discarded simply by not passing them along.
593 ;;;
594 ;;; If there is a &REST arg, then we bundle up the args and pass them
595 ;;; to LIST.
596 (defun convert-more-call (ref call fun)
597   (declare (type ref ref) (type combination call) (type optional-dispatch fun))
598   (let* ((max (optional-dispatch-max-args fun))
599          (arglist (optional-dispatch-arglist fun))
600          (args (combination-args call))
601          (more (nthcdr max args))
602          (flame (policy call (or (> speed inhibit-warnings)
603                                  (> space inhibit-warnings))))
604          (loser nil)
605          (allowp nil)
606          (allow-found nil)
607          (temps (make-gensym-list max))
608          (more-temps (make-gensym-list (length more))))
609     (collect ((ignores)
610               (supplied)
611               (key-vars))
612
613       (dolist (var arglist)
614         (let ((info (lambda-var-arg-info var)))
615           (when info
616             (ecase (arg-info-kind info)
617               (:keyword
618                (key-vars var))
619               ((:rest :optional))
620               ((:more-context :more-count)
621                (compiler-warn "can't local-call functions with &MORE args")
622                (setf (basic-combination-kind call) :error)
623                (return-from convert-more-call))))))
624
625       (when (optional-dispatch-keyp fun)
626         (when (oddp (length more))
627           (compiler-warn "function called with odd number of ~
628                           arguments in keyword portion")
629           (setf (basic-combination-kind call) :error)
630           (return-from convert-more-call))
631
632         (do ((key more (cddr key))
633              (temp more-temps (cddr temp)))
634             ((null key))
635           (let ((lvar (first key)))
636             (unless (constant-lvar-p lvar)
637               (when flame
638                 (compiler-notify "non-constant keyword in keyword call"))
639               (setf (basic-combination-kind call) :error)
640               (return-from convert-more-call))
641
642             (let ((name (lvar-value lvar))
643                   (dummy (first temp))
644                   (val (second temp)))
645               (when (and (eq name :allow-other-keys) (not allow-found))
646                 (let ((val (second key)))
647                   (cond ((constant-lvar-p val)
648                          (setq allow-found t
649                                allowp (lvar-value val)))
650                         (t (when flame
651                              (compiler-notify "non-constant :ALLOW-OTHER-KEYS value"))
652                            (setf (basic-combination-kind call) :error)
653                            (return-from convert-more-call)))))
654               (dolist (var (key-vars)
655                            (progn
656                              (ignores dummy val)
657                              (unless (eq name :allow-other-keys)
658                                (setq loser (list name)))))
659                 (let ((info (lambda-var-arg-info var)))
660                   (when (eq (arg-info-key info) name)
661                       (ignores dummy)
662                       (if (member var (supplied) :key #'car)
663                           (ignores val)
664                           (supplied (cons var val)))
665                       (return)))))))
666
667         (when (and loser (not (optional-dispatch-allowp fun)) (not allowp))
668           (compiler-warn "function called with unknown argument keyword ~S"
669                          (car loser))
670           (setf (basic-combination-kind call) :error)
671           (return-from convert-more-call)))
672
673       (collect ((call-args))
674         (do ((var arglist (cdr var))
675              (temp temps (cdr temp)))
676             ((null var))
677           (let ((info (lambda-var-arg-info (car var))))
678             (if info
679                 (ecase (arg-info-kind info)
680                   (:optional
681                    (call-args (car temp))
682                    (when (arg-info-supplied-p info)
683                      (call-args t)))
684                   (:rest
685                    (call-args `(list ,@more-temps))
686                    (return))
687                   (:keyword
688                    (return)))
689                 (call-args (car temp)))))
690
691         (dolist (var (key-vars))
692           (let ((info (lambda-var-arg-info var))
693                 (temp (cdr (assoc var (supplied)))))
694             (if temp
695                 (call-args temp)
696                 (call-args (arg-info-default info)))
697             (when (arg-info-supplied-p info)
698               (call-args (not (null temp))))))
699
700         (convert-hairy-fun-entry ref call (optional-dispatch-main-entry fun)
701                                  (append temps more-temps)
702                                  (ignores) (call-args)
703                                  more-temps))))
704
705   (values))
706 \f
707 ;;;; LET conversion
708 ;;;;
709 ;;;; Converting to a LET has differing significance to various parts
710 ;;;; of the compiler:
711 ;;;; -- The body of a LET is spliced in immediately after the
712 ;;;;    corresponding combination node, making the control transfer
713 ;;;;    explicit and allowing LETs to be mashed together into a single
714 ;;;;    block. The value of the LET is delivered directly to the
715 ;;;;    original lvar for the call, eliminating the need to
716 ;;;;    propagate information from the dummy result lvar.
717 ;;;; -- As far as IR1 optimization is concerned, it is interesting in
718 ;;;;    that there is only one expression that the variable can be bound
719 ;;;;    to, and this is easily substituted for.
720 ;;;; -- LETs are interesting to environment analysis and to the back
721 ;;;;    end because in most ways a LET can be considered to be "the
722 ;;;;    same function" as its home function.
723 ;;;; -- LET conversion has dynamic scope implications, since control
724 ;;;;    transfers within the same environment are local. In a local
725 ;;;;    control transfer, cleanup code must be emitted to remove
726 ;;;;    dynamic bindings that are no longer in effect.
727
728 ;;; Set up the control transfer to the called CLAMBDA. We split the
729 ;;; call block immediately after the call, and link the head of
730 ;;; CLAMBDA to the call block. The successor block after splitting
731 ;;; (where we return to) is returned.
732 ;;;
733 ;;; If the lambda is is a different component than the call, then we
734 ;;; call JOIN-COMPONENTS. This only happens in block compilation
735 ;;; before FIND-INITIAL-DFO.
736 (defun insert-let-body (clambda call)
737   (declare (type clambda clambda) (type basic-combination call))
738   (let* ((call-block (node-block call))
739          (bind-block (node-block (lambda-bind clambda)))
740          (component (block-component call-block)))
741     (aver-live-component component)
742     (let ((clambda-component (block-component bind-block)))
743       (unless (eq clambda-component component)
744         (aver (eq (component-kind component) :initial))
745         (join-components component clambda-component)))
746     (let ((*current-component* component))
747       (node-ends-block call))
748     (destructuring-bind (next-block)
749         (block-succ call-block)
750       (unlink-blocks call-block next-block)
751       (link-blocks call-block bind-block)
752       next-block)))
753
754 ;;; Remove CLAMBDA from the tail set of anything it used to be in the
755 ;;; same set as; but leave CLAMBDA with a valid tail set value of
756 ;;; its own, for the benefit of code which might try to pull
757 ;;; something out of it (e.g. return type).
758 (defun depart-from-tail-set (clambda)
759   ;; Until sbcl-0.pre7.37.flaky5.2, we did
760   ;;   (LET ((TAILS (LAMBDA-TAIL-SET CLAMBDA)))
761   ;;     (SETF (TAIL-SET-FUNS TAILS)
762   ;;           (DELETE CLAMBDA (TAIL-SET-FUNS TAILS))))
763   ;;   (SETF (LAMBDA-TAIL-SET CLAMBDA) NIL)
764   ;; here. Apparently the idea behind the (SETF .. NIL) was that since
765   ;; TAIL-SET-FUNS no longer thinks we're in the tail set, it's
766   ;; inconsistent, and perhaps unsafe, for us to think we're in the
767   ;; tail set. Unfortunately..
768   ;;
769   ;; The (SETF .. NIL) caused problems in sbcl-0.pre7.37.flaky5.2 when
770   ;; I was trying to get Python to emit :EXTERNAL LAMBDAs directly
771   ;; (instead of only being able to emit funny little :TOPLEVEL stubs
772   ;; which you called in order to get the address of an external LAMBDA):
773   ;; the external function was defined in terms of internal function,
774   ;; which was LET-converted, and then things blew up downstream when
775   ;; FINALIZE-XEP-DEFINITION tried to find out its DEFINED-TYPE from
776   ;; the now-NILed-out TAIL-SET. So..
777   ;;
778   ;; To deal with this problem, we no longer NIL out
779   ;; (LAMBDA-TAIL-SET CLAMBDA) here. Instead:
780   ;;   * If we're the only function in TAIL-SET-FUNS, it should
781   ;;     be safe to leave ourself linked to it, and it to you.
782   ;;   * If there are other functions in TAIL-SET-FUNS, then we're
783   ;;     afraid of future optimizations on those functions causing
784   ;;     the TAIL-SET object no longer to be valid to describe our
785   ;;     return value. Thus, we delete ourselves from that object;
786   ;;     but we save a newly-allocated tail-set, derived from the old
787   ;;     one, for ourselves, for the use of later code (e.g.
788   ;;     FINALIZE-XEP-DEFINITION) which might want to
789   ;;     know about our return type.
790   (let* ((old-tail-set (lambda-tail-set clambda))
791          (old-tail-set-funs (tail-set-funs old-tail-set)))
792     (unless (= 1 (length old-tail-set-funs))
793       (setf (tail-set-funs old-tail-set)
794             (delete clambda old-tail-set-funs))
795       (let ((new-tail-set (copy-tail-set old-tail-set)))
796         (setf (lambda-tail-set clambda) new-tail-set
797               (tail-set-funs new-tail-set) (list clambda)))))
798   ;; The documentation on TAIL-SET-INFO doesn't tell whether it could
799   ;; remain valid in this case, so we nuke it on the theory that
800   ;; missing information tends to be less dangerous than incorrect
801   ;; information.
802   (setf (tail-set-info (lambda-tail-set clambda)) nil))
803
804 ;;; Handle the PHYSENV semantics of LET conversion. We add CLAMBDA and
805 ;;; its LETs to LETs for the CALL's home function. We merge the calls
806 ;;; for CLAMBDA with the calls for the home function, removing CLAMBDA
807 ;;; in the process. We also merge the ENTRIES.
808 ;;;
809 ;;; We also unlink the function head from the component head and set
810 ;;; COMPONENT-REANALYZE to true to indicate that the DFO should be
811 ;;; recomputed.
812 (defun merge-lets (clambda call)
813
814   (declare (type clambda clambda) (type basic-combination call))
815
816   (let ((component (node-component call)))
817     (unlink-blocks (component-head component) (lambda-block clambda))
818     (setf (component-lambdas component)
819           (delete clambda (component-lambdas component)))
820     (setf (component-reanalyze component) t))
821   (setf (lambda-call-lexenv clambda) (node-lexenv call))
822
823   (depart-from-tail-set clambda)
824
825   (let* ((home (node-home-lambda call))
826          (home-physenv (lambda-physenv home))
827          (physenv (lambda-physenv clambda)))
828
829     (aver (not (eq home clambda)))
830
831     ;; CLAMBDA belongs to HOME now.
832     (push clambda (lambda-lets home))
833     (setf (lambda-home clambda) home)
834     (setf (lambda-physenv clambda) home-physenv)
835
836     (when physenv
837       (unless home-physenv
838         (setf home-physenv (get-lambda-physenv home)))
839       (setf (physenv-nlx-info home-physenv)
840             (nconc (physenv-nlx-info physenv)
841                    (physenv-nlx-info home-physenv))))
842
843     ;; All of CLAMBDA's LETs belong to HOME now.
844     (let ((lets (lambda-lets clambda)))
845       (dolist (let lets)
846         (setf (lambda-home let) home)
847         (setf (lambda-physenv let) home-physenv))
848       (setf (lambda-lets home) (nconc lets (lambda-lets home))))
849     ;; CLAMBDA no longer has an independent existence as an entity
850     ;; which has LETs.
851     (setf (lambda-lets clambda) nil)
852
853     ;; HOME no longer calls CLAMBDA, and owns all of CLAMBDA's old
854     ;; DFO dependencies.
855     (sset-union (lambda-calls-or-closes home)
856                 (lambda-calls-or-closes clambda))
857     (sset-delete clambda (lambda-calls-or-closes home))
858     ;; CLAMBDA no longer has an independent existence as an entity
859     ;; which calls things or has DFO dependencies.
860     (setf (lambda-calls-or-closes clambda) nil)
861
862     ;; All of CLAMBDA's ENTRIES belong to HOME now.
863     (setf (lambda-entries home)
864           (nconc (lambda-entries clambda)
865                  (lambda-entries home)))
866     ;; CLAMBDA no longer has an independent existence as an entity
867     ;; with ENTRIES.
868     (setf (lambda-entries clambda) nil))
869
870   (values))
871
872 ;;; Handle the value semantics of LET conversion. Delete FUN's return
873 ;;; node, and change the control flow to transfer to NEXT-BLOCK
874 ;;; instead. Move all the uses of the result lvar to CALL's lvar.
875 (defun move-return-uses (fun call next-block)
876   (declare (type clambda fun) (type basic-combination call)
877            (type cblock next-block))
878   (let* ((return (lambda-return fun))
879          (return-block (progn
880                          (ensure-block-start (node-prev return))
881                          (node-block return))))
882     (unlink-blocks return-block
883                    (component-tail (block-component return-block)))
884     (link-blocks return-block next-block)
885     (unlink-node return)
886     (delete-return return)
887     (let ((result (return-result return))
888           (lvar (if (node-tail-p call)
889                     (return-result (lambda-return (node-home-lambda call)))
890                     (node-lvar call)))
891           (call-type (node-derived-type call)))
892       (unless (eq call-type *wild-type*)
893         ;; FIXME: Replace the call with unsafe CAST. -- APD, 2003-01-26
894         (do-uses (use result)
895           (derive-node-type use call-type)))
896       (substitute-lvar-uses lvar result
897                             (and lvar (eq (lvar-uses lvar) call)))))
898   (values))
899
900 ;;; We are converting FUN to be a LET when the call is in a non-tail
901 ;;; position. Any previously tail calls in FUN are no longer tail
902 ;;; calls, and must be restored to normal calls which transfer to
903 ;;; NEXT-BLOCK (FUN's return point.) We can't do this by DO-USES on
904 ;;; the RETURN-RESULT, because the return might have been deleted (if
905 ;;; all calls were TR.)
906 (defun unconvert-tail-calls (fun call next-block)
907   (do-sset-elements (called (lambda-calls-or-closes fun))
908     (when (lambda-p called)
909       (dolist (ref (leaf-refs called))
910         (let ((this-call (node-dest ref)))
911           (when (and this-call
912                      (node-tail-p this-call)
913                      (eq (node-home-lambda this-call) fun))
914             (setf (node-tail-p this-call) nil)
915             (ecase (functional-kind called)
916               ((nil :cleanup :optional)
917                (let ((block (node-block this-call))
918                      (lvar (node-lvar call)))
919                  (unlink-blocks block (first (block-succ block)))
920                  (link-blocks block next-block)
921                  (aver (not (node-lvar this-call)))
922                  (add-lvar-use this-call lvar)))
923               (:deleted)
924               ;; The called function might be an assignment in the
925               ;; case where we are currently converting that function.
926               ;; In steady-state, assignments never appear as a called
927               ;; function.
928               (:assignment
929                (aver (eq called fun)))))))))
930   (values))
931
932 ;;; Deal with returning from a LET or assignment that we are
933 ;;; converting. FUN is the function we are calling, CALL is a call to
934 ;;; FUN, and NEXT-BLOCK is the return point for a non-tail call, or
935 ;;; NULL if call is a tail call.
936 ;;;
937 ;;; If the call is not a tail call, then we must do
938 ;;; UNCONVERT-TAIL-CALLS, since a tail call is a call which returns
939 ;;; its value out of the enclosing non-let function. When call is
940 ;;; non-TR, we must convert it back to an ordinary local call, since
941 ;;; the value must be delivered to the receiver of CALL's value.
942 ;;;
943 ;;; We do different things depending on whether the caller and callee
944 ;;; have returns left:
945
946 ;;; -- If the callee has no return we just do MOVE-LET-CALL-CONT.
947 ;;;    Either the function doesn't return, or all returns are via
948 ;;;    tail-recursive local calls.
949 ;;; -- If CALL is a non-tail call, or if both have returns, then
950 ;;;    we delete the callee's return, move its uses to the call's
951 ;;;    result lvar, and transfer control to the appropriate
952 ;;;    return point.
953 ;;; -- If the callee has a return, but the caller doesn't, then we
954 ;;;    move the return to the caller.
955 (defun move-return-stuff (fun call next-block)
956   (declare (type clambda fun) (type basic-combination call)
957            (type (or cblock null) next-block))
958   (when next-block
959     (unconvert-tail-calls fun call next-block))
960   (let* ((return (lambda-return fun))
961          (call-fun (node-home-lambda call))
962          (call-return (lambda-return call-fun)))
963     (when (and call-return
964                (block-delete-p (node-block call-return)))
965       (delete-return call-return)
966       (unlink-node call-return)
967       (setq call-return nil))
968     (cond ((not return))
969           ((or next-block call-return)
970            (unless (block-delete-p (node-block return))
971              (unless next-block
972                (ensure-block-start (node-prev call-return))
973                (setq next-block (node-block call-return)))
974              (move-return-uses fun call next-block)))
975           (t
976            (aver (node-tail-p call))
977            (setf (lambda-return call-fun) return)
978            (setf (return-lambda return) call-fun)
979            (setf (lambda-return fun) nil))))
980   (%delete-lvar-use call) ; LET call does not have value semantics
981   (values))
982
983 ;;; Actually do LET conversion. We call subfunctions to do most of the
984 ;;; work. We do REOPTIMIZE-LVAR on the args and CALL's lvar so that
985 ;;; LET-specific IR1 optimizations get a chance. We blow away any
986 ;;; entry for the function in *FREE-FUNS* so that nobody will create
987 ;;; new references to it.
988 (defun let-convert (fun call)
989   (declare (type clambda fun) (type basic-combination call))
990   (let* ((next-block (insert-let-body fun call))
991          (next-block (if (node-tail-p call)
992                          nil
993                          next-block)))
994     (move-return-stuff fun call next-block)
995     (merge-lets fun call)
996     (setf (node-tail-p call) nil)
997     ;; If CALL has a derive type NIL, it means that "its return" is
998     ;; unreachable, but the next BIND is still reachable; in order to
999     ;; not confuse MAYBE-TERMINATE-BLOCK...
1000     (setf (node-derived-type call) *wild-type*)))
1001
1002 ;;; Reoptimize all of CALL's args and its result.
1003 (defun reoptimize-call (call)
1004   (declare (type basic-combination call))
1005   (dolist (arg (basic-combination-args call))
1006     (when arg
1007       (reoptimize-lvar arg)))
1008   (reoptimize-lvar (node-lvar call))
1009   (values))
1010
1011 ;;; Are there any declarations in force to say CLAMBDA shouldn't be
1012 ;;; LET converted?
1013 (defun declarations-suppress-let-conversion-p (clambda)
1014   ;; From the user's point of view, LET-converting something that
1015   ;; has a name is inlining it. (The user can't see what we're doing
1016   ;; with anonymous things, and suppressing inlining
1017   ;; for such things can easily give Python acute indigestion, so
1018   ;; we don't.)
1019   (when (leaf-has-source-name-p clambda)
1020     ;; ANSI requires that explicit NOTINLINE be respected.
1021     (or (eq (lambda-inlinep clambda) :notinline)
1022         ;; If (= LET-CONVERSION 0) we can guess that inlining
1023         ;; generally won't be appreciated, but if the user
1024         ;; specifically requests inlining, that takes precedence over
1025         ;; our general guess.
1026         (and (policy clambda (= let-conversion 0))
1027              (not (eq (lambda-inlinep clambda) :inline))))))
1028
1029 ;;; We also don't convert calls to named functions which appear in the
1030 ;;; initial component, delaying this until optimization. This
1031 ;;; minimizes the likelihood that we will LET-convert a function which
1032 ;;; may have references added due to later local inline expansion.
1033 (defun ok-initial-convert-p (fun)
1034   (not (and (leaf-has-source-name-p fun)
1035             (or (declarations-suppress-let-conversion-p fun)
1036                 (eq (component-kind (lambda-component fun))
1037                     :initial)))))
1038
1039 ;;; This function is called when there is some reason to believe that
1040 ;;; CLAMBDA might be converted into a LET. This is done after local
1041 ;;; call analysis, and also when a reference is deleted. We return
1042 ;;; true if we converted.
1043 (defun maybe-let-convert (clambda)
1044   (declare (type clambda clambda))
1045   (unless (or (declarations-suppress-let-conversion-p clambda)
1046               (functional-has-external-references-p clambda))
1047     ;; We only convert to a LET when the function is a normal local
1048     ;; function, has no XEP, and is referenced in exactly one local
1049     ;; call. Conversion is also inhibited if the only reference is in
1050     ;; a block about to be deleted.
1051     ;;
1052     ;; These rules limiting LET conversion may seem unnecessarily
1053     ;; restrictive, since there are some cases where we could do the
1054     ;; return with a jump that don't satisfy these requirements. The
1055     ;; reason for doing things this way is that it makes the concept
1056     ;; of a LET much more useful at the level of IR1 semantics. The
1057     ;; :ASSIGNMENT function kind provides another way to optimize
1058     ;; calls to single-return/multiple call functions.
1059     ;;
1060     ;; We don't attempt to convert calls to functions that have an
1061     ;; XEP, since we might be embarrassed later when we want to
1062     ;; convert a newly discovered local call. Also, see
1063     ;; OK-INITIAL-CONVERT-P.
1064     (let ((refs (leaf-refs clambda)))
1065       (when (and refs
1066                  (null (rest refs))
1067                  (memq (functional-kind clambda) '(nil :assignment))
1068                  (not (functional-entry-fun clambda)))
1069         (binding* ((ref (first refs))
1070                    (ref-lvar (node-lvar ref) :exit-if-null)
1071                    (dest (lvar-dest ref-lvar)))
1072           (when (and (basic-combination-p dest)
1073                      (eq (basic-combination-fun dest) ref-lvar)
1074                      (eq (basic-combination-kind dest) :local)
1075                      (not (node-to-be-deleted-p dest))
1076                      (not (block-delete-p (lambda-block clambda)))
1077                      (cond ((ok-initial-convert-p clambda) t)
1078                            (t
1079                             (reoptimize-lvar ref-lvar)
1080                             nil)))
1081             (when (eq clambda (node-home-lambda dest))
1082               (delete-lambda clambda)
1083               (return-from maybe-let-convert nil))
1084             (unless (eq (functional-kind clambda) :assignment)
1085               (let-convert clambda dest))
1086             (reoptimize-call dest)
1087             (setf (functional-kind clambda)
1088                   (if (mv-combination-p dest) :mv-let :let))))
1089         t))))
1090 \f
1091 ;;;; tail local calls and assignments
1092
1093 ;;; Return T if there are no cleanups between BLOCK1 and BLOCK2, or if
1094 ;;; they definitely won't generate any cleanup code. Currently we
1095 ;;; recognize lexical entry points that are only used locally (if at
1096 ;;; all).
1097 (defun only-harmless-cleanups (block1 block2)
1098   (declare (type cblock block1 block2))
1099   (or (eq block1 block2)
1100       (let ((cleanup2 (block-start-cleanup block2)))
1101         (do ((cleanup (block-end-cleanup block1)
1102                       (node-enclosing-cleanup (cleanup-mess-up cleanup))))
1103             ((eq cleanup cleanup2) t)
1104           (case (cleanup-kind cleanup)
1105             ((:block :tagbody)
1106              (unless (null (entry-exits (cleanup-mess-up cleanup)))
1107                (return nil)))
1108             (t (return nil)))))))
1109
1110 ;;; If a potentially TR local call really is TR, then convert it to
1111 ;;; jump directly to the called function. We also call
1112 ;;; MAYBE-CONVERT-TO-ASSIGNMENT. The first value is true if we
1113 ;;; tail-convert. The second is the value of M-C-T-A.
1114 (defun maybe-convert-tail-local-call (call)
1115   (declare (type combination call))
1116   (let ((return (lvar-dest (node-lvar call)))
1117         (fun (combination-lambda call)))
1118     (aver (return-p return))
1119     (when (and (not (node-tail-p call)) ; otherwise already converted
1120                ;; this is a tail call
1121                (immediately-used-p (return-result return) call)
1122                (only-harmless-cleanups (node-block call)
1123                                        (node-block return))
1124                ;; If the call is in an XEP, we might decide to make it
1125                ;; non-tail so that we can use known return inside the
1126                ;; component.
1127                (not (eq (functional-kind (node-home-lambda call))
1128                         :external))
1129                (not (block-delete-p (lambda-block fun))))
1130       (node-ends-block call)
1131       (let ((block (node-block call)))
1132         (setf (node-tail-p call) t)
1133         (unlink-blocks block (first (block-succ block)))
1134         (link-blocks block (lambda-block fun))
1135         (delete-lvar-use call)
1136         (values t (maybe-convert-to-assignment fun))))))
1137
1138 ;;; This is called when we believe it might make sense to convert
1139 ;;; CLAMBDA to an assignment. All this function really does is
1140 ;;; determine when a function with more than one call can still be
1141 ;;; combined with the calling function's environment. We can convert
1142 ;;; when:
1143 ;;; -- The function is a normal, non-entry function, and
1144 ;;; -- Except for one call, all calls must be tail recursive calls
1145 ;;;    in the called function (i.e. are self-recursive tail calls)
1146 ;;; -- OK-INITIAL-CONVERT-P is true.
1147 ;;;
1148 ;;; There may be one outside call, and it need not be tail-recursive.
1149 ;;; Since all tail local calls have already been converted to direct
1150 ;;; transfers, the only control semantics needed are to splice in the
1151 ;;; body at the non-tail call. If there is no non-tail call, then we
1152 ;;; need only merge the environments. Both cases are handled by
1153 ;;; LET-CONVERT.
1154 ;;;
1155 ;;; ### It would actually be possible to allow any number of outside
1156 ;;; calls as long as they all return to the same place (i.e. have the
1157 ;;; same conceptual continuation.) A special case of this would be
1158 ;;; when all of the outside calls are tail recursive.
1159 (defun maybe-convert-to-assignment (clambda)
1160   (declare (type clambda clambda))
1161   (when (and (not (functional-kind clambda))
1162              (not (functional-entry-fun clambda))
1163              (not (functional-has-external-references-p clambda)))
1164     (let ((outside-non-tail-call nil)
1165           (outside-call nil))
1166       (when (and (dolist (ref (leaf-refs clambda) t)
1167                    (let ((dest (node-dest ref)))
1168                      (when (or (not dest)
1169                                (block-delete-p (node-block dest)))
1170                        (return nil))
1171                      (let ((home (node-home-lambda ref)))
1172                        (unless (eq home clambda)
1173                          (when outside-call
1174                            (return nil))
1175                          (setq outside-call dest))
1176                        (unless (node-tail-p dest)
1177                          (when (or outside-non-tail-call (eq home clambda))
1178                            (return nil))
1179                          (setq outside-non-tail-call dest)))))
1180                  (ok-initial-convert-p clambda))
1181         (cond (outside-call (setf (functional-kind clambda) :assignment)
1182                             (let-convert clambda outside-call)
1183                             (when outside-non-tail-call
1184                               (reoptimize-call outside-non-tail-call))
1185                             t)
1186               (t (delete-lambda clambda)
1187                  nil))))))