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