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