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