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