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