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