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