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