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