1.0.20.4: Use a new set implementation for constraint propagation.
[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           (sb!thread:with-recursive-lock (*big-compiler-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-universal-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       (when name
1036         (assert-global-function-definition-type name locall-fun))
1037       (setf (functional-entry-fun fun) locall-fun
1038             (functional-kind fun) :external
1039             (functional-has-external-references-p locall-fun) t
1040             (functional-has-external-references-p fun) t)
1041       fun)))
1042
1043 ;;; Compile LAMBDA-EXPRESSION into *COMPILE-OBJECT*, returning a
1044 ;;; description of the result.
1045 ;;;   * If *COMPILE-OBJECT* is a CORE-OBJECT, then write the function
1046 ;;;     into core and return the compiled FUNCTION value.
1047 ;;;   * If *COMPILE-OBJECT* is a fasl file, then write the function
1048 ;;;     into the fasl file and return a dump handle.
1049 ;;;
1050 ;;; If NAME is provided, then we try to use it as the name of the
1051 ;;; function for debugging/diagnostic information.
1052 (defun %compile (lambda-expression
1053                  *compile-object*
1054                  &key
1055                  name
1056                  (path
1057                   ;; This magical idiom seems to be the appropriate
1058                   ;; path for compiling standalone LAMBDAs, judging
1059                   ;; from the CMU CL code and experiment, so it's a
1060                   ;; nice default for things where we don't have a
1061                   ;; real source path (as in e.g. inside CL:COMPILE).
1062                   '(original-source-start 0 0)))
1063   (when name
1064     (legal-fun-name-or-type-error name))
1065   (let* ((*lexenv* (make-lexenv
1066                     :policy *policy*
1067                     :handled-conditions *handled-conditions*
1068                     :disabled-package-locks *disabled-package-locks*))
1069          (*compiler-sset-counter* 0)
1070          (fun (make-functional-from-toplevel-lambda lambda-expression
1071                                                     :name name
1072                                                     :path path)))
1073
1074     ;; FIXME: The compile-it code from here on is sort of a
1075     ;; twisted version of the code in COMPILE-TOPLEVEL. It'd be
1076     ;; better to find a way to share the code there; or
1077     ;; alternatively, to use this code to replace the code there.
1078     ;; (The second alternative might be pretty easy if we used
1079     ;; the :LOCALL-ONLY option to IR1-FOR-LAMBDA. Then maybe the
1080     ;; whole FUNCTIONAL-KIND=:TOPLEVEL case could go away..)
1081
1082     (locall-analyze-clambdas-until-done (list fun))
1083
1084     (let ((components-from-dfo (find-initial-dfo (list fun))))
1085       (dolist (component-from-dfo components-from-dfo)
1086         (compile-component component-from-dfo)
1087         (replace-toplevel-xeps component-from-dfo))
1088
1089       (let ((entry-table (etypecase *compile-object*
1090                            (fasl-output (fasl-output-entry-table
1091                                          *compile-object*))
1092                            (core-object (core-object-entry-table
1093                                          *compile-object*)))))
1094         (multiple-value-bind (result found-p)
1095             (gethash (leaf-info fun) entry-table)
1096           (aver found-p)
1097           (prog1
1098               result
1099             ;; KLUDGE: This code duplicates some other code in this
1100             ;; file. In the great reorganzation, the flow of program
1101             ;; logic changed from the original CMUCL model, and that
1102             ;; path (as of sbcl-0.7.5 in SUB-COMPILE-FILE) was no
1103             ;; longer followed for CORE-OBJECTS, leading to BUG
1104             ;; 156. This place is transparently not the right one for
1105             ;; this code, but I don't have a clear enough overview of
1106             ;; the compiler to know how to rearrange it all so that
1107             ;; this operation fits in nicely, and it was blocking
1108             ;; reimplementation of (DECLAIM (INLINE FOO)) (MACROLET
1109             ;; ((..)) (DEFUN FOO ...))
1110             ;;
1111             ;; FIXME: This KLUDGE doesn't solve all the problem in an
1112             ;; ideal way, as (1) definitions typed in at the REPL
1113             ;; without an INLINE declaration will give a NULL
1114             ;; FUNCTION-LAMBDA-EXPRESSION (allowable, but not ideal)
1115             ;; and (2) INLINE declarations will yield a
1116             ;; FUNCTION-LAMBDA-EXPRESSION headed by
1117             ;; SB-C:LAMBDA-WITH-LEXENV, even for null LEXENV.  -- CSR,
1118             ;; 2002-07-02
1119             ;;
1120             ;; (2) is probably fairly easy to fix -- it is, after all,
1121             ;; a matter of list manipulation (or possibly of teaching
1122             ;; CL:FUNCTION about SB-C:LAMBDA-WITH-LEXENV).  (1) is
1123             ;; significantly harder, as the association between
1124             ;; function object and source is a tricky one.
1125             ;;
1126             ;; FUNCTION-LAMBDA-EXPRESSION "works" (i.e. returns a
1127             ;; non-NULL list) when the function in question has been
1128             ;; compiled by (COMPILE <x> '(LAMBDA ...)); it does not
1129             ;; work when it has been compiled as part of the top-level
1130             ;; EVAL strategy of compiling everything inside (LAMBDA ()
1131             ;; ...).  -- CSR, 2002-11-02
1132             (when (core-object-p *compile-object*)
1133               (fix-core-source-info *source-info* *compile-object* result))
1134
1135             (mapc #'clear-ir1-info components-from-dfo)
1136             (clear-stuff)))))))
1137
1138 (defun process-toplevel-cold-fset (name lambda-expression path)
1139   (unless (producing-fasl-file)
1140     (error "can't COLD-FSET except in a fasl file"))
1141   (legal-fun-name-or-type-error name)
1142   (fasl-dump-cold-fset name
1143                        (%compile lambda-expression
1144                                  *compile-object*
1145                                  :name name
1146                                  :path path)
1147                        *compile-object*)
1148   (values))
1149
1150 (defun note-top-level-form (form &optional finalp)
1151   (when *compile-print*
1152     (cond ((not *top-level-form-noted*)
1153            (let ((*print-length* 2)
1154                  (*print-level* 2)
1155                  (*print-pretty* nil))
1156              (with-compiler-io-syntax
1157                  (compiler-mumble "~&; ~:[compiling~;converting~] ~S"
1158                                   *block-compile* form)))
1159              form)
1160           ((and finalp
1161                 (eq :top-level-forms *compile-print*)
1162                 (neq form *top-level-form-noted*))
1163            (let ((*print-length* 1)
1164                  (*print-level* 1)
1165                  (*print-pretty* nil))
1166              (with-compiler-io-syntax
1167                  (compiler-mumble "~&; ... top level ~S" form)))
1168            form)
1169           (t
1170            *top-level-form-noted*))))
1171
1172 ;;; Process a top level FORM with the specified source PATH.
1173 ;;;  * If this is a magic top level form, then do stuff.
1174 ;;;  * If this is a macro, then expand it.
1175 ;;;  * Otherwise, just compile it.
1176 ;;;
1177 ;;; COMPILE-TIME-TOO is as defined in ANSI
1178 ;;; "3.2.3.1 Processing of Top Level Forms".
1179 (defun process-toplevel-form (form path compile-time-too)
1180   (declare (list path))
1181
1182   (catch 'process-toplevel-form-error-abort
1183     (let* ((path (or (get-source-path form) (cons form path)))
1184            (*compiler-error-bailout*
1185             (lambda (&optional condition)
1186               (convert-and-maybe-compile
1187                (make-compiler-error-form condition form)
1188                path)
1189               (throw 'process-toplevel-form-error-abort nil))))
1190
1191       (flet ((default-processor (form)
1192                (let ((*top-level-form-noted* (note-top-level-form form)))
1193                  ;; When we're cross-compiling, consider: what should we
1194                  ;; do when we hit e.g.
1195                  ;;   (EVAL-WHEN (:COMPILE-TOPLEVEL)
1196                  ;;     (DEFUN FOO (X) (+ 7 X)))?
1197                  ;; DEFUN has a macro definition in the cross-compiler,
1198                  ;; and a different macro definition in the target
1199                  ;; compiler. The only sensible thing is to use the
1200                  ;; target compiler's macro definition, since the
1201                  ;; cross-compiler's macro is in general into target
1202                  ;; functions which can't meaningfully be executed at
1203                  ;; cross-compilation time. So make sure we do the EVAL
1204                  ;; here, before we macroexpand.
1205                  ;;
1206                  ;; Then things get even dicier with something like
1207                  ;;   (DEFCONSTANT-EQX SB!XC:LAMBDA-LIST-KEYWORDS ..)
1208                  ;; where we have to make sure that we don't uncross
1209                  ;; the SB!XC: prefix before we do EVAL, because otherwise
1210                  ;; we'd be trying to redefine the cross-compilation host's
1211                  ;; constants.
1212                  ;;
1213                  ;; (Isn't it fun to cross-compile Common Lisp?:-)
1214                  #+sb-xc-host
1215                  (progn
1216                    (when compile-time-too
1217                      (eval form)) ; letting xc host EVAL do its own macroexpansion
1218                    (let* (;; (We uncross the operator name because things
1219                           ;; like SB!XC:DEFCONSTANT and SB!XC:DEFTYPE
1220                           ;; should be equivalent to their CL: counterparts
1221                           ;; when being compiled as target code. We leave
1222                           ;; the rest of the form uncrossed because macros
1223                           ;; might yet expand into EVAL-WHEN stuff, and
1224                           ;; things inside EVAL-WHEN can't be uncrossed
1225                           ;; until after we've EVALed them in the
1226                           ;; cross-compilation host.)
1227                           (slightly-uncrossed (cons (uncross (first form))
1228                                                     (rest form)))
1229                           (expanded (preprocessor-macroexpand-1
1230                                      slightly-uncrossed)))
1231                      (if (eq expanded slightly-uncrossed)
1232                          ;; (Now that we're no longer processing toplevel
1233                          ;; forms, and hence no longer need to worry about
1234                          ;; EVAL-WHEN, we can uncross everything.)
1235                          (convert-and-maybe-compile expanded path)
1236                          ;; (We have to demote COMPILE-TIME-TOO to NIL
1237                          ;; here, no matter what it was before, since
1238                          ;; otherwise we'd tend to EVAL subforms more than
1239                          ;; once, because of WHEN COMPILE-TIME-TOO form
1240                          ;; above.)
1241                          (process-toplevel-form expanded path nil))))
1242                  ;; When we're not cross-compiling, we only need to
1243                  ;; macroexpand once, so we can follow the 1-thru-6
1244                  ;; sequence of steps in ANSI's "3.2.3.1 Processing of
1245                  ;; Top Level Forms".
1246                  #-sb-xc-host
1247                  (let ((expanded
1248                         (let ((*current-path* path))
1249                           (preprocessor-macroexpand-1 form))))
1250                    (cond ((eq expanded form)
1251                           (when compile-time-too
1252                             (eval-in-lexenv form *lexenv*))
1253                           (convert-and-maybe-compile form path))
1254                          (t
1255                           (process-toplevel-form expanded
1256                                                  path
1257                                                  compile-time-too)))))))
1258         (if (atom form)
1259             #+sb-xc-host
1260             ;; (There are no xc EVAL-WHEN issues in the ATOM case until
1261             ;; (1) SBCL gets smart enough to handle global
1262             ;; DEFINE-SYMBOL-MACRO or SYMBOL-MACROLET and (2) SBCL
1263             ;; implementors start using symbol macros in a way which
1264             ;; interacts with SB-XC/CL distinction.)
1265             (convert-and-maybe-compile form path)
1266             #-sb-xc-host
1267             (default-processor form)
1268             (flet ((need-at-least-one-arg (form)
1269                      (unless (cdr form)
1270                        (compiler-error "~S form is too short: ~S"
1271                                        (car form)
1272                                        form))))
1273               (case (car form)
1274                 ;; In the cross-compiler, top level COLD-FSET arranges
1275                 ;; for static linking at cold init time.
1276                 #+sb-xc-host
1277                 ((cold-fset)
1278                  (aver (not compile-time-too))
1279                  (destructuring-bind (cold-fset fun-name lambda-expression) form
1280                    (declare (ignore cold-fset))
1281                    (process-toplevel-cold-fset fun-name
1282                                                lambda-expression
1283                                                path)))
1284                 ((eval-when macrolet symbol-macrolet);things w/ 1 arg before body
1285                  (need-at-least-one-arg form)
1286                  (destructuring-bind (special-operator magic &rest body) form
1287                    (ecase special-operator
1288                      ((eval-when)
1289                       ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1290                       ;; "3.2.3.1 Processing of Top Level Forms".
1291                       (multiple-value-bind (ct lt e)
1292                           (parse-eval-when-situations magic)
1293                         (let ((new-compile-time-too (or ct
1294                                                         (and compile-time-too
1295                                                              e))))
1296                           (cond (lt (process-toplevel-progn
1297                                      body path new-compile-time-too))
1298                                 (new-compile-time-too (eval-in-lexenv
1299                                                        `(progn ,@body)
1300                                                        *lexenv*))))))
1301                      ((macrolet)
1302                       (funcall-in-macrolet-lexenv
1303                        magic
1304                        (lambda (&key funs prepend)
1305                          (declare (ignore funs))
1306                          (aver (null prepend))
1307                          (process-toplevel-locally body
1308                                                    path
1309                                                    compile-time-too))
1310                        :compile))
1311                      ((symbol-macrolet)
1312                       (funcall-in-symbol-macrolet-lexenv
1313                        magic
1314                        (lambda (&key vars prepend)
1315                          (aver (null prepend))
1316                          (process-toplevel-locally body
1317                                                    path
1318                                                    compile-time-too
1319                                                    :vars vars))
1320                        :compile)))))
1321                 ((locally)
1322                  (process-toplevel-locally (rest form) path compile-time-too))
1323                 ((progn)
1324                  (process-toplevel-progn (rest form) path compile-time-too))
1325                 (t (default-processor form))))))))
1326
1327   (values))
1328 \f
1329 ;;;; load time value support
1330 ;;;;
1331 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1332
1333 ;;; Return T if we are currently producing a fasl file and hence
1334 ;;; constants need to be dumped carefully.
1335 (defun producing-fasl-file ()
1336   (fasl-output-p *compile-object*))
1337
1338 ;;; Compile FORM and arrange for it to be called at load-time. Return
1339 ;;; the dumper handle and our best guess at the type of the object.
1340 (defun compile-load-time-value (form)
1341   (let ((lambda (compile-load-time-stuff form t)))
1342     (values
1343      (fasl-dump-load-time-value-lambda lambda *compile-object*)
1344      (let ((type (leaf-type lambda)))
1345        (if (fun-type-p type)
1346            (single-value-type (fun-type-returns type))
1347            *wild-type*)))))
1348
1349 ;;; Compile the FORMS and arrange for them to be called (for effect,
1350 ;;; not value) at load time.
1351 (defun compile-make-load-form-init-forms (forms)
1352   (let ((lambda (compile-load-time-stuff `(progn ,@forms) nil)))
1353     (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1354
1355 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1356 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1357 (defun compile-load-time-stuff (form for-value)
1358   (with-ir1-namespace
1359    (let* ((*lexenv* (make-null-lexenv))
1360           (lambda (ir1-toplevel form *current-path* for-value nil)))
1361      (compile-toplevel (list lambda) t)
1362      lambda)))
1363
1364 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1365 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1366 ;;; don't try to combine this component with anything else and frob
1367 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1368 ;;; compiling, because it was merged with a run-time component.
1369 (defun compile-load-time-value-lambda (lambdas)
1370   (aver (null (cdr lambdas)))
1371   (let* ((lambda (car lambdas))
1372          (component (lambda-component lambda)))
1373     (when (eql (component-kind component) :toplevel)
1374       (setf (component-name component) (leaf-debug-name lambda))
1375       (compile-component component)
1376       (clear-ir1-info component))))
1377 \f
1378 ;;;; COMPILE-FILE
1379
1380 (defun object-call-toplevel-lambda (tll)
1381   (declare (type functional tll))
1382   (let ((object *compile-object*))
1383     (etypecase object
1384       (fasl-output (fasl-dump-toplevel-lambda-call tll object))
1385       (core-object (core-call-toplevel-lambda      tll object))
1386       (null))))
1387
1388 ;;; Smash LAMBDAS into a single component, compile it, and arrange for
1389 ;;; the resulting function to be called.
1390 (defun sub-compile-toplevel-lambdas (lambdas)
1391   (declare (list lambdas))
1392   (when lambdas
1393     (multiple-value-bind (component tll) (merge-toplevel-lambdas lambdas)
1394       (compile-component component)
1395       (clear-ir1-info component)
1396       (object-call-toplevel-lambda tll)))
1397   (values))
1398
1399 ;;; Compile top level code and call the top level lambdas. We pick off
1400 ;;; top level lambdas in non-top-level components here, calling
1401 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1402 (defun compile-toplevel-lambdas (lambdas)
1403   (declare (list lambdas))
1404   (let ((len (length lambdas)))
1405     (flet ((loser (start)
1406              (or (position-if (lambda (x)
1407                                 (not (eq (component-kind
1408                                           (node-component (lambda-bind x)))
1409                                          :toplevel)))
1410                               lambdas
1411                               ;; this used to read ":start start", but
1412                               ;; start can be greater than len, which
1413                               ;; is an error according to ANSI - CSR,
1414                               ;; 2002-04-25
1415                               :start (min start len))
1416                  len)))
1417       (do* ((start 0 (1+ loser))
1418             (loser (loser start) (loser start)))
1419            ((>= start len))
1420         (sub-compile-toplevel-lambdas (subseq lambdas start loser))
1421         (unless (= loser len)
1422           (object-call-toplevel-lambda (elt lambdas loser))))))
1423   (values))
1424
1425 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1426 ;;; object file.
1427 ;;;
1428 ;;; LOAD-TIME-VALUE-P seems to control whether it's MAKE-LOAD-FORM and
1429 ;;; COMPILE-LOAD-TIME-VALUE stuff. -- WHN 20000201
1430 (defun compile-toplevel (lambdas load-time-value-p)
1431   (declare (list lambdas))
1432
1433   (maybe-mumble "locall ")
1434   (locall-analyze-clambdas-until-done lambdas)
1435
1436   (maybe-mumble "IDFO ")
1437   (multiple-value-bind (components top-components hairy-top)
1438       (find-initial-dfo lambdas)
1439     (let ((all-components (append components top-components)))
1440       (when *check-consistency*
1441         (maybe-mumble "[check]~%")
1442         (check-ir1-consistency all-components))
1443
1444       (dolist (component (append hairy-top top-components))
1445         (pre-physenv-analyze-toplevel component))
1446
1447       (dolist (component components)
1448         (compile-component component)
1449         (replace-toplevel-xeps component))
1450
1451       (when *check-consistency*
1452         (maybe-mumble "[check]~%")
1453         (check-ir1-consistency all-components))
1454
1455       (if load-time-value-p
1456           (compile-load-time-value-lambda lambdas)
1457           (compile-toplevel-lambdas lambdas))
1458
1459       (mapc #'clear-ir1-info components)
1460       (clear-stuff)))
1461   (values))
1462
1463 ;;; Actually compile any stuff that has been queued up for block
1464 ;;; compilation.
1465 (defun finish-block-compilation ()
1466   (when *block-compile*
1467     (when *compile-print*
1468       (compiler-mumble "~&; block compiling converted top level forms..."))
1469     (when *toplevel-lambdas*
1470       (compile-toplevel (nreverse *toplevel-lambdas*) nil)
1471       (setq *toplevel-lambdas* ()))
1472     (setq *block-compile* nil)
1473     (setq *entry-points* nil)))
1474
1475 (defun handle-condition-p (condition)
1476   (let ((lexenv
1477          (etypecase *compiler-error-context*
1478            (node
1479             (node-lexenv *compiler-error-context*))
1480            (compiler-error-context
1481             (let ((lexenv (compiler-error-context-lexenv
1482                            *compiler-error-context*)))
1483               (aver lexenv)
1484               lexenv))
1485            (null *lexenv*))))
1486     (let ((muffles (lexenv-handled-conditions lexenv)))
1487       (if (null muffles) ; common case
1488           nil
1489           (dolist (muffle muffles nil)
1490             (destructuring-bind (typespec . restart-name) muffle
1491               (when (and (typep condition typespec)
1492                          (find-restart restart-name condition))
1493                 (return t))))))))
1494
1495 (defun handle-condition-handler (condition)
1496   (let ((lexenv
1497          (etypecase *compiler-error-context*
1498            (node
1499             (node-lexenv *compiler-error-context*))
1500            (compiler-error-context
1501             (let ((lexenv (compiler-error-context-lexenv
1502                            *compiler-error-context*)))
1503               (aver lexenv)
1504               lexenv))
1505            (null *lexenv*))))
1506     (let ((muffles (lexenv-handled-conditions lexenv)))
1507       (aver muffles)
1508       (dolist (muffle muffles (bug "fell through"))
1509         (destructuring-bind (typespec . restart-name) muffle
1510           (when (typep condition typespec)
1511             (awhen (find-restart restart-name condition)
1512               (invoke-restart it))))))))
1513
1514 ;;; Read all forms from INFO and compile them, with output to OBJECT.
1515 ;;; Return (VALUES ABORT-P WARNINGS-P FAILURE-P).
1516 (defun sub-compile-file (info)
1517   (declare (type source-info info))
1518   (let ((*package* (sane-package))
1519         (*readtable* *readtable*)
1520         (sb!xc:*compile-file-pathname* nil) ; really bound in
1521         (sb!xc:*compile-file-truename* nil) ; SUB-SUB-COMPILE-FILE
1522         (*policy* *policy*)
1523         (*code-coverage-records* (make-hash-table :test 'equal))
1524         (*code-coverage-blocks* (make-hash-table :test 'equal))
1525         (*handled-conditions* *handled-conditions*)
1526         (*disabled-package-locks* *disabled-package-locks*)
1527         (*lexenv* (make-null-lexenv))
1528         (*block-compile* *block-compile-arg*)
1529         (*toplevel-lambdas* ())
1530         (*fun-names-in-this-file* ())
1531         (*allow-instrumenting* nil)
1532         (*compiler-error-bailout*
1533          (lambda ()
1534            (compiler-mumble "~2&; fatal error, aborting compilation~%")
1535            (return-from sub-compile-file (values t t t))))
1536         (*current-path* nil)
1537         (*last-source-context* nil)
1538         (*last-original-source* nil)
1539         (*last-source-form* nil)
1540         (*last-format-string* nil)
1541         (*last-format-args* nil)
1542         (*last-message-count* 0)
1543         ;; FIXME: Do we need this rebinding here? It's a literal
1544         ;; translation of the old CMU CL rebinding to
1545         ;; (OR *BACKEND-INFO-ENVIRONMENT* *INFO-ENVIRONMENT*),
1546         ;; and it's not obvious whether the rebinding to itself is
1547         ;; needed that SBCL doesn't need *BACKEND-INFO-ENVIRONMENT*.
1548         (*info-environment* *info-environment*)
1549         (*compiler-sset-counter* 0)
1550         (*gensym-counter* 0))
1551     (handler-case
1552         (handler-bind (((satisfies handle-condition-p) #'handle-condition-handler))
1553           (with-compilation-values
1554               (sb!xc:with-compilation-unit ()
1555                 (clear-stuff)
1556
1557                 (sub-sub-compile-file info)
1558
1559                 (unless (zerop (hash-table-count *code-coverage-records*))
1560                   ;; Dump the code coverage records into the fasl.
1561                   (fopcompile `(record-code-coverage
1562                                 ',(namestring *compile-file-pathname*)
1563                                 ',(let (list)
1564                                        (maphash (lambda (k v)
1565                                                   (declare (ignore k))
1566                                                   (push v list))
1567                                                 *code-coverage-records*)
1568                                        list))
1569                               nil
1570                               nil))
1571
1572                 (finish-block-compilation)
1573                 (let ((object *compile-object*))
1574                   (etypecase object
1575                     (fasl-output (fasl-dump-source-info info object))
1576                     (core-object (fix-core-source-info info object))
1577                     (null)))
1578                 nil)))
1579       ;; Some errors are sufficiently bewildering that we just fail
1580       ;; immediately, without trying to recover and compile more of
1581       ;; the input file.
1582       (fatal-compiler-error (condition)
1583        (signal condition)
1584        (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
1585          (format *error-output*
1586                  "~@<compilation aborted because of fatal error: ~2I~_~A~:>"
1587                  condition))
1588        (finish-output *error-output*)
1589        (values t t t)))))
1590
1591 ;;; Return a pathname for the named file. The file must exist.
1592 (defun verify-source-file (pathname-designator)
1593   (let* ((pathname (pathname pathname-designator))
1594          (default-host (make-pathname :host (pathname-host pathname))))
1595     (flet ((try-with-type (path type error-p)
1596              (let ((new (merge-pathnames
1597                          path (make-pathname :type type
1598                                              :defaults default-host))))
1599                (if (probe-file new)
1600                    new
1601                    (and error-p (truename new))))))
1602       (cond ((typep pathname 'logical-pathname)
1603              (try-with-type pathname "LISP" t))
1604             ((probe-file pathname) pathname)
1605             ((try-with-type pathname "lisp"  nil))
1606             ((try-with-type pathname "lisp"  t))))))
1607
1608 (defun elapsed-time-to-string (tsec)
1609   (multiple-value-bind (tmin sec) (truncate tsec 60)
1610     (multiple-value-bind (thr min) (truncate tmin 60)
1611       (format nil "~D:~2,'0D:~2,'0D" thr min sec))))
1612
1613 ;;; Print some junk at the beginning and end of compilation.
1614 (defun print-compile-start-note (source-info)
1615   (declare (type source-info source-info))
1616   (let ((file-info (source-info-file-info source-info)))
1617     (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1618                      (namestring (file-info-name file-info))
1619                      (sb!int:format-universal-time nil
1620                                                    (file-info-write-date
1621                                                     file-info)
1622                                                    :style :government
1623                                                    :print-weekday nil
1624                                                    :print-timezone nil)))
1625   (values))
1626
1627 (defun print-compile-end-note (source-info won)
1628   (declare (type source-info source-info))
1629   (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1630                    won
1631                    (elapsed-time-to-string
1632                     (- (get-universal-time)
1633                        (source-info-start-time source-info))))
1634   (values))
1635
1636 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1637 ;;; out of the compile, then abort the writing of the output file, so
1638 ;;; that we don't overwrite it with known garbage.
1639 (defun sb!xc:compile-file
1640     (input-file
1641      &key
1642
1643      ;; ANSI options
1644      (output-file (cfp-output-file-default input-file))
1645      ;; FIXME: ANSI doesn't seem to say anything about
1646      ;; *COMPILE-VERBOSE* and *COMPILE-PRINT* being rebound by this
1647      ;; function..
1648      ((:verbose sb!xc:*compile-verbose*) sb!xc:*compile-verbose*)
1649      ((:print sb!xc:*compile-print*) sb!xc:*compile-print*)
1650      (external-format :default)
1651
1652      ;; extensions
1653      (trace-file nil)
1654      ((:block-compile *block-compile-arg*) nil))
1655   #!+sb-doc
1656   "Compile INPUT-FILE, producing a corresponding fasl file and
1657 returning its filename.
1658
1659   :PRINT
1660      If true, a message per non-macroexpanded top level form is printed
1661      to *STANDARD-OUTPUT*. Top level forms that whose subforms are
1662      processed as top level forms (eg. EVAL-WHEN, MACROLET, PROGN) receive
1663      no such message, but their subforms do.
1664
1665      As an extension to ANSI, if :PRINT is :top-level-forms, a message
1666      per top level form after macroexpansion is printed to *STANDARD-OUTPUT*.
1667      For example, compiling an IN-PACKAGE form will result in a message about
1668      a top level SETQ in addition to the message about the IN-PACKAGE form'
1669      itself.
1670
1671      Both forms of reporting obey the SB-EXT:*COMPILER-PRINT-VARIABLE-ALIST*.
1672
1673   :BLOCK-COMPILE
1674      Though COMPILE-FILE accepts an additional :BLOCK-COMPILE
1675      argument, it is not currently supported. (non-standard)
1676
1677   :TRACE-FILE
1678      If given, internal data structures are dumped to the specified
1679      file, or if a value of T is given, to a file of *.trace type
1680      derived from the input file name. (non-standard)"
1681 ;;; Block compilation is currently broken.
1682 #|
1683   "Also, as a workaround for vaguely-non-ANSI behavior, the
1684 :BLOCK-COMPILE argument is quasi-supported, to determine whether
1685 multiple functions are compiled together as a unit, resolving function
1686 references at compile time. NIL means that global function names are
1687 never resolved at compilation time. Currently NIL is the default
1688 behavior, because although section 3.2.2.3, \"Semantic Constraints\",
1689 of the ANSI spec allows this behavior under all circumstances, the
1690 compiler's runtime scales badly when it tries to do this for large
1691 files. If/when this performance problem is fixed, the block
1692 compilation default behavior will probably be made dependent on the
1693 SPEED and COMPILATION-SPEED optimization values, and the
1694 :BLOCK-COMPILE argument will probably become deprecated."
1695 |#
1696   (let* ((fasl-output nil)
1697          (output-file-name nil)
1698          (abort-p t)
1699          (warnings-p nil)
1700          (failure-p t) ; T in case error keeps this from being set later
1701          (input-pathname (verify-source-file input-file))
1702          (source-info (make-file-source-info input-pathname external-format))
1703          (*compiler-trace-output* nil)) ; might be modified below
1704
1705     (unwind-protect
1706         (progn
1707           (when output-file
1708             (setq output-file-name
1709                   (sb!xc:compile-file-pathname input-file
1710                                                :output-file output-file))
1711             (setq fasl-output
1712                   (open-fasl-output output-file-name
1713                                     (namestring input-pathname))))
1714           (when trace-file
1715             (let* ((default-trace-file-pathname
1716                      (make-pathname :type "trace" :defaults input-pathname))
1717                    (trace-file-pathname
1718                     (if (eql trace-file t)
1719                         default-trace-file-pathname
1720                         (merge-pathnames trace-file
1721                                          default-trace-file-pathname))))
1722               (setf *compiler-trace-output*
1723                     (open trace-file-pathname
1724                           :if-exists :supersede
1725                           :direction :output))))
1726
1727           (when sb!xc:*compile-verbose*
1728             (print-compile-start-note source-info))
1729
1730           (let ((*compile-object* fasl-output))
1731             (setf (values abort-p warnings-p failure-p)
1732                   (sub-compile-file source-info))))
1733
1734       (close-source-info source-info)
1735
1736       (when fasl-output
1737         (close-fasl-output fasl-output abort-p)
1738         (setq output-file-name
1739               (pathname (fasl-output-stream fasl-output)))
1740         (when (and (not abort-p) sb!xc:*compile-verbose*)
1741           (compiler-mumble "~2&; ~A written~%" (namestring output-file-name))))
1742
1743       (when sb!xc:*compile-verbose*
1744         (print-compile-end-note source-info (not abort-p)))
1745
1746       (when *compiler-trace-output*
1747         (close *compiler-trace-output*)))
1748
1749     ;; CLHS says that the first value is NIL if the "file could not
1750     ;; be created". We interpret this to mean "a valid fasl could not
1751     ;; be created" -- which can happen if the compilation is aborted
1752     ;; before the whole file has been processed, due to eg. a reader
1753     ;; error.
1754     (values (when (and (not abort-p) output-file)
1755               ;; Hack around filesystem race condition...
1756               (or (probe-file output-file-name) output-file-name))
1757             warnings-p
1758             failure-p)))
1759 \f
1760 ;;; a helper function for COMPILE-FILE-PATHNAME: the default for
1761 ;;; the OUTPUT-FILE argument
1762 ;;;
1763 ;;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
1764 ;;; that results from merging the INPUT-FILE with the value of
1765 ;;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
1766 ;;; default to the appropriate implementation-defined default type for
1767 ;;; compiled files.
1768 (defun cfp-output-file-default (input-file)
1769   (let* ((defaults (merge-pathnames input-file *default-pathname-defaults*))
1770          (retyped (make-pathname :type *fasl-file-type* :defaults defaults)))
1771     retyped))
1772
1773 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1774 ;;;   If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1775 ;;;   the result is a logical pathname. If INPUT-FILE is a logical
1776 ;;;   pathname, it is translated into a physical pathname as if by
1777 ;;;   calling TRANSLATE-LOGICAL-PATHNAME.
1778 ;;; So I haven't really tried to make this precisely ANSI-compatible
1779 ;;; at the level of e.g. whether it returns logical pathname or a
1780 ;;; physical pathname. Patches to make it more correct are welcome.
1781 ;;; -- WHN 2000-12-09
1782 (defun sb!xc:compile-file-pathname (input-file
1783                                     &key
1784                                     (output-file nil output-file-p)
1785                                     &allow-other-keys)
1786   #!+sb-doc
1787   "Return a pathname describing what file COMPILE-FILE would write to given
1788    these arguments."
1789   (if output-file-p
1790       (merge-pathnames output-file (cfp-output-file-default input-file))
1791       (cfp-output-file-default input-file)))
1792 \f
1793 ;;;; MAKE-LOAD-FORM stuff
1794
1795 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1796 ;;; finds a constant structure, it invokes this to arrange for proper
1797 ;;; dumping. If it turns out that the constant has already been
1798 ;;; dumped, then we don't need to do anything.
1799 ;;;
1800 ;;; If the constant hasn't been dumped, then we check to see whether
1801 ;;; we are in the process of creating it. We detect this by
1802 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1803 ;;; the constants we are in the process of creating. Actually, each
1804 ;;; entry is a list of the constant and any init forms that need to be
1805 ;;; processed on behalf of that constant.
1806 ;;;
1807 ;;; It's not necessarily an error for this to happen. If we are
1808 ;;; processing the init form for some object that showed up *after*
1809 ;;; the original reference to this constant, then we just need to
1810 ;;; defer the processing of that init form. To detect this, we
1811 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1812 ;;; constants created since the last time we started processing an
1813 ;;; init form. If the constant passed to emit-make-load-form shows up
1814 ;;; in this list, then there is a circular chain through creation
1815 ;;; forms, which is an error.
1816 ;;;
1817 ;;; If there is some intervening init form, then we blow out of
1818 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1819 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1820 ;;; offending init form can be tacked onto the init forms for the
1821 ;;; circular object.
1822 ;;;
1823 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1824 ;;; we have to create it. We call MAKE-LOAD-FORM and check to see
1825 ;;; whether the creation form is the magic value
1826 ;;; :SB-JUST-DUMP-IT-NORMALLY. If it is, then we don't do anything. The
1827 ;;; dumper will eventually get its hands on the object and use the
1828 ;;; normal structure dumping noise on it.
1829 ;;;
1830 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1831 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1832 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1833 ;;; dumper to use that result instead whenever it sees this constant.
1834 ;;;
1835 ;;; Now we try to compile the init form. We bind
1836 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1837 ;;; form (and any init forms that were added because of circularity
1838 ;;; detection). If this works, great. If not, we add the init forms to
1839 ;;; the init forms for the object that caused the problems and let it
1840 ;;; deal with it.
1841 (defvar *constants-being-created* nil)
1842 (defvar *constants-created-since-last-init* nil)
1843 ;;; FIXME: Shouldn't these^ variables be unbound outside LET forms?
1844 (defun emit-make-load-form (constant &optional (name nil namep))
1845   (aver (fasl-output-p *compile-object*))
1846   (unless (or (fasl-constant-already-dumped-p constant *compile-object*)
1847               ;; KLUDGE: This special hack is because I was too lazy
1848               ;; to rework DEF!STRUCT so that the MAKE-LOAD-FORM
1849               ;; function of LAYOUT returns nontrivial forms when
1850               ;; building the cross-compiler but :IGNORE-IT when
1851               ;; cross-compiling or running under the target Lisp. --
1852               ;; WHN 19990914
1853               #+sb-xc-host (typep constant 'layout))
1854     (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
1855       (when circular-ref
1856         (when (find constant *constants-created-since-last-init* :test #'eq)
1857           (throw constant t))
1858         (throw 'pending-init circular-ref)))
1859     (multiple-value-bind (creation-form init-form)
1860         (if namep
1861             ;; If the constant is a reference to a named constant, we can
1862             ;; just use SYMBOL-VALUE during LOAD.
1863             (values `(symbol-value ',name) nil)
1864             (handler-case
1865                 (sb!xc:make-load-form constant (make-null-lexenv))
1866               (error (condition)
1867                 (compiler-error condition))))
1868       (case creation-form
1869         (:sb-just-dump-it-normally
1870          (fasl-validate-structure constant *compile-object*)
1871          t)
1872         (:ignore-it
1873          nil)
1874         (t
1875          (let* ((name (write-to-string constant :level 1 :length 2))
1876                 (info (if init-form
1877                           (list constant name init-form)
1878                           (list constant))))
1879            (let ((*constants-being-created*
1880                   (cons info *constants-being-created*))
1881                  (*constants-created-since-last-init*
1882                   (cons constant *constants-created-since-last-init*)))
1883              (when
1884                  (catch constant
1885                    (fasl-note-handle-for-constant
1886                     constant
1887                     (compile-load-time-value
1888                      creation-form)
1889                     *compile-object*)
1890                    nil)
1891                (compiler-error "circular references in creation form for ~S"
1892                                constant)))
1893            (when (cdr info)
1894              (let* ((*constants-created-since-last-init* nil)
1895                     (circular-ref
1896                      (catch 'pending-init
1897                        (loop for (name form) on (cdr info) by #'cddr
1898                          collect name into names
1899                          collect form into forms
1900                          finally (compile-make-load-form-init-forms forms))
1901                        nil)))
1902                (when circular-ref
1903                  (setf (cdr circular-ref)
1904                        (append (cdr circular-ref) (cdr info))))))))))))
1905
1906 \f
1907 ;;;; Host compile time definitions
1908 #+sb-xc-host
1909 (defun compile-in-lexenv (name lambda lexenv)
1910   (declare (ignore lexenv))
1911   (compile name lambda))
1912
1913 #+sb-xc-host
1914 (defun eval-in-lexenv (form lexenv)
1915   (declare (ignore lexenv))
1916   (eval form))