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