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