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