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