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