0.8.16.6:
[sbcl.git] / src / compiler / main.lisp
1 ;;;; the top level interfaces to the compiler, plus some other
2 ;;;; compiler-related stuff (e.g. CL:CALL-ARGUMENTS-LIMIT) which
3 ;;;; doesn't obviously belong anywhere else
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15
16 ;;; FIXME: Doesn't this belong somewhere else, like early-c.lisp?
17 (declaim (special *constants* *free-vars* *component-being-compiled*
18                   *code-vector* *next-location* *result-fixups*
19                   *free-funs* *source-paths*
20                   *seen-blocks* *seen-funs* *list-conflicts-table*
21                   *continuation-number* *continuation-numbers*
22                   *number-continuations* *tn-id* *tn-ids* *id-tns*
23                   *label-ids* *label-id* *id-labels*
24                   *undefined-warnings* *compiler-error-count*
25                   *compiler-warning-count* *compiler-style-warning-count*
26                   *compiler-note-count*
27                   *compiler-error-bailout*
28                   #!+sb-show *compiler-trace-output*
29                   *last-source-context* *last-original-source*
30                   *last-source-form* *last-format-string* *last-format-args*
31                   *last-message-count* *lexenv* *fun-names-in-this-file*
32                   *allow-instrumenting*))
33
34 ;;; Whether call of a function which cannot be defined causes a full
35 ;;; warning.
36 (defvar *flame-on-necessarily-undefined-function* nil)
37
38 (defvar *check-consistency* nil)
39 (defvar *all-components*)
40
41 ;;; Set to NIL to disable loop analysis for register allocation. 
42 (defvar *loop-analyze* t)
43
44 ;;; Bind this to a stream to capture various internal debugging output.
45 (defvar *compiler-trace-output* nil)
46
47 ;;; The current block compilation state. These are initialized to the
48 ;;; :BLOCK-COMPILE and :ENTRY-POINTS arguments that COMPILE-FILE was
49 ;;; called with.
50 ;;;
51 ;;; *BLOCK-COMPILE-ARG* holds the original value of the :BLOCK-COMPILE
52 ;;; argument, which overrides any internal declarations.
53 (defvar *block-compile*)
54 (defvar *block-compile-arg*)
55 (declaim (type (member nil t :specified) *block-compile* *block-compile-arg*))
56 (defvar *entry-points*)
57 (declaim (list *entry-points*))
58
59 ;;; When block compiling, used by PROCESS-FORM to accumulate top level
60 ;;; lambdas resulting from compiling subforms. (In reverse order.)
61 (defvar *toplevel-lambdas*)
62 (declaim (list *toplevel-lambdas*))
63
64 (defvar sb!xc:*compile-verbose* t
65   #!+sb-doc
66   "The default for the :VERBOSE argument to COMPILE-FILE.")
67 (defvar sb!xc:*compile-print* t
68   #!+sb-doc
69   "The default for the :PRINT argument to COMPILE-FILE.")
70 (defvar *compile-progress* nil
71   #!+sb-doc
72   "When this is true, the compiler prints to *ERROR-OUTPUT* progress
73   information about the phases of compilation of each function. (This
74   is useful mainly in large block compilations.)")
75
76 (defvar sb!xc:*compile-file-pathname* nil
77   #!+sb-doc
78   "The defaulted pathname of the file currently being compiled, or NIL if not
79   compiling.")
80 (defvar sb!xc:*compile-file-truename* nil
81   #!+sb-doc
82   "The TRUENAME of the file currently being compiled, or NIL if not
83   compiling.")
84
85 (declaim (type (or pathname null)
86                sb!xc:*compile-file-pathname*
87                sb!xc:*compile-file-truename*))
88
89 ;;; the SOURCE-INFO structure for the current compilation. This is
90 ;;; null globally to indicate that we aren't currently in any
91 ;;; identifiable compilation.
92 (defvar *source-info* nil)
93
94 ;;; This is true if we are within a WITH-COMPILATION-UNIT form (which
95 ;;; normally causes nested uses to be no-ops).
96 (defvar *in-compilation-unit* nil)
97
98 ;;; Count of the number of compilation units dynamically enclosed by
99 ;;; the current active WITH-COMPILATION-UNIT that were unwound out of.
100 (defvar *aborted-compilation-unit-count*)
101
102 ;;; Mumble conditional on *COMPILE-PROGRESS*.
103 (defun maybe-mumble (&rest foo)
104   (when *compile-progress*
105     (compiler-mumble "~&")
106     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
107        (apply #'compiler-mumble foo))))
108
109 (deftype object () '(or fasl-output core-object null))
110
111 (defvar *compile-object* nil)
112 (declaim (type object *compile-object*))
113 \f
114 ;;;; WITH-COMPILATION-UNIT and WITH-COMPILATION-VALUES
115
116 (defmacro sb!xc:with-compilation-unit (options &body body)
117   #!+sb-doc
118   "WITH-COMPILATION-UNIT ({Key Value}*) Form*
119   This form affects compilations that take place within its dynamic extent. It
120   is intended to be wrapped around the compilation of all files in the same
121   system. These keywords are defined:
122     :OVERRIDE Boolean-Form
123         One of the effects of this form is to delay undefined warnings
124         until the end of the form, instead of giving them at the end of each
125         compilation. If OVERRIDE is NIL (the default), then the outermost
126         WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
127         OVERRIDE true causes that form to grab any enclosed warnings, even if
128         it is enclosed by another WITH-COMPILATION-UNIT."
129   `(%with-compilation-unit (lambda () ,@body) ,@options))
130
131 (defun %with-compilation-unit (fn &key override)
132   (declare (type function fn))
133   (let ((succeeded-p nil))
134     (if (and *in-compilation-unit* (not override))
135         ;; Inside another WITH-COMPILATION-UNIT, a WITH-COMPILATION-UNIT is
136         ;; ordinarily (unless OVERRIDE) basically a no-op.
137         (unwind-protect
138              (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
139           (unless succeeded-p
140             (incf *aborted-compilation-unit-count*)))
141         (let ((*aborted-compilation-unit-count* 0)
142               (*compiler-error-count* 0)
143               (*compiler-warning-count* 0)
144               (*compiler-style-warning-count* 0)
145               (*compiler-note-count* 0)
146               (*undefined-warnings* nil)
147               (*in-compilation-unit* t))
148           (sb!thread:with-recursive-lock (*big-compiler-lock*)
149             (handler-bind ((parse-unknown-type
150                             (lambda (c)
151                               (note-undefined-reference
152                                (parse-unknown-type-specifier c)
153                                :type))))
154               (unwind-protect
155                    (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
156                 (unless succeeded-p
157                   (incf *aborted-compilation-unit-count*))
158                 (summarize-compilation-unit (not succeeded-p)))))))))
159
160 ;;; Is FUN-NAME something that no conforming program can rely on
161 ;;; defining as a function?
162 (defun fun-name-reserved-by-ansi-p (fun-name)
163   (eq (symbol-package (fun-name-block-name fun-name))
164       *cl-package*))
165
166 ;;; This is to be called at the end of a compilation unit. It signals
167 ;;; any residual warnings about unknown stuff, then prints the total
168 ;;; error counts. ABORT-P should be true when the compilation unit was
169 ;;; aborted by throwing out. ABORT-COUNT is the number of dynamically
170 ;;; enclosed nested compilation units that were aborted.
171 (defun summarize-compilation-unit (abort-p)
172   (unless abort-p
173     (handler-bind ((style-warning #'compiler-style-warning-handler)
174                    (warning #'compiler-warning-handler))
175
176       (let ((undefs (sort *undefined-warnings* #'string<
177                           :key (lambda (x)
178                                  (let ((x (undefined-warning-name x)))
179                                    (if (symbolp x)
180                                        (symbol-name x)
181                                        (prin1-to-string x)))))))
182         (dolist (undef undefs)
183           (let ((name (undefined-warning-name undef))
184                 (kind (undefined-warning-kind undef))
185                 (warnings (undefined-warning-warnings undef))
186                 (undefined-warning-count (undefined-warning-count undef)))
187             (dolist (*compiler-error-context* warnings)
188               (if #-sb-xc-host (and (eq kind :function)
189                                     (fun-name-reserved-by-ansi-p name)
190                                     *flame-on-necessarily-undefined-function*)
191                   #+sb-xc-host nil
192                   (case name
193                     ((declare)
194                      (compiler-warn
195                       "~@<There is no function named ~S. References to ~S in ~
196                        some contexts (like starts of blocks) have special ~
197                        meaning, but here it would have to be a function, ~
198                        and that shouldn't be right.~:@>"
199                       name name))
200                     (t
201                      (compiler-warn
202                       "~@<The ~(~A~) ~S is undefined, and its name is ~
203                        reserved by ANSI CL so that even if it were ~
204                        defined later, the code doing so would not be ~
205                        portable.~:@>"
206                       kind name)))
207                   (if (eq kind :variable)
208                       (compiler-warn "undefined ~(~A~): ~S" kind name)
209                       (compiler-style-warn "undefined ~(~A~): ~S" kind name))))
210             (let ((warn-count (length warnings)))
211               (when (and warnings (> undefined-warning-count warn-count))
212                 (let ((more (- undefined-warning-count warn-count)))
213                   (if (eq kind :variable)
214                       (compiler-warn
215                        "~W more use~:P of undefined ~(~A~) ~S"
216                        more kind name)
217                       (compiler-style-warn
218                        "~W more use~:P of undefined ~(~A~) ~S"
219                        more kind name)))))))
220
221         (dolist (kind '(:variable :function :type))
222           (let ((summary (mapcar #'undefined-warning-name
223                                  (remove kind undefs :test #'neq
224                                          :key #'undefined-warning-kind))))
225             (when summary
226               (if (eq kind :variable)
227                   (compiler-warn
228                    "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
229                     ~%  ~{~<~%  ~1:;~S~>~^ ~}"
230                    (cdr summary) kind summary)
231                   (compiler-style-warn
232                    "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
233                    ~%  ~{~<~%  ~1:;~S~>~^ ~}"
234                    (cdr summary) kind summary))))))))
235
236   (unless (and (not abort-p)
237                (zerop *aborted-compilation-unit-count*)
238                (zerop *compiler-error-count*)
239                (zerop *compiler-warning-count*)
240                (zerop *compiler-style-warning-count*)
241                (zerop *compiler-note-count*))
242     (format *error-output* "~&")
243     (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
244       (compiler-mumble "compilation unit ~:[finished~;aborted~]~
245                        ~[~:;~:*~&  caught ~W fatal ERROR condition~:P~]~
246                        ~[~:;~:*~&  caught ~W ERROR condition~:P~]~
247                        ~[~:;~:*~&  caught ~W WARNING condition~:P~]~
248                        ~[~:;~:*~&  caught ~W STYLE-WARNING condition~:P~]~
249                        ~[~:;~:*~&  printed ~W note~:P~]"
250                        abort-p
251                        *aborted-compilation-unit-count*
252                        *compiler-error-count*
253                        *compiler-warning-count*
254                        *compiler-style-warning-count*
255                        *compiler-note-count*)))
256   (format *error-output* "~&"))
257
258 ;;; Evaluate BODY, then return (VALUES BODY-VALUE WARNINGS-P
259 ;;; FAILURE-P), where BODY-VALUE is the first value of the body, and
260 ;;; WARNINGS-P and FAILURE-P are as in CL:COMPILE or CL:COMPILE-FILE.
261 ;;; This also wraps up WITH-IR1-NAMESPACE functionality.
262 (defmacro with-compilation-values (&body body)
263   `(with-ir1-namespace
264     (let ((*warnings-p* nil)
265           (*failure-p* nil))
266       (values (progn ,@body)
267               *warnings-p*
268               *failure-p*))))
269 \f
270 ;;;; component compilation
271
272 (defparameter *max-optimize-iterations* 3 ; ARB
273   #!+sb-doc
274   "The upper limit on the number of times that we will consecutively do IR1
275   optimization that doesn't introduce any new code. A finite limit is
276   necessary, since type inference may take arbitrarily long to converge.")
277
278 (defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called")
279 (defevent ir1-optimize-maxed-out "hit *MAX-OPTIMIZE-ITERATIONS* limit")
280
281 ;;; Repeatedly optimize COMPONENT until no further optimizations can
282 ;;; be found or we hit our iteration limit. When we hit the limit, we
283 ;;; clear the component and block REOPTIMIZE flags to discourage the
284 ;;; next optimization attempt from pounding on the same code.
285 (defun ir1-optimize-until-done (component)
286   (declare (type component component))
287   (maybe-mumble "opt")
288   (event ir1-optimize-until-done)
289   (let ((count 0)
290         (cleared-reanalyze nil))
291     (loop
292       (when (component-reanalyze component)
293         (setq count 0)
294         (setq cleared-reanalyze t)
295         (setf (component-reanalyze component) nil))
296       (setf (component-reoptimize component) nil)
297       (ir1-optimize component)
298       (cond ((component-reoptimize component)
299              (incf count)
300              (when (= count *max-optimize-iterations*)
301                (maybe-mumble "*")
302                (cond ((retry-delayed-ir1-transforms :optimize)
303                       (maybe-mumble "+")
304                       (setq count 0))
305                      (t
306                       (event ir1-optimize-maxed-out)
307                       (setf (component-reoptimize component) nil)
308                       (do-blocks (block component)
309                         (setf (block-reoptimize block) nil))
310                       (return)))))
311             ((retry-delayed-ir1-transforms :optimize)
312              (setf count 0)
313              (maybe-mumble "+"))
314             (t
315              (maybe-mumble " ")
316              (return)))
317       (maybe-mumble "."))
318     (when cleared-reanalyze
319       (setf (component-reanalyze component) t)))
320   (values))
321
322 (defparameter *constraint-propagate* t)
323
324 ;;; KLUDGE: This was bumped from 5 to 10 in a DTC patch ported by MNA
325 ;;; from CMU CL into sbcl-0.6.11.44, the same one which allowed IR1
326 ;;; transforms to be delayed. Either DTC or MNA or both didn't explain
327 ;;; why, and I don't know what the rationale was. -- WHN 2001-04-28
328 ;;;
329 ;;; FIXME: It would be good to document why it's important to have a
330 ;;; large value here, and what the drawbacks of an excessively large
331 ;;; value are; and it might also be good to make it depend on
332 ;;; optimization policy.
333 (defparameter *reoptimize-after-type-check-max* 10)
334
335 (defevent reoptimize-maxed-out
336   "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
337
338 ;;; Iterate doing FIND-DFO until no new dead code is discovered.
339 (defun dfo-as-needed (component)
340   (declare (type component component))
341   (when (component-reanalyze component)
342     (maybe-mumble "DFO")
343     (loop
344       (find-dfo component)
345       (unless (component-reanalyze component)
346         (maybe-mumble " ")
347         (return))
348       (maybe-mumble ".")))
349   (values))
350
351 ;;; Do all the IR1 phases for a non-top-level component.
352 (defun ir1-phases (component)
353   (declare (type component component))
354   (aver-live-component component)
355   (let ((*constraint-number* 0)
356         (loop-count 1)
357         (*delayed-ir1-transforms* nil))
358     (declare (special *constraint-number* *delayed-ir1-transforms*))
359     (loop
360       (ir1-optimize-until-done component)
361       (when (or (component-new-functionals component)
362                 (component-reanalyze-functionals component))
363         (maybe-mumble "locall ")
364         (locall-analyze-component component))
365       (dfo-as-needed component)
366       (when *constraint-propagate*
367         (maybe-mumble "constraint ")
368         (constraint-propagate component))
369       (when (retry-delayed-ir1-transforms :constraint)
370         (maybe-mumble "Rtran "))
371       (flet ((want-reoptimization-p ()
372                (or (component-reoptimize component)
373                    (component-reanalyze component)
374                    (component-new-functionals component)
375                    (component-reanalyze-functionals component))))
376         (unless (and (want-reoptimization-p)
377                      ;; We delay the generation of type checks until
378                      ;; the type constraints have had time to
379                      ;; propagate, else the compiler can confuse itself.
380                      (< loop-count (- *reoptimize-after-type-check-max* 4)))
381           (maybe-mumble "type ")
382           (generate-type-checks component)
383           (unless (want-reoptimization-p)
384             (return))))
385       (when (>= loop-count *reoptimize-after-type-check-max*)
386         (maybe-mumble "[reoptimize limit]")
387         (event reoptimize-maxed-out)
388         (return))
389       (incf loop-count)))
390
391   (ir1-finalize component)
392   (values))
393
394 (defun %compile-component (component)
395   (let ((*code-segment* nil)
396         (*elsewhere* nil))
397     (maybe-mumble "GTN ")
398     (gtn-analyze component)
399     (maybe-mumble "LTN ")
400     (ltn-analyze component)
401     (dfo-as-needed component)
402     (maybe-mumble "control ")
403     (control-analyze component #'make-ir2-block)
404
405     (when (or (ir2-component-values-receivers (component-info component))
406               (component-dx-lvars component))
407       (maybe-mumble "stack ")
408       (stack-analyze component)
409       ;; Assign BLOCK-NUMBER for any cleanup blocks introduced by
410       ;; stack analysis. There shouldn't be any unreachable code after
411       ;; control, so this won't delete anything.
412       (dfo-as-needed component))
413
414     (unwind-protect
415         (progn
416           (maybe-mumble "IR2tran ")
417           (init-assembler)
418           (entry-analyze component)
419           (ir2-convert component)
420
421           (when (policy *lexenv* (>= speed compilation-speed))
422             (maybe-mumble "copy ")
423             (copy-propagate component))
424
425           (select-representations component)
426
427           (when *check-consistency*
428             (maybe-mumble "check2 ")
429             (check-ir2-consistency component))
430
431           (delete-unreferenced-tns component)
432
433           (maybe-mumble "life ")
434           (lifetime-analyze component)
435
436           (when *compile-progress*
437             (compiler-mumble "") ; Sync before doing more output.
438             (pre-pack-tn-stats component *error-output*))
439
440           (when *check-consistency*
441             (maybe-mumble "check-life ")
442             (check-life-consistency component))
443
444           (maybe-mumble "pack ")
445           (pack component)
446
447           (when *check-consistency*
448             (maybe-mumble "check-pack ")
449             (check-pack-consistency component))
450
451           (when *compiler-trace-output*
452             (describe-component component *compiler-trace-output*)
453             (describe-ir2-component component *compiler-trace-output*))
454
455           (maybe-mumble "code ")
456           (multiple-value-bind (code-length trace-table fixup-notes)
457               (generate-code component)
458
459             #-sb-xc-host
460             (when *compiler-trace-output*
461               (format *compiler-trace-output*
462                       "~|~%disassembly of code for ~S~2%" component)
463               (sb!disassem:disassemble-assem-segment *code-segment*
464                                                      *compiler-trace-output*))
465
466             (etypecase *compile-object*
467               (fasl-output
468                (maybe-mumble "fasl")
469                (fasl-dump-component component
470                                     *code-segment*
471                                     code-length
472                                     trace-table
473                                     fixup-notes
474                                     *compile-object*))
475               (core-object
476                (maybe-mumble "core")
477                (make-core-component component
478                                     *code-segment*
479                                     code-length
480                                     trace-table
481                                     fixup-notes
482                                     *compile-object*))
483               (null))))))
484
485   ;; We're done, so don't bother keeping anything around.
486   (setf (component-info component) :dead)
487
488   (values))
489
490 ;;; Delete components with no external entry points before we try to
491 ;;; generate code. Unreachable closures can cause IR2 conversion to
492 ;;; puke on itself, since it is the reference to the closure which
493 ;;; normally causes the components to be combined.
494 (defun delete-if-no-entries (component)
495   (dolist (fun (component-lambdas component) (delete-component component))
496     (when (functional-has-external-references-p fun)
497       (return))
498     (case (functional-kind fun)
499       (:toplevel (return))
500       (:external
501        (unless (every (lambda (ref)
502                         (eq (node-component ref) component))
503                       (leaf-refs fun))
504          (return))))))
505
506 (defun compile-component (component)
507
508   ;; miscellaneous sanity checks
509   ;;
510   ;; FIXME: These are basically pretty wimpy compared to the checks done
511   ;; by the old CHECK-IR1-CONSISTENCY code. It would be really nice to
512   ;; make those internal consistency checks work again and use them.
513   (aver-live-component component)
514   (do-blocks (block component)
515     (aver (eql (block-component block) component)))
516   (dolist (lambda (component-lambdas component))
517     ;; sanity check to prevent weirdness from propagating insidiously as
518     ;; far from its root cause as it did in bug 138: Make sure that
519     ;; thing-to-COMPONENT links are consistent.
520     (aver (eql (lambda-component lambda) component))
521     (aver (eql (node-component (lambda-bind lambda)) component)))
522
523   (let* ((*component-being-compiled* component))
524     (when sb!xc:*compile-print*
525       (compiler-mumble "~&; compiling ~A: " (component-name component)))
526
527     (ir1-phases component)
528
529     (when *loop-analyze*
530       (dfo-as-needed component)
531       (find-dominators component)
532       (loop-analyze component))
533
534     #|
535     (when (and *loop-analyze* *compiler-trace-output*)
536       (labels ((print-blocks (block)
537                  (format *compiler-trace-output* "    ~A~%" block)
538                  (when (block-loop-next block)
539                    (print-blocks (block-loop-next block))))
540                (print-loop (loop)
541                  (format *compiler-trace-output* "loop=~A~%" loop)
542                  (print-blocks (loop-blocks loop))
543                  (dolist (l (loop-inferiors loop))
544                    (print-loop l))))
545         (print-loop (component-outer-loop component))))
546     |#
547     
548     ;; FIXME: What is MAYBE-MUMBLE for? Do we need it any more?
549     (maybe-mumble "env ")
550     (physenv-analyze component)
551     (dfo-as-needed component)
552
553     (delete-if-no-entries component)
554
555     (unless (eq (block-next (component-head component))
556                 (component-tail component))
557       (%compile-component component)))
558
559   (clear-constant-info)
560
561   (when sb!xc:*compile-print*
562     (compiler-mumble "~&"))
563
564   (values))
565 \f
566 ;;;; clearing global data structures
567 ;;;;
568 ;;;; FIXME: Is it possible to get rid of this stuff, getting rid of
569 ;;;; global data structures entirely when possible and consing up the
570 ;;;; others from scratch instead of clearing and reusing them?
571
572 ;;; Clear the INFO in constants in the *FREE-VARS*, etc. In
573 ;;; addition to allowing stuff to be reclaimed, this is required for
574 ;;; correct assignment of constant offsets, since we need to assign a
575 ;;; new offset for each component. We don't clear the FUNCTIONAL-INFO
576 ;;; slots, since they are used to keep track of functions across
577 ;;; component boundaries.
578 (defun clear-constant-info ()
579   (maphash (lambda (k v)
580              (declare (ignore k))
581              (setf (leaf-info v) nil))
582            *constants*)
583   (maphash (lambda (k v)
584              (declare (ignore k))
585              (when (constant-p v)
586                (setf (leaf-info v) nil)))
587            *free-vars*)
588   (values))
589
590 ;;; Blow away the REFS for all global variables, and let COMPONENT
591 ;;; be recycled.
592 (defun clear-ir1-info (component)
593   (declare (type component component))
594   (labels ((blast (x)
595              (maphash (lambda (k v)
596                         (declare (ignore k))
597                         (when (leaf-p v)
598                           (setf (leaf-refs v)
599                                 (delete-if #'here-p (leaf-refs v)))
600                           (when (basic-var-p v)
601                             (setf (basic-var-sets v)
602                                   (delete-if #'here-p (basic-var-sets v))))))
603                       x))
604            (here-p (x)
605              (eq (node-component x) component)))
606     (blast *free-vars*)
607     (blast *free-funs*)
608     (blast *constants*))
609   (values))
610
611 ;;; Clear global variables used by the compiler.
612 ;;;
613 ;;; FIXME: It seems kinda nasty and unmaintainable to have to do this,
614 ;;; and it adds overhead even when people aren't using the compiler.
615 ;;; Perhaps we could make these global vars unbound except when
616 ;;; actually in use, so that this function could go away.
617 (defun clear-stuff (&optional (debug-too t))
618
619   ;; Clear global tables.
620   (when (boundp '*free-funs*)
621     (clrhash *free-funs*)
622     (clrhash *free-vars*)
623     (clrhash *constants*))
624
625   ;; Clear debug counters and tables.
626   (clrhash *seen-blocks*)
627   (clrhash *seen-funs*)
628   (clrhash *list-conflicts-table*)
629
630   (when debug-too
631     (clrhash *continuation-numbers*)
632     (clrhash *number-continuations*)
633     (setq *continuation-number* 0)
634     (clrhash *tn-ids*)
635     (clrhash *id-tns*)
636     (setq *tn-id* 0)
637     (clrhash *label-ids*)
638     (clrhash *id-labels*)
639     (setq *label-id* 0))
640
641   ;; (Note: The CMU CL code used to set CL::*GENSYM-COUNTER* to zero here.
642   ;; Superficially, this seemed harmful -- the user could reasonably be
643   ;; surprised if *GENSYM-COUNTER* turned back to zero when something was
644   ;; compiled. A closer inspection showed that this actually turned out to be
645   ;; harmless in practice, because CLEAR-STUFF was only called from within
646   ;; forms which bound CL::*GENSYM-COUNTER* to zero. However, this means that
647   ;; even though zeroing CL::*GENSYM-COUNTER* here turned out to be harmless in
648   ;; practice, it was also useless in practice. So we don't do it any more.)
649
650   (values))
651 \f
652 ;;;; trace output
653
654 ;;; Print out some useful info about COMPONENT to STREAM.
655 (defun describe-component (component *standard-output*)
656   (declare (type component component))
657   (format t "~|~%;;;; component: ~S~2%" (component-name component))
658   (print-all-blocks component)
659   (values))
660
661 (defun describe-ir2-component (component *standard-output*)
662   (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
663   (format t "entries:~%")
664   (dolist (entry (ir2-component-entries (component-info component)))
665     (format t "~4TL~D: ~S~:[~; [closure]~]~%"
666             (label-id (entry-info-offset entry))
667             (entry-info-name entry)
668             (entry-info-closure-p entry)))
669   (terpri)
670   (pre-pack-tn-stats component *standard-output*)
671   (terpri)
672   (print-ir2-blocks component)
673   (terpri)
674   (values))
675 \f
676 ;;;; file reading
677 ;;;;
678 ;;;; When reading from a file, we have to keep track of some source
679 ;;;; information. We also exploit our ability to back up for printing
680 ;;;; the error context and for recovering from errors.
681 ;;;;
682 ;;;; The interface we provide to this stuff is the stream-oid
683 ;;;; SOURCE-INFO structure. The bookkeeping is done as a side effect
684 ;;;; of getting the next source form.
685
686 ;;; A FILE-INFO structure holds all the source information for a
687 ;;; given file.
688 (def!struct (file-info (:copier nil))
689   ;; If a file, the truename of the corresponding source file. If from
690   ;; a Lisp form, :LISP. If from a stream, :STREAM.
691   (name (missing-arg) :type (or pathname (member :lisp :stream)))
692   ;; the defaulted, but not necessarily absolute file name (i.e. prior
693   ;; to TRUENAME call.) Null if not a file. This is used to set
694   ;; *COMPILE-FILE-PATHNAME*, and if absolute, is dumped in the
695   ;; debug-info.
696   (untruename nil :type (or pathname null))
697   ;; the file's write date (if relevant)
698   (write-date nil :type (or unsigned-byte null))
699   ;; the source path root number of the first form in this file (i.e.
700   ;; the total number of forms converted previously in this
701   ;; compilation)
702   (source-root 0 :type unsigned-byte)
703   ;; parallel vectors containing the forms read out of the file and
704   ;; the file positions that reading of each form started at (i.e. the
705   ;; end of the previous form)
706   (forms (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t))
707   (positions (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t)))
708
709 ;;; The SOURCE-INFO structure provides a handle on all the source
710 ;;; information for an entire compilation.
711 (def!struct (source-info
712              #-no-ansi-print-object
713              (:print-object (lambda (s stream)
714                               (print-unreadable-object (s stream :type t))))
715              (:copier nil))
716   ;; the UT that compilation started at
717   (start-time (get-universal-time) :type unsigned-byte)
718   ;; the FILE-INFO structure for this compilation
719   (file-info nil :type (or file-info null))
720   ;; the stream that we are using to read the FILE-INFO, or NIL if
721   ;; no stream has been opened yet
722   (stream nil :type (or stream null)))
723
724 ;;; Given a pathname, return a SOURCE-INFO structure.
725 (defun make-file-source-info (file)
726   (let ((file-info (make-file-info :name (truename file)
727                                    :untruename file
728                                    :write-date (file-write-date file))))
729
730     (make-source-info :file-info file-info)))
731
732 ;;; Return a SOURCE-INFO to describe the incremental compilation of FORM. 
733 (defun make-lisp-source-info (form)
734   (make-source-info :start-time (get-universal-time)
735                     :file-info (make-file-info :name :lisp
736                                                :forms (vector form)
737                                                :positions '#(0))))
738
739 ;;; Return a SOURCE-INFO which will read from STREAM.
740 (defun make-stream-source-info (stream)
741   (let ((file-info (make-file-info :name :stream)))
742     (make-source-info :file-info file-info
743                       :stream stream)))
744
745 ;;; Return a form read from STREAM; or for EOF use the trick,
746 ;;; popularized by Kent Pitman, of returning STREAM itself. If an
747 ;;; error happens, then convert it to standard abort-the-compilation
748 ;;; error condition (possibly recording some extra location
749 ;;; information).
750 (defun read-for-compile-file (stream position)
751   (handler-case (read stream nil stream)
752     (reader-error (condition)
753      (error 'input-error-in-compile-file
754             :condition condition
755             ;; We don't need to supply :POSITION here because
756             ;; READER-ERRORs already know their position in the file.
757             ))
758     ;; ANSI, in its wisdom, says that READ should return END-OF-FILE
759     ;; (and that this is not a READER-ERROR) when it encounters end of
760     ;; file in the middle of something it's trying to read.
761     (end-of-file (condition)
762      (error 'input-error-in-compile-file
763             :condition condition
764             ;; We need to supply :POSITION here because the END-OF-FILE
765             ;; condition doesn't carry the position that the user
766             ;; probably cares about, where the failed READ began.
767             :position position))))
768
769 ;;; If STREAM is present, return it, otherwise open a stream to the
770 ;;; current file. There must be a current file.
771 ;;;
772 ;;; FIXME: This is probably an unnecessarily roundabout way to do
773 ;;; things now that we process a single file in COMPILE-FILE (unlike
774 ;;; the old CMU CL code, which accepted multiple files). Also, the old
775 ;;; comment said
776 ;;;   When we open a new file, we also reset *PACKAGE* and policy.
777 ;;;   This gives the effect of rebinding around each file.
778 ;;; which doesn't seem to be true now. Check to make sure that if
779 ;;; such rebinding is necessary, it's still done somewhere.
780 (defun get-source-stream (info)
781   (declare (type source-info info))
782   (or (source-info-stream info)
783       (let* ((file-info (source-info-file-info info))
784              (name (file-info-name file-info)))
785         (setf sb!xc:*compile-file-truename* name
786               sb!xc:*compile-file-pathname* (file-info-untruename file-info)
787               (source-info-stream info) (open name :direction :input)))))
788
789 ;;; Close the stream in INFO if it is open.
790 (defun close-source-info (info)
791   (declare (type source-info info))
792   (let ((stream (source-info-stream info)))
793     (when stream (close stream)))
794   (setf (source-info-stream info) nil)
795   (values))
796
797 ;;; Read and compile the source file.
798 (defun sub-sub-compile-file (info)
799   (let* ((file-info (source-info-file-info info))
800          (stream (get-source-stream info)))
801     (loop
802      (let* ((pos (file-position stream))
803             (form (read-for-compile-file stream pos)))
804        (if (eq form stream) ; i.e., if EOF
805            (return)
806            (let* ((forms (file-info-forms file-info))
807                   (current-idx (+ (fill-pointer forms)
808                                   (file-info-source-root file-info))))
809              (vector-push-extend form forms)
810              (vector-push-extend pos (file-info-positions file-info))
811              (find-source-paths form current-idx)
812              (process-toplevel-form form
813                                     `(original-source-start 0 ,current-idx)
814                                     nil)))))))
815
816 ;;; Return the INDEX'th source form read from INFO and the position
817 ;;; where it was read.
818 (defun find-source-root (index info)
819   (declare (type index index) (type source-info info))
820   (let ((file-info (source-info-file-info info)))
821     (values (aref (file-info-forms file-info) index)
822             (aref (file-info-positions file-info) index))))
823 \f
824 ;;;; processing of top level forms
825
826 ;;; This is called by top level form processing when we are ready to
827 ;;; actually compile something. If *BLOCK-COMPILE* is T, then we still
828 ;;; convert the form, but delay compilation, pushing the result on
829 ;;; *TOPLEVEL-LAMBDAS* instead.
830 (defun convert-and-maybe-compile (form path)
831   (declare (list path))
832   (let* ((*lexenv* (make-lexenv :policy *policy*
833                                 :handled-conditions *handled-conditions*
834                                 :disabled-package-locks *disabled-package-locks*))
835          (tll (ir1-toplevel form path nil)))
836     (cond ((eq *block-compile* t) (push tll *toplevel-lambdas*))
837           (t (compile-toplevel (list tll) nil)))))
838
839 ;;; Macroexpand FORM in the current environment with an error handler.
840 ;;; We only expand one level, so that we retain all the intervening
841 ;;; forms in the source path.
842 (defun preprocessor-macroexpand-1 (form)
843   (handler-case (sb!xc:macroexpand-1 form *lexenv*)
844     (error (condition)
845       (compiler-error "(during macroexpansion of ~A)~%~A"
846                       (let ((*print-level* 1)
847                             (*print-length* 2))
848                         (format nil "~S" form))
849                       condition))))
850
851 ;;; Process a PROGN-like portion of a top level form. FORMS is a list of
852 ;;; the forms, and PATH is the source path of the FORM they came out of.
853 ;;; COMPILE-TIME-TOO is as in ANSI "3.2.3.1 Processing of Top Level Forms".
854 (defun process-toplevel-progn (forms path compile-time-too)
855   (declare (list forms) (list path))
856   (dolist (form forms)
857     (process-toplevel-form form path compile-time-too)))
858
859 ;;; Process a top level use of LOCALLY, or anything else (e.g.
860 ;;; MACROLET) at top level which has declarations and ordinary forms.
861 ;;; We parse declarations and then recursively process the body.
862 (defun process-toplevel-locally (body path compile-time-too &key vars funs)
863   (declare (list path))
864   (multiple-value-bind (forms decls)
865       (parse-body body :doc-string-allowed nil :toplevel t)
866     (let* ((*lexenv* (process-decls decls vars funs))
867            ;; FIXME: VALUES declaration
868            ;;
869            ;; Binding *POLICY* is pretty much of a hack, since it
870            ;; causes LOCALLY to "capture" enclosed proclamations. It
871            ;; is necessary because CONVERT-AND-MAYBE-COMPILE uses the
872            ;; value of *POLICY* as the policy. The need for this hack
873            ;; is due to the quirk that there is no way to represent in
874            ;; a POLICY that an optimize quality came from the default.
875            ;;
876            ;; FIXME: Ideally, something should be done so that DECLAIM
877            ;; inside LOCALLY works OK. Failing that, at least we could
878            ;; issue a warning instead of silently screwing up.
879            (*policy* (lexenv-policy *lexenv*))
880            ;; This is probably also a hack
881            (*handled-conditions* (lexenv-handled-conditions *lexenv*))
882            ;; ditto
883            (*disabled-package-locks* (lexenv-disabled-package-locks *lexenv*)))
884       (process-toplevel-progn forms path compile-time-too))))
885
886 ;;; Parse an EVAL-WHEN situations list, returning three flags,
887 ;;; (VALUES COMPILE-TOPLEVEL LOAD-TOPLEVEL EXECUTE), indicating
888 ;;; the types of situations present in the list.
889 (defun parse-eval-when-situations (situations)
890   (when (or (not (listp situations))
891             (set-difference situations
892                             '(:compile-toplevel
893                               compile
894                               :load-toplevel
895                               load
896                               :execute
897                               eval)))
898     (compiler-error "bad EVAL-WHEN situation list: ~S" situations))
899   (let ((deprecated-names (intersection situations '(compile load eval))))
900     (when deprecated-names
901       (style-warn "using deprecated EVAL-WHEN situation names~{ ~S~}"
902                   deprecated-names)))
903   (values (intersection '(:compile-toplevel compile)
904                         situations)
905           (intersection '(:load-toplevel load) situations)
906           (intersection '(:execute eval) situations)))
907
908
909 ;;; utilities for extracting COMPONENTs of FUNCTIONALs
910 (defun functional-components (f)
911   (declare (type functional f))
912   (etypecase f
913     (clambda (list (lambda-component f)))
914     (optional-dispatch (let ((result nil))
915                          (flet ((maybe-frob (maybe-clambda)
916                                   (when (and maybe-clambda
917                                              (promise-ready-p maybe-clambda))
918                                     (pushnew (lambda-component
919                                               (force maybe-clambda))
920                                              result))))
921                            (map nil #'maybe-frob (optional-dispatch-entry-points f))
922                            (maybe-frob (optional-dispatch-more-entry f))
923                            (maybe-frob (optional-dispatch-main-entry f)))
924                          result))))
925
926 (defun make-functional-from-toplevel-lambda (definition
927                                              &key
928                                              name
929                                              (path
930                                               ;; I'd thought NIL should
931                                               ;; work, but it doesn't.
932                                               ;; -- WHN 2001-09-20
933                                               (missing-arg)))
934   (let* ((*current-path* path)
935          (component (make-empty-component))
936          (*current-component* component))
937     (setf (component-name component)
938           (debug-namify "~S initial component" name))
939     (setf (component-kind component) :initial)
940     (let* ((locall-fun (let ((*allow-instrumenting* t))
941                          (ir1-convert-lambdalike
942                           definition
943                           :debug-name (debug-namify "top level local call "
944                                                     name))))
945            (fun (ir1-convert-lambda (make-xep-lambda-expression locall-fun)
946                                     :source-name (or name '.anonymous.)
947                                     :debug-name (unless name
948                                                   "top level form"))))
949       (when name
950         (assert-global-function-definition-type name locall-fun))
951       (setf (functional-entry-fun fun) locall-fun
952             (functional-kind fun) :external
953             (functional-has-external-references-p fun) t)
954       fun)))
955
956 ;;; Compile LAMBDA-EXPRESSION into *COMPILE-OBJECT*, returning a
957 ;;; description of the result.
958 ;;;   * If *COMPILE-OBJECT* is a CORE-OBJECT, then write the function
959 ;;;     into core and return the compiled FUNCTION value.
960 ;;;   * If *COMPILE-OBJECT* is a fasl file, then write the function
961 ;;;     into the fasl file and return a dump handle.
962 ;;;
963 ;;; If NAME is provided, then we try to use it as the name of the
964 ;;; function for debugging/diagnostic information.
965 (defun %compile (lambda-expression
966                  *compile-object*
967                  &key
968                  name
969                  (path
970                   ;; This magical idiom seems to be the appropriate
971                   ;; path for compiling standalone LAMBDAs, judging
972                   ;; from the CMU CL code and experiment, so it's a
973                   ;; nice default for things where we don't have a
974                   ;; real source path (as in e.g. inside CL:COMPILE).
975                   '(original-source-start 0 0)))
976   (when name
977     (legal-fun-name-or-type-error name))
978   (let* (
979          (*lexenv* (make-lexenv :policy *policy*
980                                 :handled-conditions *handled-conditions*
981                                 :disabled-package-locks *disabled-package-locks*))
982          (fun (make-functional-from-toplevel-lambda lambda-expression
983                                                     :name name
984                                                     :path path)))
985
986     ;; FIXME: The compile-it code from here on is sort of a
987     ;; twisted version of the code in COMPILE-TOPLEVEL. It'd be
988     ;; better to find a way to share the code there; or
989     ;; alternatively, to use this code to replace the code there.
990     ;; (The second alternative might be pretty easy if we used
991     ;; the :LOCALL-ONLY option to IR1-FOR-LAMBDA. Then maybe the
992     ;; whole FUNCTIONAL-KIND=:TOPLEVEL case could go away..)
993
994     (locall-analyze-clambdas-until-done (list fun))
995     
996     (multiple-value-bind (components-from-dfo top-components hairy-top)
997         (find-initial-dfo (list fun))
998
999       (let ((*all-components* (append components-from-dfo top-components)))
1000         ;; FIXME: This is more monkey see monkey do based on CMU CL
1001         ;; code. If anyone figures out why to only prescan HAIRY-TOP
1002         ;; and TOP-COMPONENTS here, instead of *ALL-COMPONENTS* or
1003         ;; some other combination of results from FIND-INITIAL-VALUES,
1004         ;; it'd be good to explain it.
1005         (mapc #'preallocate-physenvs-for-toplevelish-lambdas hairy-top)
1006         (mapc #'preallocate-physenvs-for-toplevelish-lambdas top-components)
1007         (dolist (component-from-dfo components-from-dfo)
1008           (compile-component component-from-dfo)
1009           (replace-toplevel-xeps component-from-dfo)))
1010
1011       (let ((entry-table (etypecase *compile-object*
1012                            (fasl-output (fasl-output-entry-table
1013                                          *compile-object*))
1014                            (core-object (core-object-entry-table
1015                                          *compile-object*)))))
1016         (multiple-value-bind (result found-p)
1017             (gethash (leaf-info fun) entry-table)
1018           (aver found-p)
1019           (prog1 
1020               result
1021             ;; KLUDGE: This code duplicates some other code in this
1022             ;; file. In the great reorganzation, the flow of program
1023             ;; logic changed from the original CMUCL model, and that
1024             ;; path (as of sbcl-0.7.5 in SUB-COMPILE-FILE) was no
1025             ;; longer followed for CORE-OBJECTS, leading to BUG
1026             ;; 156. This place is transparently not the right one for
1027             ;; this code, but I don't have a clear enough overview of
1028             ;; the compiler to know how to rearrange it all so that
1029             ;; this operation fits in nicely, and it was blocking
1030             ;; reimplementation of (DECLAIM (INLINE FOO)) (MACROLET
1031             ;; ((..)) (DEFUN FOO ...))
1032             ;;
1033             ;; FIXME: This KLUDGE doesn't solve all the problem in an
1034             ;; ideal way, as (1) definitions typed in at the REPL
1035             ;; without an INLINE declaration will give a NULL
1036             ;; FUNCTION-LAMBDA-EXPRESSION (allowable, but not ideal)
1037             ;; and (2) INLINE declarations will yield a
1038             ;; FUNCTION-LAMBDA-EXPRESSION headed by
1039             ;; SB-C:LAMBDA-WITH-LEXENV, even for null LEXENV.  -- CSR,
1040             ;; 2002-07-02
1041             ;;
1042             ;; (2) is probably fairly easy to fix -- it is, after all,
1043             ;; a matter of list manipulation (or possibly of teaching
1044             ;; CL:FUNCTION about SB-C:LAMBDA-WITH-LEXENV).  (1) is
1045             ;; significantly harder, as the association between
1046             ;; function object and source is a tricky one.
1047             ;;
1048             ;; FUNCTION-LAMBDA-EXPRESSION "works" (i.e. returns a
1049             ;; non-NULL list) when the function in question has been
1050             ;; compiled by (COMPILE <x> '(LAMBDA ...)); it does not
1051             ;; work when it has been compiled as part of the top-level
1052             ;; EVAL strategy of compiling everything inside (LAMBDA ()
1053             ;; ...).  -- CSR, 2002-11-02
1054             (when (core-object-p *compile-object*)
1055               (fix-core-source-info *source-info* *compile-object* result))
1056
1057             (mapc #'clear-ir1-info components-from-dfo)
1058             (clear-stuff)))))))
1059
1060 (defun process-toplevel-cold-fset (name lambda-expression path)
1061   (unless (producing-fasl-file)
1062     (error "can't COLD-FSET except in a fasl file"))
1063   (legal-fun-name-or-type-error name)
1064   (fasl-dump-cold-fset name
1065                        (%compile lambda-expression
1066                                  *compile-object*
1067                                  :name name
1068                                  :path path)
1069                        *compile-object*)
1070   (values))
1071
1072 ;;; Process a top level FORM with the specified source PATH.
1073 ;;;  * If this is a magic top level form, then do stuff.
1074 ;;;  * If this is a macro, then expand it.
1075 ;;;  * Otherwise, just compile it.
1076 ;;;
1077 ;;; COMPILE-TIME-TOO is as defined in ANSI
1078 ;;; "3.2.3.1 Processing of Top Level Forms".
1079 (defun process-toplevel-form (form path compile-time-too)
1080
1081   (declare (list path))
1082
1083   (catch 'process-toplevel-form-error-abort
1084     (let* ((path (or (gethash form *source-paths*) (cons form path)))
1085            (*compiler-error-bailout*
1086             (lambda (&optional condition)
1087               (convert-and-maybe-compile
1088                (make-compiler-error-form condition form)
1089                path)
1090               (throw 'process-toplevel-form-error-abort nil))))
1091
1092       (flet ((default-processor (form)
1093                ;; When we're cross-compiling, consider: what should we
1094                ;; do when we hit e.g.
1095                ;;   (EVAL-WHEN (:COMPILE-TOPLEVEL)
1096                ;;     (DEFUN FOO (X) (+ 7 X)))?
1097                ;; DEFUN has a macro definition in the cross-compiler,
1098                ;; and a different macro definition in the target
1099                ;; compiler. The only sensible thing is to use the
1100                ;; target compiler's macro definition, since the
1101                ;; cross-compiler's macro is in general into target
1102                ;; functions which can't meaningfully be executed at
1103                ;; cross-compilation time. So make sure we do the EVAL
1104                ;; here, before we macroexpand.
1105                ;;
1106                ;; Then things get even dicier with something like
1107                ;;   (DEFCONSTANT-EQX SB!XC:LAMBDA-LIST-KEYWORDS ..)
1108                ;; where we have to make sure that we don't uncross
1109                ;; the SB!XC: prefix before we do EVAL, because otherwise
1110                ;; we'd be trying to redefine the cross-compilation host's
1111                ;; constants.
1112                ;;
1113                ;; (Isn't it fun to cross-compile Common Lisp?:-)
1114                #+sb-xc-host
1115                (progn
1116                  (when compile-time-too
1117                    (eval form)) ; letting xc host EVAL do its own macroexpansion
1118                  (let* (;; (We uncross the operator name because things
1119                         ;; like SB!XC:DEFCONSTANT and SB!XC:DEFTYPE
1120                         ;; should be equivalent to their CL: counterparts
1121                         ;; when being compiled as target code. We leave
1122                         ;; the rest of the form uncrossed because macros
1123                         ;; might yet expand into EVAL-WHEN stuff, and
1124                         ;; things inside EVAL-WHEN can't be uncrossed
1125                         ;; until after we've EVALed them in the
1126                         ;; cross-compilation host.)
1127                         (slightly-uncrossed (cons (uncross (first form))
1128                                                   (rest form)))
1129                         (expanded (preprocessor-macroexpand-1
1130                                    slightly-uncrossed)))
1131                    (if (eq expanded slightly-uncrossed)
1132                        ;; (Now that we're no longer processing toplevel
1133                        ;; forms, and hence no longer need to worry about
1134                        ;; EVAL-WHEN, we can uncross everything.)
1135                        (convert-and-maybe-compile expanded path)
1136                        ;; (We have to demote COMPILE-TIME-TOO to NIL
1137                        ;; here, no matter what it was before, since
1138                        ;; otherwise we'd tend to EVAL subforms more than
1139                        ;; once, because of WHEN COMPILE-TIME-TOO form
1140                        ;; above.)
1141                        (process-toplevel-form expanded path nil))))
1142                ;; When we're not cross-compiling, we only need to
1143                ;; macroexpand once, so we can follow the 1-thru-6
1144                ;; sequence of steps in ANSI's "3.2.3.1 Processing of
1145                ;; Top Level Forms".
1146                #-sb-xc-host
1147                (let ((expanded (preprocessor-macroexpand-1 form)))
1148                  (cond ((eq expanded form)
1149                         (when compile-time-too
1150                           (eval-in-lexenv form *lexenv*))
1151                         (convert-and-maybe-compile form path))
1152                        (t
1153                         (process-toplevel-form expanded
1154                                                path
1155                                                compile-time-too))))))
1156         (if (atom form)
1157             #+sb-xc-host
1158             ;; (There are no xc EVAL-WHEN issues in the ATOM case until
1159             ;; (1) SBCL gets smart enough to handle global
1160             ;; DEFINE-SYMBOL-MACRO or SYMBOL-MACROLET and (2) SBCL
1161             ;; implementors start using symbol macros in a way which
1162             ;; interacts with SB-XC/CL distinction.)
1163             (convert-and-maybe-compile form path)
1164             #-sb-xc-host
1165             (default-processor form)
1166             (flet ((need-at-least-one-arg (form)
1167                      (unless (cdr form)
1168                        (compiler-error "~S form is too short: ~S"
1169                                        (car form)
1170                                        form))))
1171               (case (car form)
1172                 ;; In the cross-compiler, top level COLD-FSET arranges
1173                 ;; for static linking at cold init time.
1174                 #+sb-xc-host
1175                 ((cold-fset)
1176                  (aver (not compile-time-too))
1177                  (destructuring-bind (cold-fset fun-name lambda-expression) form
1178                    (declare (ignore cold-fset))
1179                    (process-toplevel-cold-fset fun-name
1180                                                lambda-expression
1181                                                path)))
1182                 ((eval-when macrolet symbol-macrolet);things w/ 1 arg before body
1183                  (need-at-least-one-arg form)
1184                  (destructuring-bind (special-operator magic &rest body) form
1185                    (ecase special-operator
1186                      ((eval-when)
1187                       ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1188                       ;; "3.2.3.1 Processing of Top Level Forms".
1189                       (multiple-value-bind (ct lt e)
1190                           (parse-eval-when-situations magic)
1191                         (let ((new-compile-time-too (or ct
1192                                                         (and compile-time-too
1193                                                              e))))
1194                           (cond (lt (process-toplevel-progn
1195                                      body path new-compile-time-too))
1196                                 (new-compile-time-too (eval-in-lexenv
1197                                                        `(progn ,@body)
1198                                                        *lexenv*))))))
1199                      ((macrolet)
1200                       (funcall-in-macrolet-lexenv
1201                        magic
1202                        (lambda (&key funs prepend)
1203                          (declare (ignore funs))
1204                          (aver (null prepend))
1205                          (process-toplevel-locally body
1206                                                    path
1207                                                    compile-time-too))
1208                        :compile))
1209                      ((symbol-macrolet)
1210                       (funcall-in-symbol-macrolet-lexenv
1211                        magic
1212                        (lambda (&key vars prepend)
1213                          (aver (null prepend))
1214                          (process-toplevel-locally body
1215                                                    path
1216                                                    compile-time-too
1217                                                    :vars vars))
1218                        :compile)))))
1219                 ((locally)
1220                  (process-toplevel-locally (rest form) path compile-time-too))
1221                 ((progn)
1222                  (process-toplevel-progn (rest form) path compile-time-too))
1223                 (t (default-processor form))))))))
1224
1225   (values))
1226 \f
1227 ;;;; load time value support
1228 ;;;;
1229 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1230
1231 ;;; Return T if we are currently producing a fasl file and hence
1232 ;;; constants need to be dumped carefully.
1233 (defun producing-fasl-file ()
1234   (fasl-output-p *compile-object*))
1235
1236 ;;; Compile FORM and arrange for it to be called at load-time. Return
1237 ;;; the dumper handle and our best guess at the type of the object.
1238 (defun compile-load-time-value (form)
1239   (let ((lambda (compile-load-time-stuff form t)))
1240     (values
1241      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1242      (let ((type (leaf-type lambda)))
1243        (if (fun-type-p type)
1244            (single-value-type (fun-type-returns type))
1245            *wild-type*)))))
1246
1247 ;;; Compile the FORMS and arrange for them to be called (for effect,
1248 ;;; not value) at load time.
1249 (defun compile-make-load-form-init-forms (forms)
1250   (let ((lambda (compile-load-time-stuff `(progn ,@forms) nil)))
1251     (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1252
1253 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1254 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1255 (defun compile-load-time-stuff (form for-value)
1256   (with-ir1-namespace
1257    (let* ((*lexenv* (make-null-lexenv))
1258           (lambda (ir1-toplevel form *current-path* for-value)))
1259      (compile-toplevel (list lambda) t)
1260      lambda)))
1261
1262 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1263 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1264 ;;; don't try to combine this component with anything else and frob
1265 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1266 ;;; compiling, because it was merged with a run-time component.
1267 (defun compile-load-time-value-lambda (lambdas)
1268   (aver (null (cdr lambdas)))
1269   (let* ((lambda (car lambdas))
1270          (component (lambda-component lambda)))
1271     (when (eql (component-kind component) :toplevel)
1272       (setf (component-name component) (leaf-debug-name lambda))
1273       (compile-component component)
1274       (clear-ir1-info component))))
1275 \f
1276 ;;;; COMPILE-FILE
1277
1278 (defun object-call-toplevel-lambda (tll)
1279   (declare (type functional tll))
1280   (let ((object *compile-object*))
1281     (etypecase object
1282       (fasl-output (fasl-dump-toplevel-lambda-call tll object))
1283       (core-object (core-call-toplevel-lambda      tll object))
1284       (null))))
1285
1286 ;;; Smash LAMBDAS into a single component, compile it, and arrange for
1287 ;;; the resulting function to be called.
1288 (defun sub-compile-toplevel-lambdas (lambdas)
1289   (declare (list lambdas))
1290   (when lambdas
1291     (multiple-value-bind (component tll) (merge-toplevel-lambdas lambdas)
1292       (compile-component component)
1293       (clear-ir1-info component)
1294       (object-call-toplevel-lambda tll)))
1295   (values))
1296
1297 ;;; Compile top level code and call the top level lambdas. We pick off
1298 ;;; top level lambdas in non-top-level components here, calling
1299 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1300 (defun compile-toplevel-lambdas (lambdas)
1301   (declare (list lambdas))
1302   (let ((len (length lambdas)))
1303     (flet ((loser (start)
1304              (or (position-if (lambda (x)
1305                                 (not (eq (component-kind
1306                                           (node-component (lambda-bind x)))
1307                                          :toplevel)))
1308                               lambdas
1309                               ;; this used to read ":start start", but
1310                               ;; start can be greater than len, which
1311                               ;; is an error according to ANSI - CSR,
1312                               ;; 2002-04-25
1313                               :start (min start len))
1314                  len)))
1315       (do* ((start 0 (1+ loser))
1316             (loser (loser start) (loser start)))
1317            ((>= start len))
1318         (sub-compile-toplevel-lambdas (subseq lambdas start loser))
1319         (unless (= loser len)
1320           (object-call-toplevel-lambda (elt lambdas loser))))))
1321   (values))
1322
1323 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1324 ;;; object file. 
1325 ;;;
1326 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1327 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1328 (defun compile-toplevel (lambdas load-time-value-p)
1329   (declare (list lambdas))
1330
1331   (maybe-mumble "locall ")
1332   (locall-analyze-clambdas-until-done lambdas)
1333
1334   (maybe-mumble "IDFO ")
1335   (multiple-value-bind (components top-components hairy-top)
1336       (find-initial-dfo lambdas)
1337     (let ((*all-components* (append components top-components)))
1338       (when *check-consistency*
1339         (maybe-mumble "[check]~%")
1340         (check-ir1-consistency *all-components*))
1341
1342       (dolist (component (append hairy-top top-components))
1343         (pre-physenv-analyze-toplevel component))
1344
1345       (dolist (component components)
1346         (compile-component component)
1347         (replace-toplevel-xeps component))
1348         
1349       (when *check-consistency*
1350         (maybe-mumble "[check]~%")
1351         (check-ir1-consistency *all-components*))
1352         
1353       (if load-time-value-p
1354           (compile-load-time-value-lambda lambdas)
1355           (compile-toplevel-lambdas lambdas))
1356
1357       (mapc #'clear-ir1-info components)
1358       (clear-stuff)))
1359   (values))
1360
1361 ;;; Actually compile any stuff that has been queued up for block
1362 ;;; compilation.
1363 (defun finish-block-compilation ()
1364   (when *block-compile*
1365     (when *toplevel-lambdas*
1366       (compile-toplevel (nreverse *toplevel-lambdas*) nil)
1367       (setq *toplevel-lambdas* ()))
1368     (setq *block-compile* nil)
1369     (setq *entry-points* nil)))
1370
1371 (defun handle-condition-p (condition)
1372   (let ((lexenv
1373          (etypecase *compiler-error-context*
1374            (node
1375             (node-lexenv *compiler-error-context*))
1376            (compiler-error-context
1377             (let ((lexenv (compiler-error-context-lexenv
1378                            *compiler-error-context*)))
1379               (aver lexenv)
1380               lexenv))
1381            (null *lexenv*))))
1382     (let ((muffles (lexenv-handled-conditions lexenv)))
1383       (if (null muffles) ; common case
1384           nil
1385           (dolist (muffle muffles nil)
1386             (destructuring-bind (typespec . restart-name) muffle
1387               (when (and (typep condition typespec)
1388                          (find-restart restart-name condition))
1389                 (return t))))))))
1390
1391 (defun handle-condition-handler (condition)
1392   (let ((lexenv
1393          (etypecase *compiler-error-context*
1394            (node
1395             (node-lexenv *compiler-error-context*))
1396            (compiler-error-context
1397             (let ((lexenv (compiler-error-context-lexenv
1398                            *compiler-error-context*)))
1399               (aver lexenv)
1400               lexenv))
1401            (null *lexenv*))))
1402     (let ((muffles (lexenv-handled-conditions lexenv)))
1403       (aver muffles)
1404       (dolist (muffle muffles (bug "fell through"))
1405         (destructuring-bind (typespec . restart-name) muffle
1406           (when (typep condition typespec)
1407             (awhen (find-restart restart-name condition)
1408               (invoke-restart it))))))))
1409
1410 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1411 ;;; Return (VALUES NIL WARNINGS-P FAILURE-P).
1412 (defun sub-compile-file (info)
1413   (declare (type source-info info))
1414   (let ((*package* (sane-package))
1415         (*readtable* *readtable*)
1416         (sb!xc:*compile-file-pathname* nil) ; really bound in
1417         (sb!xc:*compile-file-truename* nil) ; SUB-SUB-COMPILE-FILE
1418
1419         (*policy* *policy*)
1420         (*handled-conditions* *handled-conditions*)
1421         (*disabled-package-locks* *disabled-package-locks*)
1422         (*lexenv* (make-null-lexenv))
1423         (*block-compile* *block-compile-arg*)
1424         (*source-info* info)
1425         (*toplevel-lambdas* ())
1426         (*fun-names-in-this-file* ())
1427         (*allow-instrumenting* nil)
1428         (*compiler-error-bailout*
1429          (lambda ()
1430            (compiler-mumble "~2&; fatal error, aborting compilation~%")
1431            (return-from sub-compile-file (values nil t t))))
1432         (*current-path* nil)
1433         (*last-source-context* nil)
1434         (*last-original-source* nil)
1435         (*last-source-form* nil)
1436         (*last-format-string* nil)
1437         (*last-format-args* nil)
1438         (*last-message-count* 0)
1439         ;; FIXME: Do we need this rebinding here? It's a literal
1440         ;; translation of the old CMU CL rebinding to
1441         ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
1442         ;; and it's not obvious whether the rebinding to itself is
1443         ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
1444         (*info-environment* *info-environment*)
1445         (*gensym-counter* 0))
1446     (handler-case
1447         (handler-bind (((satisfies handle-condition-p) #'handle-condition-handler))
1448           (with-compilation-values
1449               (sb!xc:with-compilation-unit ()
1450                 (clear-stuff)
1451                 
1452                 (sub-sub-compile-file info)
1453                 
1454                 (finish-block-compilation)
1455                 (let ((object *compile-object*))
1456                   (etypecase object
1457                     (fasl-output (fasl-dump-source-info info object))
1458                     (core-object (fix-core-source-info info object))
1459                     (null)))
1460                 nil)))
1461       ;; Some errors are sufficiently bewildering that we just fail
1462       ;; immediately, without trying to recover and compile more of
1463       ;; the input file.
1464       (fatal-compiler-error (condition)
1465        (signal condition)
1466        (format *error-output*
1467                "~@<compilation aborted because of fatal error: ~2I~_~A~:>"
1468                condition)
1469        (values nil t t)))))
1470
1471 ;;; Return a pathname for the named file. The file must exist.
1472 (defun verify-source-file (pathname-designator)
1473   (let* ((pathname (pathname pathname-designator))
1474          (default-host (make-pathname :host (pathname-host pathname))))
1475     (flet ((try-with-type (path type error-p)
1476              (let ((new (merge-pathnames
1477                          path (make-pathname :type type
1478                                              :defaults default-host))))
1479                (if (probe-file new)
1480                    new
1481                    (and error-p (truename new))))))
1482       (cond ((typep pathname 'logical-pathname)
1483              (try-with-type pathname "LISP" t))
1484             ((probe-file pathname) pathname)
1485             ((try-with-type pathname "lisp"  nil))
1486             ((try-with-type pathname "lisp"  t))))))
1487
1488 (defun elapsed-time-to-string (tsec)
1489   (multiple-value-bind (tmin sec) (truncate tsec 60)
1490     (multiple-value-bind (thr min) (truncate tmin 60)
1491       (format nil "~D:~2,'0D:~2,'0D" thr min sec))))
1492
1493 ;;; Print some junk at the beginning and end of compilation.
1494 (defun start-error-output (source-info)
1495   (declare (type source-info source-info))
1496   (let ((file-info (source-info-file-info source-info)))
1497     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1498                      (namestring (file-info-name file-info))
1499                      (sb!int:format-universal-time nil
1500                                                    (file-info-write-date
1501                                                     file-info)
1502                                                    :style :government
1503                                                    :print-weekday nil
1504                                                    :print-timezone nil)))
1505   (values))
1506 (defun finish-error-output (source-info won)
1507   (declare (type source-info source-info))
1508   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1509                    won
1510                    (elapsed-time-to-string
1511                     (- (get-universal-time)
1512                        (source-info-start-time source-info))))
1513   (values))
1514
1515 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1516 ;;; out of the compile, then abort the writing of the output file, so
1517 ;;; that we don't overwrite it with known garbage.
1518 (defun sb!xc:compile-file
1519     (input-file
1520      &key
1521
1522      ;; ANSI options
1523      (output-file (cfp-output-file-default input-file))
1524      ;; FIXME: ANSI doesn't seem to say anything about
1525      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1526      ;; function..
1527      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1528      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1529      (external-format :default)
1530
1531      ;; extensions
1532      (trace-file nil) 
1533      ((:block-compile *block-compile-arg*) nil))
1534
1535   #!+sb-doc
1536   "Compile INPUT-FILE, producing a corresponding fasl file and returning
1537    its filename. Besides the ANSI &KEY arguments :OUTPUT-FILE, :VERBOSE,
1538    :PRINT, and :EXTERNAL-FORMAT,the following extensions are supported:
1539      :TRACE-FILE
1540         If given, internal data structures are dumped to the specified
1541         file, or if a value of T is given, to a file of *.trace type
1542         derived from the input file name.
1543    Also, as a workaround for vaguely-non-ANSI behavior, the :BLOCK-COMPILE
1544    argument is quasi-supported, to determine whether multiple
1545    functions are compiled together as a unit, resolving function
1546    references at compile time. NIL means that global function names
1547    are never resolved at compilation time. Currently NIL is the
1548    default behavior, because although section 3.2.2.3, \"Semantic
1549    Constraints\", of the ANSI spec allows this behavior under all
1550    circumstances, the compiler's runtime scales badly when it
1551    tries to do this for large files. If/when this performance
1552    problem is fixed, the block compilation default behavior will
1553    probably be made dependent on the SPEED and COMPILATION-SPEED
1554    optimization values, and the :BLOCK-COMPILE argument will probably
1555    become deprecated."
1556
1557   (unless (eq external-format :default)
1558     (error "Non-:DEFAULT EXTERNAL-FORMAT values are not supported."))
1559   (let* ((fasl-output nil)
1560          (output-file-name nil)
1561          (compile-won nil)
1562          (warnings-p nil)
1563          (failure-p t) ; T in case error keeps this from being set later
1564          (input-pathname (verify-source-file input-file))
1565          (source-info (make-file-source-info input-pathname))
1566          (*compiler-trace-output* nil)) ; might be modified below
1567
1568     (unwind-protect
1569         (progn
1570           (when output-file
1571             (setq output-file-name
1572                   (sb!xc:compile-file-pathname input-file
1573                                                :output-file output-file))
1574             (setq fasl-output
1575                   (open-fasl-output output-file-name
1576                                     (namestring input-pathname))))
1577           (when trace-file
1578             (let* ((default-trace-file-pathname
1579                      (make-pathname :type "trace" :defaults input-pathname))
1580                    (trace-file-pathname
1581                     (if (eql trace-file t)
1582                         default-trace-file-pathname
1583                         (merge-pathnames trace-file
1584                                          default-trace-file-pathname))))
1585               (setf *compiler-trace-output*
1586                     (open trace-file-pathname
1587                           :if-exists :supersede
1588                           :direction :output))))
1589
1590           (when sb!xc:*compile-verbose*
1591             (start-error-output source-info))
1592           (let ((*compile-object* fasl-output)
1593                 dummy)
1594             (multiple-value-setq (dummy warnings-p failure-p)
1595               (sub-compile-file source-info)))
1596           (setq compile-won t))
1597
1598       (close-source-info source-info)
1599
1600       (when fasl-output
1601         (close-fasl-output fasl-output (not compile-won))
1602         (setq output-file-name
1603               (pathname (fasl-output-stream fasl-output)))
1604         (when (and compile-won sb!xc:*compile-verbose*)
1605           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1606
1607       (when sb!xc:*compile-verbose*
1608         (finish-error-output source-info compile-won))
1609
1610       (when *compiler-trace-output*
1611         (close *compiler-trace-output*)))
1612
1613     (values (if output-file
1614                 ;; Hack around filesystem race condition...
1615                 (or (probe-file output-file-name) output-file-name)
1616                 nil)
1617             warnings-p
1618             failure-p)))
1619 \f
1620 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1621 ;;; the OUTPUT-FILE argument
1622 ;;;
1623 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1624 ;;; that results from merging the INPUT-FILE with the value of
1625 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1626 ;;; default to the appropriate implementation-defined default type for
1627 ;;; compiled files.
1628 (defun cfp-output-file-default (input-file)
1629   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1630          (retyped (make-pathname :type *fasl-file-type* :defaults defaults)))
1631     retyped))
1632         
1633 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1634 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1635 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1636 ;;;   pathname, it is translated into a physical pathname as if by
1637 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1638 ;;; So I haven't really tried to make this precisely ANSI-compatible
1639 ;;; at the level of e.g. whether it returns logical pathname or a
1640 ;;; physical pathname. Patches to make it more correct are welcome.
1641 ;;; -- WHN 2000-12-09
1642 (defun sb!xc:compile-file-pathname (input-file
1643                                     &key
1644                                     (output-file (cfp-output-file-default
1645                                                   input-file))
1646                                     &allow-other-keys)
1647   #!+sb-doc
1648   "Return a pathname describing what file COMPILE-FILE would write to given
1649    these arguments."
1650   (merge-pathnames output-file (merge-pathnames input-file)))
1651 \f
1652 ;;;; MAKE-LOAD-FORM stuff
1653
1654 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1655 ;;; finds a constant structure, it invokes this to arrange for proper
1656 ;;; dumping. If it turns out that the constant has already been
1657 ;;; dumped, then we don't need to do anything.
1658 ;;;
1659 ;;; If the constant hasn't been dumped, then we check to see whether
1660 ;;; we are in the process of creating it. We detect this by
1661 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1662 ;;; the constants we are in the process of creating. Actually, each
1663 ;;; entry is a list of the constant and any init forms that need to be
1664 ;;; processed on behalf of that constant.
1665 ;;;
1666 ;;; It's not necessarily an error for this to happen. If we are
1667 ;;; processing the init form for some object that showed up *after*
1668 ;;; the original reference to this constant, then we just need to
1669 ;;; defer the processing of that init form. To detect this, we
1670 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1671 ;;; constants created since the last time we started processing an
1672 ;;; init form. If the constant passed to emit-make-load-form shows up
1673 ;;; in this list, then there is a circular chain through creation
1674 ;;; forms, which is an error.
1675 ;;;
1676 ;;; If there is some intervening init form, then we blow out of
1677 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1678 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1679 ;;; offending init form can be tacked onto the init forms for the
1680 ;;; circular object.
1681 ;;;
1682 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1683 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1684 ;;; whether the creation form is the magic value
1685 ;;; :SB-JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1686 ;;; dumper will eventually get its hands on the object and use the
1687 ;;; normal structure dumping noise on it.
1688 ;;;
1689 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1690 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1691 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1692 ;;; dumper to use that result instead whenever it sees this constant.
1693 ;;;
1694 ;;; Now we try to compile the init form. We bind
1695 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1696 ;;; form (and any init forms that were added because of circularity
1697 ;;; detection). If this works, great. If not, we add the init forms to
1698 ;;; the init forms for the object that caused the problems and let it
1699 ;;; deal with it.
1700 (defvar *constants-being-created* nil)
1701 (defvar *constants-created-since-last-init* nil)
1702 ;;; FIXME: Shouldn't these^ variables be unbound outside LET forms?
1703 (defun emit-make-load-form (constant)
1704   (aver (fasl-output-p *compile-object*))
1705   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1706               ;; KLUDGE: This special hack is because I was too lazy
1707               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1708               ;; function of LAYOUT returns nontrivial forms when
1709               ;; building the cross-compiler but :IGNORE-IT when
1710               ;; cross-compiling or running under the target Lisp. --
1711               ;; WHN 19990914
1712               #+sb-xc-host (typep constant 'layout))
1713     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1714       (when circular-ref
1715         (when (find constant *constants-created-since-last-init* :test #'eq)
1716           (throw constant t))
1717         (throw 'pending-init circular-ref)))
1718     (multiple-value-bind (creation-form init-form)
1719         (handler-case
1720             (sb!xc:make-load-form constant (make-null-lexenv))
1721           (error (condition)
1722             (compiler-error condition)))
1723       (case creation-form
1724         (:sb-just-dump-it-normally
1725          (fasl-validate-structure constant *compile-object*)
1726          t)
1727         (:ignore-it
1728          nil)
1729         (t
1730          (when (fasl-constant-already-dumped-p constant *compile-object*)
1731            (return-from emit-make-load-form nil))
1732          (let* ((name (let ((*print-level* 1) (*print-length* 2))
1733                         (with-output-to-string (stream)
1734                           (write constant :stream stream))))
1735                 (info (if init-form
1736                           (list constant name init-form)
1737                           (list constant))))
1738            (let ((*constants-being-created*
1739                   (cons info *constants-being-created*))
1740                  (*constants-created-since-last-init*
1741                   (cons constant *constants-created-since-last-init*)))
1742              (when
1743                  (catch constant
1744                    (fasl-note-handle-for-constant
1745                     constant
1746                     (compile-load-time-value
1747                      creation-form)
1748                     *compile-object*)
1749                    nil)
1750                (compiler-error "circular references in creation form for ~S"
1751                                constant)))
1752            (when (cdr info)
1753              (let* ((*constants-created-since-last-init* nil)
1754                     (circular-ref
1755                      (catch 'pending-init
1756                        (loop for (name form) on (cdr info) by #'cddr
1757                          collect name into names
1758                          collect form into forms
1759                          finally (compile-make-load-form-init-forms forms))
1760                        nil)))
1761                (when circular-ref
1762                  (setf (cdr circular-ref)
1763                        (append (cdr circular-ref) (cdr info))))))))))))
1764
1765 \f
1766 ;;;; Host compile time definitions
1767 #+sb-xc-host
1768 (defun compile-in-lexenv (name lambda lexenv)
1769   (declare (ignore lexenv))
1770   (compile name lambda))
1771
1772 #+sb-xc-host
1773 (defun eval-in-lexenv (form lexenv)
1774   (declare (ignore lexenv))
1775   (eval form))