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