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