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