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