fd0a643e5ec5d283e89f8b2870b576afe98a7096
[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 FUN is a LEAF. FORM is
716 ;;; the source for the call. We return the COMBINATION node so that
717 ;;; the caller can 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
726 ;;; node. FUN-CONT is the continuation which yields the function to
727 ;;; call. ARGS is the list of arguments for the call, which defaults
728 ;;; to the cdr of source. We return the COMBINATION node.
729 (defun ir1-convert-combination-args (fun-cont cont args)
730   (declare (type continuation fun-cont cont) (list args))
731   (let ((node (make-combination fun-cont)))
732     (setf (continuation-dest fun-cont) node)
733     (assert-continuation-type fun-cont
734                               (specifier-type '(or function symbol)))
735     (collect ((arg-conts))
736       (let ((this-start fun-cont))
737         (dolist (arg args)
738           (let ((this-cont (make-continuation node)))
739             (ir1-convert this-start this-cont arg)
740             (setq this-start this-cont)
741             (arg-conts this-cont)))
742         (link-node-to-previous-continuation node this-start)
743         (use-continuation node cont)
744         (setf (combination-args node) (arg-conts))))
745     node))
746
747 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
748 ;;; source transforms and try out any inline expansion. If there is no
749 ;;; expansion, but is :INLINE, then give an efficiency note (unless a
750 ;;; known function which will quite possibly be open-coded.) Next, we
751 ;;; go to ok-combination conversion.
752 (defun ir1-convert-srctran (start cont var form)
753   (declare (type continuation start cont) (type global-var var))
754   (let ((inlinep (when (defined-fun-p var)
755                    (defined-fun-inlinep var))))
756     (if (eq inlinep :notinline)
757         (ir1-convert-combination start cont form var)
758         (let ((transform (info :function
759                                :source-transform
760                                (leaf-source-name var))))
761           (if transform
762               (multiple-value-bind (result pass) (funcall transform form)
763                 (if pass
764                     (ir1-convert-maybe-predicate start cont form var)
765                     (ir1-convert start cont result)))
766               (ir1-convert-maybe-predicate start cont form var))))))
767
768 ;;; If the function has the PREDICATE attribute, and the CONT's DEST
769 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
770 ;;; predicate always appears in a conditional context.
771 ;;;
772 ;;; If the function isn't a predicate, then we call
773 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
774 (defun ir1-convert-maybe-predicate (start cont form var)
775   (declare (type continuation start cont) (list form) (type global-var var))
776   (let ((info (info :function :info (leaf-source-name var))))
777     (if (and info
778              (ir1-attributep (fun-info-attributes info) predicate)
779              (not (if-p (continuation-dest cont))))
780         (ir1-convert start cont `(if ,form t nil))
781         (ir1-convert-combination-checking-type start cont form var))))
782
783 ;;; Actually really convert a global function call that we are allowed
784 ;;; to early-bind.
785 ;;;
786 ;;; If we know the function type of the function, then we check the
787 ;;; call for syntactic legality with respect to the declared function
788 ;;; type. If it is impossible to determine whether the call is correct
789 ;;; due to non-constant keywords, then we give up, marking the call as
790 ;;; :FULL to inhibit further error messages. We return true when the
791 ;;; call is legal.
792 ;;;
793 ;;; If the call is legal, we also propagate type assertions from the
794 ;;; function type to the arg and result continuations. We do this now
795 ;;; so that IR1 optimize doesn't have to redundantly do the check
796 ;;; later so that it can do the type propagation.
797 (defun ir1-convert-combination-checking-type (start cont form var)
798   (declare (type continuation start cont) (list form) (type leaf var))
799   (let* ((node (ir1-convert-combination start cont form var))
800          (fun-cont (basic-combination-fun node))
801          (type (leaf-type var)))
802     (when (validate-call-type node type t)
803       (setf (continuation-%derived-type fun-cont) type)
804       (setf (continuation-reoptimize fun-cont) nil)
805       (setf (continuation-%type-check fun-cont) nil)))
806   (values))
807
808 ;;; Convert a call to a local function. If the function has already
809 ;;; been LET converted, then throw FUN to LOCAL-CALL-LOSSAGE. This
810 ;;; should only happen when we are converting inline expansions for
811 ;;; local functions during optimization.
812 (defun ir1-convert-local-combination (start cont form fun)
813   (if (functional-kind fun)
814       (throw 'local-call-lossage fun)
815       (ir1-convert-combination start cont form
816                                (maybe-reanalyze-fun fun))))
817 \f
818 ;;;; PROCESS-DECLS
819
820 ;;; Given a list of LAMBDA-VARs and a variable name, return the
821 ;;; LAMBDA-VAR for that name, or NIL if it isn't found. We return the
822 ;;; *last* variable with that name, since LET* bindings may be
823 ;;; duplicated, and declarations always apply to the last.
824 (declaim (ftype (function (list symbol) (or lambda-var list))
825                 find-in-bindings))
826 (defun find-in-bindings (vars name)
827   (let ((found nil))
828     (dolist (var vars)
829       (cond ((leaf-p var)
830              (when (eq (leaf-source-name var) name)
831                (setq found var))
832              (let ((info (lambda-var-arg-info var)))
833                (when info
834                  (let ((supplied-p (arg-info-supplied-p info)))
835                    (when (and supplied-p
836                               (eq (leaf-source-name supplied-p) name))
837                      (setq found supplied-p))))))
838             ((and (consp var) (eq (car var) name))
839              (setf found (cdr var)))))
840     found))
841
842 ;;; Called by Process-Decls to deal with a variable type declaration.
843 ;;; If a lambda-var being bound, we intersect the type with the vars
844 ;;; type, otherwise we add a type-restriction on the var. If a symbol
845 ;;; macro, we just wrap a THE around the expansion.
846 (defun process-type-decl (decl res vars)
847   (declare (list decl vars) (type lexenv res))
848   (let ((type (specifier-type (first decl))))
849     (collect ((restr nil cons)
850               (new-vars nil cons))
851       (dolist (var-name (rest decl))
852         (let* ((bound-var (find-in-bindings vars var-name))
853                (var (or bound-var
854                         (lexenv-find var-name vars)
855                         (find-free-var var-name))))
856           (etypecase var
857             (leaf
858              (let* ((old-type (or (lexenv-find var type-restrictions)
859                                   (leaf-type var)))
860                     (int (if (or (fun-type-p type)
861                                  (fun-type-p old-type))
862                              type
863                              (type-approx-intersection2 old-type type))))
864                (cond ((eq int *empty-type*)
865                       (unless (policy *lexenv* (= inhibit-warnings 3))
866                         (compiler-warn
867                          "The type declarations ~S and ~S for ~S conflict."
868                          (type-specifier old-type) (type-specifier type)
869                          var-name)))
870                      (bound-var (setf (leaf-type bound-var) int))
871                      (t
872                       (restr (cons var int))))))
873             (cons
874              ;; FIXME: non-ANSI weirdness
875              (aver (eq (car var) 'MACRO))
876              (new-vars `(,var-name . (MACRO . (the ,(first decl)
877                                                    ,(cdr var))))))
878             (heap-alien-info
879              (compiler-error
880               "~S is an alien variable, so its type can't be declared."
881               var-name)))))
882
883       (if (or (restr) (new-vars))
884           (make-lexenv :default res
885                        :type-restrictions (restr)
886                        :vars (new-vars))
887           res))))
888
889 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
890 ;;; declarations for function variables. In addition to allowing
891 ;;; declarations for functions being bound, we must also deal with
892 ;;; declarations that constrain the type of lexically apparent
893 ;;; functions.
894 (defun process-ftype-decl (spec res names fvars)
895   (declare (list spec names fvars) (type lexenv res))
896   (let ((type (specifier-type spec)))
897     (collect ((res nil cons))
898       (dolist (name names)
899         (let ((found (find name fvars
900                            :key #'leaf-source-name
901                            :test #'equal)))
902           (cond
903            (found
904             (setf (leaf-type found) type)
905             (assert-definition-type found type
906                                     :unwinnage-fun #'compiler-note
907                                     :where "FTYPE declaration"))
908            (t
909             (res (cons (find-lexically-apparent-fun
910                         name "in a function type declaration")
911                        type))))))
912       (if (res)
913           (make-lexenv :default res :type-restrictions (res))
914           res))))
915
916 ;;; Process a special declaration, returning a new LEXENV. A non-bound
917 ;;; special declaration is instantiated by throwing a special variable
918 ;;; into the variables.
919 (defun process-special-decl (spec res vars)
920   (declare (list spec vars) (type lexenv res))
921   (collect ((new-venv nil cons))
922     (dolist (name (cdr spec))
923       (let ((var (find-in-bindings vars name)))
924         (etypecase var
925           (cons
926            (aver (eq (car var) 'MACRO))
927            (compiler-error
928             "~S is a symbol-macro and thus can't be declared special."
929             name))
930           (lambda-var
931            (when (lambda-var-ignorep var)
932              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
933              ;; requires that this be a STYLE-WARNING, not a full WARNING.
934              (compiler-style-warn
935               "The ignored variable ~S is being declared special."
936               name))
937            (setf (lambda-var-specvar var)
938                  (specvar-for-binding name)))
939           (null
940            (unless (assoc name (new-venv) :test #'eq)
941              (new-venv (cons name (specvar-for-binding name))))))))
942     (if (new-venv)
943         (make-lexenv :default res :vars (new-venv))
944         res)))
945
946 ;;; Return a DEFINED-FUN which copies a GLOBAL-VAR but for its INLINEP.
947 (defun make-new-inlinep (var inlinep)
948   (declare (type global-var var) (type inlinep inlinep))
949   (let ((res (make-defined-fun
950               :%source-name (leaf-source-name var)
951               :where-from (leaf-where-from var)
952               :type (leaf-type var)
953               :inlinep inlinep)))
954     (when (defined-fun-p var)
955       (setf (defined-fun-inline-expansion res)
956             (defined-fun-inline-expansion var))
957       (setf (defined-fun-functional res)
958             (defined-fun-functional var)))
959     res))
960
961 ;;; Parse an inline/notinline declaration. If it's a local function we're
962 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
963 (defun process-inline-decl (spec res fvars)
964   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
965         (new-fenv ()))
966     (dolist (name (rest spec))
967       (let ((fvar (find name fvars
968                         :key #'leaf-source-name
969                         :test #'equal)))
970         (if fvar
971             (setf (functional-inlinep fvar) sense)
972             (let ((found
973                    (find-lexically-apparent-fun
974                     name "in an inline or notinline declaration")))
975               (etypecase found
976                 (functional
977                  (when (policy *lexenv* (>= speed inhibit-warnings))
978                    (compiler-note "ignoring ~A declaration not at ~
979                                    definition of local function:~%  ~S"
980                                   sense name)))
981                 (global-var
982                  (push (cons name (make-new-inlinep found sense))
983                        new-fenv)))))))
984
985     (if new-fenv
986         (make-lexenv :default res :funs new-fenv)
987         res)))
988
989 ;;; like FIND-IN-BINDINGS, but looks for #'FOO in the FVARS
990 (defun find-in-bindings-or-fbindings (name vars fvars)
991   (declare (list vars fvars))
992   (if (consp name)
993       (destructuring-bind (wot fn-name) name
994         (unless (eq wot 'function)
995           (compiler-error "The function or variable name ~S is unrecognizable."
996                           name))
997         (find fn-name fvars :key #'leaf-source-name :test #'equal))
998       (find-in-bindings vars name)))
999
1000 ;;; Process an ignore/ignorable declaration, checking for various losing
1001 ;;; conditions.
1002 (defun process-ignore-decl (spec vars fvars)
1003   (declare (list spec vars fvars))
1004   (dolist (name (rest spec))
1005     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
1006       (cond
1007        ((not var)
1008         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1009         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1010         (compiler-style-warn "declaring unknown variable ~S to be ignored"
1011                              name))
1012        ;; FIXME: This special case looks like non-ANSI weirdness.
1013        ((and (consp var) (consp (cdr var)) (eq (cadr var) 'macro))
1014         ;; Just ignore the IGNORE decl.
1015         )
1016        ((functional-p var)
1017         (setf (leaf-ever-used var) t))
1018        ((lambda-var-specvar var)
1019         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1020         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1021         (compiler-style-warn "declaring special variable ~S to be ignored"
1022                              name))
1023        ((eq (first spec) 'ignorable)
1024         (setf (leaf-ever-used var) t))
1025        (t
1026         (setf (lambda-var-ignorep var) t)))))
1027   (values))
1028
1029 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
1030 ;;; go away, I think.
1031 (defvar *suppress-values-declaration* nil
1032   #!+sb-doc
1033   "If true, processing of the VALUES declaration is inhibited.")
1034
1035 ;;; Process a single declaration spec, augmenting the specified LEXENV
1036 ;;; RES and returning it as a result. VARS and FVARS are as described in
1037 ;;; PROCESS-DECLS.
1038 (defun process-1-decl (raw-spec res vars fvars cont)
1039   (declare (type list raw-spec vars fvars))
1040   (declare (type lexenv res))
1041   (declare (type continuation cont))
1042   (let ((spec (canonized-decl-spec raw-spec)))
1043     (case (first spec)
1044       (special (process-special-decl spec res vars))
1045       (ftype
1046        (unless (cdr spec)
1047          (compiler-error "No type specified in FTYPE declaration: ~S" spec))
1048        (process-ftype-decl (second spec) res (cddr spec) fvars))
1049       ((inline notinline maybe-inline)
1050        (process-inline-decl spec res fvars))
1051       ((ignore ignorable)
1052        (process-ignore-decl spec vars fvars)
1053        res)
1054       (optimize
1055        (make-lexenv
1056         :default res
1057         :policy (process-optimize-decl spec (lexenv-policy res))))
1058       (type
1059        (process-type-decl (cdr spec) res vars))
1060       (values
1061        (if *suppress-values-declaration*
1062            res
1063            (let ((types (cdr spec)))
1064              (ir1ize-the-or-values (if (eql (length types) 1)
1065                                        (car types)
1066                                        `(values ,@types))
1067                                    cont
1068                                    res
1069                                    'values))))
1070       (dynamic-extent
1071        (when (policy *lexenv* (> speed inhibit-warnings))
1072          (compiler-note
1073           "compiler limitation: ~
1074         ~%  There's no special support for DYNAMIC-EXTENT (so it's ignored)."))
1075        res)
1076       (t
1077        (unless (info :declaration :recognized (first spec))
1078          (compiler-warn "unrecognized declaration ~S" raw-spec))
1079        res))))
1080
1081 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1082 ;;; and FUNCTIONAL structures which are being bound. In addition to
1083 ;;; filling in slots in the leaf structures, we return a new LEXENV
1084 ;;; which reflects pervasive special and function type declarations,
1085 ;;; (NOT)INLINE declarations and OPTIMIZE declarations. CONT is the
1086 ;;; continuation affected by VALUES declarations.
1087 ;;;
1088 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1089 ;;; of LOCALLY.
1090 (defun process-decls (decls vars fvars cont &optional (env *lexenv*))
1091   (declare (list decls vars fvars) (type continuation cont))
1092   (dolist (decl decls)
1093     (dolist (spec (rest decl))
1094       (unless (consp spec)
1095         (compiler-error "malformed declaration specifier ~S in ~S"
1096                         spec
1097                         decl))
1098       (setq env (process-1-decl spec env vars fvars cont))))
1099   env)
1100
1101 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1102 ;;; declaration. If there is a global variable of that name, then
1103 ;;; check that it isn't a constant and return it. Otherwise, create an
1104 ;;; anonymous GLOBAL-VAR.
1105 (defun specvar-for-binding (name)
1106   (cond ((not (eq (info :variable :where-from name) :assumed))
1107          (let ((found (find-free-var name)))
1108            (when (heap-alien-info-p found)
1109              (compiler-error
1110               "~S is an alien variable and so can't be declared special."
1111               name))
1112            (unless (global-var-p found)
1113              (compiler-error
1114               "~S is a constant and so can't be declared special."
1115               name))
1116            found))
1117         (t
1118          (make-global-var :kind :special
1119                           :%source-name name
1120                           :where-from :declared))))
1121 \f
1122 ;;;; LAMBDA hackery
1123
1124 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
1125 ;;;; function representation" before you seriously mess with this
1126 ;;;; stuff.
1127
1128 ;;; Verify that the NAME is a legal name for a variable and return a
1129 ;;; VAR structure for it, filling in info if it is globally special.
1130 ;;; If it is losing, we punt with a COMPILER-ERROR. NAMES-SO-FAR is a
1131 ;;; list of names which have previously been bound. If the NAME is in
1132 ;;; this list, then we error out.
1133 (declaim (ftype (function (t list) lambda-var) varify-lambda-arg))
1134 (defun varify-lambda-arg (name names-so-far)
1135   (declare (inline member))
1136   (unless (symbolp name)
1137     (compiler-error "The lambda variable ~S is not a symbol." name))
1138   (when (member name names-so-far :test #'eq)
1139     (compiler-error "The variable ~S occurs more than once in the lambda-list."
1140                     name))
1141   (let ((kind (info :variable :kind name)))
1142     (when (or (keywordp name) (eq kind :constant))
1143       (compiler-error "The name of the lambda variable ~S is already in use to name a constant."
1144                       name))
1145     (cond ((eq kind :special)
1146            (let ((specvar (find-free-var name)))
1147              (make-lambda-var :%source-name name
1148                               :type (leaf-type specvar)
1149                               :where-from (leaf-where-from specvar)
1150                               :specvar specvar)))
1151           (t
1152            (note-lexical-binding name)
1153            (make-lambda-var :%source-name name)))))
1154
1155 ;;; Make the default keyword for a &KEY arg, checking that the keyword
1156 ;;; isn't already used by one of the VARS. We also check that the
1157 ;;; keyword isn't the magical :ALLOW-OTHER-KEYS.
1158 (declaim (ftype (function (symbol list t) keyword) make-keyword-for-arg))
1159 (defun make-keyword-for-arg (symbol vars keywordify)
1160   (let ((key (if (and keywordify (not (keywordp symbol)))
1161                  (keywordicate symbol)
1162                  symbol)))
1163     (when (eq key :allow-other-keys)
1164       (compiler-error "No &KEY arg can be called :ALLOW-OTHER-KEYS."))
1165     (dolist (var vars)
1166       (let ((info (lambda-var-arg-info var)))
1167         (when (and info
1168                    (eq (arg-info-kind info) :keyword)
1169                    (eq (arg-info-key info) key))
1170           (compiler-error
1171            "The keyword ~S appears more than once in the lambda-list."
1172            key))))
1173     key))
1174
1175 ;;; Parse a lambda list into a list of VAR structures, stripping off
1176 ;;; any &AUX bindings. Each arg name is checked for legality, and
1177 ;;; duplicate names are checked for. If an arg is globally special,
1178 ;;; the var is marked as :SPECIAL instead of :LEXICAL. &KEY,
1179 ;;; &OPTIONAL and &REST args are annotated with an ARG-INFO structure
1180 ;;; which contains the extra information. If we hit something losing,
1181 ;;; we bug out with COMPILER-ERROR. These values are returned:
1182 ;;;  1. a list of the var structures for each top level argument;
1183 ;;;  2. a flag indicating whether &KEY was specified;
1184 ;;;  3. a flag indicating whether other &KEY args are allowed;
1185 ;;;  4. a list of the &AUX variables; and
1186 ;;;  5. a list of the &AUX values.
1187 (declaim (ftype (function (list) (values list boolean boolean list list))
1188                 make-lambda-vars))
1189 (defun make-lambda-vars (list)
1190   (multiple-value-bind (required optional restp rest keyp keys allowp aux
1191                         morep more-context more-count)
1192       (parse-lambda-list list)
1193     (collect ((vars)
1194               (names-so-far)
1195               (aux-vars)
1196               (aux-vals))
1197       (flet (;; PARSE-DEFAULT deals with defaults and supplied-p args
1198              ;; for optionals and keywords args.
1199              (parse-default (spec info)
1200                (when (consp (cdr spec))
1201                  (setf (arg-info-default info) (second spec))
1202                  (when (consp (cddr spec))
1203                    (let* ((supplied-p (third spec))
1204                           (supplied-var (varify-lambda-arg supplied-p
1205                                                            (names-so-far))))
1206                      (setf (arg-info-supplied-p info) supplied-var)
1207                      (names-so-far supplied-p)
1208                      (when (> (length (the list spec)) 3)
1209                        (compiler-error
1210                         "The list ~S is too long to be an arg specifier."
1211                         spec)))))))
1212         
1213         (dolist (name required)
1214           (let ((var (varify-lambda-arg name (names-so-far))))
1215             (vars var)
1216             (names-so-far name)))
1217         
1218         (dolist (spec optional)
1219           (if (atom spec)
1220               (let ((var (varify-lambda-arg spec (names-so-far))))
1221                 (setf (lambda-var-arg-info var) (make-arg-info :kind :optional))
1222                 (vars var)
1223                 (names-so-far spec))
1224               (let* ((name (first spec))
1225                      (var (varify-lambda-arg name (names-so-far)))
1226                      (info (make-arg-info :kind :optional)))
1227                 (setf (lambda-var-arg-info var) info)
1228                 (vars var)
1229                 (names-so-far name)
1230                 (parse-default spec info))))
1231         
1232         (when restp
1233           (let ((var (varify-lambda-arg rest (names-so-far))))
1234             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
1235             (vars var)
1236             (names-so-far rest)))
1237
1238         (when morep
1239           (let ((var (varify-lambda-arg more-context (names-so-far))))
1240             (setf (lambda-var-arg-info var)
1241                   (make-arg-info :kind :more-context))
1242             (vars var)
1243             (names-so-far more-context))
1244           (let ((var (varify-lambda-arg more-count (names-so-far))))
1245             (setf (lambda-var-arg-info var)
1246                   (make-arg-info :kind :more-count))
1247             (vars var)
1248             (names-so-far more-count)))
1249         
1250         (dolist (spec keys)
1251           (cond
1252            ((atom spec)
1253             (let ((var (varify-lambda-arg spec (names-so-far))))
1254               (setf (lambda-var-arg-info var)
1255                     (make-arg-info :kind :keyword
1256                                    :key (make-keyword-for-arg spec
1257                                                               (vars)
1258                                                               t)))
1259               (vars var)
1260               (names-so-far spec)))
1261            ((atom (first spec))
1262             (let* ((name (first spec))
1263                    (var (varify-lambda-arg name (names-so-far)))
1264                    (info (make-arg-info
1265                           :kind :keyword
1266                           :key (make-keyword-for-arg name (vars) t))))
1267               (setf (lambda-var-arg-info var) info)
1268               (vars var)
1269               (names-so-far name)
1270               (parse-default spec info)))
1271            (t
1272             (let ((head (first spec)))
1273               (unless (proper-list-of-length-p head 2)
1274                 (error "malformed &KEY argument specifier: ~S" spec))
1275               (let* ((name (second head))
1276                      (var (varify-lambda-arg name (names-so-far)))
1277                      (info (make-arg-info
1278                             :kind :keyword
1279                             :key (make-keyword-for-arg (first head)
1280                                                        (vars)
1281                                                        nil))))
1282                 (setf (lambda-var-arg-info var) info)
1283                 (vars var)
1284                 (names-so-far name)
1285                 (parse-default spec info))))))
1286         
1287         (dolist (spec aux)
1288           (cond ((atom spec)
1289                  (let ((var (varify-lambda-arg spec nil)))
1290                    (aux-vars var)
1291                    (aux-vals nil)
1292                    (names-so-far spec)))
1293                 (t
1294                  (unless (proper-list-of-length-p spec 1 2)
1295                    (compiler-error "malformed &AUX binding specifier: ~S"
1296                                    spec))
1297                  (let* ((name (first spec))
1298                         (var (varify-lambda-arg name nil)))
1299                    (aux-vars var)
1300                    (aux-vals (second spec))
1301                    (names-so-far name)))))
1302
1303         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
1304
1305 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that we
1306 ;;; sequentially bind each AUX-VAR to the corresponding AUX-VAL before
1307 ;;; converting the body. If there are no bindings, just convert the
1308 ;;; body, otherwise do one binding and recurse on the rest.
1309 ;;;
1310 ;;; FIXME: This could and probably should be converted to use
1311 ;;; SOURCE-NAME and DEBUG-NAME. But I (WHN) don't use &AUX bindings,
1312 ;;; so I'm not motivated. Patches will be accepted...
1313 (defun ir1-convert-aux-bindings (start cont body aux-vars aux-vals)
1314   (declare (type continuation start cont) (list body aux-vars aux-vals))
1315   (if (null aux-vars)
1316       (ir1-convert-progn-body start cont body)
1317       (let ((fun-cont (make-continuation))
1318             (fun (ir1-convert-lambda-body body
1319                                           (list (first aux-vars))
1320                                           :aux-vars (rest aux-vars)
1321                                           :aux-vals (rest aux-vals)
1322                                           :debug-name (debug-namify
1323                                                        "&AUX bindings ~S"
1324                                                        aux-vars))))
1325         (reference-leaf start fun-cont fun)
1326         (ir1-convert-combination-args fun-cont cont
1327                                       (list (first aux-vals)))))
1328   (values))
1329
1330 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that code to bind
1331 ;;; the SPECVAR for each SVAR to the value of the variable is wrapped
1332 ;;; around the body. If there are no special bindings, we just convert
1333 ;;; the body, otherwise we do one special binding and recurse on the
1334 ;;; rest.
1335 ;;;
1336 ;;; We make a cleanup and introduce it into the lexical environment.
1337 ;;; If there are multiple special bindings, the cleanup for the blocks
1338 ;;; will end up being the innermost one. We force CONT to start a
1339 ;;; block outside of this cleanup, causing cleanup code to be emitted
1340 ;;; when the scope is exited.
1341 (defun ir1-convert-special-bindings (start cont body aux-vars aux-vals svars)
1342   (declare (type continuation start cont)
1343            (list body aux-vars aux-vals svars))
1344   (cond
1345    ((null svars)
1346     (ir1-convert-aux-bindings start cont body aux-vars aux-vals))
1347    (t
1348     (continuation-starts-block cont)
1349     (let ((cleanup (make-cleanup :kind :special-bind))
1350           (var (first svars))
1351           (next-cont (make-continuation))
1352           (nnext-cont (make-continuation)))
1353       (ir1-convert start next-cont
1354                    `(%special-bind ',(lambda-var-specvar var) ,var))
1355       (setf (cleanup-mess-up cleanup) (continuation-use next-cont))
1356       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
1357         (ir1-convert next-cont nnext-cont '(%cleanup-point))
1358         (ir1-convert-special-bindings nnext-cont cont body aux-vars aux-vals
1359                                       (rest svars))))))
1360   (values))
1361
1362 ;;; Create a lambda node out of some code, returning the result. The
1363 ;;; bindings are specified by the list of VAR structures VARS. We deal
1364 ;;; with adding the names to the LEXENV-VARS for the conversion. The
1365 ;;; result is added to the NEW-FUNS in the *CURRENT-COMPONENT* and
1366 ;;; linked to the component head and tail.
1367 ;;;
1368 ;;; We detect special bindings here, replacing the original VAR in the
1369 ;;; lambda list with a temporary variable. We then pass a list of the
1370 ;;; special vars to IR1-CONVERT-SPECIAL-BINDINGS, which actually emits
1371 ;;; the special binding code.
1372 ;;;
1373 ;;; We ignore any ARG-INFO in the VARS, trusting that someone else is
1374 ;;; dealing with &nonsense.
1375 ;;;
1376 ;;; AUX-VARS is a list of VAR structures for variables that are to be
1377 ;;; sequentially bound. Each AUX-VAL is a form that is to be evaluated
1378 ;;; to get the initial value for the corresponding AUX-VAR. 
1379 (defun ir1-convert-lambda-body (body
1380                                 vars
1381                                 &key
1382                                 aux-vars
1383                                 aux-vals
1384                                 result
1385                                 (source-name '.anonymous.)
1386                                 debug-name)
1387   (declare (list body vars aux-vars aux-vals)
1388            (type (or continuation null) result))
1389
1390   ;; We're about to try to put new blocks into *CURRENT-COMPONENT*.
1391   (aver-live-component *current-component*)
1392
1393   (let* ((bind (make-bind))
1394          (lambda (make-lambda :vars vars
1395                               :bind bind
1396                               :%source-name source-name
1397                               :%debug-name debug-name))
1398          (result (or result (make-continuation))))
1399
1400     ;; just to check: This function should fail internal assertions if
1401     ;; we didn't set up a valid debug name above.
1402     ;;
1403     ;; (In SBCL we try to make everything have a debug name, since we
1404     ;; lack the omniscient perspective the original implementors used
1405     ;; to decide which things didn't need one.)
1406     (functional-debug-name lambda)
1407
1408     (setf (lambda-home lambda) lambda)
1409     (collect ((svars)
1410               (new-venv nil cons))
1411
1412       (dolist (var vars)
1413         ;; As far as I can see, LAMBDA-VAR-HOME should never have
1414         ;; been set before. Let's make sure. -- WHN 2001-09-29
1415         (aver (null (lambda-var-home var)))
1416         (setf (lambda-var-home var) lambda)
1417         (let ((specvar (lambda-var-specvar var)))
1418           (cond (specvar
1419                  (svars var)
1420                  (new-venv (cons (leaf-source-name specvar) specvar)))
1421                 (t
1422                  (note-lexical-binding (leaf-source-name var))
1423                  (new-venv (cons (leaf-source-name var) var))))))
1424
1425       (let ((*lexenv* (make-lexenv :vars (new-venv)
1426                                    :lambda lambda
1427                                    :cleanup nil)))
1428         (setf (bind-lambda bind) lambda)
1429         (setf (node-lexenv bind) *lexenv*)
1430         
1431         (let ((cont1 (make-continuation))
1432               (cont2 (make-continuation)))
1433           (continuation-starts-block cont1)
1434           (link-node-to-previous-continuation bind cont1)
1435           (use-continuation bind cont2)
1436           (ir1-convert-special-bindings cont2 result body aux-vars aux-vals
1437                                         (svars)))
1438
1439         (let ((block (continuation-block result)))
1440           (when block
1441             (let ((return (make-return :result result :lambda lambda))
1442                   (tail-set (make-tail-set :funs (list lambda)))
1443                   (dummy (make-continuation)))
1444               (setf (lambda-tail-set lambda) tail-set)
1445               (setf (lambda-return lambda) return)
1446               (setf (continuation-dest result) return)
1447               (setf (block-last block) return)
1448               (link-node-to-previous-continuation return result)
1449               (use-continuation return dummy))
1450             (link-blocks block (component-tail *current-component*))))))
1451
1452     (link-blocks (component-head *current-component*) (node-block bind))
1453     (push lambda (component-new-funs *current-component*))
1454
1455     lambda))
1456
1457 ;;; Create the actual entry-point function for an optional entry
1458 ;;; point. The lambda binds copies of each of the VARS, then calls FUN
1459 ;;; with the argument VALS and the DEFAULTS. Presumably the VALS refer
1460 ;;; to the VARS by name. The VALS are passed in in reverse order.
1461 ;;;
1462 ;;; If any of the copies of the vars are referenced more than once,
1463 ;;; then we mark the corresponding var as EVER-USED to inhibit
1464 ;;; "defined but not read" warnings for arguments that are only used
1465 ;;; by default forms.
1466 (defun convert-optional-entry (fun vars vals defaults)
1467   (declare (type clambda fun) (list vars vals defaults))
1468   (let* ((fvars (reverse vars))
1469          (arg-vars (mapcar (lambda (var)
1470                              (unless (lambda-var-specvar var)
1471                                (note-lexical-binding (leaf-source-name var)))
1472                              (make-lambda-var
1473                               :%source-name (leaf-source-name var)
1474                               :type (leaf-type var)
1475                               :where-from (leaf-where-from var)
1476                               :specvar (lambda-var-specvar var)))
1477                            fvars))
1478          (fun (ir1-convert-lambda-body `((%funcall ,fun
1479                                                    ,@(reverse vals)
1480                                                    ,@defaults))
1481                                        arg-vars
1482                                        :debug-name "&OPTIONAL processor")))
1483     (mapc (lambda (var arg-var)
1484             (when (cdr (leaf-refs arg-var))
1485               (setf (leaf-ever-used var) t)))
1486           fvars arg-vars)
1487     fun))
1488
1489 ;;; This function deals with supplied-p vars in optional arguments. If
1490 ;;; the there is no supplied-p arg, then we just call
1491 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
1492 ;;; optional entry that calls the result. If there is a supplied-p
1493 ;;; var, then we add it into the default vars and throw a T into the
1494 ;;; entry values. The resulting entry point function is returned.
1495 (defun generate-optional-default-entry (res default-vars default-vals
1496                                             entry-vars entry-vals
1497                                             vars supplied-p-p body
1498                                             aux-vars aux-vals cont
1499                                             source-name debug-name)
1500   (declare (type optional-dispatch res)
1501            (list default-vars default-vals entry-vars entry-vals vars body
1502                  aux-vars aux-vals)
1503            (type (or continuation null) cont))
1504   (let* ((arg (first vars))
1505          (arg-name (leaf-source-name arg))
1506          (info (lambda-var-arg-info arg))
1507          (supplied-p (arg-info-supplied-p info))
1508          (ep (if supplied-p
1509                  (ir1-convert-hairy-args
1510                   res
1511                   (list* supplied-p arg default-vars)
1512                   (list* (leaf-source-name supplied-p) arg-name default-vals)
1513                   (cons arg entry-vars)
1514                   (list* t arg-name entry-vals)
1515                   (rest vars) t body aux-vars aux-vals cont
1516                   source-name debug-name)
1517                  (ir1-convert-hairy-args
1518                   res
1519                   (cons arg default-vars)
1520                   (cons arg-name default-vals)
1521                   (cons arg entry-vars)
1522                   (cons arg-name entry-vals)
1523                   (rest vars) supplied-p-p body aux-vars aux-vals cont
1524                   source-name debug-name))))
1525
1526     (convert-optional-entry ep default-vars default-vals
1527                             (if supplied-p
1528                                 (list (arg-info-default info) nil)
1529                                 (list (arg-info-default info))))))
1530
1531 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
1532 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
1533 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
1534 ;;;
1535 ;;; The most interesting thing that we do is parse keywords. We create
1536 ;;; a bunch of temporary variables to hold the result of the parse,
1537 ;;; and then loop over the supplied arguments, setting the appropriate
1538 ;;; temps for the supplied keyword. Note that it is significant that
1539 ;;; we iterate over the keywords in reverse order --- this implements
1540 ;;; the CL requirement that (when a keyword appears more than once)
1541 ;;; the first value is used.
1542 ;;;
1543 ;;; If there is no supplied-p var, then we initialize the temp to the
1544 ;;; default and just pass the temp into the main entry. Since
1545 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
1546 ;;; know that the default is constant, and thus safe to evaluate out
1547 ;;; of order.
1548 ;;;
1549 ;;; If there is a supplied-p var, then we create temps for both the
1550 ;;; value and the supplied-p, and pass them into the main entry,
1551 ;;; letting it worry about defaulting.
1552 ;;;
1553 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
1554 ;;; until we have scanned all the keywords.
1555 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
1556   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
1557   (collect ((arg-vars)
1558             (arg-vals (reverse entry-vals))
1559             (temps)
1560             (body))
1561
1562     (dolist (var (reverse entry-vars))
1563       (arg-vars (make-lambda-var :%source-name (leaf-source-name var)
1564                                  :type (leaf-type var)
1565                                  :where-from (leaf-where-from var))))
1566
1567     (let* ((n-context (gensym "N-CONTEXT-"))
1568            (context-temp (make-lambda-var :%source-name n-context))
1569            (n-count (gensym "N-COUNT-"))
1570            (count-temp (make-lambda-var :%source-name n-count
1571                                         :type (specifier-type 'index))))
1572
1573       (arg-vars context-temp count-temp)
1574
1575       (when rest
1576         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
1577       (when morep
1578         (arg-vals n-context)
1579         (arg-vals n-count))
1580
1581       (when (optional-dispatch-keyp res)
1582         (let ((n-index (gensym "N-INDEX-"))
1583               (n-key (gensym "N-KEY-"))
1584               (n-value-temp (gensym "N-VALUE-TEMP-"))
1585               (n-allowp (gensym "N-ALLOWP-"))
1586               (n-losep (gensym "N-LOSEP-"))
1587               (allowp (or (optional-dispatch-allowp res)
1588                           (policy *lexenv* (zerop safety)))))
1589
1590           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
1591           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
1592
1593           (collect ((tests))
1594             (dolist (key keys)
1595               (let* ((info (lambda-var-arg-info key))
1596                      (default (arg-info-default info))
1597                      (keyword (arg-info-key info))
1598                      (supplied-p (arg-info-supplied-p info))
1599                      (n-value (gensym "N-VALUE-")))
1600                 (temps `(,n-value ,default))
1601                 (cond (supplied-p
1602                        (let ((n-supplied (gensym "N-SUPPLIED-")))
1603                          (temps n-supplied)
1604                          (arg-vals n-value n-supplied)
1605                          (tests `((eq ,n-key ',keyword)
1606                                   (setq ,n-supplied t)
1607                                   (setq ,n-value ,n-value-temp)))))
1608                       (t
1609                        (arg-vals n-value)
1610                        (tests `((eq ,n-key ',keyword)
1611                                 (setq ,n-value ,n-value-temp)))))))
1612
1613             (unless allowp
1614               (temps n-allowp n-losep)
1615               (tests `((eq ,n-key :allow-other-keys)
1616                        (setq ,n-allowp ,n-value-temp)))
1617               (tests `(t
1618                        (setq ,n-losep ,n-key))))
1619
1620             (body
1621              `(when (oddp ,n-count)
1622                 (%odd-key-args-error)))
1623
1624             (body
1625              `(locally
1626                 (declare (optimize (safety 0)))
1627                 (loop
1628                   (when (minusp ,n-index) (return))
1629                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
1630                   (decf ,n-index)
1631                   (setq ,n-key (%more-arg ,n-context ,n-index))
1632                   (decf ,n-index)
1633                   (cond ,@(tests)))))
1634
1635             (unless allowp
1636               (body `(when (and ,n-losep (not ,n-allowp))
1637                        (%unknown-key-arg-error ,n-losep)))))))
1638
1639       (let ((ep (ir1-convert-lambda-body
1640                  `((let ,(temps)
1641                      ,@(body)
1642                      (%funcall ,(optional-dispatch-main-entry res)
1643                                . ,(arg-vals)))) ; FIXME: What is the '.'? ,@?
1644                  (arg-vars)
1645                  :debug-name (debug-namify "~S processing" '&more))))
1646         (setf (optional-dispatch-more-entry res) ep))))
1647
1648   (values))
1649
1650 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
1651 ;;; or &KEY arg. The arguments are similar to that function, but we
1652 ;;; split off any &REST arg and pass it in separately. REST is the
1653 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
1654 ;;; the &KEY argument vars.
1655 ;;;
1656 ;;; When there are &KEY arguments, we introduce temporary gensym
1657 ;;; variables to hold the values while keyword defaulting is in
1658 ;;; progress to get the required sequential binding semantics.
1659 ;;;
1660 ;;; This gets interesting mainly when there are &KEY arguments with
1661 ;;; supplied-p vars or non-constant defaults. In either case, pass in
1662 ;;; a supplied-p var. If the default is non-constant, we introduce an
1663 ;;; IF in the main entry that tests the supplied-p var and decides
1664 ;;; whether to evaluate the default or not. In this case, the real
1665 ;;; incoming value is NIL, so we must union NULL with the declared
1666 ;;; type when computing the type for the main entry's argument.
1667 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
1668                              rest more-context more-count keys supplied-p-p
1669                              body aux-vars aux-vals cont
1670                              source-name debug-name)
1671   (declare (type optional-dispatch res)
1672            (list default-vars default-vals entry-vars entry-vals keys body
1673                  aux-vars aux-vals)
1674            (type (or continuation null) cont))
1675   (collect ((main-vars (reverse default-vars))
1676             (main-vals default-vals cons)
1677             (bind-vars)
1678             (bind-vals))
1679     (when rest
1680       (main-vars rest)
1681       (main-vals '()))
1682     (when more-context
1683       (main-vars more-context)
1684       (main-vals nil)
1685       (main-vars more-count)
1686       (main-vals 0))
1687
1688     (dolist (key keys)
1689       (let* ((info (lambda-var-arg-info key))
1690              (default (arg-info-default info))
1691              (hairy-default (not (sb!xc:constantp default)))
1692              (supplied-p (arg-info-supplied-p info))
1693              (n-val (make-symbol (format nil
1694                                          "~A-DEFAULTING-TEMP"
1695                                          (leaf-source-name key))))
1696              (key-type (leaf-type key))
1697              (val-temp (make-lambda-var
1698                         :%source-name n-val
1699                         :type (if hairy-default
1700                                   (type-union key-type (specifier-type 'null))
1701                                   key-type))))
1702         (main-vars val-temp)
1703         (bind-vars key)
1704         (cond ((or hairy-default supplied-p)
1705                (let* ((n-supplied (gensym "N-SUPPLIED-"))
1706                       (supplied-temp (make-lambda-var
1707                                       :%source-name n-supplied)))
1708                  (unless supplied-p
1709                    (setf (arg-info-supplied-p info) supplied-temp))
1710                  (when hairy-default
1711                    (setf (arg-info-default info) nil))
1712                  (main-vars supplied-temp)
1713                  (cond (hairy-default
1714                         (main-vals nil nil)
1715                         (bind-vals `(if ,n-supplied ,n-val ,default)))
1716                        (t
1717                         (main-vals default nil)
1718                         (bind-vals n-val)))
1719                  (when supplied-p
1720                    (bind-vars supplied-p)
1721                    (bind-vals n-supplied))))
1722               (t
1723                (main-vals (arg-info-default info))
1724                (bind-vals n-val)))))
1725
1726     (let* ((main-entry (ir1-convert-lambda-body
1727                         body (main-vars)
1728                         :aux-vars (append (bind-vars) aux-vars)
1729                         :aux-vals (append (bind-vals) aux-vals)
1730                         :result cont
1731                         :debug-name (debug-namify "varargs entry point for ~A"
1732                                                   (as-debug-name source-name
1733                                                                  debug-name))))
1734            (last-entry (convert-optional-entry main-entry default-vars
1735                                                (main-vals) ())))
1736       (setf (optional-dispatch-main-entry res) main-entry)
1737       (convert-more-entry res entry-vars entry-vals rest more-context keys)
1738
1739       (push (if supplied-p-p
1740                 (convert-optional-entry last-entry entry-vars entry-vals ())
1741                 last-entry)
1742             (optional-dispatch-entry-points res))
1743       last-entry)))
1744
1745 ;;; This function generates the entry point functions for the
1746 ;;; OPTIONAL-DISPATCH RES. We accomplish this by recursion on the list
1747 ;;; of arguments, analyzing the arglist on the way down and generating
1748 ;;; entry points on the way up.
1749 ;;;
1750 ;;; DEFAULT-VARS is a reversed list of all the argument vars processed
1751 ;;; so far, including supplied-p vars. DEFAULT-VALS is a list of the
1752 ;;; names of the DEFAULT-VARS.
1753 ;;;
1754 ;;; ENTRY-VARS is a reversed list of processed argument vars,
1755 ;;; excluding supplied-p vars. ENTRY-VALS is a list things that can be
1756 ;;; evaluated to get the values for all the vars from the ENTRY-VARS.
1757 ;;; It has the var name for each required or optional arg, and has T
1758 ;;; for each supplied-p arg.
1759 ;;;
1760 ;;; VARS is a list of the LAMBDA-VAR structures for arguments that
1761 ;;; haven't been processed yet. SUPPLIED-P-P is true if a supplied-p
1762 ;;; argument has already been processed; only in this case are the
1763 ;;; DEFAULT-XXX and ENTRY-XXX different.
1764 ;;;
1765 ;;; The result at each point is a lambda which should be called by the
1766 ;;; above level to default the remaining arguments and evaluate the
1767 ;;; body. We cause the body to be evaluated by converting it and
1768 ;;; returning it as the result when the recursion bottoms out.
1769 ;;;
1770 ;;; Each level in the recursion also adds its entry point function to
1771 ;;; the result OPTIONAL-DISPATCH. For most arguments, the defaulting
1772 ;;; function and the entry point function will be the same, but when
1773 ;;; SUPPLIED-P args are present they may be different.
1774 ;;;
1775 ;;; When we run into a &REST or &KEY arg, we punt out to
1776 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
1777 (defun ir1-convert-hairy-args (res default-vars default-vals
1778                                    entry-vars entry-vals
1779                                    vars supplied-p-p body aux-vars
1780                                    aux-vals cont
1781                                    source-name debug-name)
1782   (declare (type optional-dispatch res)
1783            (list default-vars default-vals entry-vars entry-vals vars body
1784                  aux-vars aux-vals)
1785            (type (or continuation null) cont))
1786   (cond ((not vars)
1787          (if (optional-dispatch-keyp res)
1788              ;; Handle &KEY with no keys...
1789              (ir1-convert-more res default-vars default-vals
1790                                entry-vars entry-vals
1791                                nil nil nil vars supplied-p-p body aux-vars
1792                                aux-vals cont source-name debug-name)
1793              (let ((fun (ir1-convert-lambda-body
1794                          body (reverse default-vars)
1795                          :aux-vars aux-vars
1796                          :aux-vals aux-vals
1797                          :result cont
1798                          :debug-name (debug-namify
1799                                       "hairy arg processor for ~A"
1800                                       (as-debug-name source-name
1801                                                      debug-name)))))
1802                (setf (optional-dispatch-main-entry res) fun)
1803                (push (if supplied-p-p
1804                          (convert-optional-entry fun entry-vars entry-vals ())
1805                          fun)
1806                      (optional-dispatch-entry-points res))
1807                fun)))
1808         ((not (lambda-var-arg-info (first vars)))
1809          (let* ((arg (first vars))
1810                 (nvars (cons arg default-vars))
1811                 (nvals (cons (leaf-source-name arg) default-vals)))
1812            (ir1-convert-hairy-args res nvars nvals nvars nvals
1813                                    (rest vars) nil body aux-vars aux-vals
1814                                    cont
1815                                    source-name debug-name)))
1816         (t
1817          (let* ((arg (first vars))
1818                 (info (lambda-var-arg-info arg))
1819                 (kind (arg-info-kind info)))
1820            (ecase kind
1821              (:optional
1822               (let ((ep (generate-optional-default-entry
1823                          res default-vars default-vals
1824                          entry-vars entry-vals vars supplied-p-p body
1825                          aux-vars aux-vals cont
1826                          source-name debug-name)))
1827                 (push (if supplied-p-p
1828                           (convert-optional-entry ep entry-vars entry-vals ())
1829                           ep)
1830                       (optional-dispatch-entry-points res))
1831                 ep))
1832              (:rest
1833               (ir1-convert-more res default-vars default-vals
1834                                 entry-vars entry-vals
1835                                 arg nil nil (rest vars) supplied-p-p body
1836                                 aux-vars aux-vals cont
1837                                 source-name debug-name))
1838              (:more-context
1839               (ir1-convert-more res default-vars default-vals
1840                                 entry-vars entry-vals
1841                                 nil arg (second vars) (cddr vars) supplied-p-p
1842                                 body aux-vars aux-vals cont
1843                                 source-name debug-name))
1844              (:keyword
1845               (ir1-convert-more res default-vars default-vals
1846                                 entry-vars entry-vals
1847                                 nil nil nil vars supplied-p-p body aux-vars
1848                                 aux-vals cont source-name debug-name)))))))
1849
1850 ;;; This function deals with the case where we have to make an
1851 ;;; OPTIONAL-DISPATCH to represent a LAMBDA. We cons up the result and
1852 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
1853 ;;; figure out the MIN-ARGS and MAX-ARGS.
1854 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals cont
1855                                       &key
1856                                       (source-name '.anonymous.)
1857                                       (debug-name (debug-namify
1858                                                    "OPTIONAL-DISPATCH ~S"
1859                                                    vars)))
1860   (declare (list body vars aux-vars aux-vals) (type continuation cont))
1861   (let ((res (make-optional-dispatch :arglist vars
1862                                      :allowp allowp
1863                                      :keyp keyp
1864                                      :%source-name source-name
1865                                      :%debug-name debug-name))
1866         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
1867     (aver-live-component *current-component*)
1868     (push res (component-new-funs *current-component*))
1869     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
1870                             cont source-name debug-name)
1871     (setf (optional-dispatch-min-args res) min)
1872     (setf (optional-dispatch-max-args res)
1873           (+ (1- (length (optional-dispatch-entry-points res))) min))
1874
1875     (flet ((frob (ep)
1876              (when ep
1877                (setf (functional-kind ep) :optional)
1878                (setf (leaf-ever-used ep) t)
1879                (setf (lambda-optional-dispatch ep) res))))
1880       (dolist (ep (optional-dispatch-entry-points res)) (frob ep))
1881       (frob (optional-dispatch-more-entry res))
1882       (frob (optional-dispatch-main-entry res)))
1883
1884     res))
1885
1886 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
1887 (defun ir1-convert-lambda (form &key (source-name '.anonymous.) debug-name)
1888
1889   (unless (consp form)
1890     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
1891                     (type-of form)
1892                     form))
1893   (unless (eq (car form) 'lambda)
1894     (compiler-error "~S was expected but ~S was found:~%  ~S"
1895                     'lambda
1896                     (car form)
1897                     form))
1898   (unless (and (consp (cdr form)) (listp (cadr form)))
1899     (compiler-error
1900      "The lambda expression has a missing or non-list lambda list:~%  ~S"
1901      form))
1902
1903   (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
1904       (make-lambda-vars (cadr form))
1905     (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr form))
1906       (let* ((result-cont (make-continuation))
1907              (*lexenv* (process-decls decls
1908                                       (append aux-vars vars)
1909                                       nil result-cont))
1910              (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
1911                       (ir1-convert-hairy-lambda forms vars keyp
1912                                                 allow-other-keys
1913                                                 aux-vars aux-vals result-cont
1914                                                 :source-name source-name
1915                                                 :debug-name debug-name)
1916                       (ir1-convert-lambda-body forms vars
1917                                                :aux-vars aux-vars
1918                                                :aux-vals aux-vals
1919                                                :result result-cont
1920                                                :source-name source-name
1921                                                :debug-name debug-name))))
1922         (setf (functional-inline-expansion res) form)
1923         (setf (functional-arg-documentation res) (cadr form))
1924         res))))
1925 \f
1926 ;;;; defining global functions
1927
1928 ;;; Convert FUN as a lambda in the null environment, but use the
1929 ;;; current compilation policy. Note that FUN may be a
1930 ;;; LAMBDA-WITH-LEXENV, so we may have to augment the environment to
1931 ;;; reflect the state at the definition site.
1932 (defun ir1-convert-inline-lambda (fun &key
1933                                       (source-name '.anonymous.)
1934                                       debug-name)
1935   (destructuring-bind (decls macros symbol-macros &rest body)
1936                       (if (eq (car fun) 'lambda-with-lexenv)
1937                           (cdr fun)
1938                           `(() () () . ,(cdr fun)))
1939     (let ((*lexenv* (make-lexenv
1940                      :default (process-decls decls nil nil
1941                                              (make-continuation)
1942                                              (make-null-lexenv))
1943                      :vars (copy-list symbol-macros)
1944                      :funs (mapcar (lambda (x)
1945                                      `(,(car x) .
1946                                        (macro . ,(coerce (cdr x) 'function))))
1947                                    macros)
1948                      :policy (lexenv-policy *lexenv*))))
1949       (ir1-convert-lambda `(lambda ,@body)
1950                           :source-name source-name
1951                           :debug-name debug-name))))
1952
1953 ;;; Get a DEFINED-FUN object for a function we are about to
1954 ;;; define. If the function has been forward referenced, then
1955 ;;; substitute for the previous references.
1956 (defun get-defined-fun (name)
1957   (proclaim-as-fun-name name)
1958   (let ((found (find-free-fun name "shouldn't happen! (defined-fun)")))
1959     (note-name-defined name :function)
1960     (cond ((not (defined-fun-p found))
1961            (aver (not (info :function :inlinep name)))
1962            (let* ((where-from (leaf-where-from found))
1963                   (res (make-defined-fun
1964                         :%source-name name
1965                         :where-from (if (eq where-from :declared)
1966                                         :declared :defined)
1967                         :type (leaf-type found))))
1968              (substitute-leaf res found)
1969              (setf (gethash name *free-funs*) res)))
1970           ;; If *FREE-FUNS* has a previously converted definition
1971           ;; for this name, then blow it away and try again.
1972           ((defined-fun-functional found)
1973            (remhash name *free-funs*)
1974            (get-defined-fun name))
1975           (t found))))
1976
1977 ;;; Check a new global function definition for consistency with
1978 ;;; previous declaration or definition, and assert argument/result
1979 ;;; types if appropriate. This assertion is suppressed by the
1980 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
1981 ;;; check their argument types as a consequence of type dispatching.
1982 ;;; This avoids redundant checks such as NUMBERP on the args to +, etc.
1983 (defun assert-new-definition (var fun)
1984   (let ((type (leaf-type var))
1985         (for-real (eq (leaf-where-from var) :declared))
1986         (info (info :function :info (leaf-source-name var))))
1987     (assert-definition-type
1988      fun type
1989      ;; KLUDGE: Common Lisp is such a dynamic language that in general
1990      ;; all we can do here in general is issue a STYLE-WARNING. It
1991      ;; would be nice to issue a full WARNING in the special case of
1992      ;; of type mismatches within a compilation unit (as in section
1993      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
1994      ;; keep track of whether the mismatched data came from the same
1995      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
1996      :lossage-fun #'compiler-style-warn
1997      :unwinnage-fun (cond (info #'compiler-style-warn)
1998                           (for-real #'compiler-note)
1999                           (t nil))
2000      :really-assert
2001      (and for-real
2002           (not (and info
2003                     (ir1-attributep (fun-info-attributes info)
2004                                     explicit-check))))
2005      :where (if for-real
2006                 "previous declaration"
2007                 "previous definition"))))
2008
2009 ;;; Convert a lambda doing all the basic stuff we would do if we were
2010 ;;; converting a DEFUN. In the old CMU CL system, this was used both
2011 ;;; by the %DEFUN translator and for global inline expansion, but
2012 ;;; since sbcl-0.pre7.something %DEFUN does things differently.
2013 ;;; FIXME: And now it's probably worth rethinking whether this
2014 ;;; function is a good idea.
2015 ;;;
2016 ;;; Unless a :INLINE function, we temporarily clobber the inline
2017 ;;; expansion. This prevents recursive inline expansion of
2018 ;;; opportunistic pseudo-inlines.
2019 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
2020   (declare (cons lambda) (function converter) (type defined-fun var))
2021   (let ((var-expansion (defined-fun-inline-expansion var)))
2022     (unless (eq (defined-fun-inlinep var) :inline)
2023       (setf (defined-fun-inline-expansion var) nil))
2024     (let* ((name (leaf-source-name var))
2025            (fun (funcall converter lambda :source-name name))
2026            (fun-info (info :function :info name)))
2027       (setf (functional-inlinep fun) (defined-fun-inlinep var))
2028       (assert-new-definition var fun)
2029       (setf (defined-fun-inline-expansion var) var-expansion)
2030       ;; If definitely not an interpreter stub, then substitute for any
2031       ;; old references.
2032       (unless (or (eq (defined-fun-inlinep var) :notinline)
2033                   (not *block-compile*)
2034                   (and fun-info
2035                        (or (fun-info-transforms fun-info)
2036                            (fun-info-templates fun-info)
2037                            (fun-info-ir2-convert fun-info))))
2038         (substitute-leaf fun var)
2039         ;; If in a simple environment, then we can allow backward
2040         ;; references to this function from following top level forms.
2041         (when expansion (setf (defined-fun-functional var) fun)))
2042       fun)))
2043
2044 ;;; the even-at-compile-time part of DEFUN
2045 ;;;
2046 ;;; The INLINE-EXPANSION is a LAMBDA-WITH-LEXENV, or NIL if there is
2047 ;;; no inline expansion.
2048 (defun %compiler-defun (name lambda-with-lexenv)
2049
2050   (let ((defined-fun nil)) ; will be set below if we're in the compiler
2051     
2052     (when (boundp '*lexenv*) ; when in the compiler
2053       (when sb!xc:*compile-print*
2054         (compiler-mumble "~&; recognizing DEFUN ~S~%" name))
2055       (remhash name *free-funs*)
2056       (setf defined-fun (get-defined-fun name)))
2057
2058     (become-defined-fun-name name)
2059
2060     (cond (lambda-with-lexenv
2061            (setf (info :function :inline-expansion-designator name)
2062                  lambda-with-lexenv)
2063            (when defined-fun 
2064              (setf (defined-fun-inline-expansion defined-fun)
2065                    lambda-with-lexenv)))
2066           (t
2067            (clear-info :function :inline-expansion-designator name)))
2068
2069     ;; old CMU CL comment:
2070     ;;   If there is a type from a previous definition, blast it,
2071     ;;   since it is obsolete.
2072     (when (and defined-fun
2073                (eq (leaf-where-from defined-fun) :defined))
2074       (setf (leaf-type defined-fun)
2075             ;; FIXME: If this is a block compilation thing, shouldn't
2076             ;; we be setting the type to the full derived type for the
2077             ;; definition, instead of this most general function type?
2078             (specifier-type 'function))))
2079
2080   (values))