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