89c17f6892ce600e569197cc3698d201bd77dc92
[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 (file-comment
16   "$Header$")
17
18 (declaim (special *compiler-error-bailout*))
19
20 ;;; *SOURCE-PATHS* is a hashtable from source code forms to the path
21 ;;; taken through the source to reach the form. This provides a way to
22 ;;; keep track of the location of original source forms, even when
23 ;;; macroexpansions and other arbitary permutations of the code
24 ;;; happen. This table is initialized by calling Find-Source-Paths on
25 ;;; the original source.
26 (declaim (hash-table *source-paths*))
27 (defvar *source-paths*)
28
29 ;;; *CURRENT-COMPONENT* is the Component structure which we link
30 ;;; blocks into as we generate them. This just serves to glue the
31 ;;; emitted blocks together until local call analysis and flow graph
32 ;;; canonicalization figure out what is really going on. We need to
33 ;;; keep track of all the blocks generated so that we can delete them
34 ;;; if they turn out to be unreachable.
35 ;;;
36 ;;; FIXME: It's confusing having one variable named *CURRENT-COMPONENT*
37 ;;; and another named *COMPONENT-BEING-COMPILED*. (In CMU CL they
38 ;;; were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively,
39 ;;; which also confusing.)
40 (declaim (type (or component null) *current-component*))
41 (defvar *current-component*)
42
43 ;;; *CURRENT-PATH* is the source path of the form we are currently
44 ;;; translating. See NODE-SOURCE-PATH in the NODE structure.
45 (declaim (list *current-path*))
46 (defvar *current-path* nil)
47
48 ;;; *CONVERTING-FOR-INTERPRETER* is true when we are creating IR1 to
49 ;;; be interpreted rather than compiled. This inhibits source
50 ;;; tranformations and stuff.
51 (defvar *converting-for-interpreter* nil)
52 ;;; FIXME: Rename to *IR1-FOR-INTERPRETER-NOT-COMPILER-P*.
53
54 ;;; *COMPILE-TIME-DEFINE-MACROS* is true when we want DEFMACRO
55 ;;; definitions to be installed in the compilation environment as
56 ;;; interpreted functions. We set this to false when compiling some
57 ;;; parts of the system.
58 (defvar *compile-time-define-macros* t)
59 ;;; FIXME: I think this can go away with the new system.
60
61 ;;; FIXME: This nastiness was one of my original motivations to start
62 ;;; hacking CMU CL. The non-ANSI behavior can be useful, but it should
63 ;;; be made not the default, and perhaps should be controlled by
64 ;;; DECLAIM instead of a variable like this. And whether or not this
65 ;;; kind of checking is on, declarations should be assertions to the
66 ;;; extent practical, and code which can't be compiled efficiently
67 ;;; while adhering to that principle should give warnings.
68 (defvar *derive-function-types* t
69   #!+sb-doc
70   "(Caution: Soon, this might change its semantics somewhat, or even go away.)
71   If true, argument and result type information derived from compilation of
72   DEFUNs is used when compiling calls to that function. If false, only
73   information from FTYPE proclamations will be used.")
74 \f
75 ;;;; namespace management utilities
76
77 ;;; Return a GLOBAL-VAR structure usable for referencing the global
78 ;;; function NAME.
79 (defun find-free-really-function (name)
80   (unless (info :function :kind name)
81     (setf (info :function :kind name) :function)
82     (setf (info :function :where-from name) :assumed))
83
84   (let ((where (info :function :where-from name)))
85     (when (eq where :assumed)
86       (note-undefined-reference name :function))
87     (make-global-var :kind :global-function
88                      :name name
89                      :type (if (or *derive-function-types*
90                                    (eq where :declared))
91                                (info :function :type name)
92                                (specifier-type 'function))
93                      :where-from where)))
94
95 ;;; Return a SLOT-ACCESSOR structure usable for referencing the slot
96 ;;; accessor NAME. CLASS is the structure class.
97 (defun find-structure-slot-accessor (class name)
98   (declare (type sb!xc:class class))
99   (let* ((info (layout-info
100                 (or (info :type :compiler-layout (sb!xc:class-name class))
101                     (class-layout class))))
102          (accessor (if (listp name) (cadr name) name))
103          (slot (find accessor (dd-slots info) :key #'sb!kernel:dsd-accessor))
104          (type (dd-name info))
105          (slot-type (dsd-type slot)))
106     (assert slot () "Can't find slot ~S." type)
107     (make-slot-accessor
108      :name name
109      :type (specifier-type
110             (if (listp name)
111                 `(function (,slot-type ,type) ,slot-type)
112                 `(function (,type) ,slot-type)))
113      :for class
114      :slot slot)))
115
116 ;;; If NAME is already entered in *FREE-FUNCTIONS*, then return the
117 ;;; value. Otherwise, make a new GLOBAL-VAR using information from the
118 ;;; global environment and enter it in *FREE-FUNCTIONS*. If NAME names
119 ;;; a macro or special form, then we error out using the supplied
120 ;;; context which indicates what we were trying to do that demanded a
121 ;;; function.
122 (defun find-free-function (name context)
123   (declare (string context))
124   (declare (values global-var))
125   (or (gethash name *free-functions*)
126       (ecase (info :function :kind name)
127         ;; FIXME: The :MACRO and :SPECIAL-FORM cases could be merged.
128         (:macro
129          (compiler-error "The macro name ~S was found ~A." name context))
130         (:special-form
131          (compiler-error "The special form name ~S was found ~A."
132                          name
133                          context))
134         ((:function nil)
135          (check-function-name name)
136          (note-if-setf-function-and-macro name)
137          (let ((expansion (info :function :inline-expansion name))
138                (inlinep (info :function :inlinep name)))
139            (setf (gethash name *free-functions*)
140                  (if (or expansion inlinep)
141                      (make-defined-function
142                       :name name
143                       :inline-expansion expansion
144                       :inlinep inlinep
145                       :where-from (info :function :where-from name)
146                       :type (info :function :type name))
147                      (let ((info (info :function :accessor-for name)))
148                        (etypecase info
149                          (null
150                           (find-free-really-function name))
151                          (sb!xc:structure-class
152                           (find-structure-slot-accessor info name))
153                          (sb!xc:class
154                           (if (typep (layout-info (info :type :compiler-layout
155                                                         (sb!xc:class-name
156                                                          info)))
157                                      'defstruct-description)
158                               (find-structure-slot-accessor info name)
159                               (find-free-really-function name))))))))))))
160
161 ;;; Return the LEAF structure for the lexically apparent function
162 ;;; definition of NAME.
163 (declaim (ftype (function (t string) leaf) find-lexically-apparent-function))
164 (defun find-lexically-apparent-function (name context)
165   (let ((var (lexenv-find name functions :test #'equal)))
166     (cond (var
167            (unless (leaf-p var)
168              (assert (and (consp var) (eq (car var) 'macro)))
169              (compiler-error "found macro name ~S ~A" name context))
170            var)
171           (t
172            (find-free-function name context)))))
173
174 ;;; Return the LEAF node for a global variable reference to NAME. If
175 ;;; NAME is already entered in *FREE-VARIABLES*, then we just return
176 ;;; the corresponding value. Otherwise, we make a new leaf using
177 ;;; information from the global environment and enter it in
178 ;;; *FREE-VARIABLES*. If the variable is unknown, then we emit a
179 ;;; warning.
180 (defun find-free-variable (name)
181   (declare (values (or leaf heap-alien-info)))
182   (unless (symbolp name)
183     (compiler-error "Variable name is not a symbol: ~S." name))
184   (or (gethash name *free-variables*)
185       (let ((kind (info :variable :kind name))
186             (type (info :variable :type name))
187             (where-from (info :variable :where-from name)))
188         (when (and (eq where-from :assumed) (eq kind :global))
189           (note-undefined-reference name :variable))
190
191         (setf (gethash name *free-variables*)
192               (if (eq kind :alien)
193                   (info :variable :alien-info name)
194                   (multiple-value-bind (val valp)
195                       (info :variable :constant-value name)
196                     (if (and (eq kind :constant) valp)
197                         (make-constant :value val
198                                        :name name
199                                        :type (ctype-of val)
200                                        :where-from where-from)
201                         (make-global-var :kind kind
202                                          :name name
203                                          :type type
204                                          :where-from where-from))))))))
205 \f
206 ;;; Grovel over CONSTANT checking for any sub-parts that need to be
207 ;;; processed with MAKE-LOAD-FORM. We have to be careful, because
208 ;;; CONSTANT might be circular. We also check that the constant (and
209 ;;; any subparts) are dumpable at all.
210 (defconstant list-to-hash-table-threshold 32)
211 (defun maybe-emit-make-load-forms (constant)
212   (let ((things-processed nil)
213         (count 0))
214     ;; FIXME: Does this LIST-or-HASH-TABLE messiness give much benefit?
215     (declare (type (or list hash-table) things-processed)
216              (type (integer 0 #.(1+ list-to-hash-table-threshold)) count)
217              (inline member))
218     (labels ((grovel (value)
219                ;; Unless VALUE is an object which which obviously
220                ;; can't contain other objects
221                (unless (typep value
222                               '(or #-sb-xc-host unboxed-array
223                                    symbol
224                                    number
225                                    character
226                                    string))
227                  (etypecase things-processed
228                    (list
229                     (when (member value things-processed :test #'eq)
230                       (return-from grovel nil))
231                     (push value things-processed)
232                     (incf count)
233                     (when (> count list-to-hash-table-threshold)
234                       (let ((things things-processed))
235                         (setf things-processed
236                               (make-hash-table :test 'eq))
237                         (dolist (thing things)
238                           (setf (gethash thing things-processed) t)))))
239                    (hash-table
240                     (when (gethash value things-processed)
241                       (return-from grovel nil))
242                     (setf (gethash value things-processed) t)))
243                  (typecase value
244                    (cons
245                     (grovel (car value))
246                     (grovel (cdr value)))
247                    (simple-vector
248                     (dotimes (i (length value))
249                       (grovel (svref value i))))
250                    ((vector t)
251                     (dotimes (i (length value))
252                       (grovel (aref value i))))
253                    ((simple-array t)
254                     ;; Even though the (ARRAY T) branch does the exact
255                     ;; same thing as this branch we do this separately
256                     ;; so that the compiler can use faster versions of
257                     ;; array-total-size and row-major-aref.
258                     (dotimes (i (array-total-size value))
259                       (grovel (row-major-aref value i))))
260                    ((array t)
261                     (dotimes (i (array-total-size value))
262                       (grovel (row-major-aref value i))))
263                    (;; In the target SBCL, we can dump any instance,
264                     ;; but in the cross-compilation host,
265                     ;; %INSTANCE-FOO functions don't work on general
266                     ;; instances, only on STRUCTURE!OBJECTs.
267                     #+sb-xc-host structure!object
268                     #-sb-xc-host instance
269                     (when (emit-make-load-form value)
270                       (dotimes (i (%instance-length value))
271                         (grovel (%instance-ref value i)))))
272                    (t
273                     (compiler-error
274                      "Objects of type ~S can't be dumped into fasl files."
275                      (type-of value)))))))
276       (grovel constant)))
277   (values))
278 \f
279 ;;;; some flow-graph hacking utilities
280
281 ;;; This function sets up the back link between the node and the
282 ;;; continuation which continues at it.
283 #!-sb-fluid (declaim (inline prev-link))
284 (defun prev-link (node cont)
285   (declare (type node node) (type continuation cont))
286   (assert (not (continuation-next cont)))
287   (setf (continuation-next cont) node)
288   (setf (node-prev node) cont))
289
290 ;;; This function is used to set the continuation for a node, and thus
291 ;;; determine what receives the value and what is evaluated next. If
292 ;;; the continuation has no block, then we make it be in the block
293 ;;; that the node is in. If the continuation heads its block, we end
294 ;;; our block and link it to that block. If the continuation is not
295 ;;; currently used, then we set the derived-type for the continuation
296 ;;; to that of the node, so that a little type propagation gets done.
297 ;;;
298 ;;; We also deal with a bit of THE's semantics here: we weaken the
299 ;;; assertion on CONT to be no stronger than the assertion on CONT in
300 ;;; our scope. See the IR1-CONVERT method for THE.
301 #!-sb-fluid (declaim (inline use-continuation))
302 (defun use-continuation (node cont)
303   (declare (type node node) (type continuation cont))
304   (let ((node-block (continuation-block (node-prev node))))
305     (case (continuation-kind cont)
306       (:unused
307        (setf (continuation-block cont) node-block)
308        (setf (continuation-kind cont) :inside-block)
309        (setf (continuation-use cont) node)
310        (setf (node-cont node) cont))
311       (t
312        (%use-continuation node cont)))))
313 (defun %use-continuation (node cont)
314   (declare (type node node) (type continuation cont) (inline member))
315   (let ((block (continuation-block cont))
316         (node-block (continuation-block (node-prev node))))
317     (assert (eq (continuation-kind cont) :block-start))
318     (assert (not (block-last node-block)) () "~S has already ended."
319             node-block)
320     (setf (block-last node-block) node)
321     (assert (null (block-succ node-block)) () "~S already has successors."
322             node-block)
323     (setf (block-succ node-block) (list block))
324     (assert (not (member node-block (block-pred block) :test #'eq)) ()
325             "~S is already a predecessor of ~S." node-block block)
326     (push node-block (block-pred block))
327     (add-continuation-use node cont)
328     (unless (eq (continuation-asserted-type cont) *wild-type*)
329       (let ((new (values-type-union (continuation-asserted-type cont)
330                                     (or (lexenv-find cont type-restrictions)
331                                         *wild-type*))))
332         (when (type/= new (continuation-asserted-type cont))
333           (setf (continuation-asserted-type cont) new)
334           (reoptimize-continuation cont))))))
335 \f
336 ;;;; exported functions
337
338 ;;; This function takes a form and the top-level form number for that
339 ;;; form, and returns a lambda representing the translation of that
340 ;;; form in the current global environment. The lambda is top-level
341 ;;; lambda that can be called to cause evaluation of the forms. This
342 ;;; lambda is in the initial component. If FOR-VALUE is T, then the
343 ;;; value of the form is returned from the function, otherwise NIL is
344 ;;; returned.
345 ;;;
346 ;;; This function may have arbitrary effects on the global environment
347 ;;; due to processing of PROCLAIMs and EVAL-WHENs. All syntax error
348 ;;; checking is done, with erroneous forms being replaced by a proxy
349 ;;; which signals an error if it is evaluated. Warnings about possibly
350 ;;; inconsistent or illegal changes to the global environment will
351 ;;; also be given.
352 ;;;
353 ;;; We make the initial component and convert the form in a PROGN (and
354 ;;; an optional NIL tacked on the end.) We then return the lambda. We
355 ;;; bind all of our state variables here, rather than relying on the
356 ;;; global value (if any) so that IR1 conversion will be reentrant.
357 ;;; This is necessary for EVAL-WHEN processing, etc.
358 ;;;
359 ;;; The hashtables used to hold global namespace info must be
360 ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so
361 ;;; that local macro definitions can be introduced by enclosing code.
362 (defun ir1-top-level (form path for-value)
363   (declare (list path))
364   (let* ((*current-path* path)
365          (component (make-empty-component))
366          (*current-component* component))
367     (setf (component-name component) "initial component")
368     (setf (component-kind component) :initial)
369     (let* ((forms (if for-value `(,form) `(,form nil)))
370            (res (ir1-convert-lambda-body forms ())))
371       (setf (leaf-name res) "top-level form")
372       (setf (functional-entry-function res) res)
373       (setf (functional-arg-documentation res) ())
374       (setf (functional-kind res) :top-level)
375       res)))
376
377 ;;; *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the
378 ;;; form number to associate with a source path. This should be bound
379 ;;; to 0 around the processing of each truly top-level form.
380 (declaim (type index *current-form-number*))
381 (defvar *current-form-number*)
382
383 ;;; This function is called on freshly read forms to record the
384 ;;; initial location of each form (and subform.) Form is the form to
385 ;;; find the paths in, and TLF-Num is the top-level form number of the
386 ;;; truly top-level form.
387 ;;;
388 ;;; This gets a bit interesting when the source code is circular. This
389 ;;; can (reasonably?) happen in the case of circular list constants.
390 (defun find-source-paths (form tlf-num)
391   (declare (type index tlf-num))
392   (let ((*current-form-number* 0))
393     (sub-find-source-paths form (list tlf-num)))
394   (values))
395 (defun sub-find-source-paths (form path)
396   (unless (gethash form *source-paths*)
397     (setf (gethash form *source-paths*)
398           (list* 'original-source-start *current-form-number* path))
399     (incf *current-form-number*)
400     (let ((pos 0)
401           (subform form)
402           (trail form))
403       (declare (fixnum pos))
404       (macrolet ((frob ()
405                    '(progn
406                       (when (atom subform) (return))
407                       (let ((fm (car subform)))
408                         (when (consp fm)
409                           (sub-find-source-paths fm (cons pos path)))
410                         (incf pos))
411                       (setq subform (cdr subform))
412                       (when (eq subform trail) (return)))))
413         (loop
414           (frob)
415           (frob)
416           (setq trail (cdr trail)))))))
417 \f
418 ;;;; IR1-CONVERT, macroexpansion and special form dispatching
419
420 (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws
421            ;; out of the body and converts a proxy form instead.
422            (ir1-error-bailout ((start
423                                 cont
424                                 form
425                                 &optional
426                                 (proxy ``(error "execution of a form compiled with errors:~% ~S"
427                                                 ',,form)))
428                                &body body)
429                               (let ((skip (gensym "SKIP")))
430                                 `(block ,skip
431                                    (catch 'ir1-error-abort
432                                      (let ((*compiler-error-bailout*
433                                             #'(lambda ()
434                                                 (throw 'ir1-error-abort nil))))
435                                        ,@body
436                                        (return-from ,skip nil)))
437                                    (ir1-convert ,start ,cont ,proxy)))))
438
439   ;; Translate FORM into IR1. The code is inserted as the NEXT of the
440   ;; continuation START. CONT is the continuation which receives the
441   ;; value of the FORM to be translated. The translators call this
442   ;; function recursively to translate their subnodes.
443   ;;
444   ;; As a special hack to make life easier in the compiler, a LEAF
445   ;; IR1-converts into a reference to that LEAF structure. This allows
446   ;; the creation using backquote of forms that contain leaf
447   ;; references, without having to introduce dummy names into the
448   ;; namespace.
449   (declaim (ftype (function (continuation continuation t) (values)) ir1-convert))
450   (defun ir1-convert (start cont form)
451     (ir1-error-bailout (start cont form)
452       (let ((*current-path* (or (gethash form *source-paths*)
453                                 (cons form *current-path*))))
454         (if (atom form)
455             (cond ((and (symbolp form) (not (keywordp form)))
456                    (ir1-convert-variable start cont form))
457                   ((leaf-p form)
458                    (reference-leaf start cont form))
459                   (t
460                    (reference-constant start cont form)))
461             (let ((fun (car form)))
462               (cond
463                ((symbolp fun)
464                 (let ((lexical-def (lexenv-find fun functions)))
465                   (typecase lexical-def
466                     (null (ir1-convert-global-functoid start cont form))
467                     (functional
468                      (ir1-convert-local-combination start
469                                                     cont
470                                                     form
471                                                     lexical-def))
472                     (global-var
473                      (ir1-convert-srctran start cont lexical-def form))
474                     (t
475                      (assert (and (consp lexical-def)
476                                   (eq (car lexical-def) 'macro)))
477                      (ir1-convert start cont
478                                   (careful-expand-macro (cdr lexical-def)
479                                                         form))))))
480                ((or (atom fun) (not (eq (car fun) 'lambda)))
481                 (compiler-error "illegal function call"))
482                (t
483                 (ir1-convert-combination start
484                                          cont
485                                          form
486                                          (ir1-convert-lambda fun))))))))
487     (values))
488
489   ;; Generate a reference to a manifest constant, creating a new leaf
490   ;; if necessary. If we are producing a fasl-file, make sure that
491   ;; MAKE-LOAD-FORM gets used on any parts of the constant that it
492   ;; needs to be.
493   (defun reference-constant (start cont value)
494     (declare (type continuation start cont)
495              (inline find-constant))
496     (ir1-error-bailout
497      (start cont value
498             '(error "attempt to reference undumpable constant"))
499      (when (producing-fasl-file)
500        (maybe-emit-make-load-forms value))
501      (let* ((leaf (find-constant value))
502             (res (make-ref (leaf-type leaf) leaf)))
503        (push res (leaf-refs leaf))
504        (prev-link res start)
505        (use-continuation res cont)))
506     (values)))
507
508 ;;; Add Fun to the COMPONENT-REANALYZE-FUNCTIONS. Fun is returned.
509  (defun maybe-reanalyze-function (fun)
510   (declare (type functional fun))
511   (when (typep fun '(or optional-dispatch clambda))
512     (pushnew fun (component-reanalyze-functions *current-component*)))
513   fun)
514
515 ;;; Generate a Ref node for LEAF, frobbing the LEAF structure as
516 ;;; needed. If LEAF represents a defined function which has already
517 ;;; been converted, and is not :NOTINLINE, then reference the
518 ;;; functional instead.
519 (defun reference-leaf (start cont leaf)
520   (declare (type continuation start cont) (type leaf leaf))
521   (let* ((leaf (or (and (defined-function-p leaf)
522                         (not (eq (defined-function-inlinep leaf)
523                                  :notinline))
524                         (let ((fun (defined-function-functional leaf)))
525                           (when (and fun (not (functional-kind fun)))
526                             (maybe-reanalyze-function fun))))
527                    leaf))
528          (res (make-ref (or (lexenv-find leaf type-restrictions)
529                             (leaf-type leaf))
530                         leaf)))
531     (push res (leaf-refs leaf))
532     (setf (leaf-ever-used leaf) t)
533     (prev-link res start)
534     (use-continuation res cont)))
535
536 ;;; Convert a reference to a symbolic constant or variable. If the
537 ;;; symbol is entered in the LEXENV-VARIABLES we use that definition,
538 ;;; otherwise we find the current global definition. This is also
539 ;;; where we pick off symbol macro and Alien variable references.
540 (defun ir1-convert-variable (start cont name)
541   (declare (type continuation start cont) (symbol name))
542   (let ((var (or (lexenv-find name variables) (find-free-variable name))))
543     (etypecase var
544       (leaf
545        (when (and (lambda-var-p var) (lambda-var-ignorep var))
546          ;; (ANSI's specification for the IGNORE declaration requires
547          ;; that this be a STYLE-WARNING, not a full WARNING.)
548          (compiler-style-warning "reading an ignored variable: ~S" name))
549        (reference-leaf start cont var))
550       (cons
551        (assert (eq (car var) 'MACRO))
552        (ir1-convert start cont (cdr var)))
553       (heap-alien-info
554        (ir1-convert start cont `(%heap-alien ',var)))))
555   (values))
556
557 ;;; Convert anything that looks like a special form, global function
558 ;;; or macro call.
559 (defun ir1-convert-global-functoid (start cont form)
560   (declare (type continuation start cont) (list form))
561   (let* ((fun (first form))
562          (translator (info :function :ir1-convert fun))
563          (cmacro (info :function :compiler-macro-function fun)))
564     (cond (translator (funcall translator start cont form))
565           ((and cmacro (not *converting-for-interpreter*)
566                 (not (eq (info :function :inlinep fun) :notinline)))
567            (let ((res (careful-expand-macro cmacro form)))
568              (if (eq res form)
569                  (ir1-convert-global-functoid-no-cmacro start cont form fun)
570                  (ir1-convert start cont res))))
571           (t
572            (ir1-convert-global-functoid-no-cmacro start cont form fun)))))
573
574 ;;; Handle the case of where the call was not a compiler macro, or was a
575 ;;; compiler macro and passed.
576 (defun ir1-convert-global-functoid-no-cmacro (start cont form fun)
577   (declare (type continuation start cont) (list form))
578   ;; FIXME: Couldn't all the INFO calls here be converted into
579   ;; standard CL functions, like MACRO-FUNCTION or something?
580   ;; And what happens with lexically-defined (MACROLET) macros
581   ;; here, anyway?
582   (ecase (info :function :kind fun)
583     (:macro
584      (ir1-convert start
585                   cont
586                   (careful-expand-macro (info :function :macro-function fun)
587                                         form)))
588     ((nil :function)
589      (ir1-convert-srctran start cont (find-free-function fun "Eh?") form))))
590
591 (defun muffle-warning-or-die ()
592   (muffle-warning)
593   (error "internal error -- no MUFFLE-WARNING restart"))
594
595 ;;; Trap errors during the macroexpansion.
596 (defun careful-expand-macro (fun form)
597   (handler-bind (;; When cross-compiling, we can get style warnings
598                  ;; about e.g. undefined functions. An unhandled
599                  ;; CL:STYLE-WARNING (as opposed to a
600                  ;; SB!C::COMPILER-NOTE) would cause FAILURE-P to be
601                  ;; set on the return from #'SB!XC:COMPILE-FILE, which
602                  ;; would falsely indicate an error sufficiently
603                  ;; serious that we should stop the build process. To
604                  ;; avoid this, we translate CL:STYLE-WARNING
605                  ;; conditions from the host Common Lisp into
606                  ;; cross-compiler SB!C::COMPILER-NOTE calls. (It
607                  ;; might be cleaner to just make Python use
608                  ;; CL:STYLE-WARNING internally, so that the
609                  ;; significance of any host Common Lisp
610                  ;; CL:STYLE-WARNINGs is understood automatically. But
611                  ;; for now I'm not motivated to do this. -- WHN
612                  ;; 19990412)
613                  (style-warning (lambda (c)
614                                   (compiler-note "(during macroexpansion)~%~A"
615                                                  c)
616                                   (muffle-warning-or-die)))
617                  ;; KLUDGE: CMU CL in its wisdom (version 2.4.6 for
618                  ;; Debian Linux, anyway) raises a CL:WARNING
619                  ;; condition (not a CL:STYLE-WARNING) for undefined
620                  ;; symbols when converting interpreted functions,
621                  ;; causing COMPILE-FILE to think the file has a real
622                  ;; problem, causing COMPILE-FILE to return FAILURE-P
623                  ;; set (not just WARNINGS-P set). Since undefined
624                  ;; symbol warnings are often harmless forward
625                  ;; references, and since it'd be inordinately painful
626                  ;; to try to eliminate all such forward references,
627                  ;; these warnings are basically unavoidable. Thus, we
628                  ;; need to coerce the system to work through them,
629                  ;; and this code does so, by crudely suppressing all
630                  ;; warnings in cross-compilation macroexpansion. --
631                  ;; WHN 19990412
632                  #+cmu
633                  (warning (lambda (c)
634                             (compiler-note
635                              "(during macroexpansion)~%~
636                               ~A~%~
637                               (KLUDGE: That was a non-STYLE WARNING.~%~
638                               Ordinarily that would cause compilation to~%~
639                               fail. However, since we're running under~%~
640                               CMU CL, and since CMU CL emits non-STYLE~%~
641                               warnings for safe, hard-to-fix things (e.g.~%~
642                               references to not-yet-defined functions)~%~
643                               we're going to have to ignore it and proceed~%~
644                               anyway. Hopefully we're not ignoring anything~%~
645                               horrible here..)~%"
646                              c)
647                             (muffle-warning-or-die)))
648                  (error (lambda (c)
649                           (compiler-error "(during macroexpansion)~%~A" c))))
650     (funcall sb!xc:*macroexpand-hook*
651              fun
652              form
653              *lexenv*)))
654 \f
655 ;;;; conversion utilities
656
657 ;;; Convert a bunch of forms, discarding all the values except the
658 ;;; last. If there aren't any forms, then translate a NIL.
659 (declaim (ftype (function (continuation continuation list) (values))
660                 ir1-convert-progn-body))
661 (defun ir1-convert-progn-body (start cont body)
662   (if (endp body)
663       (reference-constant start cont nil)
664       (let ((this-start start)
665             (forms body))
666         (loop
667           (let ((form (car forms)))
668             (when (endp (cdr forms))
669               (ir1-convert this-start cont form)
670               (return))
671             (let ((this-cont (make-continuation)))
672               (ir1-convert this-start this-cont form)
673               (setq this-start this-cont  forms (cdr forms)))))))
674   (values))
675 \f
676 ;;;; converting combinations
677
678 ;;; Convert a function call where the function (Fun) is a Leaf. We
679 ;;; return the Combination node so that we can poke at it if we want to.
680 (declaim (ftype (function (continuation continuation list leaf) combination)
681                 ir1-convert-combination))
682 (defun ir1-convert-combination (start cont form fun)
683   (let ((fun-cont (make-continuation)))
684     (reference-leaf start fun-cont fun)
685     (ir1-convert-combination-args fun-cont cont (cdr form))))
686
687 ;;; Convert the arguments to a call and make the Combination node. Fun-Cont
688 ;;; is the continuation which yields the function to call. Form is the source
689 ;;; for the call. Args is the list of arguments for the call, which defaults
690 ;;; to the cdr of source. We return the Combination node.
691 (defun ir1-convert-combination-args (fun-cont cont args)
692   (declare (type continuation fun-cont cont) (list args))
693   (let ((node (make-combination fun-cont)))
694     (setf (continuation-dest fun-cont) node)
695     (assert-continuation-type fun-cont
696                               (specifier-type '(or function symbol)))
697     (collect ((arg-conts))
698       (let ((this-start fun-cont))
699         (dolist (arg args)
700           (let ((this-cont (make-continuation node)))
701             (ir1-convert this-start this-cont arg)
702             (setq this-start this-cont)
703             (arg-conts this-cont)))
704         (prev-link node this-start)
705         (use-continuation node cont)
706         (setf (combination-args node) (arg-conts))))
707     node))
708
709 ;;; Convert a call to a global function. If not :NOTINLINE, then we do
710 ;;; source transforms and try out any inline expansion. If there is no
711 ;;; expansion, but is :INLINE, then give an efficiency note (unless a known
712 ;;; function which will quite possibly be open-coded.)   Next, we go to
713 ;;; ok-combination conversion.
714 (defun ir1-convert-srctran (start cont var form)
715   (declare (type continuation start cont) (type global-var var))
716   (let ((inlinep (when (defined-function-p var)
717                    (defined-function-inlinep var))))
718     (cond
719      ((eq inlinep :notinline)
720       (ir1-convert-combination start cont form var))
721      (*converting-for-interpreter*
722       (ir1-convert-combination-checking-type start cont form var))
723      (t
724       (let ((transform (info :function :source-transform (leaf-name var))))
725         (cond
726          (transform
727           (multiple-value-bind (result pass) (funcall transform form)
728             (if pass
729                 (ir1-convert-maybe-predicate start cont form var)
730                 (ir1-convert start cont result))))
731          (t
732           (ir1-convert-maybe-predicate start cont form var))))))))
733
734 ;;; If the function has the Predicate attribute, and the CONT's DEST isn't
735 ;;; an IF, then we convert (IF <form> T NIL), ensuring that a predicate always
736 ;;; appears in a conditional context.
737 ;;;
738 ;;; If the function isn't a predicate, then we call
739 ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE.
740 (defun ir1-convert-maybe-predicate (start cont form var)
741   (declare (type continuation start cont) (list form) (type global-var var))
742   (let ((info (info :function :info (leaf-name var))))
743     (if (and info
744              (ir1-attributep (function-info-attributes info) predicate)
745              (not (if-p (continuation-dest cont))))
746         (ir1-convert start cont `(if ,form t nil))
747         (ir1-convert-combination-checking-type start cont form var))))
748
749 ;;; Actually really convert a global function call that we are allowed
750 ;;; to early-bind.
751 ;;;
752 ;;; If we know the function type of the function, then we check the
753 ;;; call for syntactic legality with respect to the declared function
754 ;;; type. If it is impossible to determine whether the call is correct
755 ;;; due to non-constant keywords, then we give up, marking the call as
756 ;;; :FULL to inhibit further error messages. We return true when the
757 ;;; call is legal.
758 ;;;
759 ;;; If the call is legal, we also propagate type assertions from the
760 ;;; function type to the arg and result continuations. We do this now
761 ;;; so that IR1 optimize doesn't have to redundantly do the check
762 ;;; later so that it can do the type propagation.
763 (defun ir1-convert-combination-checking-type (start cont form var)
764   (declare (type continuation start cont) (list form) (type leaf var))
765   (let* ((node (ir1-convert-combination start cont form var))
766          (fun-cont (basic-combination-fun node))
767          (type (leaf-type var)))
768     (when (validate-call-type node type t)
769       (setf (continuation-%derived-type fun-cont) type)
770       (setf (continuation-reoptimize fun-cont) nil)
771       (setf (continuation-%type-check fun-cont) nil)))
772
773   (values))
774
775 ;;; Convert a call to a local function. If the function has already
776 ;;; been let converted, then throw FUN to LOCAL-CALL-LOSSAGE. This
777 ;;; should only happen when we are converting inline expansions for
778 ;;; local functions during optimization.
779 (defun ir1-convert-local-combination (start cont form fun)
780   (if (functional-kind fun)
781       (throw 'local-call-lossage fun)
782       (ir1-convert-combination start cont form
783                                (maybe-reanalyze-function fun))))
784 \f
785 ;;;; PROCESS-DECLS
786
787 ;;; Given a list of Lambda-Var structures and a variable name, return
788 ;;; the structure for that name, or NIL if it isn't found. We return
789 ;;; the *last* variable with that name, since LET* bindings may be
790 ;;; duplicated, and declarations always apply to the last.
791 (declaim (ftype (function (list symbol) (or lambda-var list))
792                 find-in-bindings))
793 (defun find-in-bindings (vars name)
794   (let ((found nil))
795     (dolist (var vars)
796       (cond ((leaf-p var)
797              (when (eq (leaf-name var) name)
798                (setq found var))
799              (let ((info (lambda-var-arg-info var)))
800                (when info
801                  (let ((supplied-p (arg-info-supplied-p info)))
802                    (when (and supplied-p
803                               (eq (leaf-name supplied-p) name))
804                      (setq found supplied-p))))))
805             ((and (consp var) (eq (car var) name))
806              (setf found (cdr var)))))
807     found))
808
809 ;;; Called by Process-Decls to deal with a variable type declaration.
810 ;;; If a lambda-var being bound, we intersect the type with the vars
811 ;;; type, otherwise we add a type-restriction on the var. If a symbol
812 ;;; macro, we just wrap a THE around the expansion.
813 (defun process-type-declaration (decl res vars)
814   (declare (list decl vars) (type lexenv res))
815   (let ((type (specifier-type (first decl))))
816     (collect ((restr nil cons)
817               (new-vars nil cons))
818       (dolist (var-name (rest decl))
819         (let* ((bound-var (find-in-bindings vars var-name))
820                (var (or bound-var
821                         (lexenv-find var-name variables)
822                         (find-free-variable var-name))))
823           (etypecase var
824             (leaf
825              (let* ((old-type (or (lexenv-find var type-restrictions)
826                                   (leaf-type var)))
827                     (int (if (or (function-type-p type)
828                                  (function-type-p old-type))
829                              type
830                              (type-intersection old-type type))))
831                (cond ((eq int *empty-type*)
832                       (unless (policy nil (= brevity 3))
833                         (compiler-warning
834                          "The type declarations ~S and ~S for ~S conflict."
835                          (type-specifier old-type) (type-specifier type)
836                          var-name)))
837                      (bound-var (setf (leaf-type bound-var) int))
838                      (t
839                       (restr (cons var int))))))
840             (cons
841              ;; FIXME: non-ANSI weirdness
842              (assert (eq (car var) 'MACRO))
843              (new-vars `(,var-name . (MACRO . (the ,(first decl)
844                                                    ,(cdr var))))))
845             (heap-alien-info
846              (compiler-error
847               "~S is an alien variable, so its type can't be declared."
848               var-name)))))
849
850       (if (or (restr) (new-vars))
851           (make-lexenv :default res
852                        :type-restrictions (restr)
853                        :variables (new-vars))
854           res))))
855
856 ;;; Somewhat similar to Process-Type-Declaration, but handles
857 ;;; declarations for function variables. In addition to allowing
858 ;;; declarations for functions being bound, we must also deal with
859 ;;; declarations that constrain the type of lexically apparent
860 ;;; functions.
861 (defun process-ftype-declaration (spec res names fvars)
862   (declare (list spec names fvars) (type lexenv res))
863   (let ((type (specifier-type spec)))
864     (collect ((res nil cons))
865       (dolist (name names)
866         (let ((found (find name fvars :key #'leaf-name :test #'equal)))
867           (cond
868            (found
869             (setf (leaf-type found) type)
870             (assert-definition-type found type
871                                     :warning-function #'compiler-note
872                                     :where "FTYPE declaration"))
873            (t
874             (res (cons (find-lexically-apparent-function
875                         name "in a function type declaration")
876                        type))))))
877       (if (res)
878           (make-lexenv :default res :type-restrictions (res))
879           res))))
880
881 ;;; Process a special declaration, returning a new LEXENV. A non-bound
882 ;;; special declaration is instantiated by throwing a special variable
883 ;;; into the variables.
884 (defun process-special-declaration (spec res vars)
885   (declare (list spec vars) (type lexenv res))
886   (collect ((new-venv nil cons))
887     (dolist (name (cdr spec))
888       (let ((var (find-in-bindings vars name)))
889         (etypecase var
890           (cons
891            (assert (eq (car var) 'MACRO))
892            (compiler-error
893             "~S is a symbol-macro and thus can't be declared special."
894             name))
895           (lambda-var
896            (when (lambda-var-ignorep var)
897              ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
898              ;; requires that this be a STYLE-WARNING, not a full WARNING.
899              (compiler-style-warning
900               "The ignored variable ~S is being declared special."
901               name))
902            (setf (lambda-var-specvar var)
903                  (specvar-for-binding name)))
904           (null
905            (unless (assoc name (new-venv) :test #'eq)
906              (new-venv (cons name (specvar-for-binding name))))))))
907     (if (new-venv)
908         (make-lexenv :default res :variables (new-venv))
909         res)))
910
911 ;;; Return a DEFINED-FUNCTION which copies a global-var but for its inlinep.
912 (defun make-new-inlinep (var inlinep)
913   (declare (type global-var var) (type inlinep inlinep))
914   (let ((res (make-defined-function
915               :name (leaf-name var)
916               :where-from (leaf-where-from var)
917               :type (leaf-type var)
918               :inlinep inlinep)))
919     (when (defined-function-p var)
920       (setf (defined-function-inline-expansion res)
921             (defined-function-inline-expansion var))
922       (setf (defined-function-functional res)
923             (defined-function-functional var)))
924     res))
925
926 ;;; Parse an inline/notinline declaration. If it's a local function we're
927 ;;; defining, set its INLINEP. If a global function, add a new FENV entry.
928 (defun process-inline-declaration (spec res fvars)
929   (let ((sense (cdr (assoc (first spec) inlinep-translations :test #'eq)))
930         (new-fenv ()))
931     (dolist (name (rest spec))
932       (let ((fvar (find name fvars :key #'leaf-name :test #'equal)))
933         (if fvar
934             (setf (functional-inlinep fvar) sense)
935             (let ((found
936                    (find-lexically-apparent-function
937                     name "in an inline or notinline declaration")))
938               (etypecase found
939                 (functional
940                  (when (policy nil (>= speed brevity))
941                    (compiler-note "ignoring ~A declaration not at ~
942                                    definition of local function:~%  ~S"
943                                   sense name)))
944                 (global-var
945                  (push (cons name (make-new-inlinep found sense))
946                        new-fenv)))))))
947
948     (if new-fenv
949         (make-lexenv :default res :functions new-fenv)
950         res)))
951
952 ;;; Like FIND-IN-BINDINGS, but looks for #'foo in the fvars.
953 (defun find-in-bindings-or-fbindings (name vars fvars)
954   (declare (list vars fvars))
955   (if (consp name)
956       (destructuring-bind (wot fn-name) name
957         (unless (eq wot 'function)
958           (compiler-error "The function or variable name ~S is unrecognizable."
959                           name))
960         (find fn-name fvars :key #'leaf-name :test #'equal))
961       (find-in-bindings vars name)))
962
963 ;;; Process an ignore/ignorable declaration, checking for various losing
964 ;;; conditions.
965 (defun process-ignore-declaration (spec vars fvars)
966   (declare (list spec vars fvars))
967   (dolist (name (rest spec))
968     (let ((var (find-in-bindings-or-fbindings name vars fvars)))
969       (cond
970        ((not var)
971         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
972         ;; requires that this be a STYLE-WARNING, not a full WARNING.
973         (compiler-style-warning "declaring unknown variable ~S to be ignored"
974                                 name))
975        ;; FIXME: This special case looks like non-ANSI weirdness.
976        ((and (consp var) (consp (cdr var)) (eq (cadr var) 'macro))
977         ;; Just ignore the IGNORE decl.
978         )
979        ((functional-p var)
980         (setf (leaf-ever-used var) t))
981        ((lambda-var-specvar var)
982         ;; ANSI's definition for "Declaration IGNORE, IGNORABLE"
983         ;; requires that this be a STYLE-WARNING, not a full WARNING.
984         (compiler-style-warning "declaring special variable ~S to be ignored"
985                                 name))
986        ((eq (first spec) 'ignorable)
987         (setf (leaf-ever-used var) t))
988        (t
989         (setf (lambda-var-ignorep var) t)))))
990   (values))
991
992 ;;; FIXME: This is non-ANSI, so the default should be T, or it should
993 ;;; go away, I think.
994 (defvar *suppress-values-declaration* nil
995   #!+sb-doc
996   "If true, processing of the VALUES declaration is inhibited.")
997
998 ;;; Process a single declaration spec, agumenting the specified LEXENV
999 ;;; Res and returning it as a result. Vars and Fvars are as described in
1000 ;;; PROCESS-DECLS.
1001 (defun process-1-declaration (spec res vars fvars cont)
1002   (declare (list spec vars fvars) (type lexenv res) (type continuation cont))
1003   (case (first spec)
1004     (special (process-special-declaration spec res vars))
1005     (ftype
1006      (unless (cdr spec)
1007        (compiler-error "No type specified in FTYPE declaration: ~S." spec))
1008      (process-ftype-declaration (second spec) res (cddr spec) fvars))
1009     (function
1010      ;; Handle old style FUNCTION declaration, which is an abbreviation for
1011      ;; FTYPE. Args are name, arglist, result type.
1012      (cond ((and (proper-list-of-length-p spec 3 4)
1013                  (listp (third spec)))
1014             (process-ftype-declaration `(function ,@(cddr spec)) res
1015                                        (list (second spec))
1016                                        fvars))
1017            (t
1018             (process-type-declaration spec res vars))))
1019     ((inline notinline maybe-inline)
1020      (process-inline-declaration spec res fvars))
1021     ((ignore ignorable)
1022      (process-ignore-declaration spec vars fvars)
1023      res)
1024     (optimize
1025      (make-lexenv
1026       :default res
1027       :cookie (process-optimize-declaration spec (lexenv-cookie res))))
1028     (optimize-interface
1029      (make-lexenv
1030       :default res
1031       :interface-cookie (process-optimize-declaration
1032                          spec
1033                          (lexenv-interface-cookie res))))
1034     (type
1035      (process-type-declaration (cdr spec) res vars))
1036     (sb!pcl::class
1037      (process-type-declaration (list (third spec) (second spec)) res vars))
1038     (values
1039      (if *suppress-values-declaration*
1040          res
1041          (let ((types (cdr spec)))
1042            (do-the-stuff (if (eql (length types) 1)
1043                              (car types)
1044                              `(values ,@types))
1045                          cont res 'values))))
1046     (dynamic-extent
1047      (when (policy nil (> speed brevity))
1048        (compiler-note
1049         "The DYNAMIC-EXTENT declaration is not implemented (ignored)."))
1050      res)
1051     (t
1052      (let ((what (first spec)))
1053        (cond ((member what *standard-type-names*)
1054               (process-type-declaration spec res vars))
1055              ((and (not (and (symbolp what)
1056                              (string= (symbol-name what) "CLASS"))) ; pcl hack
1057                    (or (info :type :kind what)
1058                        (and (consp what) (info :type :translator (car what)))))
1059               (unless (policy nil (= brevity 3))
1060                 ;; FIXME: Is it ANSI to warn about this? I think not.
1061                 (compiler-note "abbreviated type declaration: ~S." spec))
1062               (process-type-declaration spec res vars))
1063              ((info :declaration :recognized what)
1064               res)
1065              (t
1066               (compiler-warning "unrecognized declaration ~S" spec)
1067               res))))))
1068
1069 ;;; Use a list of DECLARE forms to annotate the lists of LAMBDA-VAR and
1070 ;;; Functional structures which are being bound. In addition to filling in
1071 ;;; slots in the leaf structures, we return a new LEXENV which reflects
1072 ;;; pervasive special and function type declarations, (NOT)INLINE declarations
1073 ;;; and OPTIMIZE declarations. CONT is the continuation affected by VALUES
1074 ;;; declarations.
1075 ;;;
1076 ;;; This is also called in main.lisp when PROCESS-FORM handles a use of
1077 ;;; LOCALLY.
1078 (defun process-decls (decls vars fvars cont &optional (env *lexenv*))
1079   (declare (list decls vars fvars) (type continuation cont))
1080   (dolist (decl decls)
1081     (dolist (spec (rest decl))
1082       (unless (consp spec)
1083         (compiler-error "malformed declaration specifier ~S in ~S"
1084                         spec
1085                         decl))
1086       (setq env (process-1-declaration spec env vars fvars cont))))
1087   env)
1088
1089 ;;; Return the Specvar for Name to use when we see a local SPECIAL
1090 ;;; declaration. If there is a global variable of that name, then
1091 ;;; check that it isn't a constant and return it. Otherwise, create an
1092 ;;; anonymous GLOBAL-VAR.
1093 (defun specvar-for-binding (name)
1094   (cond ((not (eq (info :variable :where-from name) :assumed))
1095          (let ((found (find-free-variable name)))
1096            (when (heap-alien-info-p found)
1097              (compiler-error
1098               "~S is an alien variable and so can't be declared special."
1099               name))
1100            (when (or (not (global-var-p found))
1101                      (eq (global-var-kind found) :constant))
1102              (compiler-error
1103               "~S is a constant and so can't be declared special."
1104               name))
1105            found))
1106         (t
1107          (make-global-var :kind :special
1108                           :name name
1109                           :where-from :declared))))
1110 \f
1111 ;;;; LAMBDA hackery
1112
1113 ;;;; Note: Take a look at the compiler-overview.tex section on "Hairy
1114 ;;;; function representation" before you seriously mess with this
1115 ;;;; stuff.
1116
1117 ;;; Verify that a thing is a legal name for a variable and return a
1118 ;;; Var structure for it, filling in info if it is globally special.
1119 ;;; If it is losing, we punt with a Compiler-Error. Names-So-Far is an
1120 ;;; alist of names which have previously been bound. If the name is in
1121 ;;; this list, then we error out.
1122 (declaim (ftype (function (t list) lambda-var) varify-lambda-arg))
1123 (defun varify-lambda-arg (name names-so-far)
1124   (declare (inline member))
1125   (unless (symbolp name)
1126     (compiler-error "The lambda-variable ~S is not a symbol." name))
1127   (when (member name names-so-far :test #'eq)
1128     (compiler-error "The variable ~S occurs more than once in the lambda-list."
1129                     name))
1130   (let ((kind (info :variable :kind name)))
1131     (when (or (keywordp name) (eq kind :constant))
1132       (compiler-error "The name of the lambda-variable ~S is a constant."
1133                       name))
1134     (cond ((eq kind :special)
1135            (let ((specvar (find-free-variable name)))
1136              (make-lambda-var :name name
1137                               :type (leaf-type specvar)
1138                               :where-from (leaf-where-from specvar)
1139                               :specvar specvar)))
1140           (t
1141            (note-lexical-binding name)
1142            (make-lambda-var :name name)))))
1143
1144 ;;; Make the keyword for a keyword arg, checking that the keyword
1145 ;;; isn't already used by one of the Vars. We also check that the
1146 ;;; keyword isn't the magical :allow-other-keys.
1147 (declaim (ftype (function (symbol list t) keyword) make-keyword-for-arg))
1148 (defun make-keyword-for-arg (symbol vars keywordify)
1149   (let ((key (if (and keywordify (not (keywordp symbol)))
1150                  (intern (symbol-name symbol) "KEYWORD")
1151                  symbol)))
1152     (when (eq key :allow-other-keys)
1153       (compiler-error "No keyword arg can be called :ALLOW-OTHER-KEYS."))
1154     (dolist (var vars)
1155       (let ((info (lambda-var-arg-info var)))
1156         (when (and info
1157                    (eq (arg-info-kind info) :keyword)
1158                    (eq (arg-info-keyword info) key))
1159           (compiler-error
1160            "The keyword ~S appears more than once in the lambda-list."
1161            key))))
1162     key))
1163
1164 ;;; Parse a lambda-list into a list of Var structures, stripping off
1165 ;;; any aux bindings. Each arg name is checked for legality, and
1166 ;;; duplicate names are checked for. If an arg is globally special,
1167 ;;; the var is marked as :special instead of :lexical. Keyword,
1168 ;;; optional and rest args are annotated with an arg-info structure
1169 ;;; which contains the extra information. If we hit something losing,
1170 ;;; we bug out with Compiler-Error. These values are returned:
1171 ;;;  1. A list of the var structures for each top-level argument.
1172 ;;;  2. A flag indicating whether &key was specified.
1173 ;;;  3. A flag indicating whether other keyword args are allowed.
1174 ;;;  4. A list of the &aux variables.
1175 ;;;  5. A list of the &aux values.
1176 (declaim (ftype (function (list) (values list boolean boolean list list))
1177                 find-lambda-vars))
1178 (defun find-lambda-vars (list)
1179   (multiple-value-bind (required optional restp rest keyp keys allowp aux
1180                         morep more-context more-count)
1181       (parse-lambda-list list)
1182     (collect ((vars)
1183               (names-so-far)
1184               (aux-vars)
1185               (aux-vals))
1186       ;; Parse-Default deals with defaults and supplied-p args for optionals
1187       ;; and keywords args.
1188       (flet ((parse-default (spec info)
1189                (when (consp (cdr spec))
1190                  (setf (arg-info-default info) (second spec))
1191                  (when (consp (cddr spec))
1192                    (let* ((supplied-p (third spec))
1193                           (supplied-var (varify-lambda-arg supplied-p
1194                                                            (names-so-far))))
1195                      (setf (arg-info-supplied-p info) supplied-var)
1196                      (names-so-far supplied-p)
1197                      (when (> (length (the list spec)) 3)
1198                        (compiler-error
1199                         "The list ~S is too long to be an arg specifier."
1200                         spec)))))))
1201         
1202         (dolist (name required)
1203           (let ((var (varify-lambda-arg name (names-so-far))))
1204             (vars var)
1205             (names-so-far name)))
1206         
1207         (dolist (spec optional)
1208           (if (atom spec)
1209               (let ((var (varify-lambda-arg spec (names-so-far))))
1210                 (setf (lambda-var-arg-info var) (make-arg-info :kind :optional))
1211                 (vars var)
1212                 (names-so-far spec))
1213               (let* ((name (first spec))
1214                      (var (varify-lambda-arg name (names-so-far)))
1215                      (info (make-arg-info :kind :optional)))
1216                 (setf (lambda-var-arg-info var) info)
1217                 (vars var)
1218                 (names-so-far name)
1219                 (parse-default spec info))))
1220         
1221         (when restp
1222           (let ((var (varify-lambda-arg rest (names-so-far))))
1223             (setf (lambda-var-arg-info var) (make-arg-info :kind :rest))
1224             (vars var)
1225             (names-so-far rest)))
1226
1227         (when morep
1228           (let ((var (varify-lambda-arg more-context (names-so-far))))
1229             (setf (lambda-var-arg-info var)
1230                   (make-arg-info :kind :more-context))
1231             (vars var)
1232             (names-so-far more-context))
1233           (let ((var (varify-lambda-arg more-count (names-so-far))))
1234             (setf (lambda-var-arg-info var)
1235                   (make-arg-info :kind :more-count))
1236             (vars var)
1237             (names-so-far more-count)))
1238         
1239         (dolist (spec keys)
1240           (cond
1241            ((atom spec)
1242             (let ((var (varify-lambda-arg spec (names-so-far))))
1243               (setf (lambda-var-arg-info var)
1244                     (make-arg-info :kind :keyword
1245                                    :keyword (make-keyword-for-arg spec
1246                                                                   (vars)
1247                                                                   t)))
1248               (vars var)
1249               (names-so-far spec)))
1250            ((atom (first spec))
1251             (let* ((name (first spec))
1252                    (var (varify-lambda-arg name (names-so-far)))
1253                    (info (make-arg-info
1254                           :kind :keyword
1255                           :keyword (make-keyword-for-arg name (vars) t))))
1256               (setf (lambda-var-arg-info var) info)
1257               (vars var)
1258               (names-so-far name)
1259               (parse-default spec info)))
1260            (t
1261             (let ((head (first spec)))
1262               (unless (proper-list-of-length-p head 2)
1263                 (error "malformed keyword arg specifier: ~S" spec))
1264               (let* ((name (second head))
1265                      (var (varify-lambda-arg name (names-so-far)))
1266                      (info (make-arg-info
1267                             :kind :keyword
1268                             :keyword (make-keyword-for-arg (first head)
1269                                                            (vars)
1270                                                            nil))))
1271                 (setf (lambda-var-arg-info var) info)
1272                 (vars var)
1273                 (names-so-far name)
1274                 (parse-default spec info))))))
1275         
1276         (dolist (spec aux)
1277           (cond ((atom spec)
1278                  (let ((var (varify-lambda-arg spec nil)))
1279                    (aux-vars var)
1280                    (aux-vals nil)
1281                    (names-so-far spec)))
1282                 (t
1283                  (unless (proper-list-of-length-p spec 1 2)
1284                    (compiler-error "malformed &AUX binding specifier: ~S"
1285                                    spec))
1286                  (let* ((name (first spec))
1287                         (var (varify-lambda-arg name nil)))
1288                    (aux-vars var)
1289                    (aux-vals (second spec))
1290                    (names-so-far name)))))
1291
1292         (values (vars) keyp allowp (aux-vars) (aux-vals))))))
1293
1294 ;;; Similar to IR1-Convert-Progn-Body except that we sequentially bind each
1295 ;;; Aux-Var to the corresponding Aux-Val before converting the body. If there
1296 ;;; are no bindings, just convert the body, otherwise do one binding and
1297 ;;; recurse on the rest.
1298 ;;;
1299 ;;;    If Interface is true, then we convert bindings with the interface
1300 ;;; policy. For real &aux bindings, and implicit aux bindings introduced by
1301 ;;; keyword bindings, this is always true. It is only false when LET* directly
1302 ;;; calls this function.
1303 (defun ir1-convert-aux-bindings (start cont body aux-vars aux-vals interface)
1304   (declare (type continuation start cont) (list body aux-vars aux-vals))
1305   (if (null aux-vars)
1306       (ir1-convert-progn-body start cont body)
1307       (let ((fun-cont (make-continuation))
1308             (fun (ir1-convert-lambda-body body (list (first aux-vars))
1309                                           (rest aux-vars) (rest aux-vals)
1310                                           interface)))
1311         (reference-leaf start fun-cont fun)
1312         (let ((*lexenv* (if interface
1313                             (make-lexenv
1314                              :cookie (make-interface-cookie *lexenv*))
1315                             *lexenv*)))
1316           (ir1-convert-combination-args fun-cont cont
1317                                         (list (first aux-vals))))))
1318   (values))
1319
1320 ;;; Similar to IR1-Convert-Progn-Body except that code to bind the Specvar
1321 ;;; for each Svar to the value of the variable is wrapped around the body. If
1322 ;;; there are no special bindings, we just convert the body, otherwise we do
1323 ;;; one special binding and recurse on the rest.
1324 ;;;
1325 ;;; We make a cleanup and introduce it into the lexical environment. If
1326 ;;; there are multiple special bindings, the cleanup for the blocks will end up
1327 ;;; being the innermost one. We force Cont to start a block outside of this
1328 ;;; cleanup, causing cleanup code to be emitted when the scope is exited.
1329 (defun ir1-convert-special-bindings (start cont body aux-vars aux-vals
1330                                            interface svars)
1331   (declare (type continuation start cont)
1332            (list body aux-vars aux-vals svars))
1333   (cond
1334    ((null svars)
1335     (ir1-convert-aux-bindings start cont body aux-vars aux-vals interface))
1336    (t
1337     (continuation-starts-block cont)
1338     (let ((cleanup (make-cleanup :kind :special-bind))
1339           (var (first svars))
1340           (next-cont (make-continuation))
1341           (nnext-cont (make-continuation)))
1342       (ir1-convert start next-cont
1343                    `(%special-bind ',(lambda-var-specvar var) ,var))
1344       (setf (cleanup-mess-up cleanup) (continuation-use next-cont))
1345       (let ((*lexenv* (make-lexenv :cleanup cleanup)))
1346         (ir1-convert next-cont nnext-cont '(%cleanup-point))
1347         (ir1-convert-special-bindings nnext-cont cont body aux-vars aux-vals
1348                                       interface (rest svars))))))
1349   (values))
1350
1351 ;;; Create a lambda node out of some code, returning the result. The
1352 ;;; bindings are specified by the list of var structures Vars. We deal
1353 ;;; with adding the names to the Lexenv-Variables for the conversion.
1354 ;;; The result is added to the New-Functions in the
1355 ;;; *Current-Component* and linked to the component head and tail.
1356 ;;;
1357 ;;; We detect special bindings here, replacing the original Var in the
1358 ;;; lambda list with a temporary variable. We then pass a list of the
1359 ;;; special vars to IR1-Convert-Special-Bindings, which actually emits
1360 ;;; the special binding code.
1361 ;;;
1362 ;;; We ignore any Arg-Info in the Vars, trusting that someone else is
1363 ;;; dealing with &nonsense.
1364 ;;;
1365 ;;; Aux-Vars is a list of Var structures for variables that are to be
1366 ;;; sequentially bound. Each Aux-Val is a form that is to be evaluated
1367 ;;; to get the initial value for the corresponding Aux-Var. Interface
1368 ;;; is a flag as T when there are real aux values (see let* and
1369 ;;; ir1-convert-aux-bindings.)
1370 (defun ir1-convert-lambda-body (body vars &optional aux-vars aux-vals
1371                                      interface result)
1372   (declare (list body vars aux-vars aux-vals)
1373            (type (or continuation null) result))
1374   (let* ((bind (make-bind))
1375          (lambda (make-lambda :vars vars :bind bind))
1376          (result (or result (make-continuation))))
1377     (setf (lambda-home lambda) lambda)
1378     (collect ((svars)
1379               (new-venv nil cons))
1380
1381       (dolist (var vars)
1382         (setf (lambda-var-home var) lambda)
1383         (let ((specvar (lambda-var-specvar var)))
1384           (cond (specvar
1385                  (svars var)
1386                  (new-venv (cons (leaf-name specvar) specvar)))
1387                 (t
1388                  (note-lexical-binding (leaf-name var))
1389                  (new-venv (cons (leaf-name var) var))))))
1390
1391       (let ((*lexenv* (make-lexenv :variables (new-venv)
1392                                    :lambda lambda
1393                                    :cleanup nil)))
1394         (setf (bind-lambda bind) lambda)
1395         (setf (node-lexenv bind) *lexenv*)
1396         
1397         (let ((cont1 (make-continuation))
1398               (cont2 (make-continuation)))
1399           (continuation-starts-block cont1)
1400           (prev-link bind cont1)
1401           (use-continuation bind cont2)
1402           (ir1-convert-special-bindings cont2 result body aux-vars aux-vals
1403                                         interface (svars)))
1404
1405         (let ((block (continuation-block result)))
1406           (when block
1407             (let ((return (make-return :result result :lambda lambda))
1408                   (tail-set (make-tail-set :functions (list lambda)))
1409                   (dummy (make-continuation)))
1410               (setf (lambda-tail-set lambda) tail-set)
1411               (setf (lambda-return lambda) return)
1412               (setf (continuation-dest result) return)
1413               (setf (block-last block) return)
1414               (prev-link return result)
1415               (use-continuation return dummy))
1416             (link-blocks block (component-tail *current-component*))))))
1417
1418     (link-blocks (component-head *current-component*) (node-block bind))
1419     (push lambda (component-new-functions *current-component*))
1420     lambda))
1421
1422 ;;; Create the actual entry-point function for an optional entry
1423 ;;; point. The lambda binds copies of each of the Vars, then calls Fun
1424 ;;; with the argument Vals and the Defaults. Presumably the Vals refer
1425 ;;; to the Vars by name. The Vals are passed in in reverse order.
1426 ;;;
1427 ;;; If any of the copies of the vars are referenced more than once,
1428 ;;; then we mark the corresponding var as Ever-Used to inhibit
1429 ;;; "defined but not read" warnings for arguments that are only used
1430 ;;; by default forms.
1431 ;;;
1432 ;;; We bind *LEXENV* to change the policy to the interface policy.
1433 (defun convert-optional-entry (fun vars vals defaults)
1434   (declare (type clambda fun) (list vars vals defaults))
1435   (let* ((fvars (reverse vars))
1436          (arg-vars (mapcar (lambda (var)
1437                              (unless (lambda-var-specvar var)
1438                                (note-lexical-binding (leaf-name var)))
1439                              (make-lambda-var
1440                               :name (leaf-name var)
1441                               :type (leaf-type var)
1442                               :where-from (leaf-where-from var)
1443                               :specvar (lambda-var-specvar var)))
1444                            fvars))
1445          (*lexenv* (make-lexenv :cookie (make-interface-cookie *lexenv*)))
1446          (fun
1447           (ir1-convert-lambda-body
1448            `((%funcall ,fun ,@(reverse vals) ,@defaults))
1449            arg-vars)))
1450     (mapc #'(lambda (var arg-var)
1451               (when (cdr (leaf-refs arg-var))
1452                 (setf (leaf-ever-used var) t)))
1453           fvars arg-vars)
1454     fun))
1455
1456 ;;; This function deals with supplied-p vars in optional arguments. If
1457 ;;; the there is no supplied-p arg, then we just call
1458 ;;; IR1-Convert-Hairy-Args on the remaining arguments, and generate a
1459 ;;; optional entry that calls the result. If there is a supplied-p
1460 ;;; var, then we add it into the default vars and throw a T into the
1461 ;;; entry values. The resulting entry point function is returned.
1462 (defun generate-optional-default-entry (res default-vars default-vals
1463                                             entry-vars entry-vals
1464                                             vars supplied-p-p body
1465                                             aux-vars aux-vals cont)
1466   (declare (type optional-dispatch res)
1467            (list default-vars default-vals entry-vars entry-vals vars body
1468                  aux-vars aux-vals)
1469            (type (or continuation null) cont))
1470   (let* ((arg (first vars))
1471          (arg-name (leaf-name arg))
1472          (info (lambda-var-arg-info arg))
1473          (supplied-p (arg-info-supplied-p info))
1474          (ep (if supplied-p
1475                  (ir1-convert-hairy-args
1476                   res
1477                   (list* supplied-p arg default-vars)
1478                   (list* (leaf-name supplied-p) arg-name default-vals)
1479                   (cons arg entry-vars)
1480                   (list* t arg-name entry-vals)
1481                   (rest vars) t body aux-vars aux-vals cont)
1482                  (ir1-convert-hairy-args
1483                   res
1484                   (cons arg default-vars)
1485                   (cons arg-name default-vals)
1486                   (cons arg entry-vars)
1487                   (cons arg-name entry-vals)
1488                   (rest vars) supplied-p-p body aux-vars aux-vals cont))))
1489
1490     (convert-optional-entry ep default-vars default-vals
1491                             (if supplied-p
1492                                 (list (arg-info-default info) nil)
1493                                 (list (arg-info-default info))))))
1494
1495 ;;; Create the More-Entry function for the Optional-Dispatch Res.
1496 ;;; Entry-Vars and Entry-Vals describe the fixed arguments. Rest is the var
1497 ;;; for any Rest arg. Keys is a list of the keyword arg vars.
1498 ;;;
1499 ;;; The most interesting thing that we do is parse keywords. We create a
1500 ;;; bunch of temporary variables to hold the result of the parse, and then loop
1501 ;;; over the supplied arguments, setting the appropriate temps for the supplied
1502 ;;; keyword. Note that it is significant that we iterate over the keywords in
1503 ;;; reverse order --- this implements the CL requirement that (when a keyword
1504 ;;; appears more than once) the first value is used.
1505 ;;;
1506 ;;; If there is no supplied-p var, then we initialize the temp to the
1507 ;;; default and just pass the temp into the main entry. Since non-constant
1508 ;;; keyword args are forcibly given a supplied-p var, we know that the default
1509 ;;; is constant, and thus safe to evaluate out of order.
1510 ;;;
1511 ;;; If there is a supplied-p var, then we create temps for both the value
1512 ;;; and the supplied-p, and pass them into the main entry, letting it worry
1513 ;;; about defaulting.
1514 ;;;
1515 ;;; We deal with :allow-other-keys by delaying unknown keyword errors until
1516 ;;; we have scanned all the keywords.
1517 ;;;
1518 ;;; When converting the function, we bind *LEXENV* to change the
1519 ;;; compilation policy over to the interface policy, so that keyword
1520 ;;; args will be checked even when type checking isn't on in general.
1521 (defun convert-more-entry (res entry-vars entry-vals rest morep keys)
1522   (declare (type optional-dispatch res) (list entry-vars entry-vals keys))
1523   (collect ((arg-vars)
1524             (arg-vals (reverse entry-vals))
1525             (temps)
1526             (body))
1527
1528     (dolist (var (reverse entry-vars))
1529       (arg-vars (make-lambda-var :name (leaf-name var)
1530                                  :type (leaf-type var)
1531                                  :where-from (leaf-where-from var))))
1532
1533     (let* ((n-context (gensym "N-CONTEXT-"))
1534            (context-temp (make-lambda-var :name n-context))
1535            (n-count (gensym "N-COUNT-"))
1536            (count-temp (make-lambda-var :name n-count
1537                                         :type (specifier-type 'index)))
1538            (*lexenv* (make-lexenv :cookie (make-interface-cookie *lexenv*))))
1539
1540       (arg-vars context-temp count-temp)
1541
1542       (when rest
1543         (arg-vals `(%listify-rest-args ,n-context ,n-count)))
1544       (when morep
1545         (arg-vals n-context)
1546         (arg-vals n-count))
1547
1548       (when (optional-dispatch-keyp res)
1549         (let ((n-index (gensym "N-INDEX-"))
1550               (n-key (gensym "N-KEY-"))
1551               (n-value-temp (gensym "N-VALUE-TEMP-"))
1552               (n-allowp (gensym "N-ALLOWP-"))
1553               (n-losep (gensym "N-LOSEP-"))
1554               (allowp (or (optional-dispatch-allowp res)
1555                           (policy nil (zerop safety)))))
1556
1557           (temps `(,n-index (1- ,n-count)) n-key n-value-temp)
1558           (body `(declare (fixnum ,n-index) (ignorable ,n-key ,n-value-temp)))
1559
1560           (collect ((tests))
1561             (dolist (key keys)
1562               (let* ((info (lambda-var-arg-info key))
1563                      (default (arg-info-default info))
1564                      (keyword (arg-info-keyword info))
1565                      (supplied-p (arg-info-supplied-p info))
1566                      (n-value (gensym "N-VALUE-")))
1567                 (temps `(,n-value ,default))
1568                 (cond (supplied-p
1569                        (let ((n-supplied (gensym "N-SUPPLIED-")))
1570                          (temps n-supplied)
1571                          (arg-vals n-value n-supplied)
1572                          (tests `((eq ,n-key ,keyword)
1573                                   (setq ,n-supplied t)
1574                                   (setq ,n-value ,n-value-temp)))))
1575                       (t
1576                        (arg-vals n-value)
1577                        (tests `((eq ,n-key ,keyword)
1578                                 (setq ,n-value ,n-value-temp)))))))
1579
1580             (unless allowp
1581               (temps n-allowp n-losep)
1582               (tests `((eq ,n-key :allow-other-keys)
1583                        (setq ,n-allowp ,n-value-temp)))
1584               (tests `(t
1585                        (setq ,n-losep ,n-key))))
1586
1587             (body
1588              `(when (oddp ,n-count)
1589                 (%odd-keyword-arguments-error)))
1590
1591             (body
1592              `(locally
1593                 (declare (optimize (safety 0)))
1594                 (loop
1595                   (when (minusp ,n-index) (return))
1596                   (setf ,n-value-temp (%more-arg ,n-context ,n-index))
1597                   (decf ,n-index)
1598                   (setq ,n-key (%more-arg ,n-context ,n-index))
1599                   (decf ,n-index)
1600                   (cond ,@(tests)))))
1601
1602             (unless allowp
1603               (body `(when (and ,n-losep (not ,n-allowp))
1604                        (%unknown-keyword-argument-error ,n-losep)))))))
1605
1606       (let ((ep (ir1-convert-lambda-body
1607                  `((let ,(temps)
1608                      ,@(body)
1609                      (%funcall ,(optional-dispatch-main-entry res)
1610                                . ,(arg-vals)))) ; FIXME: What is the '.'? ,@?
1611                  (arg-vars))))
1612         (setf (optional-dispatch-more-entry res) ep))))
1613
1614   (values))
1615
1616 ;;; Called by IR1-Convert-Hairy-Args when we run into a rest or
1617 ;;; keyword arg. The arguments are similar to that function, but we
1618 ;;; split off any rest arg and pass it in separately. Rest is the rest
1619 ;;; arg var, or NIL if there is no rest arg. Keys is a list of the
1620 ;;; keyword argument vars.
1621 ;;;
1622 ;;; When there are keyword arguments, we introduce temporary gensym
1623 ;;; variables to hold the values while keyword defaulting is in
1624 ;;; progress to get the required sequential binding semantics.
1625 ;;;
1626 ;;; This gets interesting mainly when there are keyword arguments with
1627 ;;; supplied-p vars or non-constant defaults. In either case, pass in
1628 ;;; a supplied-p var. If the default is non-constant, we introduce an
1629 ;;; IF in the main entry that tests the supplied-p var and decides
1630 ;;; whether to evaluate the default or not. In this case, the real
1631 ;;; incoming value is NIL, so we must union NULL with the declared
1632 ;;; type when computing the type for the main entry's argument.
1633 (defun ir1-convert-more (res default-vars default-vals entry-vars entry-vals
1634                              rest more-context more-count keys supplied-p-p
1635                              body aux-vars aux-vals cont)
1636   (declare (type optional-dispatch res)
1637            (list default-vars default-vals entry-vars entry-vals keys body
1638                  aux-vars aux-vals)
1639            (type (or continuation null) cont))
1640   (collect ((main-vars (reverse default-vars))
1641             (main-vals default-vals cons)
1642             (bind-vars)
1643             (bind-vals))
1644     (when rest
1645       (main-vars rest)
1646       (main-vals '()))
1647     (when more-context
1648       (main-vars more-context)
1649       (main-vals nil)
1650       (main-vars more-count)
1651       (main-vals 0))
1652
1653     (dolist (key keys)
1654       (let* ((info (lambda-var-arg-info key))
1655              (default (arg-info-default info))
1656              (hairy-default (not (sb!xc:constantp default)))
1657              (supplied-p (arg-info-supplied-p info))
1658              (n-val (make-symbol (format nil
1659                                          "~A-DEFAULTING-TEMP"
1660                                          (leaf-name key))))
1661              (key-type (leaf-type key))
1662              (val-temp (make-lambda-var
1663                         :name n-val
1664                         :type (if hairy-default
1665                                   (type-union key-type (specifier-type 'null))
1666                                   key-type))))
1667         (main-vars val-temp)
1668         (bind-vars key)
1669         (cond ((or hairy-default supplied-p)
1670                (let* ((n-supplied (gensym "N-SUPPLIED-"))
1671                       (supplied-temp (make-lambda-var :name n-supplied)))
1672                  (unless supplied-p
1673                    (setf (arg-info-supplied-p info) supplied-temp))
1674                  (when hairy-default
1675                    (setf (arg-info-default info) nil))
1676                  (main-vars supplied-temp)
1677                  (cond (hairy-default
1678                         (main-vals nil nil)
1679                         (bind-vals `(if ,n-supplied ,n-val ,default)))
1680                        (t
1681                         (main-vals default nil)
1682                         (bind-vals n-val)))
1683                  (when supplied-p
1684                    (bind-vars supplied-p)
1685                    (bind-vals n-supplied))))
1686               (t
1687                (main-vals (arg-info-default info))
1688                (bind-vals n-val)))))
1689
1690     (let* ((main-entry (ir1-convert-lambda-body body (main-vars)
1691                                                 (append (bind-vars) aux-vars)
1692                                                 (append (bind-vals) aux-vals)
1693                                                 t
1694                                                 cont))
1695            (last-entry (convert-optional-entry main-entry default-vars
1696                                                (main-vals) ())))
1697       (setf (optional-dispatch-main-entry res) main-entry)
1698       (convert-more-entry res entry-vars entry-vals rest more-context keys)
1699
1700       (push (if supplied-p-p
1701                 (convert-optional-entry last-entry entry-vars entry-vals ())
1702                 last-entry)
1703             (optional-dispatch-entry-points res))
1704       last-entry)))
1705
1706 ;;; This function generates the entry point functions for the
1707 ;;; optional-dispatch Res. We accomplish this by recursion on the list of
1708 ;;; arguments, analyzing the arglist on the way down and generating entry
1709 ;;; points on the way up.
1710 ;;;
1711 ;;; Default-Vars is a reversed list of all the argument vars processed so
1712 ;;; far, including supplied-p vars. Default-Vals is a list of the names of the
1713 ;;; Default-Vars.
1714 ;;;
1715 ;;; Entry-Vars is a reversed list of processed argument vars, excluding
1716 ;;; supplied-p vars. Entry-Vals is a list things that can be evaluated to get
1717 ;;; the values for all the vars from the Entry-Vars. It has the var name for
1718 ;;; each required or optional arg, and has T for each supplied-p arg.
1719 ;;;
1720 ;;; Vars is a list of the Lambda-Var structures for arguments that haven't
1721 ;;; been processed yet. Supplied-p-p is true if a supplied-p argument has
1722 ;;; already been processed; only in this case are the Default-XXX and Entry-XXX
1723 ;;; different.
1724 ;;;
1725 ;;; The result at each point is a lambda which should be called by the above
1726 ;;; level to default the remaining arguments and evaluate the body. We cause
1727 ;;; the body to be evaluated by converting it and returning it as the result
1728 ;;; when the recursion bottoms out.
1729 ;;;
1730 ;;; Each level in the recursion also adds its entry point function to the
1731 ;;; result Optional-Dispatch. For most arguments, the defaulting function and
1732 ;;; the entry point function will be the same, but when supplied-p args are
1733 ;;; present they may be different.
1734 ;;;
1735 ;;; When we run into a rest or keyword arg, we punt out to
1736 ;;; IR1-Convert-More, which finishes for us in this case.
1737 (defun ir1-convert-hairy-args (res default-vars default-vals
1738                                    entry-vars entry-vals
1739                                    vars supplied-p-p body aux-vars
1740                                    aux-vals cont)
1741   (declare (type optional-dispatch res)
1742            (list default-vars default-vals entry-vars entry-vals vars body
1743                  aux-vars aux-vals)
1744            (type (or continuation null) cont))
1745   (cond ((not vars)
1746          (if (optional-dispatch-keyp res)
1747              ;; Handle &KEY with no keys...
1748              (ir1-convert-more res default-vars default-vals
1749                                entry-vars entry-vals
1750                                nil nil nil vars supplied-p-p body aux-vars
1751                                aux-vals cont)
1752              (let ((fun (ir1-convert-lambda-body body (reverse default-vars)
1753                                                  aux-vars aux-vals t cont)))
1754                (setf (optional-dispatch-main-entry res) fun)
1755                (push (if supplied-p-p
1756                          (convert-optional-entry fun entry-vars entry-vals ())
1757                          fun)
1758                      (optional-dispatch-entry-points res))
1759                fun)))
1760         ((not (lambda-var-arg-info (first vars)))
1761          (let* ((arg (first vars))
1762                 (nvars (cons arg default-vars))
1763                 (nvals (cons (leaf-name arg) default-vals)))
1764            (ir1-convert-hairy-args res nvars nvals nvars nvals
1765                                    (rest vars) nil body aux-vars aux-vals
1766                                    cont)))
1767         (t
1768          (let* ((arg (first vars))
1769                 (info (lambda-var-arg-info arg))
1770                 (kind (arg-info-kind info)))
1771            (ecase kind
1772              (:optional
1773               (let ((ep (generate-optional-default-entry
1774                          res default-vars default-vals
1775                          entry-vars entry-vals vars supplied-p-p body
1776                          aux-vars aux-vals cont)))
1777                 (push (if supplied-p-p
1778                           (convert-optional-entry ep entry-vars entry-vals ())
1779                           ep)
1780                       (optional-dispatch-entry-points res))
1781                 ep))
1782              (:rest
1783               (ir1-convert-more res default-vars default-vals
1784                                 entry-vars entry-vals
1785                                 arg nil nil (rest vars) supplied-p-p body
1786                                 aux-vars aux-vals cont))
1787              (:more-context
1788               (ir1-convert-more res default-vars default-vals
1789                                 entry-vars entry-vals
1790                                 nil arg (second vars) (cddr vars) supplied-p-p
1791                                 body aux-vars aux-vals cont))
1792              (:keyword
1793               (ir1-convert-more res default-vars default-vals
1794                                 entry-vars entry-vals
1795                                 nil nil nil vars supplied-p-p body aux-vars
1796                                 aux-vals cont)))))))
1797
1798 ;;; This function deals with the case where we have to make an
1799 ;;; Optional-Dispatch to represent a lambda. We cons up the result and call
1800 ;;; IR1-Convert-Hairy-Args to do the work. When it is done, we figure out the
1801 ;;; min-args and max-args.
1802 (defun ir1-convert-hairy-lambda (body vars keyp allowp aux-vars aux-vals cont)
1803   (declare (list body vars aux-vars aux-vals) (type continuation cont))
1804   (let ((res (make-optional-dispatch :arglist vars
1805                                      :allowp allowp
1806                                      :keyp keyp))
1807         (min (or (position-if #'lambda-var-arg-info vars) (length vars))))
1808     (push res (component-new-functions *current-component*))
1809     (ir1-convert-hairy-args res () () () () vars nil body aux-vars aux-vals
1810                             cont)
1811     (setf (optional-dispatch-min-args res) min)
1812     (setf (optional-dispatch-max-args res)
1813           (+ (1- (length (optional-dispatch-entry-points res))) min))
1814
1815     (flet ((frob (ep)
1816              (when ep
1817                (setf (functional-kind ep) :optional)
1818                (setf (leaf-ever-used ep) t)
1819                (setf (lambda-optional-dispatch ep) res))))
1820       (dolist (ep (optional-dispatch-entry-points res)) (frob ep))
1821       (frob (optional-dispatch-more-entry res))
1822       (frob (optional-dispatch-main-entry res)))
1823
1824     res))
1825
1826 ;;; Convert a Lambda into a Lambda or Optional-Dispatch leaf.
1827 (defun ir1-convert-lambda (form &optional name)
1828   (unless (consp form)
1829     (compiler-error "A ~S was found when expecting a lambda expression:~%  ~S"
1830                     (type-of form)
1831                     form))
1832   (unless (eq (car form) 'lambda)
1833     (compiler-error "~S was expected but ~S was found:~%  ~S"
1834                     'lambda
1835                     (car form)
1836                     form))
1837   (unless (and (consp (cdr form)) (listp (cadr form)))
1838     (compiler-error
1839      "The lambda expression has a missing or non-list lambda-list:~%  ~S"
1840      form))
1841
1842   (multiple-value-bind (vars keyp allow-other-keys aux-vars aux-vals)
1843       (find-lambda-vars (cadr form))
1844     (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr form))
1845       (let* ((cont (make-continuation))
1846              (*lexenv* (process-decls decls
1847                                       (append aux-vars vars)
1848                                       nil cont))
1849              (res (if (or (find-if #'lambda-var-arg-info vars) keyp)
1850                       (ir1-convert-hairy-lambda forms vars keyp
1851                                                 allow-other-keys
1852                                                 aux-vars aux-vals cont)
1853                       (ir1-convert-lambda-body forms vars aux-vars aux-vals
1854                                                t cont))))
1855         (setf (functional-inline-expansion res) form)
1856         (setf (functional-arg-documentation res) (cadr form))
1857         (setf (leaf-name res) name)
1858         res))))
1859 \f
1860 ;;; FIXME: This file is rather long, and contains two distinct sections,
1861 ;;; transform machinery above this point and transforms themselves below this
1862 ;;; point. Why not split it in two? (ir1translate.lisp and
1863 ;;; ir1translators.lisp?) Then consider byte-compiling the translators, too.
1864 \f
1865 ;;;; control special forms
1866
1867 (def-ir1-translator progn ((&rest forms) start cont)
1868   #!+sb-doc
1869   "Progn Form*
1870   Evaluates each Form in order, returning the values of the last form. With no
1871   forms, returns NIL."
1872   (ir1-convert-progn-body start cont forms))
1873
1874 (def-ir1-translator if ((test then &optional else) start cont)
1875   #!+sb-doc
1876   "If Predicate Then [Else]
1877   If Predicate evaluates to non-null, evaluate Then and returns its values,
1878   otherwise evaluate Else and return its values. Else defaults to NIL."
1879   (let* ((pred (make-continuation))
1880          (then-cont (make-continuation))
1881          (then-block (continuation-starts-block then-cont))
1882          (else-cont (make-continuation))
1883          (else-block (continuation-starts-block else-cont))
1884          (dummy-cont (make-continuation))
1885          (node (make-if :test pred
1886                         :consequent then-block
1887                         :alternative else-block)))
1888     (setf (continuation-dest pred) node)
1889     (ir1-convert start pred test)
1890     (prev-link node pred)
1891     (use-continuation node dummy-cont)
1892
1893     (let ((start-block (continuation-block pred)))
1894       (setf (block-last start-block) node)
1895       (continuation-starts-block cont)
1896
1897       (link-blocks start-block then-block)
1898       (link-blocks start-block else-block)
1899
1900       (ir1-convert then-cont cont then)
1901       (ir1-convert else-cont cont else))))
1902 \f
1903 ;;;; BLOCK and TAGBODY
1904
1905 ;;;; We make an Entry node to mark the start and a :Entry cleanup to
1906 ;;;; mark its extent. When doing GO or RETURN-FROM, we emit an Exit
1907 ;;;; node.
1908
1909 ;;; Make a :entry cleanup and emit an Entry node, then convert the
1910 ;;; body in the modified environment. We make Cont start a block now,
1911 ;;; since if it was done later, the block would be in the wrong
1912 ;;; environment.
1913 (def-ir1-translator block ((name &rest forms) start cont)
1914   #!+sb-doc
1915   "Block Name Form*
1916   Evaluate the Forms as a PROGN. Within the lexical scope of the body,
1917   (RETURN-FROM Name Value-Form) can be used to exit the form, returning the
1918   result of Value-Form."
1919   (unless (symbolp name)
1920     (compiler-error "The block name ~S is not a symbol." name))
1921   (continuation-starts-block cont)
1922   (let* ((dummy (make-continuation))
1923          (entry (make-entry))
1924          (cleanup (make-cleanup :kind :block
1925                                 :mess-up entry)))
1926     (push entry (lambda-entries (lexenv-lambda *lexenv*)))
1927     (setf (entry-cleanup entry) cleanup)
1928     (prev-link entry start)
1929     (use-continuation entry dummy)
1930     (let ((*lexenv* (make-lexenv :blocks (list (cons name (list entry cont)))
1931                                  :cleanup cleanup)))
1932       (ir1-convert-progn-body dummy cont forms))))
1933
1934 ;;; We make Cont start a block just so that it will have a block
1935 ;;; assigned. People assume that when they pass a continuation into
1936 ;;; IR1-Convert as Cont, it will have a block when it is done.
1937 (def-ir1-translator return-from ((name &optional value)
1938                                  start cont)
1939   #!+sb-doc
1940   "Return-From Block-Name Value-Form
1941   Evaluate the Value-Form, returning its values from the lexically enclosing
1942   BLOCK Block-Name. This is constrained to be used only within the dynamic
1943   extent of the BLOCK."
1944   (continuation-starts-block cont)
1945   (let* ((found (or (lexenv-find name blocks)
1946                     (compiler-error "return for unknown block: ~S" name)))
1947          (value-cont (make-continuation))
1948          (entry (first found))
1949          (exit (make-exit :entry entry
1950                           :value value-cont)))
1951     (push exit (entry-exits entry))
1952     (setf (continuation-dest value-cont) exit)
1953     (ir1-convert start value-cont value)
1954     (prev-link exit value-cont)
1955     (use-continuation exit (second found))))
1956
1957 ;;; Return a list of the segments of a tagbody. Each segment looks
1958 ;;; like (<tag> <form>* (go <next tag>)). That is, we break up the
1959 ;;; tagbody into segments of non-tag statements, and explicitly
1960 ;;; represent the drop-through with a GO. The first segment has a
1961 ;;; dummy NIL tag, since it represents code before the first tag. The
1962 ;;; last segment (which may also be the first segment) ends in NIL
1963 ;;; rather than a GO.
1964 (defun parse-tagbody (body)
1965   (declare (list body))
1966   (collect ((segments))
1967     (let ((current (cons nil body)))
1968       (loop
1969         (let ((tag-pos (position-if-not #'listp current :start 1)))
1970           (unless tag-pos
1971             (segments `(,@current nil))
1972             (return))
1973           (let ((tag (elt current tag-pos)))
1974             (when (assoc tag (segments))
1975               (compiler-error
1976                "The tag ~S appears more than once in the tagbody."
1977                tag))
1978             (unless (or (symbolp tag) (integerp tag))
1979               (compiler-error "~S is not a legal tagbody statement." tag))
1980             (segments `(,@(subseq current 0 tag-pos) (go ,tag))))
1981           (setq current (nthcdr tag-pos current)))))
1982     (segments)))
1983
1984 ;;; Set up the cleanup, emitting the entry node. Then make a block for
1985 ;;; each tag, building up the tag list for LEXENV-TAGS as we go.
1986 ;;; Finally, convert each segment with the precomputed Start and Cont
1987 ;;; values.
1988 (def-ir1-translator tagbody ((&rest statements) start cont)
1989   #!+sb-doc
1990   "Tagbody {Tag | Statement}*
1991   Define tags for used with GO. The Statements are evaluated in order
1992   (skipping Tags) and NIL is returned. If a statement contains a GO to a
1993   defined Tag within the lexical scope of the form, then control is transferred
1994   to the next statement following that tag. A Tag must an integer or a
1995   symbol. A statement must be a list. Other objects are illegal within the
1996   body."
1997   (continuation-starts-block cont)
1998   (let* ((dummy (make-continuation))
1999          (entry (make-entry))
2000          (segments (parse-tagbody statements))
2001          (cleanup (make-cleanup :kind :tagbody
2002                                 :mess-up entry)))
2003     (push entry (lambda-entries (lexenv-lambda *lexenv*)))
2004     (setf (entry-cleanup entry) cleanup)
2005     (prev-link entry start)
2006     (use-continuation entry dummy)
2007
2008     (collect ((tags)
2009               (starts)
2010               (conts))
2011       (starts dummy)
2012       (dolist (segment (rest segments))
2013         (let ((tag-cont (make-continuation)))
2014           (conts tag-cont)
2015           (starts tag-cont)
2016           (continuation-starts-block tag-cont)
2017           (tags (list (car segment) entry tag-cont))))
2018       (conts cont)
2019
2020       (let ((*lexenv* (make-lexenv :cleanup cleanup :tags (tags))))
2021         (mapc #'(lambda (segment start cont)
2022                   (ir1-convert-progn-body start cont (rest segment)))
2023               segments (starts) (conts))))))
2024
2025 ;;; Emit an Exit node without any value.
2026 (def-ir1-translator go ((tag) start cont)
2027   #!+sb-doc
2028   "Go Tag
2029   Transfer control to the named Tag in the lexically enclosing TAGBODY. This
2030   is constrained to be used only within the dynamic extent of the TAGBODY."
2031   (continuation-starts-block cont)
2032   (let* ((found (or (lexenv-find tag tags :test #'eql)
2033                     (compiler-error "Go to nonexistent tag: ~S." tag)))
2034          (entry (first found))
2035          (exit (make-exit :entry entry)))
2036     (push exit (entry-exits entry))
2037     (prev-link exit start)
2038     (use-continuation exit (second found))))
2039 \f
2040 ;;;; translators for compiler-magic special forms
2041
2042 ;;; Do stuff to do an EVAL-WHEN. This is split off from the IR1
2043 ;;; convert method so that it can be shared by the special-case
2044 ;;; top-level form processing code. We play with the dynamic
2045 ;;; environment and eval stuff, then call Fun with a list of forms to
2046 ;;; be processed at load time.
2047 ;;;
2048 ;;; Note: the EVAL situation is always ignored: this is conceptually a
2049 ;;; compile-only implementation.
2050 ;;;
2051 ;;; We have to interact with the interpreter to ensure that the forms
2052 ;;; get EVAL'ed exactly once. We bind *ALREADY-EVALED-THIS* to true to
2053 ;;; inhibit evaluation of any enclosed EVAL-WHENs, either by IR1
2054 ;;; conversion done by EVAL, or by conversion of the body for
2055 ;;; load-time processing. If *ALREADY-EVALED-THIS* is true then we *do
2056 ;;; not* eval since some enclosing eval-when already did.
2057 ;;;
2058 ;;; We know we are EVAL'ing for LOAD since we wouldn't get called
2059 ;;; otherwise. If LOAD is a situation we call FUN on body. If we
2060 ;;; aren't evaluating for LOAD, then we call FUN on NIL for the result
2061 ;;; of the EVAL-WHEN.
2062 (defun do-eval-when-stuff (situations body fun)
2063
2064   (when (or (not (listp situations))
2065             (set-difference situations
2066                             '(compile load eval
2067                               :compile-toplevel :load-toplevel :execute)))
2068     (compiler-error "bad EVAL-WHEN situation list: ~S" situations))
2069
2070   (let ((deprecated-names (intersection situations '(compile load eval))))
2071     (when deprecated-names
2072       (style-warn "using deprecated EVAL-WHEN situation names ~S"
2073                   deprecated-names)))
2074
2075   (let* ((do-eval (and (intersection '(compile :compile-toplevel) situations)
2076                        (not sb!eval::*already-evaled-this*)))
2077          (sb!eval::*already-evaled-this* t))
2078     (when do-eval
2079       (eval `(progn ,@body)))
2080     (if (or (intersection '(:load-toplevel load) situations)
2081             (and *converting-for-interpreter*
2082                  (intersection '(:execute eval) situations)))
2083         (funcall fun body)
2084         (funcall fun '(nil)))))
2085
2086 (def-ir1-translator eval-when ((situations &rest body) start cont)
2087   #!+sb-doc
2088   "EVAL-WHEN (Situation*) Form*
2089   Evaluate the Forms in the specified Situations, any of COMPILE, LOAD, EVAL.
2090   This is conceptually a compile-only implementation, so EVAL is a no-op."
2091   (do-eval-when-stuff situations body
2092                       #'(lambda (forms)
2093                           (ir1-convert-progn-body start cont forms))))
2094
2095 ;;; Like DO-EVAL-WHEN-STUFF, only do a macrolet. Fun is not passed any
2096 ;;; arguments.
2097 (defun do-macrolet-stuff (definitions fun)
2098   (declare (list definitions) (type function fun))
2099   (let ((whole (gensym "WHOLE"))
2100         (environment (gensym "ENVIRONMENT")))
2101     (collect ((new-fenv))
2102       (dolist (def definitions)
2103         (let ((name (first def))
2104               (arglist (second def))
2105               (body (cddr def)))
2106           (unless (symbolp name)
2107             (compiler-error "The local macro name ~S is not a symbol." name))
2108           (when (< (length def) 2)
2109             (compiler-error
2110              "The list ~S is too short to be a legal local macro definition."
2111              name))
2112           (multiple-value-bind (body local-decs)
2113               (parse-defmacro arglist whole body name 'macrolet
2114                               :environment environment)
2115             (new-fenv `(,(first def) macro .
2116                         ,(coerce `(lambda (,whole ,environment)
2117                                     ,@local-decs (block ,name ,body))
2118                                  'function))))))
2119
2120       (let ((*lexenv* (make-lexenv :functions (new-fenv))))
2121         (funcall fun))))
2122
2123   (values))
2124
2125 (def-ir1-translator macrolet ((definitions &rest body) start cont)
2126   #!+sb-doc
2127   "MACROLET ({(Name Lambda-List Form*)}*) Body-Form*
2128   Evaluate the Body-Forms in an environment with the specified local macros
2129   defined. Name is the local macro name, Lambda-List is the DEFMACRO style
2130   destructuring lambda list, and the Forms evaluate to the expansion. The
2131   Forms are evaluated in the null environment."
2132   (do-macrolet-stuff definitions
2133                      #'(lambda ()
2134                          (ir1-convert-progn-body start cont body))))
2135
2136 ;;; not really a special form, but..
2137 (def-ir1-translator declare ((&rest stuff) start cont)
2138   (declare (ignore stuff))
2139   ;; We ignore START and CONT too, but we can't use DECLARE IGNORE to
2140   ;; tell the compiler about it here, because the DEF-IR1-TRANSLATOR
2141   ;; macro would put the DECLARE in the wrong place, so..
2142   start cont
2143   (compiler-error "misplaced declaration"))
2144 \f
2145 ;;;; %PRIMITIVE
2146 ;;;;
2147 ;;;; Uses of %PRIMITIVE are either expanded into Lisp code or turned
2148 ;;;; into a funny function.
2149
2150 ;;; Carefully evaluate a list of forms, returning a list of the results.
2151 (defun eval-info-args (args)
2152   (declare (list args))
2153   (handler-case (mapcar #'eval args)
2154     (error (condition)
2155       (compiler-error "Lisp error during evaluation of info args:~%~A"
2156                       condition))))
2157
2158 ;;; a hashtable that translates from primitive names to translation functions
2159 (defvar *primitive-translators* (make-hash-table :test 'eq))
2160
2161 ;;; If there is a primitive translator, then we expand the call.
2162 ;;; Otherwise, we convert to the %%PRIMITIVE funny function. The first
2163 ;;; argument is the template, the second is a list of the results of
2164 ;;; any codegen-info args, and the remaining arguments are the runtime
2165 ;;; arguments.
2166 ;;;
2167 ;;; We do a bunch of error checking now so that we don't bomb out with
2168 ;;; a fatal error during IR2 conversion.
2169 ;;;
2170 ;;; KLUDGE: It's confusing having multiple names floating around for
2171 ;;; nearly the same concept: PRIMITIVE, TEMPLATE, VOP. Might it be
2172 ;;; possible to reimplement BYTE-BLT (the only use of
2173 ;;; *PRIMITIVE-TRANSLATORS*) some other way, then get rid of primitive
2174 ;;; translators altogether, so that there would be no distinction
2175 ;;; between primitives and vops? Then we could call primitives vops,
2176 ;;; rename TEMPLATE to VOP-TEMPLATE, rename BACKEND-TEMPLATE-NAMES to
2177 ;;; BACKEND-VOPS, and rename %PRIMITIVE to VOP.. -- WHN 19990906
2178 ;;; FIXME: Look at doing this ^, it doesn't look too hard actually. I
2179 ;;; think BYTE-BLT could probably just become an inline function.
2180 (def-ir1-translator %primitive ((&whole form name &rest args) start cont)
2181
2182   (unless (symbolp name)
2183     (compiler-error "The primitive name ~S is not a symbol." name))
2184
2185   (let* ((translator (gethash name *primitive-translators*)))
2186     (if translator
2187         (ir1-convert start cont (funcall translator (cdr form)))
2188         (let* ((template (or (gethash name *backend-template-names*)
2189                              (compiler-error
2190                               "The primitive name ~A is not defined."
2191                               name)))
2192                (required (length (template-arg-types template)))
2193                (info (template-info-arg-count template))
2194                (min (+ required info))
2195                (nargs (length args)))
2196           (if (template-more-args-type template)
2197               (when (< nargs min)
2198                 (compiler-error "Primitive ~A was called with ~R argument~:P, ~
2199                                  but wants at least ~R."
2200                                 name
2201                                 nargs
2202                                 min))
2203               (unless (= nargs min)
2204                 (compiler-error "Primitive ~A was called with ~R argument~:P, ~
2205                                  but wants exactly ~R."
2206                                 name
2207                                 nargs
2208                                 min)))
2209
2210           (when (eq (template-result-types template) :conditional)
2211             (compiler-error
2212              "%PRIMITIVE was used with a conditional template."))
2213
2214           (when (template-more-results-type template)
2215             (compiler-error
2216              "%PRIMITIVE was used with an unknown values template."))
2217
2218           (ir1-convert start
2219                        cont
2220                       `(%%primitive ',template
2221                                     ',(eval-info-args
2222                                        (subseq args required min))
2223                                     ,@(subseq args 0 required)
2224                                     ,@(subseq args min)))))))
2225 \f
2226 ;;;; QUOTE and FUNCTION
2227
2228 (def-ir1-translator quote ((thing) start cont)
2229   #!+sb-doc
2230   "QUOTE Value
2231   Return Value without evaluating it."
2232   (reference-constant start cont thing))
2233
2234 (def-ir1-translator function ((thing) start cont)
2235   #!+sb-doc
2236   "FUNCTION Name
2237   Return the lexically apparent definition of the function Name. Name may also
2238   be a lambda."
2239   (if (consp thing)
2240       (case (car thing)
2241         ((lambda)
2242          (reference-leaf start cont (ir1-convert-lambda thing)))
2243         ((setf)
2244          (let ((var (find-lexically-apparent-function
2245                      thing "as the argument to FUNCTION")))
2246            (reference-leaf start cont var)))
2247         ((instance-lambda)
2248          (let ((res (ir1-convert-lambda `(lambda ,@(cdr thing)))))
2249            (setf (getf (functional-plist res) :fin-function) t)
2250            (reference-leaf start cont res)))
2251         (t
2252          (compiler-error "~S is not a legal function name." thing)))
2253       (let ((var (find-lexically-apparent-function
2254                   thing "as the argument to FUNCTION")))
2255         (reference-leaf start cont var))))
2256 \f
2257 ;;;; FUNCALL
2258
2259 ;;; FUNCALL is implemented on %FUNCALL, which can only call functions
2260 ;;; (not symbols). %FUNCALL is used directly in some places where the
2261 ;;; call should always be open-coded even if FUNCALL is :NOTINLINE.
2262 (deftransform funcall ((function &rest args) * * :when :both)
2263   (let ((arg-names (make-gensym-list (length args))))
2264     `(lambda (function ,@arg-names)
2265        (%funcall ,(if (csubtypep (continuation-type function)
2266                                  (specifier-type 'function))
2267                       'function
2268                       '(%coerce-callable-to-function function))
2269                  ,@arg-names))))
2270
2271 (def-ir1-translator %funcall ((function &rest args) start cont)
2272   (let ((fun-cont (make-continuation)))
2273     (ir1-convert start fun-cont function)
2274     (assert-continuation-type fun-cont (specifier-type 'function))
2275     (ir1-convert-combination-args fun-cont cont args)))
2276
2277 ;;; This source transform exists to reduce the amount of work for the
2278 ;;; compiler. If the called function is a FUNCTION form, then convert
2279 ;;; directly to %FUNCALL, instead of waiting around for type
2280 ;;; inference.
2281 (def-source-transform funcall (function &rest args)
2282   (if (and (consp function) (eq (car function) 'function))
2283       `(%funcall ,function ,@args)
2284       (values nil t)))
2285
2286 (deftransform %coerce-callable-to-function ((thing) (function) *
2287                                             :when :both
2288                                             :important t)
2289   "optimize away possible call to FDEFINITION at runtime"
2290   'thing)
2291 \f
2292 ;;;; symbol macros
2293
2294 (def-ir1-translator symbol-macrolet ((specs &body body) start cont)
2295   #!+sb-doc
2296   "SYMBOL-MACROLET ({(Name Expansion)}*) Decl* Form*
2297   Define the Names as symbol macros with the given Expansions. Within the
2298   body, references to a Name will effectively be replaced with the Expansion."
2299   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2300     (collect ((res))
2301       (dolist (spec specs)
2302         (unless (proper-list-of-length-p spec 2)
2303           (compiler-error "The symbol macro binding ~S is malformed." spec))
2304         (let ((name (first spec))
2305               (def (second spec)))
2306           (unless (symbolp name)
2307             (compiler-error "The symbol macro name ~S is not a symbol." name))
2308           (when (assoc name (res) :test #'eq)
2309             (compiler-style-warning
2310              "The name ~S occurs more than once in SYMBOL-MACROLET."
2311              name))
2312           (res `(,name . (MACRO . ,def)))))
2313
2314       (let* ((*lexenv* (make-lexenv :variables (res)))
2315              (*lexenv* (process-decls decls (res) nil cont)))
2316         (ir1-convert-progn-body start cont forms)))))
2317 \f
2318 ;;; This is a frob that DEFSTRUCT expands into to establish the compiler
2319 ;;; semantics. The other code in the expansion and %%COMPILER-DEFSTRUCT do
2320 ;;; most of the work, we just clear all of the functions out of
2321 ;;; *FREE-FUNCTIONS* to keep things in synch. %%COMPILER-DEFSTRUCT is also
2322 ;;; called at load-time.
2323 (def-ir1-translator %compiler-defstruct ((info) start cont :kind :function)
2324   (let* ((info (eval info)))
2325     (%%compiler-defstruct info)
2326     (dolist (slot (dd-slots info))
2327       (let ((fun (dsd-accessor slot)))
2328         (remhash fun *free-functions*)
2329         (unless (dsd-read-only slot)
2330           (remhash `(setf ,fun) *free-functions*))))
2331     (remhash (dd-predicate info) *free-functions*)
2332     (remhash (dd-copier info) *free-functions*)
2333     (ir1-convert start cont `(%%compiler-defstruct ',info))))
2334
2335 ;;; Return the contents of a quoted form.
2336 (defun unquote (x)
2337   (if (and (consp x)
2338            (= 2 (length x))
2339            (eq 'quote (first x)))
2340     (second x)
2341     (error "not a quoted form")))
2342
2343 ;;; Don't actually compile anything, instead call the function now.
2344 (def-ir1-translator %compiler-only-defstruct
2345                     ((info inherits) start cont :kind :function)
2346   (function-%compiler-only-defstruct (unquote info) (unquote inherits))
2347   (reference-constant start cont nil))
2348 \f
2349 ;;;; LET and LET*
2350 ;;;;
2351 ;;;; (LET and LET* can't be implemented as macros due to the fact that
2352 ;;;; any pervasive declarations also affect the evaluation of the
2353 ;;;; arguments.)
2354
2355 ;;; Given a list of binding specifiers in the style of Let, return:
2356 ;;;  1. The list of var structures for the variables bound.
2357 ;;;  2. The initial value form for each variable.
2358 ;;;
2359 ;;; The variable names are checked for legality and globally special
2360 ;;; variables are marked as such. Context is the name of the form, for
2361 ;;; error reporting purposes.
2362 (declaim (ftype (function (list symbol) (values list list list))
2363                 extract-let-variables))
2364 (defun extract-let-variables (bindings context)
2365   (collect ((vars)
2366             (vals)
2367             (names))
2368     (flet ((get-var (name)
2369              (varify-lambda-arg name
2370                                 (if (eq context 'let*)
2371                                     nil
2372                                     (names)))))
2373       (dolist (spec bindings)
2374         (cond ((atom spec)
2375                (let ((var (get-var spec)))
2376                  (vars var)
2377                  (names (cons spec var))
2378                  (vals nil)))
2379               (t
2380                (unless (proper-list-of-length-p spec 1 2)
2381                  (compiler-error "The ~S binding spec ~S is malformed."
2382                                  context
2383                                  spec))
2384                (let* ((name (first spec))
2385                       (var (get-var name)))
2386                  (vars var)
2387                  (names name)
2388                  (vals (second spec)))))))
2389
2390     (values (vars) (vals) (names))))
2391
2392 (def-ir1-translator let ((bindings &body body)
2393                          start cont)
2394   #!+sb-doc
2395   "LET ({(Var [Value]) | Var}*) Declaration* Form*
2396   During evaluation of the Forms, bind the Vars to the result of evaluating the
2397   Value forms. The variables are bound in parallel after all of the Values are
2398   evaluated."
2399   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2400     (multiple-value-bind (vars values) (extract-let-variables bindings 'let)
2401       (let* ((*lexenv* (process-decls decls vars nil cont))
2402              (fun-cont (make-continuation))
2403              (fun (ir1-convert-lambda-body forms vars)))
2404         (reference-leaf start fun-cont fun)
2405         (ir1-convert-combination-args fun-cont cont values)))))
2406
2407 (def-ir1-translator let* ((bindings &body body)
2408                           start cont)
2409   #!+sb-doc
2410   "LET* ({(Var [Value]) | Var}*) Declaration* Form*
2411   Similar to LET, but the variables are bound sequentially, allowing each Value
2412   form to reference any of the previous Vars."
2413   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2414     (multiple-value-bind (vars values) (extract-let-variables bindings 'let*)
2415       (let ((*lexenv* (process-decls decls vars nil cont)))
2416         (ir1-convert-aux-bindings start cont forms vars values nil)))))
2417
2418 ;;; This is a lot like a LET* with no bindings. Unlike LET*, LOCALLY
2419 ;;; has to preserves top-level-formness, but we don't need to worry
2420 ;;; about that here, because special logic in the compiler main loop
2421 ;;; grabs top-level LOCALLYs and takes care of them before this
2422 ;;; transform ever sees them.
2423 (def-ir1-translator locally ((&body body)
2424                              start cont)
2425   #!+sb-doc
2426   "LOCALLY Declaration* Form*
2427   Sequentially evaluate the Forms in a lexical environment where the
2428   the Declarations have effect. If LOCALLY is a top-level form, then
2429   the Forms are also processed as top-level forms."
2430   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2431     (let* ((*lexenv* (process-decls decls nil nil cont)))
2432       (ir1-convert-aux-bindings start cont forms nil nil nil))))
2433 \f
2434 ;;;; FLET and LABELS
2435
2436 ;;; Given a list of local function specifications in the style of
2437 ;;; Flet, return lists of the function names and of the lambdas which
2438 ;;; are their definitions.
2439 ;;;
2440 ;;; The function names are checked for legality. Context is the name
2441 ;;; of the form, for error reporting.
2442 (declaim (ftype (function (list symbol) (values list list))
2443                 extract-flet-variables))
2444 (defun extract-flet-variables (definitions context)
2445   (collect ((names)
2446             (defs))
2447     (dolist (def definitions)
2448       (when (or (atom def) (< (length def) 2))
2449         (compiler-error "The ~S definition spec ~S is malformed." context def))
2450
2451       (let ((name (check-function-name (first def))))
2452         (names name)
2453         (multiple-value-bind (forms decls) (sb!sys:parse-body (cddr def))
2454           (defs `(lambda ,(second def)
2455                    ,@decls
2456                    (block ,(function-name-block-name name)
2457                      . ,forms))))))
2458     (values (names) (defs))))
2459
2460 (def-ir1-translator flet ((definitions &body body)
2461                           start cont)
2462   #!+sb-doc
2463   "FLET ({(Name Lambda-List Declaration* Form*)}*) Declaration* Body-Form*
2464   Evaluate the Body-Forms with some local function definitions. The bindings
2465   do not enclose the definitions; any use of Name in the Forms will refer to
2466   the lexically apparent function definition in the enclosing environment."
2467   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2468     (multiple-value-bind (names defs)
2469         (extract-flet-variables definitions 'flet)
2470       (let* ((fvars (mapcar (lambda (n d)
2471                               (ir1-convert-lambda d n))
2472                             names defs))
2473              (*lexenv* (make-lexenv
2474                         :default (process-decls decls nil fvars cont)
2475                         :functions (pairlis names fvars))))
2476         (ir1-convert-progn-body start cont forms)))))
2477
2478 ;;; For LABELS, we have to create dummy function vars and add them to
2479 ;;; the function namespace while converting the functions. We then
2480 ;;; modify all the references to these leaves so that they point to
2481 ;;; the real functional leaves. We also backpatch the FENV so that if
2482 ;;; the lexical environment is used for inline expansion we will get
2483 ;;; the right functions.
2484 (def-ir1-translator labels ((definitions &body body) start cont)
2485   #!+sb-doc
2486   "LABELS ({(Name Lambda-List Declaration* Form*)}*) Declaration* Body-Form*
2487   Evaluate the Body-Forms with some local function definitions. The bindings
2488   enclose the new definitions, so the defined functions can call themselves or
2489   each other."
2490   (multiple-value-bind (forms decls) (sb!sys:parse-body body nil)
2491     (multiple-value-bind (names defs)
2492         (extract-flet-variables definitions 'labels)
2493       (let* ((new-fenv (loop for name in names
2494                              collect (cons name (make-functional :name name))))
2495              (real-funs
2496               (let ((*lexenv* (make-lexenv :functions new-fenv)))
2497                 (mapcar (lambda (n d)
2498                           (ir1-convert-lambda d n))
2499                         names defs))))
2500
2501         (loop for real in real-funs and env in new-fenv do
2502               (let ((dum (cdr env)))
2503                 (substitute-leaf real dum)
2504                 (setf (cdr env) real)))
2505
2506         (let ((*lexenv* (make-lexenv
2507                          :default (process-decls decls nil real-funs cont)
2508                          :functions (pairlis names real-funs))))
2509           (ir1-convert-progn-body start cont forms))))))
2510 \f
2511 ;;;; THE
2512
2513 ;;; Do stuff to recognize a THE or VALUES declaration. Cont is the
2514 ;;; continuation that the assertion applies to, Type is the type
2515 ;;; specifier and Lexenv is the current lexical environment. Name is
2516 ;;; the name of the declaration we are doing, for use in error
2517 ;;; messages.
2518 ;;;
2519 ;;; This is somewhat involved, since a type assertion may only be made
2520 ;;; on a continuation, not on a node. We can't just set the
2521 ;;; continuation asserted type and let it go at that, since there may
2522 ;;; be parallel THE's for the same continuation, i.e.:
2523 ;;;     (if ...
2524 ;;;      (the foo ...)
2525 ;;;      (the bar ...))
2526 ;;;
2527 ;;; In this case, our representation can do no better than the union
2528 ;;; of these assertions. And if there is a branch with no assertion,
2529 ;;; we have nothing at all. We really need to recognize scoping, since
2530 ;;; we need to be able to discern between parallel assertions (which
2531 ;;; we union) and nested ones (which we intersect).
2532 ;;;
2533 ;;; We represent the scoping by throwing our innermost (intersected)
2534 ;;; assertion on Cont into the TYPE-RESTRICTIONS. As we go down, we
2535 ;;; intersect our assertions together. If Cont has no uses yet, we
2536 ;;; have not yet bottomed out on the first COND branch; in this case
2537 ;;; we optimistically assume that this type will be the one we end up
2538 ;;; with, and set the ASSERTED-TYPE to it. We can never get better
2539 ;;; than the type that we have the first time we bottom out. Later
2540 ;;; THE's (or the absence thereof) can only weaken this result.
2541 ;;;
2542 ;;; We make this work by getting USE-CONTINUATION to do the unioning
2543 ;;; across COND branches. We can't do it here, since we don't know how
2544 ;;; many branches there are going to be.
2545 (defun do-the-stuff (type cont lexenv name)
2546   (declare (type continuation cont) (type lexenv lexenv))
2547   (let* ((ctype (values-specifier-type type))
2548          (old-type (or (lexenv-find cont type-restrictions)
2549                        *wild-type*))
2550          (intersects (values-types-intersect old-type ctype))
2551          (int (values-type-intersection old-type ctype))
2552          (new (if intersects int old-type)))
2553     (when (null (find-uses cont))
2554       (setf (continuation-asserted-type cont) new))
2555     (when (and (not intersects)
2556                (not (policy nil (= brevity 3)))) ;FIXME: really OK to suppress?
2557       (compiler-warning
2558        "The type ~S in ~S declaration conflicts with an enclosing assertion:~%   ~S"
2559        (type-specifier ctype)
2560        name
2561        (type-specifier old-type)))
2562     (make-lexenv :type-restrictions `((,cont . ,new))
2563                  :default lexenv)))
2564
2565 ;;; FIXME: In a version of CMU CL that I used at Cadabra ca. 20000101,
2566 ;;; this didn't seem to expand into an assertion, at least for ALIEN
2567 ;;; values. Check that SBCL doesn't have this problem.
2568 (def-ir1-translator the ((type value) start cont)
2569   #!+sb-doc
2570   "THE Type Form
2571   Assert that Form evaluates to the specified type (which may be a VALUES
2572   type.)"
2573   (let ((*lexenv* (do-the-stuff type cont *lexenv* 'the)))
2574     (ir1-convert start cont value)))
2575
2576 ;;; Since the CONTINUATION-DERIVED-TYPE is computed as the union of
2577 ;;; its uses's types, setting it won't work. Instead we must intersect
2578 ;;; the type with the uses's DERIVED-TYPE.
2579 (def-ir1-translator truly-the ((type value) start cont)
2580   #!+sb-doc
2581   "Truly-The Type Value
2582   Like the THE special form, except that it believes whatever you tell it. It
2583   will never generate a type check, but will cause a warning if the compiler
2584   can prove the assertion is wrong."
2585   (declare (inline member))
2586   (let ((type (values-specifier-type type))
2587         (old (find-uses cont)))
2588     (ir1-convert start cont value)
2589     (do-uses (use cont)
2590       (unless (member use old :test #'eq)
2591         (derive-node-type use type)))))
2592 \f
2593 ;;;; SETQ
2594
2595 ;;; If there is a definition in LEXENV-VARIABLES, just set that,
2596 ;;; otherwise look at the global information. If the name is for a
2597 ;;; constant, then error out.
2598 (def-ir1-translator setq ((&whole source &rest things) start cont)
2599   #!+sb-doc
2600   "SETQ {Var Value}*
2601   Set the variables to the values. If more than one pair is supplied, the
2602   assignments are done sequentially. If Var names a symbol macro, SETF the
2603   expansion."
2604   (let ((len (length things)))
2605     (when (oddp len)
2606       (compiler-error "odd number of args to SETQ: ~S" source))
2607     (if (= len 2)
2608         (let* ((name (first things))
2609                (leaf (or (lexenv-find name variables)
2610                          (find-free-variable name))))
2611           (etypecase leaf
2612             (leaf
2613              (when (or (constant-p leaf)
2614                        (and (global-var-p leaf)
2615                             (eq (global-var-kind leaf) :constant)))
2616                (compiler-error "~S is a constant and thus can't be set." name))
2617              (when (and (lambda-var-p leaf)
2618                         (lambda-var-ignorep leaf))
2619                ;; ANSI's definition of "Declaration IGNORE, IGNORABLE"
2620                ;; requires that this be a STYLE-WARNING, not a full warning.
2621                (compiler-style-warning
2622                 "~S is being set even though it was declared to be ignored."
2623                 name))
2624              (set-variable start cont leaf (second things)))
2625             (cons
2626              (assert (eq (car leaf) 'MACRO))
2627              (ir1-convert start cont `(setf ,(cdr leaf) ,(second things))))
2628             (heap-alien-info
2629              (ir1-convert start cont
2630                           `(%set-heap-alien ',leaf ,(second things))))))
2631         (collect ((sets))
2632           (do ((thing things (cddr thing)))
2633               ((endp thing)
2634                (ir1-convert-progn-body start cont (sets)))
2635             (sets `(setq ,(first thing) ,(second thing))))))))
2636
2637 ;;; Kind of like Reference-Leaf, but we generate a Set node. This
2638 ;;; should only need to be called in Setq.
2639 (defun set-variable (start cont var value)
2640   (declare (type continuation start cont) (type basic-var var))
2641   (let ((dest (make-continuation)))
2642     (setf (continuation-asserted-type dest) (leaf-type var))
2643     (ir1-convert start dest value)
2644     (let ((res (make-set :var var :value dest)))
2645       (setf (continuation-dest dest) res)
2646       (setf (leaf-ever-used var) t)
2647       (push res (basic-var-sets var))
2648       (prev-link res dest)
2649       (use-continuation res cont))))
2650 \f
2651 ;;;; CATCH, THROW and UNWIND-PROTECT
2652
2653 ;;; We turn THROW into a multiple-value-call of a magical function,
2654 ;;; since as as far as IR1 is concerned, it has no interesting
2655 ;;; properties other than receiving multiple-values.
2656 (def-ir1-translator throw ((tag result) start cont)
2657   #!+sb-doc
2658   "Throw Tag Form
2659   Do a non-local exit, return the values of Form from the CATCH whose tag
2660   evaluates to the same thing as Tag."
2661   (ir1-convert start cont
2662                `(multiple-value-call #'%throw ,tag ,result)))
2663
2664 ;;; This is a special special form used to instantiate a cleanup as
2665 ;;; the current cleanup within the body. Kind is a the kind of cleanup
2666 ;;; to make, and Mess-Up is a form that does the mess-up action. We
2667 ;;; make the MESS-UP be the USE of the Mess-Up form's continuation,
2668 ;;; and introduce the cleanup into the lexical environment. We
2669 ;;; back-patch the Entry-Cleanup for the current cleanup to be the new
2670 ;;; cleanup, since this inner cleanup is the interesting one.
2671 (def-ir1-translator %within-cleanup ((kind mess-up &body body) start cont)
2672   (let ((dummy (make-continuation))
2673         (dummy2 (make-continuation)))
2674     (ir1-convert start dummy mess-up)
2675     (let* ((mess-node (continuation-use dummy))
2676            (cleanup (make-cleanup :kind kind
2677                                   :mess-up mess-node))
2678            (old-cup (lexenv-cleanup *lexenv*))
2679            (*lexenv* (make-lexenv :cleanup cleanup)))
2680       (setf (entry-cleanup (cleanup-mess-up old-cup)) cleanup)
2681       (ir1-convert dummy dummy2 '(%cleanup-point))
2682       (ir1-convert-progn-body dummy2 cont body))))
2683
2684 ;;; This is a special special form that makes an "escape function"
2685 ;;; which returns unknown values from named block. We convert the
2686 ;;; function, set its kind to :Escape, and then reference it. The
2687 ;;; :Escape kind indicates that this function's purpose is to
2688 ;;; represent a non-local control transfer, and that it might not
2689 ;;; actually have to be compiled.
2690 ;;;
2691 ;;; Note that environment analysis replaces references to escape
2692 ;;; functions with references to the corresponding NLX-Info structure.
2693 (def-ir1-translator %escape-function ((tag) start cont)
2694   (let ((fun (ir1-convert-lambda
2695               `(lambda ()
2696                  (return-from ,tag (%unknown-values))))))
2697     (setf (functional-kind fun) :escape)
2698     (reference-leaf start cont fun)))
2699
2700 ;;; Yet another special special form. This one looks up a local
2701 ;;; function and smashes it to a :Cleanup function, as well as
2702 ;;; referencing it.
2703 (def-ir1-translator %cleanup-function ((name) start cont)
2704   (let ((fun (lexenv-find name functions)))
2705     (assert (lambda-p fun))
2706     (setf (functional-kind fun) :cleanup)
2707     (reference-leaf start cont fun)))
2708
2709 ;;; We represent the possibility of the control transfer by making an
2710 ;;; "escape function" that does a lexical exit, and instantiate the
2711 ;;; cleanup using %within-cleanup.
2712 (def-ir1-translator catch ((tag &body body) start cont)
2713   #!+sb-doc
2714   "Catch Tag Form*
2715   Evaluates Tag and instantiates it as a catcher while the body forms are
2716   evaluated in an implicit PROGN. If a THROW is done to Tag within the dynamic
2717   scope of the body, then control will be transferred to the end of the body
2718   and the thrown values will be returned."
2719   (ir1-convert
2720    start cont
2721    (let ((exit-block (gensym "EXIT-BLOCK-")))
2722      `(block ,exit-block
2723         (%within-cleanup
2724             :catch
2725             (%catch (%escape-function ,exit-block) ,tag)
2726           ,@body)))))
2727
2728 ;;; UNWIND-PROTECT is similar to CATCH, but more hairy. We make the
2729 ;;; cleanup forms into a local function so that they can be referenced
2730 ;;; both in the case where we are unwound and in any local exits. We
2731 ;;; use %Cleanup-Function on this to indicate that reference by
2732 ;;; %Unwind-Protect isn't "real", and thus doesn't cause creation of
2733 ;;; an XEP.
2734 (def-ir1-translator unwind-protect ((protected &body cleanup) start cont)
2735   #!+sb-doc
2736   "Unwind-Protect Protected Cleanup*
2737   Evaluate the form Protected, returning its values. The cleanup forms are
2738   evaluated whenever the dynamic scope of the Protected form is exited (either
2739   due to normal completion or a non-local exit such as THROW)."
2740   (ir1-convert
2741    start cont
2742    (let ((cleanup-fun (gensym "CLEANUP-FUN-"))
2743          (drop-thru-tag (gensym "DROP-THRU-TAG-"))
2744          (exit-tag (gensym "EXIT-TAG-"))
2745          (next (gensym "NEXT"))
2746          (start (gensym "START"))
2747          (count (gensym "COUNT")))
2748      `(flet ((,cleanup-fun () ,@cleanup nil))
2749         ;; FIXME: If we ever get DYNAMIC-EXTENT working, then
2750         ;; ,CLEANUP-FUN should probably be declared DYNAMIC-EXTENT,
2751         ;; and something can be done to make %ESCAPE-FUNCTION have
2752         ;; dynamic extent too.
2753         (block ,drop-thru-tag
2754           (multiple-value-bind (,next ,start ,count)
2755               (block ,exit-tag
2756                 (%within-cleanup
2757                     :unwind-protect
2758                     (%unwind-protect (%escape-function ,exit-tag)
2759                                      (%cleanup-function ,cleanup-fun))
2760                   (return-from ,drop-thru-tag ,protected)))
2761             (,cleanup-fun)
2762             (%continue-unwind ,next ,start ,count)))))))
2763 \f
2764 ;;;; multiple-value stuff
2765
2766 ;;; If there are arguments, MULTIPLE-VALUE-CALL turns into an
2767 ;;; MV-Combination.
2768 ;;;
2769 ;;; If there are no arguments, then we convert to a normal
2770 ;;; combination, ensuring that a MV-Combination always has at least
2771 ;;; one argument. This can be regarded as an optimization, but it is
2772 ;;; more important for simplifying compilation of MV-Combinations.
2773 (def-ir1-translator multiple-value-call ((fun &rest args) start cont)
2774   #!+sb-doc
2775   "MULTIPLE-VALUE-CALL Function Values-Form*
2776   Call Function, passing all the values of each Values-Form as arguments,
2777   values from the first Values-Form making up the first argument, etc."
2778   (let* ((fun-cont (make-continuation))
2779          (node (if args
2780                    (make-mv-combination fun-cont)
2781                    (make-combination fun-cont))))
2782     (ir1-convert start fun-cont
2783                  (if (and (consp fun) (eq (car fun) 'function))
2784                      fun
2785                      `(%coerce-callable-to-function ,fun)))
2786     (setf (continuation-dest fun-cont) node)
2787     (assert-continuation-type fun-cont
2788                               (specifier-type '(or function symbol)))
2789     (collect ((arg-conts))
2790       (let ((this-start fun-cont))
2791         (dolist (arg args)
2792           (let ((this-cont (make-continuation node)))
2793             (ir1-convert this-start this-cont arg)
2794             (setq this-start this-cont)
2795             (arg-conts this-cont)))
2796         (prev-link node this-start)
2797         (use-continuation node cont)
2798         (setf (basic-combination-args node) (arg-conts))))))
2799
2800 ;;; Multiple-Value-Prog1 is represented implicitly in IR1 by having a
2801 ;;; the result code use result continuation (CONT), but transfer
2802 ;;; control to the evaluation of the body. In other words, the result
2803 ;;; continuation isn't Immediately-Used-P by the nodes that compute
2804 ;;; the result.
2805 ;;;
2806 ;;; In order to get the control flow right, we convert the result with
2807 ;;; a dummy result continuation, then convert all the uses of the
2808 ;;; dummy to be uses of CONT. If a use is an Exit, then we also
2809 ;;; substitute CONT for the dummy in the corresponding Entry node so
2810 ;;; that they are consistent. Note that this doesn't amount to
2811 ;;; changing the exit target, since the control destination of an exit
2812 ;;; is determined by the block successor; we are just indicating the
2813 ;;; continuation that the result is delivered to.
2814 ;;;
2815 ;;; We then convert the body, using another dummy continuation in its
2816 ;;; own block as the result. After we are done converting the body, we
2817 ;;; move all predecessors of the dummy end block to CONT's block.
2818 ;;;
2819 ;;; Note that we both exploit and maintain the invariant that the CONT
2820 ;;; to an IR1 convert method either has no block or starts the block
2821 ;;; that control should transfer to after completion for the form.
2822 ;;; Nested MV-Prog1's work because during conversion of the result
2823 ;;; form, we use dummy continuation whose block is the true control
2824 ;;; destination.
2825 (def-ir1-translator multiple-value-prog1 ((result &rest forms) start cont)
2826   #!+sb-doc
2827   "MULTIPLE-VALUE-PROG1 Values-Form Form*
2828   Evaluate Values-Form and then the Forms, but return all the values of
2829   Values-Form."
2830   (continuation-starts-block cont)
2831   (let* ((dummy-result (make-continuation))
2832          (dummy-start (make-continuation))
2833          (cont-block (continuation-block cont)))
2834     (continuation-starts-block dummy-start)
2835     (ir1-convert start dummy-start result)
2836
2837     (substitute-continuation-uses cont dummy-start)
2838
2839     (continuation-starts-block dummy-result)
2840     (ir1-convert-progn-body dummy-start dummy-result forms)
2841     (let ((end-block (continuation-block dummy-result)))
2842       (dolist (pred (block-pred end-block))
2843         (unlink-blocks pred end-block)
2844         (link-blocks pred cont-block))
2845       (assert (not (continuation-dest dummy-result)))
2846       (delete-continuation dummy-result)
2847       (remove-from-dfo end-block))))
2848 \f
2849 ;;;; interface to defining macros
2850
2851 ;;;; DEFMACRO, DEFUN and DEFCONSTANT expand into calls to %DEFxxx
2852 ;;;; functions so that we get a chance to see what is going on. We
2853 ;;;; define IR1 translators for these functions which look at the
2854 ;;;; definition and then generate a call to the %%DEFxxx function.
2855
2856 ;;; Return a new source path with any stuff intervening between the
2857 ;;; current path and the first form beginning with Name stripped off.
2858 ;;; This is used to hide the guts of DEFmumble macros to prevent
2859 ;;; annoying error messages.
2860 (defun revert-source-path (name)
2861   (do ((path *current-path* (cdr path)))
2862       ((null path) *current-path*)
2863     (let ((first (first path)))
2864       (when (or (eq first name)
2865                 (eq first 'original-source-start))
2866         (return path)))))
2867
2868 ;;; Warn about incompatible or illegal definitions and add the macro
2869 ;;; to the compiler environment.
2870 ;;;
2871 ;;; Someday we could check for macro arguments being incompatibly
2872 ;;; redefined. Doing this right will involve finding the old macro
2873 ;;; lambda-list and comparing it with the new one.
2874 (def-ir1-translator %defmacro ((qname qdef lambda-list doc) start cont
2875                                :kind :function)
2876   (let (;; QNAME is typically a quoted name. I think the idea is to let
2877         ;; %DEFMACRO work as an ordinary function when interpreting. Whatever
2878         ;; the reason it's there, we don't want it any more. -- WHN 19990603
2879         (name (eval qname))
2880         ;; QDEF should be a sharp-quoted definition. We don't want to make a
2881         ;; function of it just yet, so we just drop the sharp-quote.
2882         (def (progn
2883                (assert (eq 'function (first qdef)))
2884                (assert (proper-list-of-length-p qdef 2))
2885                (second qdef))))
2886
2887     (unless (symbolp name)
2888       (compiler-error "The macro name ~S is not a symbol." name))
2889
2890     (ecase (info :function :kind name)
2891       ((nil))
2892       (:function
2893        (remhash name *free-functions*)
2894        (undefine-function-name name)
2895        (compiler-warning
2896         "~S is being redefined as a macro when it was previously ~(~A~) to be a function."
2897         name
2898         (info :function :where-from name)))
2899       (:macro)
2900       (:special-form
2901        (compiler-error "The special form ~S can't be redefined as a macro."
2902                        name)))
2903
2904     (setf (info :function :kind name) :macro)
2905     (setf (info :function :where-from name) :defined)
2906
2907     (when *compile-time-define-macros*
2908       (setf (info :function :macro-function name)
2909             (coerce def 'function)))
2910
2911     (let* ((*current-path* (revert-source-path 'defmacro))
2912            (fun (ir1-convert-lambda def name)))
2913       (setf (leaf-name fun)
2914             (concatenate 'string "DEFMACRO " (symbol-name name)))
2915       (setf (functional-arg-documentation fun) (eval lambda-list))
2916
2917       (ir1-convert start cont `(%%defmacro ',name ,fun ,doc)))
2918
2919     (when sb!xc:*compile-print*
2920       (compiler-mumble "converted ~S~%" name))))
2921
2922 (def-ir1-translator %define-compiler-macro ((name def lambda-list doc)
2923                                             start cont
2924                                             :kind :function)
2925   (let ((name (eval name))
2926         (def (second def))) ; Don't want to make a function just yet...
2927
2928     (when (eq (info :function :kind name) :special-form)
2929       (compiler-error "attempt to define a compiler-macro for special form ~S"
2930                       name))
2931
2932     (when *compile-time-define-macros*
2933       (setf (info :function :compiler-macro-function name)
2934             (coerce def 'function)))
2935
2936     (let* ((*current-path* (revert-source-path 'define-compiler-macro))
2937            (fun (ir1-convert-lambda def name)))
2938       (setf (leaf-name fun)
2939             (let ((*print-case* :upcase))
2940               (format nil "DEFINE-COMPILER-MACRO ~S" name)))
2941       (setf (functional-arg-documentation fun) (eval lambda-list))
2942
2943       (ir1-convert start cont `(%%define-compiler-macro ',name ,fun ,doc)))
2944
2945     (when sb!xc:*compile-print*
2946       (compiler-mumble "converted ~S~%" name))))
2947
2948 ;;; Update the global environment to correspond to the new definition.
2949 (def-ir1-translator %defconstant ((name value doc) start cont
2950                                   :kind :function)
2951   (let ((name (eval name))
2952         (newval (eval value)))
2953     (unless (symbolp name)
2954       (compiler-error "constant name not a symbol: ~S" name))
2955     (when (eq name t)
2956       (compiler-error "The value of T can't be changed."))
2957     (when (eq name nil)
2958       (compiler-error "Nihil ex nihil. (can't change NIL)"))
2959     (when (keywordp name)
2960       (compiler-error "Keyword values can't be changed."))
2961
2962     (let ((kind (info :variable :kind name)))
2963       (case kind
2964         (:constant
2965          ;; FIXME: ANSI says EQL, not EQUALP. Perhaps make a special
2966          ;; variant of this warning for the case where they're EQUALP,
2967          ;; since people seem to be confused about this.
2968          (unless (equalp newval (info :variable :constant-value name))
2969            (compiler-warning "redefining constant ~S as:~%  ~S" name newval)))
2970         (:global)
2971         (t
2972          (compiler-warning "redefining ~(~A~) ~S to be a constant"
2973                            kind
2974                            name))))
2975
2976     (setf (info :variable :kind name) :constant)
2977     (setf (info :variable :where-from name) :defined)
2978     (setf (info :variable :constant-value name) newval)
2979     (remhash name *free-variables*))
2980
2981   (ir1-convert start cont `(%%defconstant ,name ,value ,doc)))
2982 \f
2983 ;;;; defining global functions
2984
2985 ;;; Convert FUN as a lambda in the null environment, but use the
2986 ;;; current compilation policy. Note that FUN may be a
2987 ;;; LAMBDA-WITH-ENVIRONMENT, so we may have to augment the environment
2988 ;;; to reflect the state at the definition site.
2989 (defun ir1-convert-inline-lambda (fun &optional name)
2990   (destructuring-bind (decls macros symbol-macros &rest body)
2991                       (if (eq (car fun) 'lambda-with-environment)
2992                           (cdr fun)
2993                           `(() () () . ,(cdr fun)))
2994     (let ((*lexenv* (make-lexenv
2995                      :default (process-decls decls nil nil
2996                                              (make-continuation)
2997                                              (make-null-lexenv))
2998                      :variables (copy-list symbol-macros)
2999                      :functions
3000                      (mapcar #'(lambda (x)
3001                                  `(,(car x) .
3002                                    (macro . ,(coerce (cdr x) 'function))))
3003                              macros)
3004                      :cookie (lexenv-cookie *lexenv*)
3005                      :interface-cookie (lexenv-interface-cookie *lexenv*))))
3006       (ir1-convert-lambda `(lambda ,@body) name))))
3007
3008 ;;; Return a lambda that has been "closed" with respect to ENV,
3009 ;;; returning a LAMBDA-WITH-ENVIRONMENT if there are interesting
3010 ;;; macros or declarations. If there is something too complex (like a
3011 ;;; lexical variable) in the environment, then we return NIL.
3012 (defun inline-syntactic-closure-lambda (lambda &optional (env *lexenv*))
3013   (let ((variables (lexenv-variables env))
3014         (functions (lexenv-functions env))
3015         (decls ())
3016         (symmacs ())
3017         (macros ()))
3018     (cond ((or (lexenv-blocks env) (lexenv-tags env)) nil)
3019           ((and (null variables) (null functions))
3020            lambda)
3021           ((dolist (x variables nil)
3022              (let ((name (car x))
3023                    (what (cdr x)))
3024                (when (eq x (assoc name variables :test #'eq))
3025                  (typecase what
3026                    (cons
3027                     (assert (eq (car what) 'macro))
3028                     (push x symmacs))
3029                    (global-var
3030                     (assert (eq (global-var-kind what) :special))
3031                     (push `(special ,name) decls))
3032                    (t (return t))))))
3033            nil)
3034           ((dolist (x functions nil)
3035              (let ((name (car x))
3036                    (what (cdr x)))
3037                (when (eq x (assoc name functions :test #'equal))
3038                  (typecase what
3039                    (cons
3040                     (push (cons name
3041                                 (function-lambda-expression (cdr what)))
3042                           macros))
3043                    (global-var
3044                     (when (defined-function-p what)
3045                       (push `(,(car (rassoc (defined-function-inlinep what)
3046                                             inlinep-translations))
3047                               ,name)
3048                             decls)))
3049                    (t (return t))))))
3050            nil)
3051           (t
3052            `(lambda-with-environment ,decls
3053                                      ,macros
3054                                      ,symmacs
3055                                      . ,(rest lambda))))))
3056
3057 ;;; Get a DEFINED-FUNCTION object for a function we are about to
3058 ;;; define. If the function has been forward referenced, then
3059 ;;; substitute for the previous references.
3060 (defun get-defined-function (name)
3061   (let* ((name (proclaim-as-function-name name))
3062          (found (find-free-function name "Eh?")))
3063     (note-name-defined name :function)
3064     (cond ((not (defined-function-p found))
3065            (assert (not (info :function :inlinep name)))
3066            (let* ((where-from (leaf-where-from found))
3067                   (res (make-defined-function
3068                         :name name
3069                         :where-from (if (eq where-from :declared)
3070                                         :declared :defined)
3071                         :type (leaf-type found))))
3072              (substitute-leaf res found)
3073              (setf (gethash name *free-functions*) res)))
3074           ;; If *FREE-FUNCTIONS* has a previously converted definition for this
3075           ;; name, then blow it away and try again.
3076           ((defined-function-functional found)
3077            (remhash name *free-functions*)
3078            (get-defined-function name))
3079           (t found))))
3080
3081 ;;; Check a new global function definition for consistency with
3082 ;;; previous declaration or definition, and assert argument/result
3083 ;;; types if appropriate. This this assertion is suppressed by the
3084 ;;; EXPLICIT-CHECK attribute, which is specified on functions that
3085 ;;; check their argument types as a consequence of type dispatching.
3086 ;;; This avoids redundant checks such as NUMBERP on the args to +,
3087 ;;; etc.
3088 (defun assert-new-definition (var fun)
3089   (let ((type (leaf-type var))
3090         (for-real (eq (leaf-where-from var) :declared))
3091         (info (info :function :info (leaf-name var))))
3092     (assert-definition-type
3093      fun type
3094      :error-function #'compiler-warning
3095      :warning-function (cond (info #'compiler-warning)
3096                              (for-real #'compiler-note)
3097                              (t nil))
3098      :really-assert
3099      (and for-real
3100           (not (and info
3101                     (ir1-attributep (function-info-attributes info)
3102                                     explicit-check))))
3103      :where (if for-real
3104                 "previous declaration"
3105                 "previous definition"))))
3106
3107 ;;; Convert a lambda doing all the basic stuff we would do if we were
3108 ;;; converting a DEFUN. This is used both by the %DEFUN translator and
3109 ;;; for global inline expansion.
3110 ;;;
3111 ;;; Unless a :INLINE function, we temporarily clobber the inline
3112 ;;; expansion. This prevents recursive inline expansion of
3113 ;;; opportunistic pseudo-inlines.
3114 (defun ir1-convert-lambda-for-defun (lambda var expansion converter)
3115   (declare (cons lambda) (function converter) (type defined-function var))
3116   (let ((var-expansion (defined-function-inline-expansion var)))
3117     (unless (eq (defined-function-inlinep var) :inline)
3118       (setf (defined-function-inline-expansion var) nil))
3119     (let* ((name (leaf-name var))
3120            (fun (funcall converter lambda name))
3121            (function-info (info :function :info name)))
3122       (setf (functional-inlinep fun) (defined-function-inlinep var))
3123       (assert-new-definition var fun)
3124       (setf (defined-function-inline-expansion var) var-expansion)
3125       ;; If definitely not an interpreter stub, then substitute for any
3126       ;; old references.
3127       (unless (or (eq (defined-function-inlinep var) :notinline)
3128                   (not *block-compile*)
3129                   (and function-info
3130                        (or (function-info-transforms function-info)
3131                            (function-info-templates function-info)
3132                            (function-info-ir2-convert function-info))))
3133         (substitute-leaf fun var)
3134         ;; If in a simple environment, then we can allow backward
3135         ;; references to this function from following top-level forms.
3136         (when expansion (setf (defined-function-functional var) fun)))
3137       fun)))
3138
3139 ;;; Convert the definition and install it in the global environment
3140 ;;; with a LABELS-like effect. If the lexical environment is not null,
3141 ;;; then we only install the definition during the processing of this
3142 ;;; DEFUN, ensuring that the function cannot be called outside of the
3143 ;;; correct environment. If the function is globally NOTINLINE, then
3144 ;;; that inhibits even local substitution. Also, emit top-level code
3145 ;;; to install the definition.
3146 ;;;
3147 ;;; This is one of the major places where the semantics of block
3148 ;;; compilation is handled. Substitution for global names is totally
3149 ;;; inhibited if *BLOCK-COMPILE* is NIL. And if *BLOCK-COMPILE* is
3150 ;;; true and entry points are specified, then we don't install global
3151 ;;; definitions for non-entry functions (effectively turning them into
3152 ;;; local lexical functions.)
3153 (def-ir1-translator %defun ((name def doc source) start cont
3154                             :kind :function)
3155   (declare (ignore source))
3156   (let* ((name (eval name))
3157          (lambda (second def))
3158          (*current-path* (revert-source-path 'defun))
3159          (expansion (unless (eq (info :function :inlinep name) :notinline)
3160                       (inline-syntactic-closure-lambda lambda))))
3161     ;; If not in a simple environment or NOTINLINE, then discard any forward
3162     ;; references to this function.
3163     (unless expansion (remhash name *free-functions*))
3164
3165     (let* ((var (get-defined-function name))
3166            (save-expansion (and (member (defined-function-inlinep var)
3167                                         '(:inline :maybe-inline))
3168                                 expansion)))
3169       (setf (defined-function-inline-expansion var) expansion)
3170       (setf (info :function :inline-expansion name) save-expansion)
3171       ;; If there is a type from a previous definition, blast it, since it is
3172       ;; obsolete.
3173       (when (eq (leaf-where-from var) :defined)
3174         (setf (leaf-type var) (specifier-type 'function)))
3175
3176       (let ((fun (ir1-convert-lambda-for-defun lambda
3177                                                var
3178                                                expansion
3179                                                #'ir1-convert-lambda)))
3180         (ir1-convert
3181          start cont
3182          (if (and *block-compile* *entry-points*
3183                   (not (member name *entry-points* :test #'equal)))
3184              `',name
3185              `(%%defun ',name ,fun ,doc
3186                        ,@(when save-expansion `(',save-expansion)))))
3187
3188         (when sb!xc:*compile-print*
3189           (compiler-mumble "converted ~S~%" name))))))