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