(I seem to've screwed up during the checkin of 0.pre7.131 before, so
[sbcl.git] / src / compiler / ir1tran.lisp
1 ;;;; This file contains code which does the translation from Lisp code
2 ;;;; to the first intermediate representation (IR1).
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14
15 (declaim (special *compiler-error-bailout*))
16
17 ;;; *SOURCE-PATHS* is a hashtable from source code forms to the path
18 ;;; taken through the source to reach the form. This provides a way to
19 ;;; keep track of the location of original source forms, even when
20 ;;; macroexpansions and other arbitary permutations of the code
21 ;;; happen. This table is initialized by calling FIND-SOURCE-PATHS on
22 ;;; the original source.
23 (declaim (hash-table *source-paths*))
24 (defvar *source-paths*)
25
26 ;;; *CURRENT-COMPONENT* is the COMPONENT structure which we link
27 ;;; blocks into as we generate them. This just serves to glue the
28 ;;; emitted blocks together until local call analysis and flow graph
29 ;;; canonicalization figure out what is really going on. We need to
30 ;;; keep track of all the blocks generated so that we can delete them
31 ;;; if they turn out to be unreachable.
32 ;;;
33 ;;; FIXME: It's confusing having one variable named *CURRENT-COMPONENT*
34 ;;; and another named *COMPONENT-BEING-COMPILED*. (In CMU CL they
35 ;;; were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively,
36 ;;; which was also confusing.)
37 (declaim (type (or component null) *current-component*))
38 (defvar *current-component*)
39
40 ;;; *CURRENT-PATH* is the source path of the form we are currently
41 ;;; translating. See NODE-SOURCE-PATH in the NODE structure.
42 (declaim (list *current-path*))
43 (defvar *current-path*)
44
45 (defvar *derive-function-types* nil
46   "Should the compiler assume that function types will never change,
47   so that it can use type information inferred from current definitions
48   to optimize code which uses those definitions? Setting this true
49   gives non-ANSI, early-CMU-CL behavior. It can be useful for improving
50   the efficiency of stable code.")
51 \f
52 ;;;; namespace management utilities
53
54 ;;; Return a GLOBAL-VAR structure usable for referencing the global
55 ;;; function NAME.
56 (defun find-free-really-fun (name)
57   (unless (info :function :kind name)
58     (setf (info :function :kind name) :function)
59     (setf (info :function :where-from name) :assumed))
60
61   (let ((where (info :function :where-from name)))
62     (when (and (eq where :assumed)
63                ;; In the ordinary target Lisp, it's silly to report
64                ;; undefinedness when the function is defined in the
65                ;; running Lisp. But at cross-compile time, the current
66                ;; definedness of a function is irrelevant to the
67                ;; definedness at runtime, which is what matters.
68                #-sb-xc-host (not (fboundp name)))
69       (note-undefined-reference name :function))
70     (make-global-var :kind :global-function
71                      :%source-name name
72                      :type (if (or *derive-function-types*
73                                    (eq where :declared))
74                                (info :function :type name)
75                                (specifier-type 'function))
76                      :where-from where)))
77
78 ;;; Has the *FREE-FUNS* entry FREE-FUN become invalid?
79 ;;;
80 ;;; In CMU CL, the answer was implicitly always true, so this 
81 ;;; predicate didn't exist.
82 ;;;
83 ;;; This predicate was added to fix bug 138 in SBCL. In some obscure
84 ;;; circumstances, it was possible for a *FREE-FUNS* to contain a
85 ;;; DEFINED-FUN whose DEFINED-FUN-FUNCTIONAL object contained IR1
86 ;;; stuff (NODEs, BLOCKs...) referring to an already compiled (aka
87 ;;; "dead") component. When this IR1 stuff was reused in a new
88 ;;; component, under further obscure circumstances it could be used by
89 ;;; WITH-IR1-ENVIRONMENT-FROM-NODE to generate a binding for
90 ;;; *CURRENT-COMPONENT*. At that point things got all confused, since
91 ;;; IR1 conversion was sending code to a component which had already
92 ;;; been compiled and would never be compiled again.
93 (defun invalid-free-fun-p (free-fun)
94   ;; There might be other reasons that *FREE-FUN* entries could
95   ;; become invalid, but the only one we've been bitten by so far
96   ;; (sbcl-0.pre7.118) is this one:
97   (and (defined-fun-p free-fun)
98        (let ((functional (defined-fun-functional free-fun)))
99          (and (lambda-p functional)
100               (or
101                ;; (The main reason for this first test is to bail out
102                ;; early in cases where the LAMBDA-COMPONENT call in
103                ;; the second test would fail because links it needs
104                ;; are uninitialized or invalid.)
105                ;;
106                ;; If the BIND node for this LAMBDA is null, then
107                ;; according to the slot comments, the LAMBDA has been
108                ;; deleted or its call has been deleted. In that case,
109                ;; it seems rather questionable to reuse it, and
110                ;; certainly it shouldn't be necessary to reuse it, so
111                ;; we cheerfully declare it invalid.
112                (null (lambda-bind functional))
113                ;; If this IR1 stuff belongs to a dead component, then
114                ;; we can't reuse it without getting into bizarre
115                ;; confusion.
116                (eql (component-info (lambda-component functional)) :dead))))))
117
118 ;;; If NAME already has a valid entry in *FREE-FUNS*, then return
119 ;;; the value. Otherwise, make a new GLOBAL-VAR using information from
120 ;;; the global environment and enter it in *FREE-FUNS*. If NAME
121 ;;; names a macro or special form, then we error out using the
122 ;;; supplied context which indicates what we were trying to do that
123 ;;; demanded a function.
124 (defun find-free-fun (name context)
125   (declare (string context))
126   (declare (values global-var))
127   (or (let ((old-free-fun (gethash name *free-funs*)))
128         (and (not (invalid-free-fun-p old-free-fun))
129              old-free-fun))
130       (ecase (info :function :kind name)
131         ;; FIXME: The :MACRO and :SPECIAL-FORM cases could be merged.
132         (:macro
133          (compiler-error "The macro name ~S was found ~A." name context))
134         (:special-form
135          (compiler-error "The special form name ~S was found ~A."
136                          name
137                          context))
138         ((:function nil)
139          (check-fun-name name)
140          (note-if-setf-fun-and-macro name)
141          (let ((expansion (fun-name-inline-expansion name))
142                (inlinep (info :function :inlinep name)))
143            (setf (gethash name *free-funs*)
144                  (if (or expansion inlinep)
145                      (make-defined-fun
146                       :%source-name name
147                       :inline-expansion expansion
148                       :inlinep inlinep
149                       :where-from (info :function :where-from name)
150                       :type (info :function :type name))
151                      (find-free-really-fun name))))))))
152
153 ;;; Return the LEAF structure for the lexically apparent function
154 ;;; definition of NAME.
155 (declaim (ftype (function (t string) leaf) find-lexically-apparent-fun))
156 (defun find-lexically-apparent-fun (name context)
157   (let ((var (lexenv-find name funs :test #'equal)))
158     (cond (var
159            (unless (leaf-p var)
160              (aver (and (consp var) (eq (car var) 'macro)))
161              (compiler-error "found macro name ~S ~A" name context))
162            var)
163           (t
164            (find-free-fun name context)))))
165
166 ;;; Return the LEAF node for a global variable reference to NAME. If
167 ;;; NAME is already entered in *FREE-VARS*, then we just return the
168 ;;; corresponding value. Otherwise, we make a new leaf using
169 ;;; information from the global environment and enter it in
170 ;;; *FREE-VARS*. If the variable is unknown, then we emit a warning.
171 (defun find-free-var (name)
172   (declare (values (or leaf heap-alien-info)))
173   (unless (symbolp name)
174     (compiler-error "Variable name is not a symbol: ~S." name))
175   (or (gethash name *free-vars*)
176       (let ((kind (info :variable :kind name))
177             (type (info :variable :type name))
178             (where-from (info :variable :where-from name)))
179         (when (and (eq where-from :assumed) (eq kind :global))
180           (note-undefined-reference name :variable))
181         (setf (gethash name *free-vars*)
182               (case kind
183                 (:alien
184                  (info :variable :alien-info name))
185                 (:constant
186                  (let ((value (info :variable :constant-value name)))
187                    (make-constant :value value
188                                   :%source-name name
189                                   :type (ctype-of value)
190                                   :where-from where-from)))
191                 (t
192                  (make-global-var :kind kind
193                                   :%source-name name
194                                   :type type
195                                   :where-from where-from)))))))
196 \f
197 ;;; Grovel over CONSTANT checking for any sub-parts that need to be
198 ;;; processed with MAKE-LOAD-FORM. We have to be careful, because
199 ;;; CONSTANT might be circular. We also check that the constant (and
200 ;;; any subparts) are dumpable at all.
201 (eval-when (:compile-toplevel :load-toplevel :execute)
202   ;; The EVAL-WHEN is necessary for #.(1+ LIST-TO-HASH-TABLE-THRESHOLD) 
203   ;; below. -- AL 20010227
204   (defconstant list-to-hash-table-threshold 32))
205 (defun maybe-emit-make-load-forms (constant)
206   (let ((things-processed nil)
207         (count 0))
208     ;; FIXME: Does this LIST-or-HASH-TABLE messiness give much benefit?
209     (declare (type (or list hash-table) things-processed)
210              (type (integer 0 #.(1+ list-to-hash-table-threshold)) count)
211              (inline member))
212     (labels ((grovel (value)
213                ;; Unless VALUE is an object which which obviously
214                ;; can't contain other objects
215                (unless (typep value
216                               '(or #-sb-xc-host unboxed-array
217                                    symbol
218                                    number
219                                    character
220                                    string))
221                  (etypecase things-processed
222                    (list
223                     (when (member value things-processed :test #'eq)
224                       (return-from grovel nil))
225                     (push value things-processed)
226                     (incf count)
227                     (when (> count list-to-hash-table-threshold)
228                       (let ((things things-processed))
229                         (setf things-processed
230                               (make-hash-table :test 'eq))
231                         (dolist (thing things)
232                           (setf (gethash thing things-processed) t)))))
233                    (hash-table
234                     (when (gethash value things-processed)
235                       (return-from grovel nil))
236                     (setf (gethash value things-processed) t)))
237                  (typecase value
238                    (cons
239                     (grovel (car value))
240                     (grovel (cdr value)))
241                    (simple-vector
242                     (dotimes (i (length value))
243                       (grovel (svref value i))))
244                    ((vector t)
245                     (dotimes (i (length value))
246                       (grovel (aref value i))))
247                    ((simple-array t)
248                     ;; Even though the (ARRAY T) branch does the exact
249                     ;; same thing as this branch we do this separately
250                     ;; so that the compiler can use faster versions of
251                     ;; array-total-size and row-major-aref.
252                     (dotimes (i (array-total-size value))
253                       (grovel (row-major-aref value i))))
254                    ((array t)
255                     (dotimes (i (array-total-size value))
256                       (grovel (row-major-aref value i))))
257                    (;; In the target SBCL, we can dump any instance,
258                     ;; but in the cross-compilation host,
259                     ;; %INSTANCE-FOO functions don't work on general
260                     ;; instances, only on STRUCTURE!OBJECTs.
261                     #+sb-xc-host structure!object
262                     #-sb-xc-host instance
263                     (when (emit-make-load-form value)
264                       (dotimes (i (%instance-length value))
265                         (grovel (%instance-ref value i)))))
266                    (t
267                     (compiler-error
268                      "Objects of type ~S can't be dumped into fasl files."
269                      (type-of value)))))))
270       (grovel constant)))
271   (values))
272 \f
273 ;;;; some flow-graph hacking utilities
274
275 ;;; This function sets up the back link between the node and the
276 ;;; continuation which continues at it.
277 (defun link-node-to-previous-continuation (node cont)
278   (declare (type node node) (type continuation cont))
279   (aver (not (continuation-next cont)))
280   (setf (continuation-next cont) node)
281   (setf (node-prev node) cont))
282
283 ;;; This function is used to set the continuation for a node, and thus
284 ;;; determine what receives the value and what is evaluated next. If
285 ;;; the continuation has no block, then we make it be in the block
286 ;;; that the node is in. If the continuation heads its block, we end
287 ;;; our block and link it to that block. If the continuation is not
288 ;;; currently used, then we set the DERIVED-TYPE for the continuation
289 ;;; to that of the node, so that a little type propagation gets done.
290 ;;;
291 ;;; We also deal with a bit of THE's semantics here: we weaken the
292 ;;; assertion on CONT to be no stronger than the assertion on CONT in
293 ;;; our scope. See the IR1-CONVERT method for THE.
294 #!-sb-fluid (declaim (inline use-continuation))
295 (defun use-continuation (node cont)
296   (declare (type node node) (type continuation cont))
297   (let ((node-block (continuation-block (node-prev node))))
298     (case (continuation-kind cont)
299       (:unused
300        (setf (continuation-block cont) node-block)
301        (setf (continuation-kind cont) :inside-block)
302        (setf (continuation-use cont) node)
303        (setf (node-cont node) cont))
304       (t
305        (%use-continuation node cont)))))
306 (defun %use-continuation (node cont)
307   (declare (type node node) (type continuation cont) (inline member))
308   (let ((block (continuation-block cont))
309         (node-block (continuation-block (node-prev node))))
310     (aver (eq (continuation-kind cont) :block-start))
311     (when (block-last node-block)
312       (error "~S has already ended." node-block))
313     (setf (block-last node-block) node)
314     (when (block-succ node-block)
315       (error "~S already has successors." node-block))
316     (setf (block-succ node-block) (list block))
317     (when (memq node-block (block-pred block))
318       (error "~S is already a predecessor of ~S." node-block block))
319     (push node-block (block-pred block))
320     (add-continuation-use node cont)
321     (unless (eq (continuation-asserted-type cont) *wild-type*)
322       (let ((new (values-type-union (continuation-asserted-type cont)
323                                     (or (lexenv-find cont type-restrictions)
324                                         *wild-type*))))
325         (when (type/= new (continuation-asserted-type cont))
326           (setf (continuation-asserted-type cont) new)
327           (reoptimize-continuation cont))))))
328 \f
329 ;;;; exported functions
330
331 ;;; This function takes a form and the top level form number for that
332 ;;; form, and returns a lambda representing the translation of that
333 ;;; form in the current global environment. The returned lambda is a
334 ;;; top level lambda that can be called to cause evaluation of the
335 ;;; forms. This lambda is in the initial component. If FOR-VALUE is T,
336 ;;; then the value of the form is returned from the function,
337 ;;; otherwise NIL is returned.
338 ;;;
339 ;;; This function may have arbitrary effects on the global environment
340 ;;; due to processing of EVAL-WHENs. All syntax error checking is
341 ;;; done, with erroneous forms being replaced by a proxy which signals
342 ;;; an error if it is evaluated. Warnings about possibly inconsistent
343 ;;; or illegal changes to the global environment will also be given.
344 ;;;
345 ;;; We make the initial component and convert the form in a PROGN (and
346 ;;; an optional NIL tacked on the end.) We then return the lambda. We
347 ;;; bind all of our state variables here, rather than relying on the
348 ;;; global value (if any) so that IR1 conversion will be reentrant.
349 ;;; This is necessary for EVAL-WHEN processing, etc.
350 ;;;
351 ;;; The hashtables used to hold global namespace info must be
352 ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so
353 ;;; that local macro definitions can be introduced by enclosing code.
354 (defun ir1-toplevel (form path for-value)
355   (declare (list path))
356   (let* ((*current-path* path)
357          (component (make-empty-component))
358          (*current-component* component))
359     (setf (component-name component) "initial component")
360     (setf (component-kind component) :initial)
361     (let* ((forms (if for-value `(,form) `(,form nil)))
362            (res (ir1-convert-lambda-body
363                  forms ()
364                  :debug-name (debug-namify "top level form ~S" form))))
365       (setf (functional-entry-fun res) res
366             (functional-arg-documentation res) ()
367             (functional-kind res) :toplevel)
368       res)))
369
370 ;;; *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the
371 ;;; form number to associate with a source path. This should be bound
372 ;;; to an initial value of 0 before the processing of each truly
373 ;;; top level form.
374 (declaim (type index *current-form-number*))
375 (defvar *current-form-number*)
376
377 ;;; This function is called on freshly read forms to record the
378 ;;; initial location of each form (and subform.) Form is the form to
379 ;;; find the paths in, and TLF-NUM is the top level form number of the
380 ;;; truly top level form.
381 ;;;
382 ;;; This gets a bit interesting when the source code is circular. This
383 ;;; can (reasonably?) happen in the case of circular list constants.
384 (defun find-source-paths (form tlf-num)
385   (declare (type index tlf-num))
386   (let ((*current-form-number* 0))
387     (sub-find-source-paths form (list tlf-num)))
388   (values))
389 (defun sub-find-source-paths (form path)
390   (unless (gethash form *source-paths*)
391     (setf (gethash form *source-paths*)
392           (list* 'original-source-start *current-form-number* path))
393     (incf *current-form-number*)
394     (let ((pos 0)
395           (subform form)
396           (trail form))
397       (declare (fixnum pos))
398       (macrolet ((frob ()
399                    '(progn
400                       (when (atom subform) (return))
401                       (let ((fm (car subform)))
402                         (when (consp fm)
403                           (sub-find-source-paths fm (cons pos path)))
404                         (incf pos))
405                       (setq subform (cdr subform))
406                       (when (eq subform trail) (return)))))
407         (loop
408           (frob)
409           (frob)
410           (setq trail (cdr trail)))))))
411 \f
412 ;;;; IR1-CONVERT, macroexpansion and special form dispatching
413
414 (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws
415            ;; out of the body and converts a proxy form instead.
416            (ir1-error-bailout ((start
417                                 cont
418                                 form
419                                 &optional
420                                 (proxy ``(error "execution of a form compiled with errors:~% ~S"
421                                                 ',,form)))
422                                &body body)
423                               (let ((skip (gensym "SKIP")))
424                                 `(block ,skip
425                                    (catch 'ir1-error-abort
426                                      (let ((*compiler-error-bailout*
427                                             (lambda ()
428                                               (throw 'ir1-error-abort nil))))
429                                        ,@body
430                                        (return-from ,skip nil)))
431                                    (ir1-convert ,start ,cont ,proxy)))))
432
433   ;; Translate FORM into IR1. The code is inserted as the NEXT of the
434   ;; continuation START. CONT is the continuation which receives the
435   ;; value of the FORM to be translated. The translators call this
436   ;; function recursively to translate their subnodes.
437   ;;
438   ;; As a special hack to make life easier in the compiler, a LEAF
439   ;; IR1-converts into a reference to that LEAF structure. This allows
440   ;; the creation using backquote of forms that contain leaf
441   ;; references, without having to introduce dummy names into the
442   ;; namespace.
443   (declaim (ftype (function (continuation continuation t) (values)) ir1-convert))
444   (defun ir1-convert (start cont form)
445     (ir1-error-bailout (start cont form)
446       (let ((*current-path* (or (gethash form *source-paths*)
447                                 (cons form *current-path*))))
448         (if (atom form)
449             (cond ((and (symbolp form) (not (keywordp form)))
450                    (ir1-convert-var start cont form))
451                   ((leaf-p form)
452                    (reference-leaf start cont form))
453                   (t
454                    (reference-constant start cont form)))
455             (let ((opname (car form)))
456               (cond ((symbolp opname)
457                      (let ((lexical-def (lexenv-find opname funs)))
458                        (typecase lexical-def
459                          (null (ir1-convert-global-functoid start cont form))
460                          (functional
461                           (ir1-convert-local-combination start
462                                                          cont
463                                                          form
464                                                          lexical-def))
465                          (global-var
466                           (ir1-convert-srctran start cont lexical-def form))
467                          (t
468                           (aver (and (consp lexical-def)
469                                      (eq (car lexical-def) 'macro)))
470                           (ir1-convert start cont
471                                        (careful-expand-macro (cdr lexical-def)
472                                                              form))))))
473                     ((or (atom opname) (not (eq (car opname) 'lambda)))
474                      (compiler-error "illegal function call"))
475                     (t
476                      ;; implicitly (LAMBDA ..) because the LAMBDA
477                      ;; expression is the CAR of an executed form
478                      (ir1-convert-combination start
479                                               cont
480                                               form
481                                               (ir1-convert-lambda
482                                                opname
483                                                :debug-name (debug-namify
484                                                             "LAMBDA CAR ~S"
485                                                             opname)))))))))
486     (values))
487
488   ;; Generate a reference to a manifest constant, creating a new leaf
489   ;; if necessary. If we are producing a fasl file, make sure that
490   ;; MAKE-LOAD-FORM gets used on any parts of the constant that it
491   ;; needs to be.
492   (defun reference-constant (start cont value)
493     (declare (type continuation start cont)
494              (inline find-constant))
495     (ir1-error-bailout
496      (start cont value '(error "attempt to reference undumpable constant"))
497      (when (producing-fasl-file)
498        (maybe-emit-make-load-forms value))
499      (let* ((leaf (find-constant value))
500             (res (make-ref (leaf-type leaf) leaf)))
501        (push res (leaf-refs leaf))
502        (link-node-to-previous-continuation res start)
503        (use-continuation res cont)))
504     (values)))
505
506 ;;; Add FUN to the COMPONENT-REANALYZE-FUNS, unless it's some trivial
507 ;;; type for which reanalysis is a trivial no-op, or unless it doesn't
508 ;;; belong in this component at all.
509 ;;;
510 ;;; FUN is returned.
511 (defun maybe-reanalyze-fun (fun)
512   (declare (type functional fun))
513
514   (aver-live-component *current-component*)
515
516   ;; When FUN is of a type for which reanalysis isn't a trivial no-op
517   (when (typep fun '(or optional-dispatch clambda))
518
519     ;; When FUN knows its component
520     (when (lambda-p fun) 
521       (aver (eql (lambda-component fun) *current-component*)))
522
523     (pushnew fun (component-reanalyze-funs *current-component*)))
524
525   fun)
526
527 ;;; Generate a REF node for LEAF, frobbing the LEAF structure as
528 ;;; needed. If LEAF represents a defined function which has already
529 ;;; been converted, and is not :NOTINLINE, then reference the
530 ;;; functional instead.
531 (defun reference-leaf (start cont leaf)
532   (declare (type continuation start cont) (type leaf leaf))
533   (let* ((leaf (or (and (defined-fun-p leaf)
534                         (not (eq (defined-fun-inlinep leaf)
535                                  :notinline))
536                         (let ((fun (defined-fun-functional leaf)))
537                           (when (and fun (not (functional-kind fun)))
538                             (maybe-reanalyze-fun fun))))
539                    leaf))
540          (res (make-ref (or (lexenv-find leaf type-restrictions)
541                             (leaf-type leaf))
542                         leaf)))
543     (push res (leaf-refs leaf))
544     (setf (leaf-ever-used leaf) t)
545     (link-node-to-previous-continuation res start)
546     (use-continuation res cont)))
547
548 ;;; Convert a reference to a symbolic constant or variable. If the
549 ;;; symbol is entered in the LEXENV-VARS we use that definition,
550 ;;; otherwise we find the current global definition. This is also
551 ;;; where we pick off symbol macro and alien variable references.
552 (defun ir1-convert-var (start cont name)
553   (declare (type continuation start cont) (symbol name))
554   (let ((var (or (lexenv-find name vars) (find-free-var name))))
555     (etypecase var
556       (leaf
557        (when (lambda-var-p var)
558          (let ((home (continuation-home-lambda-or-null start)))
559            (when home
560              (pushnew var (lambda-calls-or-closes home))))
561          (when (lambda-var-ignorep var)
562            ;; (ANSI's specification for the IGNORE declaration requires
563            ;; that this be a STYLE-WARNING, not a full WARNING.)
564            (compiler-style-warn "reading an ignored variable: ~S" name)))
565        (reference-leaf start cont var))
566       (cons
567        (aver (eq (car var) 'MACRO))
568        (ir1-convert start cont (cdr var)))
569       (heap-alien-info
570        (ir1-convert start cont `(%heap-alien ',var)))))
571   (values))
572
573 ;;; Convert anything that looks like a special form, global function
574 ;;; or macro call.
575 (defun ir1-convert-global-functoid (start cont form)
576   (declare (type continuation start cont) (list form))
577   (let* ((fun (first form))
578          (translator (info :function :ir1-convert fun))
579          (cmacro (info :function :compiler-macro-function fun)))
580     (cond (translator (funcall translator start cont form))
581           ((and cmacro
582                 (not (eq (info :function :inlinep fun)
583                          :notinline)))
584            (let ((res (careful-expand-macro cmacro form)))
585              (if (eq res form)
586                  (ir1-convert-global-functoid-no-cmacro start cont form fun)
587                  (ir1-convert start cont res))))
588           (t
589            (ir1-convert-global-functoid-no-cmacro start cont form fun)))))
590
591 ;;; Handle the case of where the call was not a compiler macro, or was
592 ;;; a compiler macro and passed.
593 (defun ir1-convert-global-functoid-no-cmacro (start cont form fun)
594   (declare (type continuation start cont) (list form))
595   ;; FIXME: Couldn't all the INFO calls here be converted into
596   ;; standard CL functions, like MACRO-FUNCTION or something?
597   ;; And what happens with lexically-defined (MACROLET) macros
598   ;; here, anyway?
599   (ecase (info :function :kind fun)
600     (:macro
601      (ir1-convert start
602                   cont
603                   (careful-expand-macro (info :function :macro-function fun)
604                                         form)))
605     ((nil :function)
606      (ir1-convert-srctran start
607                           cont
608                           (find-free-fun fun "shouldn't happen! (no-cmacro)")
609                           form))))
610
611 (defun muffle-warning-or-die ()
612   (muffle-warning)
613   (error "internal error -- no MUFFLE-WARNING restart"))
614
615 ;;; Expand FORM using the macro whose MACRO-FUNCTION is FUN, trapping
616 ;;; errors which occur during the macroexpansion.
617 (defun careful-expand-macro (fun form)
618   (let (;; a hint I (WHN) wish I'd known earlier
619         (hint "(hint: For more precise location, try *BREAK-ON-SIGNALS*.)"))
620     (flet (;; Return a string to use as a prefix in error reporting,
621            ;; telling something about which form caused the problem.
622            (wherestring ()
623              (let ((*print-pretty* nil)
624                    ;; We rely on the printer to abbreviate FORM. 
625                    (*print-length* 3)
626                    (*print-level* 1))
627                (format
628                 nil
629                 #-sb-xc-host "(in macroexpansion of ~S)"
630                 ;; longer message to avoid ambiguity "Was it the xc host
631                 ;; or the cross-compiler which encountered the problem?"
632                 #+sb-xc-host "(in cross-compiler macroexpansion of ~S)"
633                 form))))
634       (handler-bind (;; When cross-compiling, we can get style warnings
635                      ;; about e.g. undefined functions. An unhandled
636                      ;; CL:STYLE-WARNING (as opposed to a
637                      ;; SB!C::COMPILER-NOTE) would cause FAILURE-P to be
638                      ;; set on the return from #'SB!XC:COMPILE-FILE, which
639                      ;; would falsely indicate an error sufficiently
640                      ;; serious that we should stop the build process. To
641                      ;; avoid this, we translate CL:STYLE-WARNING
642                      ;; conditions from the host Common Lisp into
643                      ;; cross-compiler SB!C::COMPILER-NOTE calls. (It
644                      ;; might be cleaner to just make Python use
645                      ;; CL:STYLE-WARNING internally, so that the
646                      ;; significance of any host Common Lisp
647                      ;; CL:STYLE-WARNINGs is understood automatically. But
648                      ;; for now I'm not motivated to do this. -- WHN
649                      ;; 19990412)
650                      (style-warning (lambda (c)
651                                       (compiler-note "~@<~A~:@_~A~:@_~A~:>"
652                                                      (wherestring) hint c)
653                                       (muffle-warning-or-die)))
654                      ;; KLUDGE: CMU CL in its wisdom (version 2.4.6 for
655                      ;; Debian Linux, anyway) raises a CL:WARNING
656                      ;; condition (not a CL:STYLE-WARNING) for undefined
657                      ;; symbols when converting interpreted functions,
658                      ;; causing COMPILE-FILE to think the file has a real
659                      ;; problem, causing COMPILE-FILE to return FAILURE-P
660                      ;; set (not just WARNINGS-P set). Since undefined
661                      ;; symbol warnings are often harmless forward
662                      ;; references, and since it'd be inordinately painful
663                      ;; to try to eliminate all such forward references,
664                      ;; these warnings are basically unavoidable. Thus, we
665                      ;; need to coerce the system to work through them,
666                      ;; and this code does so, by crudely suppressing all
667                      ;; warnings in cross-compilation macroexpansion. --
668                      ;; WHN 19990412
669                      #+cmu
670                      (warning (lambda (c)
671                                 (compiler-note
672                                  "~@<~A~:@_~
673                                   ~A~:@_~
674                                   ~@<(KLUDGE: That was a non-STYLE WARNING. ~
675                                   Ordinarily that would cause compilation to ~
676                                   fail. However, since we're running under ~
677                                   CMU CL, and since CMU CL emits non-STYLE ~
678                                   warnings for safe, hard-to-fix things (e.g. ~
679                                   references to not-yet-defined functions) ~
680                                   we're going to have to ignore it and ~
681                                   proceed anyway. Hopefully we're not ~
682                                   ignoring anything  horrible here..)~:@>~:>"
683                                  (wherestring)
684                                  c)
685                                 (muffle-warning-or-die)))
686                      (error (lambda (c)
687                               (compiler-error "~@<~A~:@_~A~@:_~A~:>"
688                                               (wherestring) hint c))))
689         (funcall sb!xc:*macroexpand-hook* fun form *lexenv*)))))
690 \f
691 ;;;; conversion utilities
692
693 ;;; Convert a bunch of forms, discarding all the values except the
694 ;;; last. If there aren't any forms, then translate a NIL.
695 (declaim (ftype (function (continuation continuation list) (values))
696                 ir1-convert-progn-body))
697 (defun ir1-convert-progn-body (start cont body)
698   (if (endp body)
699       (reference-constant start cont nil)
700       (let ((this-start start)
701             (forms body))
702         (loop
703           (let ((form (car forms)))
704             (when (endp (cdr forms))
705               (ir1-convert this-start cont form)
706               (return))
707             (let ((this-cont (make-continuation)))
708               (ir1-convert this-start this-cont form)
709               (setq this-start this-cont
710                     forms (cdr forms)))))))
711   (values))
712 \f
713 ;;;; converting combinations
714
715 ;;; Convert a function call where the function (i.e. the FUN argument)
716 ;;; is a LEAF. We return the COMBINATION node so that the caller can
717 ;;; poke at it if it wants to.
718 (declaim (ftype (function (continuation continuation list leaf) combination)
719                 ir1-convert-combination))
720 (defun ir1-convert-combination (start cont form fun)
721   (let ((fun-cont (make-continuation)))
722     (reference-leaf start fun-cont fun)
723     (ir1-convert-combination-args fun-cont cont (cdr form))))
724
725 ;;; Convert the arguments to a call and make the COMBINATION node.
726 ;;; FUN-CONT is the continuation which yields the function to call.
727 ;;; FORM is the source for the call. ARGS is the list of arguments for
728 ;;; the call, which defaults to the cdr of source. We return the
729 ;;; COMBINATION node.
730 (defun ir1-convert-combination-args (fun-cont cont args)
731   (declare (type continuation fun-cont cont) (list args))
732   (let ((node (make-combination fun-cont)))
733     (setf (continuation-dest fun-cont) node)
734     (assert-continuation-type fun-cont
735                               (specifier-type '(or function symbol)))
736     (collect ((arg-conts))
737       (let ((this-start fun-cont))
738         (dolist (arg args)
739           (let ((this-cont (make-continuation node)))
740             (ir1-convert this-start this-cont arg)
741             (setq this-start this-cont)
742             (arg-conts this-cont)))
743         (link-node-to-previous-continuation node this-start)
744         (use-continuation node cont)
745         (setf (combination-args node) (arg-conts))))
746     node))
747
748 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
749 ;;; source transforms and try out any inline expansion. If there is no
750 ;;; expansion, but is :INLINE, then give an efficiency note (unless a
751 ;;; known function which will quite possibly be open-coded.) Next, we
752 ;;; go to ok-combination conversion.
753 (defun ir1-convert-srctran (start cont var form)
754   (declare (type continuation start cont) (type global-var var))
755   (let ((inlinep (when (defined-fun-p var)
756                    (defined-fun-inlinep var))))
757     (if (eq inlinep :notinline)
758         (ir1-convert-combination start cont form var)
759         (let ((transform (info :function
760                                :source-transform
761                                (leaf-source-name var))))
762           (if transform
763               (multiple-value-bind (result pass) (funcall transform form)
764                 (if pass
765                     (ir1-convert-maybe-predicate start cont form var)
766                     (ir1-convert start cont result)))
767               (ir1-convert-maybe-predicate start cont form var))))))
768
769 ;;; If the function has the PREDICATE attribute, and the CONT's DEST
770 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
771 ;;; predicate always appears in a conditional context.
772 ;;;
773 ;;; If the function isn't a predicate, then we call
774 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
775 (defun ir1-convert-maybe-predicate (start cont form var)
776   (declare (type continuation start cont) (list form) (type global-var var))
777   (let ((info (info :function :info (leaf-source-name var))))
778     (if (and info
779              (ir1-attributep (fun-info-attributes info) predicate)
780              (not (if-p (continuation-dest cont))))
781         (ir1-convert start cont `(if ,form t nil))
782         (ir1-convert-combination-checking-type start cont form var))))
783
784 ;;; Actually really convert a global function call that we are allowed
785 ;;; to early-bind.
786 ;;;
787 ;;; If we know the function type of the function, then we check the
788 ;;; call for syntactic legality with respect to the declared function
789 ;;; type. If it is impossible to determine whether the call is correct
790 ;;; due to non-constant keywords, then we give up, marking the call as
791 ;;; :FULL to inhibit further error messages. We return true when the
792 ;;; call is legal.
793 ;;;
794 ;;; If the call is legal, we also propagate type assertions from the
795 ;;; function type to the arg and result continuations. We do this now
796 ;;; so that IR1 optimize doesn't have to redundantly do the check
797 ;;; later so that it can do the type propagation.
798 (defun ir1-convert-combination-checking-type (start cont form var)
799   (declare (type continuation start cont) (list form) (type leaf var))
800   (let* ((node (ir1-convert-combination start cont form var))
801          (fun-cont (basic-combination-fun node))
802          (type (leaf-type var)))
803     (when (validate-call-type node type t)
804       (setf (continuation-%derived-type fun-cont) type)
805       (setf (continuation-reoptimize fun-cont) nil)
806       (setf (continuation-%type-check fun-cont) nil)))
807   (values))
808
809 ;;; Convert a call to a local function. If the function has already
810 ;;; been LET converted, then throw FUN to LOCAL-CALL-LOSSAGE. This
811 ;;; should only happen when we are converting inline expansions for
812 ;;; local functions during optimization.
813 (defun ir1-convert-local-combination (start cont form fun)
814   (if (functional-kind fun)
815       (throw 'local-call-lossage fun)
816       (ir1-convert-combination start cont form
817                                (maybe-reanalyze-fun fun))))
818 \f
819 ;;;; PROCESS-DECLS
820
821 ;;; Given a list of LAMBDA-VARs and a variable name, return the
822 ;;; LAMBDA-VAR for that name, or NIL if it isn't found. We return the
823 ;;; *last* variable with that name, since LET* bindings may be
824 ;;; duplicated, and declarations always apply to the last.
825 (declaim (ftype (function (list symbol) (or lambda-var list))
826                 find-in-bindings))
827 (defun find-in-bindings (vars name)
828   (let ((found nil))
829     (dolist (var vars)
830       (cond ((leaf-p var)
831              (when (eq (leaf-source-name var) name)
832                (setq found var))
833              (let ((info (lambda-var-arg-info var)))
834                (when info
835                  (let ((supplied-p (arg-info-supplied-p info)))
836                    (when (and supplied-p
837                               (eq (leaf-source-name supplied-p) name))
838                      (setq found supplied-p))))))
839             ((and (consp var) (eq (car var) name))
840              (setf found (cdr var)))))
841     found))
842
843 ;;; Called by Process-Decls to deal with a variable type declaration.
844 ;;; If a lambda-var being bound, we intersect the type with the vars
845 ;;; type, otherwise we add a type-restriction on the var. If a symbol
846 ;;; macro, we just wrap a THE around the expansion.
847 (defun process-type-decl (decl res vars)
848   (declare (list decl vars) (type lexenv res))
849   (let ((type (specifier-type (first decl))))
850     (collect ((restr nil cons)
851               (new-vars nil cons))
852       (dolist (var-name (rest decl))
853         (let* ((bound-var (find-in-bindings vars var-name))
854                (var (or bound-var
855                         (lexenv-find var-name vars)
856                         (find-free-var var-name))))
857           (etypecase var
858             (leaf
859              (let* ((old-type (or (lexenv-find var type-restrictions)
860                                   (leaf-type var)))
861                     (int (if (or (fun-type-p type)
862                                  (fun-type-p old-type))
863                              type
864                              (type-approx-intersection2 old-type type))))
865                (cond ((eq int *empty-type*)
866                       (unless (policy *lexenv* (= inhibit-warnings 3))
867                         (compiler-warn
868                          "The type declarations ~S and ~S for ~S conflict."
869                          (type-specifier old-type) (type-specifier type)
870                          var-name)))
871                      (bound-var (setf (leaf-type bound-var) int))
872                      (t
873                       (restr (cons var int))))))
874             (cons
875              ;; FIXME: non-ANSI weirdness
876              (aver (eq (car var) 'MACRO))
877              (new-vars `(,var-name . (MACRO . (the ,(first decl)
878                                                    ,(cdr var))))))
879             (heap-alien-info
880              (compiler-error
881               "~S is an alien variable, so its type can't be declared."
882               var-name)))))
883
884       (if (or (restr) (new-vars))
885           (make-lexenv :default res
886                        :type-restrictions (restr)
887                        :vars (new-vars))
888           res))))
889
890 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
891 ;;; declarations for function variables. In addition to allowing
892 ;;; declarations for functions being bound, we must also deal with
893 ;;; declarations that constrain the type of lexically apparent
894 ;;; functions.
895 (defun process-ftype-decl (spec res names fvars)
896   (declare (list spec names fvars) (type lexenv res))
897   (let ((type (specifier-type spec)))
898     (collect ((res nil cons))
899       (dolist (name names)
900         (let ((found (find name fvars
901                            :key #'leaf-source-name
902                            :test #'equal)))
903           (cond
904            (found
905             (setf (leaf-type found) type)
906             (assert-definition-type found type
907                                     :unwinnage-fun #'compiler-note
908                                     :where "FTYPE declaration"))
909            (t
910             (res (cons (find-lexically-apparent-fun
911                         name "in a function type declaration")
912                        type))))))
913       (if (res)
914           (make-lexenv :default res :type-restrictions (res))
915           res))))
916
917 ;;; Process a special declaration, returning a new LEXENV. A non-bound
918 ;;; special declaration is instantiated by throwing a special variable
919 ;;; into the variables.
920 (defun process-special-decl (spec res vars)
921   (declare (list spec vars) (type lexenv res))
922   (collect ((new-venv nil cons))
923     (dolist (name (cdr spec))
924       (let ((var (find-in-bindings vars name)))
925         (etypecase var
926           (cons
927            (aver (eq (car var) 'MACRO))
928            (compiler-error
929             "~S is a symbol-macro and thus can't be declared special."
930             name))
931           (lambda-var
932            (when (lambda-var-ignorep var)
933              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
934              ;; requires that this be a STYLE-WARNING, not a full WARNING.
935              (compiler-style-warn
936               "The ignored variable ~S is being declared special."
937               name))
938            (setf (lambda-var-specvar var)
939                  (specvar-for-binding name)))
940           (null
941            (unless (assoc name (new-venv) :test #'eq)
942              (new-venv (cons name (specvar-for-binding name))))))))
943     (if (new-venv)
944         (make-lexenv :default res :vars (new-venv))
945         res)))
946
947 ;;; Return a DEFINED-FUN which copies a GLOBAL-VAR but for its INLINEP.
948 (defun make-new-inlinep (var inlinep)
949   (declare (type global-var var) (type inlinep inlinep))
950   (let ((res (make-defined-fun
951               :%source-name (leaf-source-name var)
952               :where-from (leaf-where-from var)
953               :type (leaf-type var)
954               :inlinep inlinep)))
955     (when (defined-fun-p var)
956       (setf (defined-fun-inline-expansion res)
957             (defined-fun-inline-expansion var))
958       (setf (defined-fun-functional res)
959             (defined-fun-functional var)))
960     res))
961
962 ;;; Parse an inline/notinline declaration. If it's a local function we're
963 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
964 (defun process-inline-decl (spec res fvars)
965   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
966         (new-fenv ()))
967     (dolist (name (rest spec))
968       (let ((fvar (find name fvars
969                         :key #'leaf-source-name
970                         :test #'equal)))
971         (if fvar
972             (setf (functional-inlinep fvar) sense)
973             (let ((found
974                    (find-lexically-apparent-fun
975                     name "in an inline or notinline declaration")))
976               (etypecase found
977                 (functional
978                  (when (policy *lexenv* (>= speed inhibit-warnings))
979                    (compiler-note "ignoring ~A declaration not at ~
980                                    definition of local function:~%  ~S"
981                                   sense name)))
982                 (global-var
983                  (push (cons name (make-new-inlinep found sense))
984                        new-fenv)))))))
985
986     (if new-fenv
987         (make-lexenv :default res :funs new-fenv)
988         res)))
989
990 ;;; Like FIND-IN-BINDINGS, but looks for #'foo in the fvars.
991 (defun find-in-bindings-or-fbindings (name vars fvars)
992   (declare (list vars fvars))
993   (if (consp name)
994       (destructuring-bind (wot fn-name) name
995         (unless (eq wot 'function)
996           (compiler-error "The function or variable name ~S is unrecognizable."
997                           name))
998         (find fn-name fvars :key #'leaf-source-name :test #'equal))
999       (find-in-bindings vars name)))
1000
1001 ;;; Process an ignore/ignorable declaration, checking for various losing
1002 ;;; conditions.
1003 (defun process-ignore-decl (spec vars fvars)
1004   (declare (list spec vars fvars))
1005   (dolist (name (rest spec))
1006     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
1007       (cond
1008        ((not var)
1009         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1010         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1011         (compiler-style-warn "declaring unknown variable ~S to be ignored"
1012                              name))
1013        ;; FIXME: This special case looks like non-ANSI weirdness.
1014        ((and (consp var) (consp (cdr var)) (eq (cadr var) 'macro))
1015         ;; Just ignore the IGNORE decl.
1016         )
1017        ((functional-p var)
1018         (setf (leaf-ever-used var) t))
1019        ((lambda-var-specvar var)
1020         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1021         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1022         (compiler-style-warn "declaring special variable ~S to be ignored"
1023                              name))
1024        ((eq (first spec) 'ignorable)
1025         (setf (leaf-ever-used var) t))
1026        (t
1027         (setf (lambda-var-ignorep var) t)))))
1028   (values))
1029
1030 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
1031 ;;; go away, I think.
1032 (defvar *suppress-values-declaration* nil
1033   #!+sb-doc
1034   "If true, processing of the VALUES declaration is inhibited.")
1035
1036 ;;; Process a single declaration spec, augmenting the specified LEXENV
1037 ;;; RES and returning it as a result. VARS and FVARS are as described in
1038 ;;; PROCESS-DECLS.
1039 (defun process-1-decl (raw-spec res vars fvars cont)
1040   (declare (type list raw-spec vars fvars))
1041   (declare (type lexenv res))
1042   (declare (type continuation cont))
1043   (let ((spec (canonized-decl-spec raw-spec)))
1044     (case (first spec)
1045       (special (process-special-decl spec res vars))
1046       (ftype
1047        (unless (cdr spec)
1048          (compiler-error "No type specified in FTYPE declaration: ~S" spec))
1049        (process-ftype-decl (second spec) res (cddr spec) fvars))
1050       ((inline notinline maybe-inline)
1051        (process-inline-decl spec res fvars))
1052       ((ignore ignorable)
1053        (process-ignore-decl spec vars fvars)
1054        res)
1055       (optimize
1056        (make-lexenv
1057         :default res
1058         :policy (process-optimize-decl spec (lexenv-policy res))))
1059       (type
1060        (process-type-decl (cdr spec) res vars))
1061       (values
1062        (if *suppress-values-declaration*
1063            res
1064            (let ((types (cdr spec)))
1065              (do-the-stuff (if (eql (length types) 1)
1066                                (car types)
1067                                `(values ,@types))
1068                            cont res 'values))))
1069       (dynamic-extent
1070        (when (policy *lexenv* (> speed inhibit-warnings))
1071          (compiler-note
1072           "compiler limitation: ~
1073         ~%  There's no special support for DYNAMIC-EXTENT (so it's ignored)."))
1074        res)
1075       (t
1076        (unless (info :declaration :recognized (first spec))
1077          (compiler-warn "unrecognized declaration ~S" raw-spec))
1078        res))))
1079
1080 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1081 ;;; and FUNCTIONAL structures which are being bound. In addition to
1082 ;;; filling in slots in the leaf structures, we return a new LEXENV
1083 ;;; which reflects pervasive special and function type declarations,
1084 ;;; (NOT)INLINE declarations and OPTIMIZE declarations. CONT is the
1085 ;;; continuation affected by VALUES declarations.
1086 ;;;
1087 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1088 ;;; of LOCALLY.
1089 (defun process-decls (decls vars fvars cont &optional (env *lexenv*))
1090   (declare (list decls vars fvars) (type continuation cont))
1091   (dolist (decl decls)
1092     (dolist (spec (rest decl))
1093       (unless (consp spec)
1094         (compiler-error "malformed declaration specifier ~S in ~S"
1095                         spec
1096                         decl))
1097       (setq env (process-1-decl spec env vars fvars cont))))
1098   env)
1099
1100 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1101 ;;; declaration. If there is a global variable of that name, then
1102 ;;; check that it isn't a constant and return it. Otherwise, create an
1103 ;;; anonymous GLOBAL-VAR.
1104 (defun specvar-for-binding (name)
1105   (cond ((not (eq (info :variable :where-from name) :assumed))
1106          (let ((found (find-free-var name)))
1107            (when (heap-alien-info-p found)
1108              (compiler-error
1109               "~S is an alien variable and so can't be declared special."
1110               name))
1111            (unless (global-var-p found)
1112              (compiler-error
1113               "~S is a constant and so can't be declared special."
1114               name))
1115            found))
1116         (t
1117          (make-global-var :kind :special
1118                           :%source-name name
1119                           :where-from :declared))))
1120 \f
1121 ;;;; LAMBDA hackery
1122
1123 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
1124 ;;;; function representation" before you seriously mess with this
1125 ;;;; stuff.
1126
1127 ;;; Verify that a thing is a legal name for a variable and return a
1128 ;;; Var structure for it, filling in info if it is globally special.
1129 ;;; If it is losing, we punt with a Compiler-Error. Names-So-Far is an
1130 ;;; alist of names which have previously been bound. If the name is in
1131 ;;; this list, then we error out.
1132 (declaim (ftype (function (t list) lambda-var) varify-lambda-arg))
1133 (defun varify-lambda-arg (name names-so-far)
1134   (declare (inline member))
1135   (unless (symbolp name)
1136     (compiler-error "The lambda-variable ~S is not a symbol." name))
1137   (when (member name names-so-far :test #'eq)
1138     (compiler-error "The variable ~S occurs more than once in the lambda-list."
1139                     name))
1140   (let ((kind (info :variable :kind name)))
1141     (when (or (keywordp name) (eq kind :constant))
1142       (compiler-error "The name of the lambda-variable ~S is a constant."
1143                       name))
1144     (cond ((eq kind :special)
1145            (let ((specvar (find-free-var name)))
1146              (make-lambda-var :%source-name name
1147                               :type (leaf-type specvar)
1148                               :where-from (leaf-where-from specvar)
1149                               :specvar specvar)))
1150           (t
1151            (note-lexical-binding name)
1152            (make-lambda-var :%source-name name)))))
1153
1154 ;;; Make the default keyword for a &KEY arg, checking that the keyword
1155 ;;; isn't already used by one of the VARS. We also check that the
1156 ;;; keyword isn't the magical :ALLOW-OTHER-KEYS.
1157 (declaim (ftype (function (symbol list t) keyword) make-keyword-for-arg))
1158 (defun make-keyword-for-arg (symbol vars keywordify)
1159   (let ((key (if (and keywordify (not (keywordp symbol)))
1160                  (keywordicate symbol)
1161                  symbol)))
1162     (when (eq key :allow-other-keys)
1163       (compiler-error "No &KEY arg can be called :ALLOW-OTHER-KEYS."))
1164     (dolist (var vars)
1165       (let ((info (lambda-var-arg-info var)))
1166         (when (and info
1167                    (eq (arg-info-kind info) :keyword)
1168                    (eq (arg-info-key info) key))
1169           (compiler-error
1170            "The keyword ~S appears more than once in the lambda-list."
1171            key))))
1172     key))
1173
1174 ;;; Parse a lambda list into a list of VAR structures, stripping off
1175 ;;; any &AUX bindings. Each arg name is checked for legality, and
1176 ;;; duplicate names are checked for. If an arg is globally special,
1177 ;;; the var is marked as :SPECIAL instead of :LEXICAL. &KEY,
1178 ;;; &OPTIONAL and &REST args are annotated with an ARG-INFO structure
1179 ;;; which contains the extra information. If we hit something losing,
1180 ;;; we bug out with COMPILER-ERROR. These values are returned:
1181 ;;;  1. a list of the var structures for each top level argument;
1182 ;;;  2. a flag indicating whether &KEY was specified;
1183 ;;;  3. a flag indicating whether other &KEY args are allowed;
1184 ;;;  4. a list of the &AUX variables; and
1185 ;;;  5. a list of the &AUX values.
1186 (declaim (ftype (function (list) (values list boolean boolean list list))
1187                 make-lambda-vars))
1188 (defun make-lambda-vars (list)
1189   (multiple-value-bind (required optional restp rest keyp keys allowp aux
1190                         morep more-context more-count)
1191       (parse-lambda-list list)
1192     (collect ((vars)
1193               (names-so-far)
1194               (aux-vars)
1195               (aux-vals))
1196       (flet (;; PARSE-DEFAULT deals with defaults and supplied-p args
1197              ;; for optionals and keywords args.
1198              (parse-default (spec info)
1199                (when (consp (cdr spec))
1200                  (setf (arg-info-default info) (second spec))
1201                  (when (consp (cddr spec))
1202                    (let* ((supplied-p (third spec))
1203                           (supplied-var (varify-lambda-arg supplied-p
1204                                                            (names-so-far))))
1205                      (setf (arg-info-supplied-p info) supplied-var)
1206                      (names-so-far supplied-p)
1207                      (when (> (length (the list spec)) 3)
1208                        (compiler-error
1209                         "The list ~S is too long to be an arg specifier."
1210                         spec)))))))
1211         
1212         (dolist (name required)
1213           (let ((var (varify-lambda-arg name (names-so-far))))
1214             (vars var)
1215             (names-so-far name)))
1216         
1217         (dolist (spec optional)
1218           (if (atom spec)
1219               (let ((var (varify-lambda-arg spec (names-so-far))))
1220                 (setf (lambda-var-arg-info var) (make-arg-info :kind :optional))
1221                 (vars var)
1222                 (names-so-far spec))
1223               (let* ((name (first spec))
1224                      (var (varify-lambda-arg name (names-so-far)))
1225                      (info (make-arg-info :kind :optional)))
1226                 (setf (lambda-var-arg-info var) info)
1227                 (vars var)
1228                 (names-so-far name)
1229                 (parse-default spec info))))
1230         
1231         (when restp
1232           (let ((var (varify-lambda-arg rest (names-so-far))))
1233             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
1234             (vars var)
1235             (names-so-far rest)))
1236
1237         (when morep
1238           (let ((var (varify-lambda-arg more-context (names-so-far))))
1239             (setf (lambda-var-arg-info var)
1240                   (make-arg-info :kind :more-context))
1241             (vars var)
1242             (names-so-far more-context))
1243           (let ((var (varify-lambda-arg more-count (names-so-far))))
1244             (setf (lambda-var-arg-info var)
1245                   (make-arg-info :kind :more-count))
1246             (vars var)
1247             (names-so-far more-count)))
1248         
1249         (dolist (spec keys)
1250           (cond
1251            ((atom spec)
1252             (let ((var (varify-lambda-arg spec (names-so-far))))
1253               (setf (lambda-var-arg-info var)
1254                     (make-arg-info :kind :keyword
1255                                    :key (make-keyword-for-arg spec
1256                                                               (vars)
1257                                                               t)))
1258               (vars var)
1259               (names-so-far spec)))
1260            ((atom (first spec))
1261             (let* ((name (first spec))
1262                    (var (varify-lambda-arg name (names-so-far)))
1263                    (info (make-arg-info
1264                           :kind :keyword
1265                           :key (make-keyword-for-arg name (vars) t))))
1266               (setf (lambda-var-arg-info var) info)
1267               (vars var)
1268               (names-so-far name)
1269               (parse-default spec info)))
1270            (t
1271             (let ((head (first spec)))
1272               (unless (proper-list-of-length-p head 2)
1273                 (error "malformed &KEY argument specifier: ~S" spec))
1274               (let* ((name (second head))
1275                      (var (varify-lambda-arg name (names-so-far)))
1276                      (info (make-arg-info
1277                             :kind :keyword
1278                             :key (make-keyword-for-arg (first head)
1279                                                        (vars)
1280                                                        nil))))
1281                 (setf (lambda-var-arg-info var) info)
1282                 (vars var)
1283                 (names-so-far name)
1284                 (parse-default spec info))))))
1285         
1286         (dolist (spec aux)
1287           (cond ((atom spec)
1288                  (let ((var (varify-lambda-arg spec nil)))
1289                    (aux-vars var)
1290                    (aux-vals nil)
1291                    (names-so-far spec)))
1292                 (t
1293                  (unless (proper-list-of-length-p spec 1 2)
1294                    (compiler-error "malformed &AUX binding specifier: ~S"
1295                                    spec))
1296                  (let* ((name (first spec))
1297                         (var (varify-lambda-arg name nil)))
1298                    (aux-vars var)
1299                    (aux-vals (second spec))
1300                    (names-so-far name)))))
1301
1302         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
1303
1304 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that we
1305 ;;; sequentially bind each AUX-VAR to the corresponding AUX-VAL before
1306 ;;; converting the body. If there are no bindings, just convert the
1307 ;;; body, otherwise do one binding and recurse on the rest.
1308 ;;;
1309 ;;; FIXME: This could and probably should be converted to use
1310 ;;; SOURCE-NAME and DEBUG-NAME. But I (WHN) don't use &AUX bindings,
1311 ;;; so I'm not motivated. Patches will be accepted...
1312 (defun ir1-convert-aux-bindings (start cont body aux-vars aux-vals)
1313   (declare (type continuation start cont) (list body aux-vars aux-vals))
1314   (if (null aux-vars)
1315       (ir1-convert-progn-body start cont body)
1316       (let ((fun-cont (make-continuation))
1317             (fun (ir1-convert-lambda-body body
1318                                           (list (first aux-vars))
1319                                           :aux-vars (rest aux-vars)
1320                                           :aux-vals (rest aux-vals)
1321                                           :debug-name (debug-namify
1322                                                        "&AUX bindings ~S"
1323                                                        aux-vars))))
1324         (reference-leaf start fun-cont fun)
1325         (ir1-convert-combination-args fun-cont cont
1326                                       (list (first aux-vals)))))
1327   (values))
1328
1329 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that code to bind
1330 ;;; the SPECVAR for each SVAR to the value of the variable is wrapped
1331 ;;; around the body. If there are no special bindings, we just convert
1332 ;;; the body, otherwise we do one special binding and recurse on the
1333 ;;; rest.
1334 ;;;
1335 ;;; We make a cleanup and introduce it into the lexical environment.
1336 ;;; If there are multiple special bindings, the cleanup for the blocks
1337 ;;; will end up being the innermost one. We force CONT to start a
1338 ;;; block outside of this cleanup, causing cleanup code to be emitted
1339 ;;; when the scope is exited.
1340 (defun ir1-convert-special-bindings (start cont body aux-vars aux-vals svars)
1341   (declare (type continuation start cont)
1342            (list body aux-vars aux-vals svars))
1343   (cond
1344    ((null svars)
1345     (ir1-convert-aux-bindings start cont body aux-vars aux-vals))
1346    (t
1347     (continuation-starts-block cont)
1348     (let ((cleanup (make-cleanup :kind :special-bind))
1349           (var (first svars))
1350           (next-cont (make-continuation))
1351           (nnext-cont (make-continuation)))
1352       (ir1-convert start next-cont
1353                    `(%special-bind ',(lambda-var-specvar var) ,var))
1354       (setf (cleanup-mess-up cleanup) (continuation-use next-cont))
1355       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
1356         (ir1-convert next-cont nnext-cont '(%cleanup-point))
1357         (ir1-convert-special-bindings nnext-cont cont body aux-vars aux-vals
1358                                       (rest svars))))))
1359   (values))
1360
1361 ;;; Create a lambda node out of some code, returning the result. The
1362 ;;; bindings are specified by the list of VAR structures VARS. We deal
1363 ;;; with adding the names to the LEXENV-VARS for the conversion. The
1364 ;;; result is added to the NEW-FUNS in the *CURRENT-COMPONENT* and
1365 ;;; linked to the component head and tail.
1366 ;;;
1367 ;;; We detect special bindings here, replacing the original VAR in the
1368 ;;; lambda list with a temporary variable. We then pass a list of the
1369 ;;; special vars to IR1-CONVERT-SPECIAL-BINDINGS, which actually emits
1370 ;;; the special binding code.
1371 ;;;
1372 ;;; We ignore any ARG-INFO in the VARS, trusting that someone else is
1373 ;;; dealing with &nonsense.
1374 ;;;
1375 ;;; AUX-VARS is a list of VAR structures for variables that are to be
1376 ;;; sequentially bound. Each AUX-VAL is a form that is to be evaluated
1377 ;;; to get the initial value for the corresponding AUX-VAR. 
1378 (defun ir1-convert-lambda-body (body
1379                                 vars
1380                                 &key
1381                                 aux-vars
1382                                 aux-vals
1383                                 result
1384                                 (source-name '.anonymous.)
1385                                 debug-name)
1386   (declare (list body vars aux-vars aux-vals)
1387            (type (or continuation null) result))
1388
1389   ;; We're about to try to put new blocks into *CURRENT-COMPONENT*.
1390   (aver-live-component *current-component*)
1391
1392   (let* ((bind (make-bind))
1393          (lambda (make-lambda :vars vars
1394                               :bind bind
1395                               :%source-name source-name
1396                               :%debug-name debug-name))
1397          (result (or result (make-continuation))))
1398
1399     ;; just to check: This function should fail internal assertions if
1400     ;; we didn't set up a valid debug name above.
1401     ;;
1402     ;; (In SBCL we try to make everything have a debug name, since we
1403     ;; lack the omniscient perspective the original implementors used
1404     ;; to decide which things didn't need one.)
1405     (functional-debug-name lambda)
1406
1407     (setf (lambda-home lambda) lambda)
1408     (collect ((svars)
1409               (new-venv nil cons))
1410
1411       (dolist (var vars)
1412         ;; As far as I can see, LAMBDA-VAR-HOME should never have
1413         ;; been set before. Let's make sure. -- WHN 2001-09-29
1414         (aver (null (lambda-var-home var)))
1415         (setf (lambda-var-home var) lambda)
1416         (let ((specvar (lambda-var-specvar var)))
1417           (cond (specvar
1418                  (svars var)
1419                  (new-venv (cons (leaf-source-name specvar) specvar)))
1420                 (t
1421                  (note-lexical-binding (leaf-source-name var))
1422                  (new-venv (cons (leaf-source-name var) var))))))
1423
1424       (let ((*lexenv* (make-lexenv :vars (new-venv)
1425                                    :lambda lambda
1426                                    :cleanup nil)))
1427         (setf (bind-lambda bind) lambda)
1428         (setf (node-lexenv bind) *lexenv*)
1429         
1430         (let ((cont1 (make-continuation))
1431               (cont2 (make-continuation)))
1432           (continuation-starts-block cont1)
1433           (link-node-to-previous-continuation bind cont1)
1434           (use-continuation bind cont2)
1435           (ir1-convert-special-bindings cont2 result body aux-vars aux-vals
1436                                         (svars)))
1437
1438         (let ((block (continuation-block result)))
1439           (when block
1440             (let ((return (make-return :result result :lambda lambda))
1441                   (tail-set (make-tail-set :funs (list lambda)))
1442                   (dummy (make-continuation)))
1443               (setf (lambda-tail-set lambda) tail-set)
1444               (setf (lambda-return lambda) return)
1445               (setf (continuation-dest result) return)
1446               (setf (block-last block) return)
1447               (link-node-to-previous-continuation return result)
1448               (use-continuation return dummy))
1449             (link-blocks block (component-tail *current-component*))))))
1450
1451     (link-blocks (component-head *current-component*) (node-block bind))
1452     (push lambda (component-new-funs *current-component*))
1453
1454     lambda))
1455
1456 ;;; Create the actual entry-point function for an optional entry
1457 ;;; point. The lambda binds copies of each of the VARS, then calls FUN
1458 ;;; with the argument VALS and the DEFAULTS. Presumably the VALS refer
1459 ;;; to the VARS by name. The VALS are passed in in reverse order.
1460 ;;;
1461 ;;; If any of the copies of the vars are referenced more than once,
1462 ;;; then we mark the corresponding var as EVER-USED to inhibit
1463 ;;; "defined but not read" warnings for arguments that are only used
1464 ;;; by default forms.
1465 (defun convert-optional-entry (fun vars vals defaults)
1466   (declare (type clambda fun) (list vars vals defaults))
1467   (let* ((fvars (reverse vars))
1468          (arg-vars (mapcar (lambda (var)
1469                              (unless (lambda-var-specvar var)
1470                                (note-lexical-binding (leaf-source-name var)))
1471                              (make-lambda-var
1472                               :%source-name (leaf-source-name var)
1473                               :type (leaf-type var)
1474                               :where-from (leaf-where-from var)
1475                               :specvar (lambda-var-specvar var)))
1476                            fvars))
1477          (fun (ir1-convert-lambda-body `((%funcall ,fun
1478                                                    ,@(reverse vals)
1479                                                    ,@defaults))
1480                                        arg-vars
1481                                        :debug-name "&OPTIONAL processor")))
1482     (mapc (lambda (var arg-var)
1483             (when (cdr (leaf-refs arg-var))
1484               (setf (leaf-ever-used var) t)))
1485           fvars arg-vars)
1486     fun))
1487
1488 ;;; This function deals with supplied-p vars in optional arguments. If
1489 ;;; the there is no supplied-p arg, then we just call
1490 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
1491 ;;; optional entry that calls the result. If there is a supplied-p
1492 ;;; var, then we add it into the default vars and throw a T into the
1493 ;;; entry values. The resulting entry point function is returned.
1494 (defun generate-optional-default-entry (res default-vars default-vals
1495                                             entry-vars entry-vals
1496                                             vars supplied-p-p body
1497                                             aux-vars aux-vals cont
1498                                             source-name debug-name)
1499   (declare (type optional-dispatch res)
1500            (list default-vars default-vals entry-vars entry-vals vars body
1501                  aux-vars aux-vals)
1502            (type (or continuation null) cont))
1503   (let* ((arg (first vars))
1504          (arg-name (leaf-source-name arg))
1505          (info (lambda-var-arg-info arg))
1506          (supplied-p (arg-info-supplied-p info))
1507          (ep (if supplied-p
1508                  (ir1-convert-hairy-args
1509                   res
1510                   (list* supplied-p arg default-vars)
1511                   (list* (leaf-source-name supplied-p) arg-name default-vals)
1512                   (cons arg entry-vars)
1513                   (list* t arg-name entry-vals)
1514                   (rest vars) t body aux-vars aux-vals cont
1515                   source-name debug-name)
1516                  (ir1-convert-hairy-args
1517                   res
1518                   (cons arg default-vars)
1519                   (cons arg-name default-vals)
1520                   (cons arg entry-vars)
1521                   (cons arg-name entry-vals)
1522                   (rest vars) supplied-p-p body aux-vars aux-vals cont
1523                   source-name debug-name))))
1524
1525     (convert-optional-entry ep default-vars default-vals
1526                             (if supplied-p
1527                                 (list (arg-info-default info) nil)
1528                                 (list (arg-info-default info))))))
1529
1530 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
1531 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
1532 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
1533 ;;;
1534 ;;; The most interesting thing that we do is parse keywords. We create
1535 ;;; a bunch of temporary variables to hold the result of the parse,
1536 ;;; and then loop over the supplied arguments, setting the appropriate
1537 ;;; temps for the supplied keyword. Note that it is significant that
1538 ;;; we iterate over the keywords in reverse order --- this implements
1539 ;;; the CL requirement that (when a keyword appears more than once)
1540 ;;; the first value is used.
1541 ;;;
1542 ;;; If there is no supplied-p var, then we initialize the temp to the
1543 ;;; default and just pass the temp into the main entry. Since
1544 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
1545 ;;; know that the default is constant, and thus safe to evaluate out
1546 ;;; of order.
1547 ;;;
1548 ;;; If there is a supplied-p var, then we create temps for both the
1549 ;;; value and the supplied-p, and pass them into the main entry,
1550 ;;; letting it worry about defaulting.
1551 ;;;
1552 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
1553 ;;; until we have scanned all the keywords.
1554 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
1555   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
1556   (collect ((arg-vars)
1557             (arg-vals (reverse entry-vals))
1558             (temps)
1559             (body))
1560
1561     (dolist (var (reverse entry-vars))
1562       (arg-vars (make-lambda-var :%source-name (leaf-source-name var)
1563                                  :type (leaf-type var)
1564                                  :where-from (leaf-where-from var))))
1565
1566     (let* ((n-context (gensym "N-CONTEXT-"))
1567            (context-temp (make-lambda-var :%source-name n-context))
1568            (n-count (gensym "N-COUNT-"))
1569            (count-temp (make-lambda-var :%source-name n-count
1570                                         :type (specifier-type 'index))))
1571
1572       (arg-vars context-temp count-temp)
1573
1574       (when rest
1575         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
1576       (when morep
1577         (arg-vals n-context)
1578         (arg-vals n-count))
1579
1580       (when (optional-dispatch-keyp res)
1581         (let ((n-index (gensym "N-INDEX-"))
1582               (n-key (gensym "N-KEY-"))
1583               (n-value-temp (gensym "N-VALUE-TEMP-"))
1584               (n-allowp (gensym "N-ALLOWP-"))
1585               (n-losep (gensym "N-LOSEP-"))
1586               (allowp (or (optional-dispatch-allowp res)
1587                           (policy *lexenv* (zerop safety)))))
1588
1589           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
1590           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
1591
1592           (collect ((tests))
1593             (dolist (key keys)
1594               (let* ((info (lambda-var-arg-info key))
1595                      (default (arg-info-default info))
1596                      (keyword (arg-info-key info))
1597                      (supplied-p (arg-info-supplied-p info))
1598                      (n-value (gensym "N-VALUE-")))
1599                 (temps `(,n-value ,default))
1600                 (cond (supplied-p
1601                        (let ((n-supplied (gensym "N-SUPPLIED-")))
1602                          (temps n-supplied)
1603                          (arg-vals n-value n-supplied)
1604                          (tests `((eq ,n-key ',keyword)
1605                                   (setq ,n-supplied t)
1606                                   (setq ,n-value ,n-value-temp)))))
1607                       (t
1608                        (arg-vals n-value)
1609                        (tests `((eq ,n-key ',keyword)
1610                                 (setq ,n-value ,n-value-temp)))))))
1611
1612             (unless allowp
1613               (temps n-allowp n-losep)
1614               (tests `((eq ,n-key :allow-other-keys)
1615                        (setq ,n-allowp ,n-value-temp)))
1616               (tests `(t
1617                        (setq ,n-losep ,n-key))))
1618
1619             (body
1620              `(when (oddp ,n-count)
1621                 (%odd-key-arguments-error)))
1622
1623             (body
1624              `(locally
1625                 (declare (optimize (safety 0)))
1626                 (loop
1627                   (when (minusp ,n-index) (return))
1628                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
1629                   (decf ,n-index)
1630                   (setq ,n-key (%more-arg ,n-context ,n-index))
1631                   (decf ,n-index)
1632                   (cond ,@(tests)))))
1633
1634             (unless allowp
1635               (body `(when (and ,n-losep (not ,n-allowp))
1636                        (%unknown-key-argument-error ,n-losep)))))))
1637
1638       (let ((ep (ir1-convert-lambda-body
1639                  `((let ,(temps)
1640                      ,@(body)
1641                      (%funcall ,(optional-dispatch-main-entry res)
1642                                . ,(arg-vals)))) ; FIXME: What is the '.'? ,@?
1643                  (arg-vars)
1644                  :debug-name (debug-namify "~S processing" '&more))))
1645         (setf (optional-dispatch-more-entry res) ep))))
1646
1647   (values))
1648
1649 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
1650 ;;; or &KEY arg. The arguments are similar to that function, but we
1651 ;;; split off any &REST arg and pass it in separately. REST is the
1652 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
1653 ;;; the &KEY argument vars.
1654 ;;;
1655 ;;; When there are &KEY arguments, we introduce temporary gensym
1656 ;;; variables to hold the values while keyword defaulting is in
1657 ;;; progress to get the required sequential binding semantics.
1658 ;;;
1659 ;;; This gets interesting mainly when there are &KEY arguments with
1660 ;;; supplied-p vars or non-constant defaults. In either case, pass in
1661 ;;; a supplied-p var. If the default is non-constant, we introduce an
1662 ;;; IF in the main entry that tests the supplied-p var and decides
1663 ;;; whether to evaluate the default or not. In this case, the real
1664 ;;; incoming value is NIL, so we must union NULL with the declared
1665 ;;; type when computing the type for the main entry's argument.
1666 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
1667                              rest more-context more-count keys supplied-p-p
1668                              body aux-vars aux-vals cont
1669                              source-name debug-name)
1670   (declare (type optional-dispatch res)
1671            (list default-vars default-vals entry-vars entry-vals keys body
1672                  aux-vars aux-vals)
1673            (type (or continuation null) cont))
1674   (collect ((main-vars (reverse default-vars))
1675             (main-vals default-vals cons)
1676             (bind-vars)
1677             (bind-vals))
1678     (when rest
1679       (main-vars rest)
1680       (main-vals '()))
1681     (when more-context
1682       (main-vars more-context)
1683       (main-vals nil)
1684       (main-vars more-count)
1685       (main-vals 0))
1686
1687     (dolist (key keys)
1688       (let* ((info (lambda-var-arg-info key))
1689              (default (arg-info-default info))
1690              (hairy-default (not (sb!xc:constantp default)))
1691              (supplied-p (arg-info-supplied-p info))
1692              (n-val (make-symbol (format nil
1693                                          "~A-DEFAULTING-TEMP"
1694                                          (leaf-source-name key))))
1695              (key-type (leaf-type key))
1696              (val-temp (make-lambda-var
1697                         :%source-name n-val
1698                         :type (if hairy-default
1699                                   (type-union key-type (specifier-type 'null))
1700                                   key-type))))
1701         (main-vars val-temp)
1702         (bind-vars key)
1703         (cond ((or hairy-default supplied-p)
1704                (let* ((n-supplied (gensym "N-SUPPLIED-"))
1705                       (supplied-temp (make-lambda-var
1706                                       :%source-name n-supplied)))
1707                  (unless supplied-p
1708                    (setf (arg-info-supplied-p info) supplied-temp))
1709                  (when hairy-default
1710                    (setf (arg-info-default info) nil))
1711                  (main-vars supplied-temp)
1712                  (cond (hairy-default
1713                         (main-vals nil nil)
1714                         (bind-vals `(if ,n-supplied ,n-val ,default)))
1715                        (t
1716                         (main-vals default nil)
1717                         (bind-vals n-val)))
1718                  (when supplied-p
1719                    (bind-vars supplied-p)
1720                    (bind-vals n-supplied))))
1721               (t
1722                (main-vals (arg-info-default info))
1723                (bind-vals n-val)))))
1724
1725     (let* ((main-entry (ir1-convert-lambda-body
1726                         body (main-vars)
1727                         :aux-vars (append (bind-vars) aux-vars)
1728                         :aux-vals (append (bind-vals) aux-vals)
1729                         :result cont
1730                         :debug-name (debug-namify "varargs entry point for ~A"
1731                                                   (as-debug-name source-name
1732                                                                  debug-name))))
1733            (last-entry (convert-optional-entry main-entry default-vars
1734                                                (main-vals) ())))
1735       (setf (optional-dispatch-main-entry res) main-entry)
1736       (convert-more-entry res entry-vars entry-vals rest more-context keys)
1737
1738       (push (if supplied-p-p
1739                 (convert-optional-entry last-entry entry-vars entry-vals ())
1740                 last-entry)
1741             (optional-dispatch-entry-points res))
1742       last-entry)))
1743
1744 ;;; This function generates the entry point functions for the
1745 ;;; OPTIONAL-DISPATCH RES. We accomplish this by recursion on the list
1746 ;;; of arguments, analyzing the arglist on the way down and generating
1747 ;;; entry points on the way up.
1748 ;;;
1749 ;;; DEFAULT-VARS is a reversed list of all the argument vars processed
1750 ;;; so far, including supplied-p vars. DEFAULT-VALS is a list of the
1751 ;;; names of the DEFAULT-VARS.
1752 ;;;
1753 ;;; ENTRY-VARS is a reversed list of processed argument vars,
1754 ;;; excluding supplied-p vars. ENTRY-VALS is a list things that can be
1755 ;;; evaluated to get the values for all the vars from the ENTRY-VARS.
1756 ;;; It has the var name for each required or optional arg, and has T
1757 ;;; for each supplied-p arg.
1758 ;;;
1759 ;;; VARS is a list of the LAMBDA-VAR structures for arguments that
1760 ;;; haven't been processed yet. SUPPLIED-P-P is true if a supplied-p
1761 ;;; argument has already been processed; only in this case are the
1762 ;;; DEFAULT-XXX and ENTRY-XXX different.
1763 ;;;
1764 ;;; The result at each point is a lambda which should be called by the
1765 ;;; above level to default the remaining arguments and evaluate the
1766 ;;; body. We cause the body to be evaluated by converting it and
1767 ;;; returning it as the result when the recursion bottoms out.
1768 ;;;
1769 ;;; Each level in the recursion also adds its entry point function to
1770 ;;; the result OPTIONAL-DISPATCH. For most arguments, the defaulting
1771 ;;; function and the entry point function will be the same, but when
1772 ;;; SUPPLIED-P args are present they may be different.
1773 ;;;
1774 ;;; When we run into a &REST or &KEY arg, we punt out to
1775 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
1776 (defun ir1-convert-hairy-args (res default-vars default-vals
1777                                    entry-vars entry-vals
1778                                    vars supplied-p-p body aux-vars
1779                                    aux-vals cont
1780                                    source-name debug-name)
1781   (declare (type optional-dispatch res)
1782            (list default-vars default-vals entry-vars entry-vals vars body
1783                  aux-vars aux-vals)
1784            (type (or continuation null) cont))
1785   (cond ((not vars)
1786          (if (optional-dispatch-keyp res)
1787              ;; Handle &KEY with no keys...
1788              (ir1-convert-more res default-vars default-vals
1789                                entry-vars entry-vals
1790                                nil nil nil vars supplied-p-p body aux-vars
1791                                aux-vals cont source-name debug-name)
1792              (let ((fun (ir1-convert-lambda-body
1793                          body (reverse default-vars)
1794                          :aux-vars aux-vars
1795                          :aux-vals aux-vals
1796                          :result cont
1797                          :debug-name (debug-namify
1798                                       "hairy arg processor for ~A"
1799                                       (as-debug-name source-name
1800                                                      debug-name)))))
1801                (setf (optional-dispatch-main-entry res) fun)
1802                (push (if supplied-p-p
1803                          (convert-optional-entry fun entry-vars entry-vals ())
1804                          fun)
1805                      (optional-dispatch-entry-points res))
1806                fun)))
1807         ((not (lambda-var-arg-info (first vars)))
1808          (let* ((arg (first vars))
1809                 (nvars (cons arg default-vars))
1810                 (nvals (cons (leaf-source-name arg) default-vals)))
1811            (ir1-convert-hairy-args res nvars nvals nvars nvals
1812                                    (rest vars) nil body aux-vars aux-vals
1813                                    cont
1814                                    source-name debug-name)))
1815         (t
1816          (let* ((arg (first vars))
1817                 (info (lambda-var-arg-info arg))
1818                 (kind (arg-info-kind info)))
1819            (ecase kind
1820              (:optional
1821               (let ((ep (generate-optional-default-entry
1822                          res default-vars default-vals
1823                          entry-vars entry-vals vars supplied-p-p body
1824                          aux-vars aux-vals cont
1825                          source-name debug-name)))
1826                 (push (if supplied-p-p
1827                           (convert-optional-entry ep entry-vars entry-vals ())
1828                           ep)
1829                       (optional-dispatch-entry-points res))
1830                 ep))
1831              (:rest
1832               (ir1-convert-more res default-vars default-vals
1833                                 entry-vars entry-vals
1834                                 arg nil nil (rest vars) supplied-p-p body
1835                                 aux-vars aux-vals cont
1836                                 source-name debug-name))
1837              (:more-context
1838               (ir1-convert-more res default-vars default-vals
1839                                 entry-vars entry-vals
1840                                 nil arg (second vars) (cddr vars) supplied-p-p
1841                                 body aux-vars aux-vals cont
1842                                 source-name debug-name))
1843              (:keyword
1844               (ir1-convert-more res default-vars default-vals
1845                                 entry-vars entry-vals
1846                                 nil nil nil vars supplied-p-p body aux-vars
1847                                 aux-vals cont source-name debug-name)))))))
1848
1849 ;;; This function deals with the case where we have to make an
1850 ;;; OPTIONAL-DISPATCH to represent a LAMBDA. We cons up the result and
1851 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
1852 ;;; figure out the MIN-ARGS and MAX-ARGS.
1853 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals cont
1854                                       &key
1855                                       (source-name '.anonymous.)
1856                                       (debug-name (debug-namify
1857                                                    "OPTIONAL-DISPATCH ~S"
1858                                                    vars)))
1859   (declare (list body vars aux-vars aux-vals) (type continuation cont))
1860   (let ((res (make-optional-dispatch :arglist vars
1861                                      :allowp allowp
1862                                      :keyp keyp
1863                                      :%source-name source-name
1864                                      :%debug-name debug-name))
1865         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
1866     (aver-live-component *current-component*)
1867     (push res (component-new-funs *current-component*))
1868     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
1869                             cont source-name debug-name)
1870     (setf (optional-dispatch-min-args res) min)
1871     (setf (optional-dispatch-max-args res)
1872           (+ (1- (length (optional-dispatch-entry-points res))) min))
1873
1874     (flet ((frob (ep)
1875              (when ep
1876                (setf (functional-kind ep) :optional)
1877                (setf (leaf-ever-used ep) t)
1878                (setf (lambda-optional-dispatch ep) res))))
1879       (dolist (ep (optional-dispatch-entry-points res)) (frob ep))
1880       (frob (optional-dispatch-more-entry res))
1881       (frob (optional-dispatch-main-entry res)))
1882
1883     res))
1884
1885 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
1886 (defun ir1-convert-lambda (form &key (source-name '.anonymous.) debug-name)
1887
1888   (unless (consp form)
1889     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
1890                     (type-of form)
1891                     form))
1892   (unless (eq (car form) 'lambda)
1893     (compiler-error "~S was expected but ~S was found:~%  ~S"
1894                     'lambda
1895                     (car form)
1896                     form))
1897   (unless (and (consp (cdr form)) (listp (cadr form)))
1898     (compiler-error
1899      "The lambda expression has a missing or non-list lambda list:~%  ~S"
1900      form))
1901
1902   (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
1903       (make-lambda-vars (cadr form))
1904     (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr form))
1905       (let* ((result-cont (make-continuation))
1906              (*lexenv* (process-decls decls
1907                                       (append aux-vars vars)
1908                                       nil result-cont))
1909              (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
1910                       (ir1-convert-hairy-lambda forms vars keyp
1911                                                 allow-other-keys
1912                                                 aux-vars aux-vals result-cont
1913                                                 :source-name source-name
1914                                                 :debug-name debug-name)
1915                       (ir1-convert-lambda-body forms vars
1916                                                :aux-vars aux-vars
1917                                                :aux-vals aux-vals
1918                                                :result result-cont
1919                                                :source-name source-name
1920                                                :debug-name debug-name))))
1921         (setf (functional-inline-expansion res) form)
1922         (setf (functional-arg-documentation res) (cadr form))
1923         res))))
1924 \f
1925 ;;;; defining global functions
1926
1927 ;;; Convert FUN as a lambda in the null environment, but use the
1928 ;;; current compilation policy. Note that FUN may be a
1929 ;;; LAMBDA-WITH-LEXENV, so we may have to augment the environment to
1930 ;;; reflect the state at the definition site.
1931 (defun ir1-convert-inline-lambda (fun &key
1932                                       (source-name '.anonymous.)
1933                                       debug-name)
1934   (destructuring-bind (decls macros symbol-macros &rest body)
1935                       (if (eq (car fun) 'lambda-with-lexenv)
1936                           (cdr fun)
1937                           `(() () () . ,(cdr fun)))
1938     (let ((*lexenv* (make-lexenv
1939                      :default (process-decls decls nil nil
1940                                              (make-continuation)
1941                                              (make-null-lexenv))
1942                      :vars (copy-list symbol-macros)
1943                      :funs (mapcar (lambda (x)
1944                                      `(,(car x) .
1945                                        (macro . ,(coerce (cdr x) 'function))))
1946                                    macros)
1947                      :policy (lexenv-policy *lexenv*))))
1948       (ir1-convert-lambda `(lambda ,@body)
1949                           :source-name source-name
1950                           :debug-name debug-name))))
1951
1952 ;;; Get a DEFINED-FUN object for a function we are about to
1953 ;;; define. If the function has been forward referenced, then
1954 ;;; substitute for the previous references.
1955 (defun get-defined-fun (name)
1956   (proclaim-as-fun-name name)
1957   (let ((found (find-free-fun name "shouldn't happen! (defined-fun)")))
1958     (note-name-defined name :function)
1959     (cond ((not (defined-fun-p found))
1960            (aver (not (info :function :inlinep name)))
1961            (let* ((where-from (leaf-where-from found))
1962                   (res (make-defined-fun
1963                         :%source-name name
1964                         :where-from (if (eq where-from :declared)
1965                                         :declared :defined)
1966                         :type (leaf-type found))))
1967              (substitute-leaf res found)
1968              (setf (gethash name *free-funs*) res)))
1969           ;; If *FREE-FUNS* has a previously converted definition
1970           ;; for this name, then blow it away and try again.
1971           ((defined-fun-functional found)
1972            (remhash name *free-funs*)
1973            (get-defined-fun name))
1974           (t found))))
1975
1976 ;;; Check a new global function definition for consistency with
1977 ;;; previous declaration or definition, and assert argument/result
1978 ;;; types if appropriate. This assertion is suppressed by the
1979 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
1980 ;;; check their argument types as a consequence of type dispatching.
1981 ;;; This avoids redundant checks such as NUMBERP on the args to +, etc.
1982 (defun assert-new-definition (var fun)
1983   (let ((type (leaf-type var))
1984         (for-real (eq (leaf-where-from var) :declared))
1985         (info (info :function :info (leaf-source-name var))))
1986     (assert-definition-type
1987      fun type
1988      ;; KLUDGE: Common Lisp is such a dynamic language that in general
1989      ;; all we can do here in general is issue a STYLE-WARNING. It
1990      ;; would be nice to issue a full WARNING in the special case of
1991      ;; of type mismatches within a compilation unit (as in section
1992      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
1993      ;; keep track of whether the mismatched data came from the same
1994      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
1995      :lossage-fun #'compiler-style-warn
1996      :unwinnage-fun (cond (info #'compiler-style-warn)
1997                           (for-real #'compiler-note)
1998                           (t nil))
1999      :really-assert
2000      (and for-real
2001           (not (and info
2002                     (ir1-attributep (fun-info-attributes info)
2003                                     explicit-check))))
2004      :where (if for-real
2005                 "previous declaration"
2006                 "previous definition"))))
2007
2008 ;;; Convert a lambda doing all the basic stuff we would do if we were
2009 ;;; converting a DEFUN. In the old CMU CL system, this was used both
2010 ;;; by the %DEFUN translator and for global inline expansion, but
2011 ;;; since sbcl-0.pre7.something %DEFUN does things differently.
2012 ;;; FIXME: And now it's probably worth rethinking whether this
2013 ;;; function is a good idea.
2014 ;;;
2015 ;;; Unless a :INLINE function, we temporarily clobber the inline
2016 ;;; expansion. This prevents recursive inline expansion of
2017 ;;; opportunistic pseudo-inlines.
2018 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
2019   (declare (cons lambda) (function converter) (type defined-fun var))
2020   (let ((var-expansion (defined-fun-inline-expansion var)))
2021     (unless (eq (defined-fun-inlinep var) :inline)
2022       (setf (defined-fun-inline-expansion var) nil))
2023     (let* ((name (leaf-source-name var))
2024            (fun (funcall converter lambda :source-name name))
2025            (fun-info (info :function :info name)))
2026       (setf (functional-inlinep fun) (defined-fun-inlinep var))
2027       (assert-new-definition var fun)
2028       (setf (defined-fun-inline-expansion var) var-expansion)
2029       ;; If definitely not an interpreter stub, then substitute for any
2030       ;; old references.
2031       (unless (or (eq (defined-fun-inlinep var) :notinline)
2032                   (not *block-compile*)
2033                   (and fun-info
2034                        (or (fun-info-transforms fun-info)
2035                            (fun-info-templates fun-info)
2036                            (fun-info-ir2-convert fun-info))))
2037         (substitute-leaf fun var)
2038         ;; If in a simple environment, then we can allow backward
2039         ;; references to this function from following top level forms.
2040         (when expansion (setf (defined-fun-functional var) fun)))
2041       fun)))
2042
2043 ;;; the even-at-compile-time part of DEFUN
2044 ;;;
2045 ;;; The INLINE-EXPANSION is a LAMBDA-WITH-LEXENV, or NIL if there is
2046 ;;; no inline expansion.
2047 (defun %compiler-defun (name lambda-with-lexenv)
2048
2049   (let ((defined-fun nil)) ; will be set below if we're in the compiler
2050     
2051     (when (boundp '*lexenv*) ; when in the compiler
2052       (when sb!xc:*compile-print*
2053         (compiler-mumble "~&; recognizing DEFUN ~S~%" name))
2054       (remhash name *free-funs*)
2055       (setf defined-fun (get-defined-fun name)))
2056
2057     (become-defined-fun-name name)
2058
2059     (cond (lambda-with-lexenv
2060            (setf (info :function :inline-expansion-designator name)
2061                  lambda-with-lexenv)
2062            (when defined-fun 
2063              (setf (defined-fun-inline-expansion defined-fun)
2064                    lambda-with-lexenv)))
2065           (t
2066            (clear-info :function :inline-expansion-designator name)))
2067
2068     ;; old CMU CL comment:
2069     ;;   If there is a type from a previous definition, blast it,
2070     ;;   since it is obsolete.
2071     (when (and defined-fun
2072                (eq (leaf-where-from defined-fun) :defined))
2073       (setf (leaf-type defined-fun)
2074             ;; FIXME: If this is a block compilation thing, shouldn't
2075             ;; we be setting the type to the full derived type for the
2076             ;; definition, instead of this most general function type?
2077             (specifier-type 'function))))
2078
2079   (values))