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