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