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