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