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