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