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