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