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