1881835e16196e0ebd9e3a8a39bacb4d70274b8a
[sbcl.git] / src / compiler / ir1tran.lisp
1 ;;;; This file contains code which does the translation from Lisp code
2 ;;;; to the first intermediate representation (IR1).
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14
15 (declaim (special *compiler-error-bailout*))
16
17 ;;; *SOURCE-PATHS* is a hashtable from source code forms to the path
18 ;;; taken through the source to reach the form. This provides a way to
19 ;;; keep track of the location of original source forms, even when
20 ;;; macroexpansions and other arbitary permutations of the code
21 ;;; happen. This table is initialized by calling FIND-SOURCE-PATHS on
22 ;;; the original source.
23 (declaim (hash-table *source-paths*))
24 (defvar *source-paths*)
25
26 ;;; *CURRENT-COMPONENT* is the COMPONENT structure which we link
27 ;;; blocks into as we generate them. This just serves to glue the
28 ;;; emitted blocks together until local call analysis and flow graph
29 ;;; canonicalization figure out what is really going on. We need to
30 ;;; keep track of all the blocks generated so that we can delete them
31 ;;; if they turn out to be unreachable.
32 ;;;
33 ;;; FIXME: It's confusing having one variable named *CURRENT-COMPONENT*
34 ;;; and another named *COMPONENT-BEING-COMPILED*. (In CMU CL they
35 ;;; were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively,
36 ;;; which was also confusing.)
37 (declaim (type (or component null) *current-component*))
38 (defvar *current-component*)
39
40 ;;; *CURRENT-PATH* is the source path of the form we are currently
41 ;;; translating. See NODE-SOURCE-PATH in the NODE structure.
42 (declaim (list *current-path*))
43 (defvar *current-path*)
44
45 (defvar *derive-function-types* nil
46   "Should the compiler assume that function types will never change,
47   so that it can use type information inferred from current definitions
48   to optimize code which uses those definitions? Setting this true
49   gives non-ANSI, early-CMU-CL behavior. It can be useful for improving
50   the efficiency of stable code.")
51 \f
52 ;;;; namespace management utilities
53
54 ;;; Return a GLOBAL-VAR structure usable for referencing the global
55 ;;; function NAME.
56 (defun find-free-really-fun (name)
57   (unless (info :function :kind name)
58     (setf (info :function :kind name) :function)
59     (setf (info :function :where-from name) :assumed))
60
61   (let ((where (info :function :where-from name)))
62     (when (and (eq where :assumed)
63                ;; In the ordinary target Lisp, it's silly to report
64                ;; undefinedness when the function is defined in the
65                ;; running Lisp. But at cross-compile time, the current
66                ;; definedness of a function is irrelevant to the
67                ;; definedness at runtime, which is what matters.
68                #-sb-xc-host (not (fboundp name)))
69       (note-undefined-reference name :function))
70     (make-global-var :kind :global-function
71                      :%source-name name
72                      :type (if (or *derive-function-types*
73                                    (eq where :declared))
74                                (info :function :type name)
75                                (specifier-type 'function))
76                      :where-from where)))
77
78 ;;; 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-FUNS* entry FREE-FUN 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-FUNS* 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-fun-p (free-fun)
117   ;; There might be other reasons that *FREE-FUN* 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-fun)
121        (let ((functional (defined-fun-functional free-fun)))
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-FUNS*, then return
142 ;;; the value. Otherwise, make a new GLOBAL-VAR using information from
143 ;;; the global environment and enter it in *FREE-FUNS*. 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-fun (name context)
148   (declare (string context))
149   (declare (values global-var))
150   (or (let ((old-free-fun (gethash name *free-funs*)))
151         (and (not (invalid-free-fun-p old-free-fun))
152              old-free-fun))
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-fun-and-macro name)
164          (let ((expansion (fun-name-inline-expansion name))
165                (inlinep (info :function :inlinep name)))
166            (setf (gethash name *free-funs*)
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-fun 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-fun))
179 (defun find-lexically-apparent-fun (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-fun 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-fun fun "shouldn't happen! (no-cmacro)")
633                           form))))
634
635 (defun muffle-warning-or-die ()
636   (muffle-warning)
637   (error "internal error -- no MUFFLE-WARNING restart"))
638
639 ;;; Expand FORM using the macro whose MACRO-FUNCTION is FUN, trapping
640 ;;; errors which occur during the macroexpansion.
641 (defun careful-expand-macro (fun form)
642   (let (;; a hint I (WHN) wish I'd known earlier
643         (hint "(hint: For more precise location, try *BREAK-ON-SIGNALS*.)"))
644     (flet (;; Return a string to use as a prefix in error reporting,
645            ;; telling something about which form caused the problem.
646            (wherestring ()
647              (let ((*print-pretty* nil)
648                    ;; We rely on the printer to abbreviate FORM. 
649                    (*print-length* 3)
650                    (*print-level* 1))
651                (format
652                 nil
653                 #-sb-xc-host "(in macroexpansion of ~S)"
654                 ;; longer message to avoid ambiguity "Was it the xc host
655                 ;; or the cross-compiler which encountered the problem?"
656                 #+sb-xc-host "(in cross-compiler macroexpansion of ~S)"
657                 form))))
658       (handler-bind (;; When cross-compiling, we can get style warnings
659                      ;; about e.g. undefined functions. An unhandled
660                      ;; CL:STYLE-WARNING (as opposed to a
661                      ;; SB!C::COMPILER-NOTE) would cause FAILURE-P to be
662                      ;; set on the return from #'SB!XC:COMPILE-FILE, which
663                      ;; would falsely indicate an error sufficiently
664                      ;; serious that we should stop the build process. To
665                      ;; avoid this, we translate CL:STYLE-WARNING
666                      ;; conditions from the host Common Lisp into
667                      ;; cross-compiler SB!C::COMPILER-NOTE calls. (It
668                      ;; might be cleaner to just make Python use
669                      ;; CL:STYLE-WARNING internally, so that the
670                      ;; significance of any host Common Lisp
671                      ;; CL:STYLE-WARNINGs is understood automatically. But
672                      ;; for now I'm not motivated to do this. -- WHN
673                      ;; 19990412)
674                      (style-warning (lambda (c)
675                                       (compiler-note "~@<~A~:@_~A~:@_~A~:>"
676                                                      (wherestring) hint c)
677                                       (muffle-warning-or-die)))
678                      ;; KLUDGE: CMU CL in its wisdom (version 2.4.6 for
679                      ;; Debian Linux, anyway) raises a CL:WARNING
680                      ;; condition (not a CL:STYLE-WARNING) for undefined
681                      ;; symbols when converting interpreted functions,
682                      ;; causing COMPILE-FILE to think the file has a real
683                      ;; problem, causing COMPILE-FILE to return FAILURE-P
684                      ;; set (not just WARNINGS-P set). Since undefined
685                      ;; symbol warnings are often harmless forward
686                      ;; references, and since it'd be inordinately painful
687                      ;; to try to eliminate all such forward references,
688                      ;; these warnings are basically unavoidable. Thus, we
689                      ;; need to coerce the system to work through them,
690                      ;; and this code does so, by crudely suppressing all
691                      ;; warnings in cross-compilation macroexpansion. --
692                      ;; WHN 19990412
693                      #+cmu
694                      (warning (lambda (c)
695                                 (compiler-note
696                                  "~@<~A~:@_~
697                                   ~A~:@_~
698                                   ~@<(KLUDGE: That was a non-STYLE WARNING. ~
699                                   Ordinarily that would cause compilation to ~
700                                   fail. However, since we're running under ~
701                                   CMU CL, and since CMU CL emits non-STYLE ~
702                                   warnings for safe, hard-to-fix things (e.g. ~
703                                   references to not-yet-defined functions) ~
704                                   we're going to have to ignore it and ~
705                                   proceed anyway. Hopefully we're not ~
706                                   ignoring anything  horrible here..)~:@>~:>"
707                                  (wherestring)
708                                  c)
709                                 (muffle-warning-or-die)))
710                      (error (lambda (c)
711                               (compiler-error "~@<~A~:@_~A~@:_~A~:>"
712                                               (wherestring) hint c))))
713         (funcall sb!xc:*macroexpand-hook* fun form *lexenv*)))))
714 \f
715 ;;;; conversion utilities
716
717 ;;; Convert a bunch of forms, discarding all the values except the
718 ;;; last. If there aren't any forms, then translate a NIL.
719 (declaim (ftype (function (continuation continuation list) (values))
720                 ir1-convert-progn-body))
721 (defun ir1-convert-progn-body (start cont body)
722   (if (endp body)
723       (reference-constant start cont nil)
724       (let ((this-start start)
725             (forms body))
726         (loop
727           (let ((form (car forms)))
728             (when (endp (cdr forms))
729               (ir1-convert this-start cont form)
730               (return))
731             (let ((this-cont (make-continuation)))
732               (ir1-convert this-start this-cont form)
733               (setq this-start this-cont
734                     forms (cdr forms)))))))
735   (values))
736 \f
737 ;;;; converting combinations
738
739 ;;; Convert a function call where the function (i.e. the FUN argument)
740 ;;; is a LEAF. We return the COMBINATION node so that the caller can
741 ;;; poke at it if it wants to.
742 (declaim (ftype (function (continuation continuation list leaf) combination)
743                 ir1-convert-combination))
744 (defun ir1-convert-combination (start cont form fun)
745   (let ((fun-cont (make-continuation)))
746     (reference-leaf start fun-cont fun)
747     (ir1-convert-combination-args fun-cont cont (cdr form))))
748
749 ;;; Convert the arguments to a call and make the COMBINATION node.
750 ;;; FUN-CONT is the continuation which yields the function to call.
751 ;;; FORM is the source for the call. ARGS is the list of arguments for
752 ;;; the call, which defaults to the cdr of source. We return the
753 ;;; COMBINATION node.
754 (defun ir1-convert-combination-args (fun-cont cont args)
755   (declare (type continuation fun-cont cont) (list args))
756   (let ((node (make-combination fun-cont)))
757     (setf (continuation-dest fun-cont) node)
758     (assert-continuation-type fun-cont
759                               (specifier-type '(or function symbol)))
760     (collect ((arg-conts))
761       (let ((this-start fun-cont))
762         (dolist (arg args)
763           (let ((this-cont (make-continuation node)))
764             (ir1-convert this-start this-cont arg)
765             (setq this-start this-cont)
766             (arg-conts this-cont)))
767         (link-node-to-previous-continuation node this-start)
768         (use-continuation node cont)
769         (setf (combination-args node) (arg-conts))))
770     node))
771
772 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
773 ;;; source transforms and try out any inline expansion. If there is no
774 ;;; expansion, but is :INLINE, then give an efficiency note (unless a
775 ;;; known function which will quite possibly be open-coded.) Next, we
776 ;;; go to ok-combination conversion.
777 (defun ir1-convert-srctran (start cont var form)
778   (declare (type continuation start cont) (type global-var var))
779   (let ((inlinep (when (defined-fun-p var)
780                    (defined-fun-inlinep var))))
781     (if (eq inlinep :notinline)
782         (ir1-convert-combination start cont form var)
783         (let ((transform (info :function
784                                :source-transform
785                                (leaf-source-name var))))
786           (if transform
787               (multiple-value-bind (result pass) (funcall transform form)
788                 (if pass
789                     (ir1-convert-maybe-predicate start cont form var)
790                     (ir1-convert start cont result)))
791               (ir1-convert-maybe-predicate start cont form var))))))
792
793 ;;; If the function has the PREDICATE attribute, and the CONT's DEST
794 ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a
795 ;;; predicate always appears in a conditional context.
796 ;;;
797 ;;; If the function isn't a predicate, then we call
798 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
799 (defun ir1-convert-maybe-predicate (start cont form var)
800   (declare (type continuation start cont) (list form) (type global-var var))
801   (let ((info (info :function :info (leaf-source-name var))))
802     (if (and info
803              (ir1-attributep (fun-info-attributes info) predicate)
804              (not (if-p (continuation-dest cont))))
805         (ir1-convert start cont `(if ,form t nil))
806         (ir1-convert-combination-checking-type start cont form var))))
807
808 ;;; Actually really convert a global function call that we are allowed
809 ;;; to early-bind.
810 ;;;
811 ;;; If we know the function type of the function, then we check the
812 ;;; call for syntactic legality with respect to the declared function
813 ;;; type. If it is impossible to determine whether the call is correct
814 ;;; due to non-constant keywords, then we give up, marking the call as
815 ;;; :FULL to inhibit further error messages. We return true when the
816 ;;; call is legal.
817 ;;;
818 ;;; If the call is legal, we also propagate type assertions from the
819 ;;; function type to the arg and result continuations. We do this now
820 ;;; so that IR1 optimize doesn't have to redundantly do the check
821 ;;; later so that it can do the type propagation.
822 (defun ir1-convert-combination-checking-type (start cont form var)
823   (declare (type continuation start cont) (list form) (type leaf var))
824   (let* ((node (ir1-convert-combination start cont form var))
825          (fun-cont (basic-combination-fun node))
826          (type (leaf-type var)))
827     (when (validate-call-type node type t)
828       (setf (continuation-%derived-type fun-cont) type)
829       (setf (continuation-reoptimize fun-cont) nil)
830       (setf (continuation-%type-check fun-cont) nil)))
831   (values))
832
833 ;;; Convert a call to a local function. If the function has already
834 ;;; been LET converted, then throw FUN to LOCAL-CALL-LOSSAGE. This
835 ;;; should only happen when we are converting inline expansions for
836 ;;; local functions during optimization.
837 (defun ir1-convert-local-combination (start cont form fun)
838   (if (functional-kind fun)
839       (throw 'local-call-lossage fun)
840       (ir1-convert-combination start cont form
841                                (maybe-reanalyze-fun fun))))
842 \f
843 ;;;; PROCESS-DECLS
844
845 ;;; Given a list of LAMBDA-VARs and a variable name, return the
846 ;;; LAMBDA-VAR for that name, or NIL if it isn't found. We return the
847 ;;; *last* variable with that name, since LET* bindings may be
848 ;;; duplicated, and declarations always apply to the last.
849 (declaim (ftype (function (list symbol) (or lambda-var list))
850                 find-in-bindings))
851 (defun find-in-bindings (vars name)
852   (let ((found nil))
853     (dolist (var vars)
854       (cond ((leaf-p var)
855              (when (eq (leaf-source-name var) name)
856                (setq found var))
857              (let ((info (lambda-var-arg-info var)))
858                (when info
859                  (let ((supplied-p (arg-info-supplied-p info)))
860                    (when (and supplied-p
861                               (eq (leaf-source-name supplied-p) name))
862                      (setq found supplied-p))))))
863             ((and (consp var) (eq (car var) name))
864              (setf found (cdr var)))))
865     found))
866
867 ;;; Called by Process-Decls to deal with a variable type declaration.
868 ;;; If a lambda-var being bound, we intersect the type with the vars
869 ;;; type, otherwise we add a type-restriction on the var. If a symbol
870 ;;; macro, we just wrap a THE around the expansion.
871 (defun process-type-decl (decl res vars)
872   (declare (list decl vars) (type lexenv res))
873   (let ((type (specifier-type (first decl))))
874     (collect ((restr nil cons)
875               (new-vars nil cons))
876       (dolist (var-name (rest decl))
877         (let* ((bound-var (find-in-bindings vars var-name))
878                (var (or bound-var
879                         (lexenv-find var-name variables)
880                         (find-free-variable var-name))))
881           (etypecase var
882             (leaf
883              (let* ((old-type (or (lexenv-find var type-restrictions)
884                                   (leaf-type var)))
885                     (int (if (or (fun-type-p type)
886                                  (fun-type-p old-type))
887                              type
888                              (type-approx-intersection2 old-type type))))
889                (cond ((eq int *empty-type*)
890                       (unless (policy *lexenv* (= inhibit-warnings 3))
891                         (compiler-warn
892                          "The type declarations ~S and ~S for ~S conflict."
893                          (type-specifier old-type) (type-specifier type)
894                          var-name)))
895                      (bound-var (setf (leaf-type bound-var) int))
896                      (t
897                       (restr (cons var int))))))
898             (cons
899              ;; FIXME: non-ANSI weirdness
900              (aver (eq (car var) 'MACRO))
901              (new-vars `(,var-name . (MACRO . (the ,(first decl)
902                                                    ,(cdr var))))))
903             (heap-alien-info
904              (compiler-error
905               "~S is an alien variable, so its type can't be declared."
906               var-name)))))
907
908       (if (or (restr) (new-vars))
909           (make-lexenv :default res
910                        :type-restrictions (restr)
911                        :variables (new-vars))
912           res))))
913
914 ;;; This is somewhat similar to PROCESS-TYPE-DECL, but handles
915 ;;; declarations for function variables. In addition to allowing
916 ;;; declarations for functions being bound, we must also deal with
917 ;;; declarations that constrain the type of lexically apparent
918 ;;; functions.
919 (defun process-ftype-decl (spec res names fvars)
920   (declare (list spec names fvars) (type lexenv res))
921   (let ((type (specifier-type spec)))
922     (collect ((res nil cons))
923       (dolist (name names)
924         (let ((found (find name fvars
925                            :key #'leaf-source-name
926                            :test #'equal)))
927           (cond
928            (found
929             (setf (leaf-type found) type)
930             (assert-definition-type found type
931                                     :unwinnage-fun #'compiler-note
932                                     :where "FTYPE declaration"))
933            (t
934             (res (cons (find-lexically-apparent-fun
935                         name "in a function type declaration")
936                        type))))))
937       (if (res)
938           (make-lexenv :default res :type-restrictions (res))
939           res))))
940
941 ;;; Process a special declaration, returning a new LEXENV. A non-bound
942 ;;; special declaration is instantiated by throwing a special variable
943 ;;; into the variables.
944 (defun process-special-decl (spec res vars)
945   (declare (list spec vars) (type lexenv res))
946   (collect ((new-venv nil cons))
947     (dolist (name (cdr spec))
948       (let ((var (find-in-bindings vars name)))
949         (etypecase var
950           (cons
951            (aver (eq (car var) 'MACRO))
952            (compiler-error
953             "~S is a symbol-macro and thus can't be declared special."
954             name))
955           (lambda-var
956            (when (lambda-var-ignorep var)
957              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
958              ;; requires that this be a STYLE-WARNING, not a full WARNING.
959              (compiler-style-warn
960               "The ignored variable ~S is being declared special."
961               name))
962            (setf (lambda-var-specvar var)
963                  (specvar-for-binding name)))
964           (null
965            (unless (assoc name (new-venv) :test #'eq)
966              (new-venv (cons name (specvar-for-binding name))))))))
967     (if (new-venv)
968         (make-lexenv :default res :variables (new-venv))
969         res)))
970
971 ;;; Return a DEFINED-FUN which copies a GLOBAL-VAR but for its INLINEP.
972 (defun make-new-inlinep (var inlinep)
973   (declare (type global-var var) (type inlinep inlinep))
974   (let ((res (make-defined-fun
975               :%source-name (leaf-source-name var)
976               :where-from (leaf-where-from var)
977               :type (leaf-type var)
978               :inlinep inlinep)))
979     (when (defined-fun-p var)
980       (setf (defined-fun-inline-expansion res)
981             (defined-fun-inline-expansion var))
982       (setf (defined-fun-functional res)
983             (defined-fun-functional var)))
984     res))
985
986 ;;; Parse an inline/notinline declaration. If it's a local function we're
987 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
988 (defun process-inline-decl (spec res fvars)
989   (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq)))
990         (new-fenv ()))
991     (dolist (name (rest spec))
992       (let ((fvar (find name fvars
993                         :key #'leaf-source-name
994                         :test #'equal)))
995         (if fvar
996             (setf (functional-inlinep fvar) sense)
997             (let ((found
998                    (find-lexically-apparent-fun
999                     name "in an inline or notinline declaration")))
1000               (etypecase found
1001                 (functional
1002                  (when (policy *lexenv* (>= speed inhibit-warnings))
1003                    (compiler-note "ignoring ~A declaration not at ~
1004                                    definition of local function:~%  ~S"
1005                                   sense name)))
1006                 (global-var
1007                  (push (cons name (make-new-inlinep found sense))
1008                        new-fenv)))))))
1009
1010     (if new-fenv
1011         (make-lexenv :default res :functions new-fenv)
1012         res)))
1013
1014 ;;; Like FIND-IN-BINDINGS, but looks for #'foo in the fvars.
1015 (defun find-in-bindings-or-fbindings (name vars fvars)
1016   (declare (list vars fvars))
1017   (if (consp name)
1018       (destructuring-bind (wot fn-name) name
1019         (unless (eq wot 'function)
1020           (compiler-error "The function or variable name ~S is unrecognizable."
1021                           name))
1022         (find fn-name fvars :key #'leaf-source-name :test #'equal))
1023       (find-in-bindings vars name)))
1024
1025 ;;; Process an ignore/ignorable declaration, checking for various losing
1026 ;;; conditions.
1027 (defun process-ignore-decl (spec vars fvars)
1028   (declare (list spec vars fvars))
1029   (dolist (name (rest spec))
1030     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
1031       (cond
1032        ((not var)
1033         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1034         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1035         (compiler-style-warn "declaring unknown variable ~S to be ignored"
1036                              name))
1037        ;; FIXME: This special case looks like non-ANSI weirdness.
1038        ((and (consp var) (consp (cdr var)) (eq (cadr var) 'macro))
1039         ;; Just ignore the IGNORE decl.
1040         )
1041        ((functional-p var)
1042         (setf (leaf-ever-used var) t))
1043        ((lambda-var-specvar var)
1044         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
1045         ;; requires that this be a STYLE-WARNING, not a full WARNING.
1046         (compiler-style-warn "declaring special variable ~S to be ignored"
1047                              name))
1048        ((eq (first spec) 'ignorable)
1049         (setf (leaf-ever-used var) t))
1050        (t
1051         (setf (lambda-var-ignorep var) t)))))
1052   (values))
1053
1054 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
1055 ;;; go away, I think.
1056 (defvar *suppress-values-declaration* nil
1057   #!+sb-doc
1058   "If true, processing of the VALUES declaration is inhibited.")
1059
1060 ;;; Process a single declaration spec, augmenting the specified LEXENV
1061 ;;; RES and returning it as a result. VARS and FVARS are as described in
1062 ;;; PROCESS-DECLS.
1063 (defun process-1-decl (raw-spec res vars fvars cont)
1064   (declare (type list raw-spec vars fvars))
1065   (declare (type lexenv res))
1066   (declare (type continuation cont))
1067   (let ((spec (canonized-decl-spec raw-spec)))
1068     (case (first spec)
1069       (special (process-special-decl spec res vars))
1070       (ftype
1071        (unless (cdr spec)
1072          (compiler-error "No type specified in FTYPE declaration: ~S" spec))
1073        (process-ftype-decl (second spec) res (cddr spec) fvars))
1074       ((inline notinline maybe-inline)
1075        (process-inline-decl spec res fvars))
1076       ((ignore ignorable)
1077        (process-ignore-decl spec vars fvars)
1078        res)
1079       (optimize
1080        (make-lexenv
1081         :default res
1082         :policy (process-optimize-decl spec (lexenv-policy res))))
1083       (type
1084        (process-type-decl (cdr spec) res vars))
1085       (values
1086        (if *suppress-values-declaration*
1087            res
1088            (let ((types (cdr spec)))
1089              (do-the-stuff (if (eql (length types) 1)
1090                                (car types)
1091                                `(values ,@types))
1092                            cont res 'values))))
1093       (dynamic-extent
1094        (when (policy *lexenv* (> speed inhibit-warnings))
1095          (compiler-note
1096           "compiler limitation: ~
1097         ~%  There's no special support for DYNAMIC-EXTENT (so it's ignored)."))
1098        res)
1099       (t
1100        (unless (info :declaration :recognized (first spec))
1101          (compiler-warn "unrecognized declaration ~S" raw-spec))
1102        res))))
1103
1104 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR
1105 ;;; and FUNCTIONAL structures which are being bound. In addition to
1106 ;;; filling in slots in the leaf structures, we return a new LEXENV
1107 ;;; which reflects pervasive special and function type declarations,
1108 ;;; (NOT)INLINE declarations and OPTIMIZE declarations. CONT is the
1109 ;;; continuation affected by VALUES declarations.
1110 ;;;
1111 ;;; This is also called in main.lisp when PROCESS-FORM handles a use
1112 ;;; of LOCALLY.
1113 (defun process-decls (decls vars fvars cont &optional (env *lexenv*))
1114   (declare (list decls vars fvars) (type continuation cont))
1115   (dolist (decl decls)
1116     (dolist (spec (rest decl))
1117       (unless (consp spec)
1118         (compiler-error "malformed declaration specifier ~S in ~S"
1119                         spec
1120                         decl))
1121       (setq env (process-1-decl spec env vars fvars cont))))
1122   env)
1123
1124 ;;; Return the SPECVAR for NAME to use when we see a local SPECIAL
1125 ;;; declaration. If there is a global variable of that name, then
1126 ;;; check that it isn't a constant and return it. Otherwise, create an
1127 ;;; anonymous GLOBAL-VAR.
1128 (defun specvar-for-binding (name)
1129   (cond ((not (eq (info :variable :where-from name) :assumed))
1130          (let ((found (find-free-variable name)))
1131            (when (heap-alien-info-p found)
1132              (compiler-error
1133               "~S is an alien variable and so can't be declared special."
1134               name))
1135            (unless (global-var-p found)
1136              (compiler-error
1137               "~S is a constant and so can't be declared special."
1138               name))
1139            found))
1140         (t
1141          (make-global-var :kind :special
1142                           :%source-name name
1143                           :where-from :declared))))
1144 \f
1145 ;;;; LAMBDA hackery
1146
1147 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
1148 ;;;; function representation" before you seriously mess with this
1149 ;;;; stuff.
1150
1151 ;;; Verify that a thing is a legal name for a variable and return a
1152 ;;; Var structure for it, filling in info if it is globally special.
1153 ;;; If it is losing, we punt with a Compiler-Error. Names-So-Far is an
1154 ;;; alist of names which have previously been bound. If the name is in
1155 ;;; this list, then we error out.
1156 (declaim (ftype (function (t list) lambda-var) varify-lambda-arg))
1157 (defun varify-lambda-arg (name names-so-far)
1158   (declare (inline member))
1159   (unless (symbolp name)
1160     (compiler-error "The lambda-variable ~S is not a symbol." name))
1161   (when (member name names-so-far :test #'eq)
1162     (compiler-error "The variable ~S occurs more than once in the lambda-list."
1163                     name))
1164   (let ((kind (info :variable :kind name)))
1165     (when (or (keywordp name) (eq kind :constant))
1166       (compiler-error "The name of the lambda-variable ~S is a constant."
1167                       name))
1168     (cond ((eq kind :special)
1169            (let ((specvar (find-free-variable name)))
1170              (make-lambda-var :%source-name name
1171                               :type (leaf-type specvar)
1172                               :where-from (leaf-where-from specvar)
1173                               :specvar specvar)))
1174           (t
1175            (note-lexical-binding name)
1176            (make-lambda-var :%source-name name)))))
1177
1178 ;;; Make the default keyword for a &KEY arg, checking that the keyword
1179 ;;; isn't already used by one of the VARS. We also check that the
1180 ;;; keyword isn't the magical :ALLOW-OTHER-KEYS.
1181 (declaim (ftype (function (symbol list t) keyword) make-keyword-for-arg))
1182 (defun make-keyword-for-arg (symbol vars keywordify)
1183   (let ((key (if (and keywordify (not (keywordp symbol)))
1184                  (keywordicate symbol)
1185                  symbol)))
1186     (when (eq key :allow-other-keys)
1187       (compiler-error "No &KEY arg can be called :ALLOW-OTHER-KEYS."))
1188     (dolist (var vars)
1189       (let ((info (lambda-var-arg-info var)))
1190         (when (and info
1191                    (eq (arg-info-kind info) :keyword)
1192                    (eq (arg-info-key info) key))
1193           (compiler-error
1194            "The keyword ~S appears more than once in the lambda-list."
1195            key))))
1196     key))
1197
1198 ;;; Parse a lambda list into a list of VAR structures, stripping off
1199 ;;; any &AUX bindings. Each arg name is checked for legality, and
1200 ;;; duplicate names are checked for. If an arg is globally special,
1201 ;;; the var is marked as :SPECIAL instead of :LEXICAL. &KEY,
1202 ;;; &OPTIONAL and &REST args are annotated with an ARG-INFO structure
1203 ;;; which contains the extra information. If we hit something losing,
1204 ;;; we bug out with COMPILER-ERROR. These values are returned:
1205 ;;;  1. a list of the var structures for each top level argument;
1206 ;;;  2. a flag indicating whether &KEY was specified;
1207 ;;;  3. a flag indicating whether other &KEY args are allowed;
1208 ;;;  4. a list of the &AUX variables; and
1209 ;;;  5. a list of the &AUX values.
1210 (declaim (ftype (function (list) (values list boolean boolean list list))
1211                 make-lambda-vars))
1212 (defun make-lambda-vars (list)
1213   (multiple-value-bind (required optional restp rest keyp keys allowp aux
1214                         morep more-context more-count)
1215       (parse-lambda-list list)
1216     (collect ((vars)
1217               (names-so-far)
1218               (aux-vars)
1219               (aux-vals))
1220       (flet (;; PARSE-DEFAULT deals with defaults and supplied-p args
1221              ;; for optionals and keywords args.
1222              (parse-default (spec info)
1223                (when (consp (cdr spec))
1224                  (setf (arg-info-default info) (second spec))
1225                  (when (consp (cddr spec))
1226                    (let* ((supplied-p (third spec))
1227                           (supplied-var (varify-lambda-arg supplied-p
1228                                                            (names-so-far))))
1229                      (setf (arg-info-supplied-p info) supplied-var)
1230                      (names-so-far supplied-p)
1231                      (when (> (length (the list spec)) 3)
1232                        (compiler-error
1233                         "The list ~S is too long to be an arg specifier."
1234                         spec)))))))
1235         
1236         (dolist (name required)
1237           (let ((var (varify-lambda-arg name (names-so-far))))
1238             (vars var)
1239             (names-so-far name)))
1240         
1241         (dolist (spec optional)
1242           (if (atom spec)
1243               (let ((var (varify-lambda-arg spec (names-so-far))))
1244                 (setf (lambda-var-arg-info var) (make-arg-info :kind :optional))
1245                 (vars var)
1246                 (names-so-far spec))
1247               (let* ((name (first spec))
1248                      (var (varify-lambda-arg name (names-so-far)))
1249                      (info (make-arg-info :kind :optional)))
1250                 (setf (lambda-var-arg-info var) info)
1251                 (vars var)
1252                 (names-so-far name)
1253                 (parse-default spec info))))
1254         
1255         (when restp
1256           (let ((var (varify-lambda-arg rest (names-so-far))))
1257             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
1258             (vars var)
1259             (names-so-far rest)))
1260
1261         (when morep
1262           (let ((var (varify-lambda-arg more-context (names-so-far))))
1263             (setf (lambda-var-arg-info var)
1264                   (make-arg-info :kind :more-context))
1265             (vars var)
1266             (names-so-far more-context))
1267           (let ((var (varify-lambda-arg more-count (names-so-far))))
1268             (setf (lambda-var-arg-info var)
1269                   (make-arg-info :kind :more-count))
1270             (vars var)
1271             (names-so-far more-count)))
1272         
1273         (dolist (spec keys)
1274           (cond
1275            ((atom spec)
1276             (let ((var (varify-lambda-arg spec (names-so-far))))
1277               (setf (lambda-var-arg-info var)
1278                     (make-arg-info :kind :keyword
1279                                    :key (make-keyword-for-arg spec
1280                                                               (vars)
1281                                                               t)))
1282               (vars var)
1283               (names-so-far spec)))
1284            ((atom (first spec))
1285             (let* ((name (first spec))
1286                    (var (varify-lambda-arg name (names-so-far)))
1287                    (info (make-arg-info
1288                           :kind :keyword
1289                           :key (make-keyword-for-arg name (vars) t))))
1290               (setf (lambda-var-arg-info var) info)
1291               (vars var)
1292               (names-so-far name)
1293               (parse-default spec info)))
1294            (t
1295             (let ((head (first spec)))
1296               (unless (proper-list-of-length-p head 2)
1297                 (error "malformed &KEY argument specifier: ~S" spec))
1298               (let* ((name (second head))
1299                      (var (varify-lambda-arg name (names-so-far)))
1300                      (info (make-arg-info
1301                             :kind :keyword
1302                             :key (make-keyword-for-arg (first head)
1303                                                        (vars)
1304                                                        nil))))
1305                 (setf (lambda-var-arg-info var) info)
1306                 (vars var)
1307                 (names-so-far name)
1308                 (parse-default spec info))))))
1309         
1310         (dolist (spec aux)
1311           (cond ((atom spec)
1312                  (let ((var (varify-lambda-arg spec nil)))
1313                    (aux-vars var)
1314                    (aux-vals nil)
1315                    (names-so-far spec)))
1316                 (t
1317                  (unless (proper-list-of-length-p spec 1 2)
1318                    (compiler-error "malformed &AUX binding specifier: ~S"
1319                                    spec))
1320                  (let* ((name (first spec))
1321                         (var (varify-lambda-arg name nil)))
1322                    (aux-vars var)
1323                    (aux-vals (second spec))
1324                    (names-so-far name)))))
1325
1326         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
1327
1328 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that we
1329 ;;; sequentially bind each AUX-VAR to the corresponding AUX-VAL before
1330 ;;; converting the body. If there are no bindings, just convert the
1331 ;;; body, otherwise do one binding and recurse on the rest.
1332 ;;;
1333 ;;; FIXME: This could and probably should be converted to use
1334 ;;; SOURCE-NAME and DEBUG-NAME. But I (WHN) don't use &AUX bindings,
1335 ;;; so I'm not motivated. Patches will be accepted...
1336 (defun ir1-convert-aux-bindings (start cont body aux-vars aux-vals)
1337   (declare (type continuation start cont) (list body aux-vars aux-vals))
1338   (if (null aux-vars)
1339       (ir1-convert-progn-body start cont body)
1340       (let ((fun-cont (make-continuation))
1341             (fun (ir1-convert-lambda-body body
1342                                           (list (first aux-vars))
1343                                           :aux-vars (rest aux-vars)
1344                                           :aux-vals (rest aux-vals)
1345                                           :debug-name (debug-namify
1346                                                        "&AUX bindings ~S"
1347                                                        aux-vars))))
1348         (reference-leaf start fun-cont fun)
1349         (ir1-convert-combination-args fun-cont cont
1350                                       (list (first aux-vals)))))
1351   (values))
1352
1353 ;;; This is similar to IR1-CONVERT-PROGN-BODY except that code to bind
1354 ;;; the SPECVAR for each SVAR to the value of the variable is wrapped
1355 ;;; around the body. If there are no special bindings, we just convert
1356 ;;; the body, otherwise we do one special binding and recurse on the
1357 ;;; rest.
1358 ;;;
1359 ;;; We make a cleanup and introduce it into the lexical environment.
1360 ;;; If there are multiple special bindings, the cleanup for the blocks
1361 ;;; will end up being the innermost one. We force CONT to start a
1362 ;;; block outside of this cleanup, causing cleanup code to be emitted
1363 ;;; when the scope is exited.
1364 (defun ir1-convert-special-bindings (start cont body aux-vars aux-vals svars)
1365   (declare (type continuation start cont)
1366            (list body aux-vars aux-vals svars))
1367   (cond
1368    ((null svars)
1369     (ir1-convert-aux-bindings start cont body aux-vars aux-vals))
1370    (t
1371     (continuation-starts-block cont)
1372     (let ((cleanup (make-cleanup :kind :special-bind))
1373           (var (first svars))
1374           (next-cont (make-continuation))
1375           (nnext-cont (make-continuation)))
1376       (ir1-convert start next-cont
1377                    `(%special-bind ',(lambda-var-specvar var) ,var))
1378       (setf (cleanup-mess-up cleanup) (continuation-use next-cont))
1379       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
1380         (ir1-convert next-cont nnext-cont '(%cleanup-point))
1381         (ir1-convert-special-bindings nnext-cont cont body aux-vars aux-vals
1382                                       (rest svars))))))
1383   (values))
1384
1385 ;;; Create a lambda node out of some code, returning the result. The
1386 ;;; bindings are specified by the list of VAR structures VARS. We deal
1387 ;;; with adding the names to the LEXENV-VARIABLES for the conversion.
1388 ;;; The result is added to the NEW-FUNS in the *CURRENT-COMPONENT* and
1389 ;;; linked to the component head and tail.
1390 ;;;
1391 ;;; We detect special bindings here, replacing the original VAR in the
1392 ;;; lambda list with a temporary variable. We then pass a list of the
1393 ;;; special vars to IR1-CONVERT-SPECIAL-BINDINGS, which actually emits
1394 ;;; the special binding code.
1395 ;;;
1396 ;;; We ignore any ARG-INFO in the VARS, trusting that someone else is
1397 ;;; dealing with &nonsense.
1398 ;;;
1399 ;;; AUX-VARS is a list of VAR structures for variables that are to be
1400 ;;; sequentially bound. Each AUX-VAL is a form that is to be evaluated
1401 ;;; to get the initial value for the corresponding AUX-VAR. 
1402 (defun ir1-convert-lambda-body (body
1403                                 vars
1404                                 &key
1405                                 aux-vars
1406                                 aux-vals
1407                                 result
1408                                 (source-name '.anonymous.)
1409                                 debug-name)
1410   (declare (list body vars aux-vars aux-vals)
1411            (type (or continuation null) result))
1412
1413   ;; We're about to try to put new blocks into *CURRENT-COMPONENT*.
1414   (aver-live-component *current-component*)
1415
1416   (let* ((bind (make-bind))
1417          (lambda (make-lambda :vars vars
1418                               :bind bind
1419                               :%source-name source-name
1420                               :%debug-name debug-name))
1421          (result (or result (make-continuation))))
1422
1423     ;; just to check: This function should fail internal assertions if
1424     ;; we didn't set up a valid debug name above.
1425     ;;
1426     ;; (In SBCL we try to make everything have a debug name, since we
1427     ;; lack the omniscient perspective the original implementors used
1428     ;; to decide which things didn't need one.)
1429     (functional-debug-name lambda)
1430
1431     (setf (lambda-home lambda) lambda)
1432     (collect ((svars)
1433               (new-venv nil cons))
1434
1435       (dolist (var vars)
1436         ;; As far as I can see, LAMBDA-VAR-HOME should never have
1437         ;; been set before. Let's make sure. -- WHN 2001-09-29
1438         (aver (null (lambda-var-home var)))
1439         (setf (lambda-var-home var) lambda)
1440         (let ((specvar (lambda-var-specvar var)))
1441           (cond (specvar
1442                  (svars var)
1443                  (new-venv (cons (leaf-source-name specvar) specvar)))
1444                 (t
1445                  (note-lexical-binding (leaf-source-name var))
1446                  (new-venv (cons (leaf-source-name var) var))))))
1447
1448       (let ((*lexenv* (make-lexenv :variables (new-venv)
1449                                    :lambda lambda
1450                                    :cleanup nil)))
1451         (setf (bind-lambda bind) lambda)
1452         (setf (node-lexenv bind) *lexenv*)
1453         
1454         (let ((cont1 (make-continuation))
1455               (cont2 (make-continuation)))
1456           (continuation-starts-block cont1)
1457           (link-node-to-previous-continuation bind cont1)
1458           (use-continuation bind cont2)
1459           (ir1-convert-special-bindings cont2 result body aux-vars aux-vals
1460                                         (svars)))
1461
1462         (let ((block (continuation-block result)))
1463           (when block
1464             (let ((return (make-return :result result :lambda lambda))
1465                   (tail-set (make-tail-set :funs (list lambda)))
1466                   (dummy (make-continuation)))
1467               (setf (lambda-tail-set lambda) tail-set)
1468               (setf (lambda-return lambda) return)
1469               (setf (continuation-dest result) return)
1470               (setf (block-last block) return)
1471               (link-node-to-previous-continuation return result)
1472               (use-continuation return dummy))
1473             (link-blocks block (component-tail *current-component*))))))
1474
1475     (link-blocks (component-head *current-component*) (node-block bind))
1476     (push lambda (component-new-funs *current-component*))
1477
1478     lambda))
1479
1480 ;;; Create the actual entry-point function for an optional entry
1481 ;;; point. The lambda binds copies of each of the VARS, then calls FUN
1482 ;;; with the argument VALS and the DEFAULTS. Presumably the VALS refer
1483 ;;; to the VARS by name. The VALS are passed in in reverse order.
1484 ;;;
1485 ;;; If any of the copies of the vars are referenced more than once,
1486 ;;; then we mark the corresponding var as EVER-USED to inhibit
1487 ;;; "defined but not read" warnings for arguments that are only used
1488 ;;; by default forms.
1489 (defun convert-optional-entry (fun vars vals defaults)
1490   (declare (type clambda fun) (list vars vals defaults))
1491   (let* ((fvars (reverse vars))
1492          (arg-vars (mapcar (lambda (var)
1493                              (unless (lambda-var-specvar var)
1494                                (note-lexical-binding (leaf-source-name var)))
1495                              (make-lambda-var
1496                               :%source-name (leaf-source-name var)
1497                               :type (leaf-type var)
1498                               :where-from (leaf-where-from var)
1499                               :specvar (lambda-var-specvar var)))
1500                            fvars))
1501          (fun (ir1-convert-lambda-body `((%funcall ,fun
1502                                                    ,@(reverse vals)
1503                                                    ,@defaults))
1504                                        arg-vars
1505                                        :debug-name "&OPTIONAL processor")))
1506     (mapc (lambda (var arg-var)
1507             (when (cdr (leaf-refs arg-var))
1508               (setf (leaf-ever-used var) t)))
1509           fvars arg-vars)
1510     fun))
1511
1512 ;;; This function deals with supplied-p vars in optional arguments. If
1513 ;;; the there is no supplied-p arg, then we just call
1514 ;;; IR1-CONVERT-HAIRY-ARGS on the remaining arguments, and generate a
1515 ;;; optional entry that calls the result. If there is a supplied-p
1516 ;;; var, then we add it into the default vars and throw a T into the
1517 ;;; entry values. The resulting entry point function is returned.
1518 (defun generate-optional-default-entry (res default-vars default-vals
1519                                             entry-vars entry-vals
1520                                             vars supplied-p-p body
1521                                             aux-vars aux-vals cont
1522                                             source-name debug-name)
1523   (declare (type optional-dispatch res)
1524            (list default-vars default-vals entry-vars entry-vals vars body
1525                  aux-vars aux-vals)
1526            (type (or continuation null) cont))
1527   (let* ((arg (first vars))
1528          (arg-name (leaf-source-name arg))
1529          (info (lambda-var-arg-info arg))
1530          (supplied-p (arg-info-supplied-p info))
1531          (ep (if supplied-p
1532                  (ir1-convert-hairy-args
1533                   res
1534                   (list* supplied-p arg default-vars)
1535                   (list* (leaf-source-name supplied-p) arg-name default-vals)
1536                   (cons arg entry-vars)
1537                   (list* t arg-name entry-vals)
1538                   (rest vars) t body aux-vars aux-vals cont
1539                   source-name debug-name)
1540                  (ir1-convert-hairy-args
1541                   res
1542                   (cons arg default-vars)
1543                   (cons arg-name default-vals)
1544                   (cons arg entry-vars)
1545                   (cons arg-name entry-vals)
1546                   (rest vars) supplied-p-p body aux-vars aux-vals cont
1547                   source-name debug-name))))
1548
1549     (convert-optional-entry ep default-vars default-vals
1550                             (if supplied-p
1551                                 (list (arg-info-default info) nil)
1552                                 (list (arg-info-default info))))))
1553
1554 ;;; Create the MORE-ENTRY function for the OPTIONAL-DISPATCH RES.
1555 ;;; ENTRY-VARS and ENTRY-VALS describe the fixed arguments. REST is
1556 ;;; the var for any &REST arg. KEYS is a list of the &KEY arg vars.
1557 ;;;
1558 ;;; The most interesting thing that we do is parse keywords. We create
1559 ;;; a bunch of temporary variables to hold the result of the parse,
1560 ;;; and then loop over the supplied arguments, setting the appropriate
1561 ;;; temps for the supplied keyword. Note that it is significant that
1562 ;;; we iterate over the keywords in reverse order --- this implements
1563 ;;; the CL requirement that (when a keyword appears more than once)
1564 ;;; the first value is used.
1565 ;;;
1566 ;;; If there is no supplied-p var, then we initialize the temp to the
1567 ;;; default and just pass the temp into the main entry. Since
1568 ;;; non-constant &KEY args are forcibly given a supplied-p var, we
1569 ;;; know that the default is constant, and thus safe to evaluate out
1570 ;;; of order.
1571 ;;;
1572 ;;; If there is a supplied-p var, then we create temps for both the
1573 ;;; value and the supplied-p, and pass them into the main entry,
1574 ;;; letting it worry about defaulting.
1575 ;;;
1576 ;;; We deal with :ALLOW-OTHER-KEYS by delaying unknown keyword errors
1577 ;;; until we have scanned all the keywords.
1578 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
1579   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
1580   (collect ((arg-vars)
1581             (arg-vals (reverse entry-vals))
1582             (temps)
1583             (body))
1584
1585     (dolist (var (reverse entry-vars))
1586       (arg-vars (make-lambda-var :%source-name (leaf-source-name var)
1587                                  :type (leaf-type var)
1588                                  :where-from (leaf-where-from var))))
1589
1590     (let* ((n-context (gensym "N-CONTEXT-"))
1591            (context-temp (make-lambda-var :%source-name n-context))
1592            (n-count (gensym "N-COUNT-"))
1593            (count-temp (make-lambda-var :%source-name n-count
1594                                         :type (specifier-type 'index))))
1595
1596       (arg-vars context-temp count-temp)
1597
1598       (when rest
1599         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
1600       (when morep
1601         (arg-vals n-context)
1602         (arg-vals n-count))
1603
1604       (when (optional-dispatch-keyp res)
1605         (let ((n-index (gensym "N-INDEX-"))
1606               (n-key (gensym "N-KEY-"))
1607               (n-value-temp (gensym "N-VALUE-TEMP-"))
1608               (n-allowp (gensym "N-ALLOWP-"))
1609               (n-losep (gensym "N-LOSEP-"))
1610               (allowp (or (optional-dispatch-allowp res)
1611                           (policy *lexenv* (zerop safety)))))
1612
1613           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
1614           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
1615
1616           (collect ((tests))
1617             (dolist (key keys)
1618               (let* ((info (lambda-var-arg-info key))
1619                      (default (arg-info-default info))
1620                      (keyword (arg-info-key info))
1621                      (supplied-p (arg-info-supplied-p info))
1622                      (n-value (gensym "N-VALUE-")))
1623                 (temps `(,n-value ,default))
1624                 (cond (supplied-p
1625                        (let ((n-supplied (gensym "N-SUPPLIED-")))
1626                          (temps n-supplied)
1627                          (arg-vals n-value n-supplied)
1628                          (tests `((eq ,n-key ',keyword)
1629                                   (setq ,n-supplied t)
1630                                   (setq ,n-value ,n-value-temp)))))
1631                       (t
1632                        (arg-vals n-value)
1633                        (tests `((eq ,n-key ',keyword)
1634                                 (setq ,n-value ,n-value-temp)))))))
1635
1636             (unless allowp
1637               (temps n-allowp n-losep)
1638               (tests `((eq ,n-key :allow-other-keys)
1639                        (setq ,n-allowp ,n-value-temp)))
1640               (tests `(t
1641                        (setq ,n-losep ,n-key))))
1642
1643             (body
1644              `(when (oddp ,n-count)
1645                 (%odd-key-arguments-error)))
1646
1647             (body
1648              `(locally
1649                 (declare (optimize (safety 0)))
1650                 (loop
1651                   (when (minusp ,n-index) (return))
1652                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
1653                   (decf ,n-index)
1654                   (setq ,n-key (%more-arg ,n-context ,n-index))
1655                   (decf ,n-index)
1656                   (cond ,@(tests)))))
1657
1658             (unless allowp
1659               (body `(when (and ,n-losep (not ,n-allowp))
1660                        (%unknown-key-argument-error ,n-losep)))))))
1661
1662       (let ((ep (ir1-convert-lambda-body
1663                  `((let ,(temps)
1664                      ,@(body)
1665                      (%funcall ,(optional-dispatch-main-entry res)
1666                                . ,(arg-vals)))) ; FIXME: What is the '.'? ,@?
1667                  (arg-vars)
1668                  :debug-name (debug-namify "~S processing" '&more))))
1669         (setf (optional-dispatch-more-entry res) ep))))
1670
1671   (values))
1672
1673 ;;; This is called by IR1-CONVERT-HAIRY-ARGS when we run into a &REST
1674 ;;; or &KEY arg. The arguments are similar to that function, but we
1675 ;;; split off any &REST arg and pass it in separately. REST is the
1676 ;;; &REST arg var, or NIL if there is no &REST arg. KEYS is a list of
1677 ;;; the &KEY argument vars.
1678 ;;;
1679 ;;; When there are &KEY arguments, we introduce temporary gensym
1680 ;;; variables to hold the values while keyword defaulting is in
1681 ;;; progress to get the required sequential binding semantics.
1682 ;;;
1683 ;;; This gets interesting mainly when there are &KEY arguments with
1684 ;;; supplied-p vars or non-constant defaults. In either case, pass in
1685 ;;; a supplied-p var. If the default is non-constant, we introduce an
1686 ;;; IF in the main entry that tests the supplied-p var and decides
1687 ;;; whether to evaluate the default or not. In this case, the real
1688 ;;; incoming value is NIL, so we must union NULL with the declared
1689 ;;; type when computing the type for the main entry's argument.
1690 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
1691                              rest more-context more-count keys supplied-p-p
1692                              body aux-vars aux-vals cont
1693                              source-name debug-name)
1694   (declare (type optional-dispatch res)
1695            (list default-vars default-vals entry-vars entry-vals keys body
1696                  aux-vars aux-vals)
1697            (type (or continuation null) cont))
1698   (collect ((main-vars (reverse default-vars))
1699             (main-vals default-vals cons)
1700             (bind-vars)
1701             (bind-vals))
1702     (when rest
1703       (main-vars rest)
1704       (main-vals '()))
1705     (when more-context
1706       (main-vars more-context)
1707       (main-vals nil)
1708       (main-vars more-count)
1709       (main-vals 0))
1710
1711     (dolist (key keys)
1712       (let* ((info (lambda-var-arg-info key))
1713              (default (arg-info-default info))
1714              (hairy-default (not (sb!xc:constantp default)))
1715              (supplied-p (arg-info-supplied-p info))
1716              (n-val (make-symbol (format nil
1717                                          "~A-DEFAULTING-TEMP"
1718                                          (leaf-source-name key))))
1719              (key-type (leaf-type key))
1720              (val-temp (make-lambda-var
1721                         :%source-name n-val
1722                         :type (if hairy-default
1723                                   (type-union key-type (specifier-type 'null))
1724                                   key-type))))
1725         (main-vars val-temp)
1726         (bind-vars key)
1727         (cond ((or hairy-default supplied-p)
1728                (let* ((n-supplied (gensym "N-SUPPLIED-"))
1729                       (supplied-temp (make-lambda-var
1730                                       :%source-name n-supplied)))
1731                  (unless supplied-p
1732                    (setf (arg-info-supplied-p info) supplied-temp))
1733                  (when hairy-default
1734                    (setf (arg-info-default info) nil))
1735                  (main-vars supplied-temp)
1736                  (cond (hairy-default
1737                         (main-vals nil nil)
1738                         (bind-vals `(if ,n-supplied ,n-val ,default)))
1739                        (t
1740                         (main-vals default nil)
1741                         (bind-vals n-val)))
1742                  (when supplied-p
1743                    (bind-vars supplied-p)
1744                    (bind-vals n-supplied))))
1745               (t
1746                (main-vals (arg-info-default info))
1747                (bind-vals n-val)))))
1748
1749     (let* ((main-entry (ir1-convert-lambda-body
1750                         body (main-vars)
1751                         :aux-vars (append (bind-vars) aux-vars)
1752                         :aux-vals (append (bind-vals) aux-vals)
1753                         :result cont
1754                         :debug-name (debug-namify "varargs entry point for ~A"
1755                                                   (as-debug-name source-name
1756                                                                  debug-name))))
1757            (last-entry (convert-optional-entry main-entry default-vars
1758                                                (main-vals) ())))
1759       (setf (optional-dispatch-main-entry res) main-entry)
1760       (convert-more-entry res entry-vars entry-vals rest more-context keys)
1761
1762       (push (if supplied-p-p
1763                 (convert-optional-entry last-entry entry-vars entry-vals ())
1764                 last-entry)
1765             (optional-dispatch-entry-points res))
1766       last-entry)))
1767
1768 ;;; This function generates the entry point functions for the
1769 ;;; OPTIONAL-DISPATCH RES. We accomplish this by recursion on the list
1770 ;;; of arguments, analyzing the arglist on the way down and generating
1771 ;;; entry points on the way up.
1772 ;;;
1773 ;;; DEFAULT-VARS is a reversed list of all the argument vars processed
1774 ;;; so far, including supplied-p vars. DEFAULT-VALS is a list of the
1775 ;;; names of the DEFAULT-VARS.
1776 ;;;
1777 ;;; ENTRY-VARS is a reversed list of processed argument vars,
1778 ;;; excluding supplied-p vars. ENTRY-VALS is a list things that can be
1779 ;;; evaluated to get the values for all the vars from the ENTRY-VARS.
1780 ;;; It has the var name for each required or optional arg, and has T
1781 ;;; for each supplied-p arg.
1782 ;;;
1783 ;;; VARS is a list of the LAMBDA-VAR structures for arguments that
1784 ;;; haven't been processed yet. SUPPLIED-P-P is true if a supplied-p
1785 ;;; argument has already been processed; only in this case are the
1786 ;;; DEFAULT-XXX and ENTRY-XXX different.
1787 ;;;
1788 ;;; The result at each point is a lambda which should be called by the
1789 ;;; above level to default the remaining arguments and evaluate the
1790 ;;; body. We cause the body to be evaluated by converting it and
1791 ;;; returning it as the result when the recursion bottoms out.
1792 ;;;
1793 ;;; Each level in the recursion also adds its entry point function to
1794 ;;; the result OPTIONAL-DISPATCH. For most arguments, the defaulting
1795 ;;; function and the entry point function will be the same, but when
1796 ;;; SUPPLIED-P args are present they may be different.
1797 ;;;
1798 ;;; When we run into a &REST or &KEY arg, we punt out to
1799 ;;; IR1-CONVERT-MORE, which finishes for us in this case.
1800 (defun ir1-convert-hairy-args (res default-vars default-vals
1801                                    entry-vars entry-vals
1802                                    vars supplied-p-p body aux-vars
1803                                    aux-vals cont
1804                                    source-name debug-name)
1805   (declare (type optional-dispatch res)
1806            (list default-vars default-vals entry-vars entry-vals vars body
1807                  aux-vars aux-vals)
1808            (type (or continuation null) cont))
1809   (cond ((not vars)
1810          (if (optional-dispatch-keyp res)
1811              ;; Handle &KEY with no keys...
1812              (ir1-convert-more res default-vars default-vals
1813                                entry-vars entry-vals
1814                                nil nil nil vars supplied-p-p body aux-vars
1815                                aux-vals cont source-name debug-name)
1816              (let ((fun (ir1-convert-lambda-body
1817                          body (reverse default-vars)
1818                          :aux-vars aux-vars
1819                          :aux-vals aux-vals
1820                          :result cont
1821                          :debug-name (debug-namify
1822                                       "hairy arg processor for ~A"
1823                                       (as-debug-name source-name
1824                                                      debug-name)))))
1825                (setf (optional-dispatch-main-entry res) fun)
1826                (push (if supplied-p-p
1827                          (convert-optional-entry fun entry-vars entry-vals ())
1828                          fun)
1829                      (optional-dispatch-entry-points res))
1830                fun)))
1831         ((not (lambda-var-arg-info (first vars)))
1832          (let* ((arg (first vars))
1833                 (nvars (cons arg default-vars))
1834                 (nvals (cons (leaf-source-name arg) default-vals)))
1835            (ir1-convert-hairy-args res nvars nvals nvars nvals
1836                                    (rest vars) nil body aux-vars aux-vals
1837                                    cont
1838                                    source-name debug-name)))
1839         (t
1840          (let* ((arg (first vars))
1841                 (info (lambda-var-arg-info arg))
1842                 (kind (arg-info-kind info)))
1843            (ecase kind
1844              (:optional
1845               (let ((ep (generate-optional-default-entry
1846                          res default-vars default-vals
1847                          entry-vars entry-vals vars supplied-p-p body
1848                          aux-vars aux-vals cont
1849                          source-name debug-name)))
1850                 (push (if supplied-p-p
1851                           (convert-optional-entry ep entry-vars entry-vals ())
1852                           ep)
1853                       (optional-dispatch-entry-points res))
1854                 ep))
1855              (:rest
1856               (ir1-convert-more res default-vars default-vals
1857                                 entry-vars entry-vals
1858                                 arg nil nil (rest vars) supplied-p-p body
1859                                 aux-vars aux-vals cont
1860                                 source-name debug-name))
1861              (:more-context
1862               (ir1-convert-more res default-vars default-vals
1863                                 entry-vars entry-vals
1864                                 nil arg (second vars) (cddr vars) supplied-p-p
1865                                 body aux-vars aux-vals cont
1866                                 source-name debug-name))
1867              (:keyword
1868               (ir1-convert-more res default-vars default-vals
1869                                 entry-vars entry-vals
1870                                 nil nil nil vars supplied-p-p body aux-vars
1871                                 aux-vals cont source-name debug-name)))))))
1872
1873 ;;; This function deals with the case where we have to make an
1874 ;;; OPTIONAL-DISPATCH to represent a LAMBDA. We cons up the result and
1875 ;;; call IR1-CONVERT-HAIRY-ARGS to do the work. When it is done, we
1876 ;;; figure out the MIN-ARGS and MAX-ARGS.
1877 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals cont
1878                                       &key
1879                                       (source-name '.anonymous.)
1880                                       (debug-name (debug-namify
1881                                                    "OPTIONAL-DISPATCH ~S"
1882                                                    vars)))
1883   (declare (list body vars aux-vars aux-vals) (type continuation cont))
1884   (let ((res (make-optional-dispatch :arglist vars
1885                                      :allowp allowp
1886                                      :keyp keyp
1887                                      :%source-name source-name
1888                                      :%debug-name debug-name))
1889         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
1890     (aver-live-component *current-component*)
1891     (push res (component-new-funs *current-component*))
1892     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
1893                             cont source-name debug-name)
1894     (setf (optional-dispatch-min-args res) min)
1895     (setf (optional-dispatch-max-args res)
1896           (+ (1- (length (optional-dispatch-entry-points res))) min))
1897
1898     (flet ((frob (ep)
1899              (when ep
1900                (setf (functional-kind ep) :optional)
1901                (setf (leaf-ever-used ep) t)
1902                (setf (lambda-optional-dispatch ep) res))))
1903       (dolist (ep (optional-dispatch-entry-points res)) (frob ep))
1904       (frob (optional-dispatch-more-entry res))
1905       (frob (optional-dispatch-main-entry res)))
1906
1907     res))
1908
1909 ;;; Convert a LAMBDA form into a LAMBDA leaf or an OPTIONAL-DISPATCH leaf.
1910 (defun ir1-convert-lambda (form &key (source-name '.anonymous.) debug-name)
1911
1912   (unless (consp form)
1913     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
1914                     (type-of form)
1915                     form))
1916   (unless (eq (car form) 'lambda)
1917     (compiler-error "~S was expected but ~S was found:~%  ~S"
1918                     'lambda
1919                     (car form)
1920                     form))
1921   (unless (and (consp (cdr form)) (listp (cadr form)))
1922     (compiler-error
1923      "The lambda expression has a missing or non-list lambda list:~%  ~S"
1924      form))
1925
1926   (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
1927       (make-lambda-vars (cadr form))
1928     (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr form))
1929       (let* ((result-cont (make-continuation))
1930              (*lexenv* (process-decls decls
1931                                       (append aux-vars vars)
1932                                       nil result-cont))
1933              (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
1934                       (ir1-convert-hairy-lambda forms vars keyp
1935                                                 allow-other-keys
1936                                                 aux-vars aux-vals result-cont
1937                                                 :source-name source-name
1938                                                 :debug-name debug-name)
1939                       (ir1-convert-lambda-body forms vars
1940                                                :aux-vars aux-vars
1941                                                :aux-vals aux-vals
1942                                                :result result-cont
1943                                                :source-name source-name
1944                                                :debug-name debug-name))))
1945         (setf (functional-inline-expansion res) form)
1946         (setf (functional-arg-documentation res) (cadr form))
1947         res))))
1948 \f
1949 ;;;; defining global functions
1950
1951 ;;; Convert FUN as a lambda in the null environment, but use the
1952 ;;; current compilation policy. Note that FUN may be a
1953 ;;; LAMBDA-WITH-LEXENV, so we may have to augment the environment to
1954 ;;; reflect the state at the definition site.
1955 (defun ir1-convert-inline-lambda (fun &key
1956                                       (source-name '.anonymous.)
1957                                       debug-name)
1958   (destructuring-bind (decls macros symbol-macros &rest body)
1959                       (if (eq (car fun) 'lambda-with-lexenv)
1960                           (cdr fun)
1961                           `(() () () . ,(cdr fun)))
1962     (let ((*lexenv* (make-lexenv
1963                      :default (process-decls decls nil nil
1964                                              (make-continuation)
1965                                              (make-null-lexenv))
1966                      :variables (copy-list symbol-macros)
1967                      :functions
1968                      (mapcar (lambda (x)
1969                                `(,(car x) .
1970                                  (macro . ,(coerce (cdr x) 'function))))
1971                              macros)
1972                      :policy (lexenv-policy *lexenv*))))
1973       (ir1-convert-lambda `(lambda ,@body)
1974                           :source-name source-name
1975                           :debug-name debug-name))))
1976
1977 ;;; Get a DEFINED-FUN object for a function we are about to
1978 ;;; define. If the function has been forward referenced, then
1979 ;;; substitute for the previous references.
1980 (defun get-defined-fun (name)
1981   (proclaim-as-fun-name name)
1982   (let ((found (find-free-fun name "shouldn't happen! (defined-fun)")))
1983     (note-name-defined name :function)
1984     (cond ((not (defined-fun-p found))
1985            (aver (not (info :function :inlinep name)))
1986            (let* ((where-from (leaf-where-from found))
1987                   (res (make-defined-fun
1988                         :%source-name name
1989                         :where-from (if (eq where-from :declared)
1990                                         :declared :defined)
1991                         :type (leaf-type found))))
1992              (substitute-leaf res found)
1993              (setf (gethash name *free-funs*) res)))
1994           ;; If *FREE-FUNS* has a previously converted definition
1995           ;; for this name, then blow it away and try again.
1996           ((defined-fun-functional found)
1997            (remhash name *free-funs*)
1998            (get-defined-fun name))
1999           (t found))))
2000
2001 ;;; Check a new global function definition for consistency with
2002 ;;; previous declaration or definition, and assert argument/result
2003 ;;; types if appropriate. This assertion is suppressed by the
2004 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
2005 ;;; check their argument types as a consequence of type dispatching.
2006 ;;; This avoids redundant checks such as NUMBERP on the args to +, etc.
2007 (defun assert-new-definition (var fun)
2008   (let ((type (leaf-type var))
2009         (for-real (eq (leaf-where-from var) :declared))
2010         (info (info :function :info (leaf-source-name var))))
2011     (assert-definition-type
2012      fun type
2013      ;; KLUDGE: Common Lisp is such a dynamic language that in general
2014      ;; all we can do here in general is issue a STYLE-WARNING. It
2015      ;; would be nice to issue a full WARNING in the special case of
2016      ;; of type mismatches within a compilation unit (as in section
2017      ;; 3.2.2.3 of the spec) but at least as of sbcl-0.6.11, we don't
2018      ;; keep track of whether the mismatched data came from the same
2019      ;; compilation unit, so we can't do that. -- WHN 2001-02-11
2020      :lossage-fun #'compiler-style-warn
2021      :unwinnage-fun (cond (info #'compiler-style-warn)
2022                           (for-real #'compiler-note)
2023                           (t nil))
2024      :really-assert
2025      (and for-real
2026           (not (and info
2027                     (ir1-attributep (fun-info-attributes info)
2028                                     explicit-check))))
2029      :where (if for-real
2030                 "previous declaration"
2031                 "previous definition"))))
2032
2033 ;;; Convert a lambda doing all the basic stuff we would do if we were
2034 ;;; converting a DEFUN. In the old CMU CL system, this was used both
2035 ;;; by the %DEFUN translator and for global inline expansion, but
2036 ;;; since sbcl-0.pre7.something %DEFUN does things differently.
2037 ;;; FIXME: And now it's probably worth rethinking whether this
2038 ;;; function is a good idea.
2039 ;;;
2040 ;;; Unless a :INLINE function, we temporarily clobber the inline
2041 ;;; expansion. This prevents recursive inline expansion of
2042 ;;; opportunistic pseudo-inlines.
2043 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
2044   (declare (cons lambda) (function converter) (type defined-fun var))
2045   (let ((var-expansion (defined-fun-inline-expansion var)))
2046     (unless (eq (defined-fun-inlinep var) :inline)
2047       (setf (defined-fun-inline-expansion var) nil))
2048     (let* ((name (leaf-source-name var))
2049            (fun (funcall converter lambda :source-name name))
2050            (fun-info (info :function :info name)))
2051       (setf (functional-inlinep fun) (defined-fun-inlinep var))
2052       (assert-new-definition var fun)
2053       (setf (defined-fun-inline-expansion var) var-expansion)
2054       ;; If definitely not an interpreter stub, then substitute for any
2055       ;; old references.
2056       (unless (or (eq (defined-fun-inlinep var) :notinline)
2057                   (not *block-compile*)
2058                   (and fun-info
2059                        (or (fun-info-transforms fun-info)
2060                            (fun-info-templates fun-info)
2061                            (fun-info-ir2-convert fun-info))))
2062         (substitute-leaf fun var)
2063         ;; If in a simple environment, then we can allow backward
2064         ;; references to this function from following top level forms.
2065         (when expansion (setf (defined-fun-functional var) fun)))
2066       fun)))
2067
2068 ;;; the even-at-compile-time part of DEFUN
2069 ;;;
2070 ;;; The INLINE-EXPANSION is a LAMBDA-WITH-LEXENV, or NIL if there is
2071 ;;; no inline expansion.
2072 (defun %compiler-defun (name lambda-with-lexenv)
2073
2074   (let ((defined-fun nil)) ; will be set below if we're in the compiler
2075     
2076     (when (boundp '*lexenv*) ; when in the compiler
2077       (when sb!xc:*compile-print*
2078         (compiler-mumble "~&; recognizing DEFUN ~S~%" name))
2079       (remhash name *free-funs*)
2080       (setf defined-fun (get-defined-fun name)))
2081
2082     (become-defined-fun-name name)
2083
2084     (cond (lambda-with-lexenv
2085            (setf (info :function :inline-expansion-designator name)
2086                  lambda-with-lexenv)
2087            (when defined-fun 
2088              (setf (defined-fun-inline-expansion defined-fun)
2089                    lambda-with-lexenv)))
2090           (t
2091            (clear-info :function :inline-expansion-designator name)))
2092
2093     ;; old CMU CL comment:
2094     ;;   If there is a type from a previous definition, blast it,
2095     ;;   since it is obsolete.
2096     (when (and defined-fun
2097                (eq (leaf-where-from defined-fun) :defined))
2098       (setf (leaf-type defined-fun)
2099             ;; FIXME: If this is a block compilation thing, shouldn't
2100             ;; we be setting the type to the full derived type for the
2101             ;; definition, instead of this most general function type?
2102             (specifier-type 'function))))
2103
2104   (values))