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