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