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