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