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