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