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