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