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