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