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