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