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