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