Fix -sb-unicode
[sbcl.git] / src / compiler / main.lisp
blob3881946a36cd5dab589926e260ac3fe9faa98ef2
1 ;;;; the top level interfaces to the compiler
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB-C")
14 (defvar *block-compile-default* nil
15 "The default value for the :Block-Compile argument to COMPILE-FILE.")
17 ;;; *BLOCK-COMPILE-ARGUMENT* holds the original value of the :BLOCK-COMPILE
18 ;;; argument, which overrides any internal declarations.
19 (defvar *block-compile-argument*)
20 (declaim (type (member nil t :specified)
21 *block-compile-default* *block-compile-argument*))
23 (defvar *entry-points-argument*)
24 (declaim (type list *entry-points-argument*))
26 (defvar *check-consistency* nil)
28 (defvar *compile-verbose* t
29 "The default for the :VERBOSE argument to COMPILE-FILE.")
30 (defvar *compile-print* nil
31 "The default for the :PRINT argument to COMPILE-FILE.")
32 (defvar *compile-progress* nil
33 "When this is true, the compiler prints to *STANDARD-OUTPUT* progress
34 information about the phases of compilation of each function. (This
35 is useful mainly in large block compilations.)")
37 (defvar *compile-file-pathname* nil
38 "The defaulted pathname of the file currently being compiled, or NIL if not
39 compiling.")
40 (defvar *compile-file-truename* nil
41 "The TRUENAME of the file currently being compiled, or NIL if not
42 compiling.")
44 (declaim (type (or pathname null)
45 *compile-file-pathname*
46 *compile-file-truename*))
48 ;;; the SOURCE-INFO structure for the current compilation. This is
49 ;;; null globally to indicate that we aren't currently in any
50 ;;; identifiable compilation.
51 (defvar *source-info* nil)
53 ;;; This is true if we are within a WITH-COMPILATION-UNIT form (which
54 ;;; normally causes nested uses to be no-ops).
55 (defvar *in-compilation-unit* nil)
57 ;;; Count of the number of compilation units dynamically enclosed by
58 ;;; the current active WITH-COMPILATION-UNIT that were unwound out of.
59 (defvar *aborted-compilation-unit-count*)
61 ;;; Mumble conditional on *COMPILE-PROGRESS*.
62 (defun maybe-mumble (&rest foo)
63 (when *compile-progress*
64 (apply #'compiler-mumble foo)))
67 (deftype object () '(or fasl-output #-sb-xc-host core-object null))
69 (defvar *compile-object* nil)
70 (declaim (type object *compile-object*))
72 (defvar *emit-cfasl* nil)
74 (declaim (inline code-coverage-records code-coverage-blocks))
75 ;; Used during compilation to map code paths to the matching
76 ;; instrumentation conses.
77 (defun code-coverage-records (x) (car x))
78 ;; Used during compilation to keep track of with source paths have been
79 ;; instrumented in which blocks.
80 (defun code-coverage-blocks (x) (cdr x))
82 ;;;; WITH-COMPILATION-UNIT and WITH-COMPILATION-VALUES
84 (defmacro with-compilation-unit (options &body body)
85 "Affects compilations that take place within its dynamic extent. It is
86 intended to be eg. wrapped around the compilation of all files in the same system.
88 Following options are defined:
90 :OVERRIDE Boolean-Form
91 One of the effects of this form is to delay undefined warnings until the
92 end of the form, instead of giving them at the end of each compilation.
93 If OVERRIDE is NIL (the default), then the outermost
94 WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
95 OVERRIDE true causes that form to grab any enclosed warnings, even if it
96 is enclosed by another WITH-COMPILATION-UNIT.
98 :POLICY Optimize-Declaration-Form
99 Provides dynamic scoping for global compiler optimization qualities and
100 restrictions, limiting effects of subsequent OPTIMIZE proclamations and
101 calls to SB-EXT:RESTRICT-COMPILER-POLICY to the dynamic scope of BODY.
103 If OVERRIDE is false, specified POLICY is merged with current global
104 policy. If OVERRIDE is true, current global policy, including any
105 restrictions, is discarded in favor of the specified POLICY.
107 Supplying POLICY NIL is equivalent to the option not being supplied at
108 all, ie. dynamic scoping of policy does not take place.
110 This option is an SBCL-specific experimental extension: Interface
111 subject to change.
113 :SOURCE-NAMESTRING Namestring-Form
114 Attaches the value returned by the Namestring-Form to the internal
115 debug-source information as the namestring of the source file. Normally
116 the namestring of the input-file for COMPILE-FILE is used: this option
117 can be used to provide source-file information for functions compiled
118 using COMPILE, or to override the input-file of COMPILE-FILE.
120 If both an outer and an inner WITH-COMPILATION-UNIT provide a
121 SOURCE-NAMESTRING, the inner one takes precedence. Unaffected
122 by :OVERRIDE.
124 This is an SBCL-specific extension.
126 :SOURCE-PLIST Plist-Form
127 Attaches the value returned by the Plist-Form to internal debug-source
128 information of functions compiled in within the dynamic extent of BODY.
130 Primarily for use by development environments, in order to eg. associate
131 function definitions with editor-buffers. Can be accessed using
132 SB-INTROSPECT:DEFINITION-SOURCE-PLIST.
134 If an outer WITH-COMPILATION-UNIT form also provide a SOURCE-PLIST, it
135 is appended to the end of the provided SOURCE-PLIST. Unaffected
136 by :OVERRIDE.
138 This is an SBCL-specific extension.
140 Examples:
142 ;; Prevent proclamations from the file leaking, and restrict
143 ;; SAFETY to 3 -- otherwise uses the current global policy.
144 (with-compilation-unit (:policy '(optimize))
145 (restrict-compiler-policy 'safety 3)
146 (load \"foo.lisp\"))
148 ;; Using default policy instead of the current global one,
149 ;; except for DEBUG 3.
150 (with-compilation-unit (:policy '(optimize debug)
151 :override t)
152 (load \"foo.lisp\"))
154 ;; Same as if :POLICY had not been specified at all: SAFETY 3
155 ;; proclamation leaks out from WITH-COMPILATION-UNIT.
156 (with-compilation-unit (:policy nil)
157 (declaim (optimize safety))
158 (load \"foo.lisp\"))
160 `(%with-compilation-unit (lambda () ,@body) ,@options))
162 (defvar *source-plist* nil)
163 (defvar *source-namestring* nil)
165 (defun %with-compilation-unit (fn &key override policy source-plist source-namestring)
166 (declare (type function fn))
167 (declare (dynamic-extent fn))
168 (flet ((with-it ()
169 (let ((succeeded-p nil)
170 (*source-plist* (append source-plist *source-plist*))
171 (*source-namestring*
172 (awhen (or source-namestring *source-namestring*)
173 (possibly-base-stringize it))))
174 (if (and *in-compilation-unit* (not override))
175 ;; Inside another WITH-COMPILATION-UNIT, a WITH-COMPILATION-UNIT is
176 ;; ordinarily (unless OVERRIDE) basically a no-op.
177 (unwind-protect
178 (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
179 (unless succeeded-p
180 (incf *aborted-compilation-unit-count*)))
181 (let ((*aborted-compilation-unit-count* 0)
182 (*compiler-error-count* 0)
183 (*compiler-warning-count* 0)
184 (*compiler-style-warning-count* 0)
185 (*compiler-note-count* 0)
186 (*undefined-warnings* nil)
187 *argument-mismatch-warnings*
188 *methods-in-compilation-unit*
189 (*in-compilation-unit* t))
190 (handler-bind ((parse-unknown-type
191 (lambda (c)
192 (note-undefined-reference
193 (parse-unknown-type-specifier c)
194 :type))))
195 (unwind-protect
196 (multiple-value-prog1 (funcall fn) (setf succeeded-p t))
197 (unless succeeded-p
198 (incf *aborted-compilation-unit-count*))
199 (summarize-compilation-unit (not succeeded-p)))))))))
200 (if policy
201 (let ((*policy* (process-optimize-decl policy (unless override *policy*)))
202 (*policy-min* (unless override *policy-min*))
203 (*policy-max* (unless override *policy-max*)))
204 (with-it))
205 (with-it))))
207 ;;; Is NAME something that no conforming program can rely on
208 ;;; defining?
209 (defun name-reserved-by-ansi-p (name kind)
210 (declare (ignorable name kind))
211 #-sb-xc-host ; always return NIL in the cross-compiler
212 (ecase kind
213 (:function
214 (eq (sb-xc:symbol-package (fun-name-block-name name))
215 *cl-package*))
216 (:type
217 (let ((symbol (typecase name
218 (symbol name)
219 ((cons symbol) (car name))
220 (t (return-from name-reserved-by-ansi-p nil)))))
221 (eq (sb-xc:symbol-package symbol) *cl-package*)))))
223 ;;; This is to be called at the end of a compilation unit. It signals
224 ;;; any residual warnings about unknown stuff, then prints the total
225 ;;; error counts. ABORT-P should be true when the compilation unit was
226 ;;; aborted by throwing out. ABORT-COUNT is the number of dynamically
227 ;;; enclosed nested compilation units that were aborted.
228 (defun summarize-compilation-unit (abort-p)
229 (let (summary)
230 (unless abort-p
231 (let ((undefs (sort *undefined-warnings* #'string<
232 :key (lambda (x)
233 (let ((x (undefined-warning-name x)))
234 (if (symbolp x)
235 (symbol-name x)
236 (prin1-to-string x))))))
237 (*last-message-count* (list* 0 nil nil))
238 (*last-error-context* nil))
239 (handler-bind ((style-warning #'compiler-style-warning-handler)
240 (warning #'compiler-warning-handler))
241 (report-key-arg-mismatches)
242 (dolist (kind '(:variable :function :type))
243 (let ((names (mapcar #'undefined-warning-name
244 (remove kind undefs :test #'neq
245 :key #'undefined-warning-kind))))
246 (when names (push (cons kind names) summary))))
247 (dolist (undef undefs)
248 (let ((name (undefined-warning-name undef))
249 (kind (undefined-warning-kind undef))
250 (warnings (undefined-warning-warnings undef))
251 (undefined-warning-count (undefined-warning-count undef)))
252 (dolist (*compiler-error-context* warnings)
253 (if (and (member kind '(:function :type))
254 (name-reserved-by-ansi-p name kind))
255 (ecase kind
256 (:function
257 (compiler-warn
258 "~@<The function ~S is undefined, and its name is ~
259 reserved by ANSI CL so that even if it were ~
260 defined later, the code doing so would not be ~
261 portable.~:@>" name))
262 (:type
263 (if (and (consp name) (eq 'quote (car name)))
264 (compiler-warn
265 "~@<Undefined type ~S. The name starts with ~S: ~
266 probably use of a quoted type name in a context ~
267 where the name is not evaluated.~:@>"
268 name 'quote)
269 (compiler-warn
270 "~@<Undefined type ~S. Note that name ~S is ~
271 reserved by ANSI CL, so code defining a type with ~
272 that name would not be portable.~:@>" name
273 name))))
274 (funcall
275 (if (eq kind :variable) #'compiler-warn #'compiler-style-warn)
276 (sb-format:tokens "undefined ~(~A~): ~/sb-ext:print-symbol-with-prefix/")
277 kind name)))
278 (let ((warn-count (length warnings)))
279 (when (and warnings (> undefined-warning-count warn-count))
280 (let ((more (- undefined-warning-count warn-count)))
281 (if (eq kind :variable)
282 (compiler-warn
283 "~W more use~:P of undefined ~(~A~) ~S"
284 more kind name)
285 (compiler-style-warn
286 "~W more use~:P of undefined ~(~A~) ~S"
287 more kind name))))))))))
289 (unless (and (not abort-p)
290 (zerop *aborted-compilation-unit-count*)
291 (zerop *compiler-error-count*)
292 (zerop *compiler-warning-count*)
293 (zerop *compiler-style-warning-count*)
294 (zerop *compiler-note-count*))
295 (fresh-line *error-output*)
296 (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
297 (format *error-output* "~&compilation unit ~:[finished~;aborted~]"
298 abort-p)
299 (dolist (cell summary)
300 (destructuring-bind (kind &rest names) cell
301 (format *error-output*
302 "~& Undefined ~(~A~)~p:~
303 ~% ~{~<~% ~1:;~S~>~^ ~}"
304 kind (length names) names)))
305 (format *error-output* "~[~:;~:*~& caught ~W fatal ERROR condition~:P~]~
306 ~[~:;~:*~& caught ~W ERROR condition~:P~]~
307 ~[~:;~:*~& caught ~W WARNING condition~:P~]~
308 ~[~:;~:*~& caught ~W STYLE-WARNING condition~:P~]~
309 ~[~:;~:*~& printed ~W note~:P~]"
310 *aborted-compilation-unit-count*
311 *compiler-error-count*
312 *compiler-warning-count*
313 *compiler-style-warning-count*
314 *compiler-note-count*))
315 (terpri *error-output*)
316 (force-output *error-output*))))
318 ;;; Evaluate BODY, then return (VALUES BODY-VALUE WARNINGS-P
319 ;;; FAILURE-P), where BODY-VALUE is the first value of the body, and
320 ;;; WARNINGS-P and FAILURE-P are as in CL:COMPILE or CL:COMPILE-FILE.
321 (defmacro with-compilation-values (&body body)
322 `(let ((*finite-sbs*
323 (vector
324 ,@(loop for sb across *backend-sbs*
325 unless (eq (sb-kind sb) :non-packed)
326 collect
327 (let ((size (sb-size sb)))
328 `(make-finite-sb
329 :conflicts (make-array ,size :initial-element #())
330 :always-live (make-array ,size :initial-element #*)
331 :live-tns (make-array ,size :initial-element nil)))))))
332 (let ((*warnings-p* nil)
333 (*failure-p* nil))
334 (handler-bind ((compiler-error #'compiler-error-handler)
335 (style-warning #'compiler-style-warning-handler)
336 (warning #'compiler-warning-handler))
337 (values (progn ,@body) *warnings-p* *failure-p*)))))
339 ;;; THING is a kind of thing about which we'd like to issue a warning,
340 ;;; but showing at most one warning for a given set of <THING,FMT,ARGS>.
341 ;;; The compiler does a good job of making sure not to print repetitive
342 ;;; warnings for code that it compiles, but this solves a different problem.
343 ;;; Specifically, for a warning from PARSE-LAMBDA-LIST, there are three calls:
344 ;;; - once in the expander for defmacro itself, as it calls MAKE-MACRO-LAMBDA
345 ;;; which calls PARSE-LAMBDA-LIST. This is the toplevel form processing.
346 ;;; - again for :compile-toplevel, where the DS-BIND calls PARSE-LAMBDA-LIST.
347 ;;; If compiling in compile-toplevel, then *COMPILE-OBJECT* is a core object,
348 ;;; but if interpreting, then it is still a fasl.
349 ;;; - once for compiling to fasl. *COMPILE-OBJECT* is a fasl.
350 ;;; I'd have liked the data to be associated with the fasl, except that
351 ;;; as indicated above, the second line hides some information.
352 (defun style-warn-once (thing fmt-or-condition &rest args)
353 (declare (notinline style-warn)) ; See COMPILER-STYLE-WARN for rationale
354 (let* ((source-info *source-info*)
355 (file-info (and (source-info-p source-info)
356 (source-info-file-info source-info)))
357 (file-compiling-p (file-info-p file-info)))
358 (flet ((match-p (entry)
359 (destructuring-bind (entry-thing entry-fmt &rest entry-args) entry
360 ;; THING is compared by EQ, FMT mostly by STRING=.
361 (and (eq entry-thing thing)
362 (cond ((typep entry-fmt 'condition)
363 (and (typep fmt-or-condition 'condition)
364 (string= (princ-to-string entry-fmt)
365 (princ-to-string fmt-or-condition))))
366 ((typep fmt-or-condition 'condition)
367 nil)
368 ;; If at least one is a FMT-CONTROL-PROXY
369 ;; the two should be either EQ or a
370 ;; mismatch.
371 ((not (stringp entry-fmt))
372 (and (not (stringp fmt-or-condition))
373 (eq entry-fmt fmt-or-condition)))
374 ((string= entry-fmt fmt-or-condition)))
375 ;; We don't want to walk into default values,
376 ;; e.g. (&optional (b #<insane-struct))
377 ;; because #<insane-struct> might be circular.
378 (list-elts-eq entry-args args)))))
379 (unless (and file-compiling-p
380 (find-if #'match-p
381 (file-info-style-warning-tracker file-info)))
382 (when file-compiling-p
383 (push (list* thing fmt-or-condition args)
384 (file-info-style-warning-tracker file-info)))
385 (apply 'style-warn fmt-or-condition args)))))
387 ;;;; component compilation
389 (defparameter *max-optimize-iterations* 3 ; ARB
390 "The upper limit on the number of times that we will consecutively do IR1
391 optimization that doesn't introduce any new code. A finite limit is
392 necessary, since type inference may take arbitrarily long to converge.")
394 (defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called")
395 (defevent ir1-optimize-maxed-out "hit *MAX-OPTIMIZE-ITERATIONS* limit")
399 ;;; Repeatedly optimize COMPONENT until no further optimizations can
400 ;;; be found or we hit our iteration limit. When we hit the limit, we
401 ;;; clear the component and block REOPTIMIZE flags to discourage the
402 ;;; next optimization attempt from pounding on the same code.
403 (defun ir1-optimize-until-done (component)
404 (declare (type component component))
405 (maybe-mumble "Opt")
406 (event ir1-optimize-until-done)
407 (let ((count 0)
408 (cleared-reanalyze nil)
409 (fastp nil)
410 reoptimized)
411 (loop
412 (when (component-reanalyze component)
413 (setf count 0
414 fastp nil
415 cleared-reanalyze t
416 (component-reanalyze component) nil))
417 (setf (component-reoptimize component) nil)
418 (ir1-optimize component fastp)
419 (cond ((component-reoptimize component)
420 (setf reoptimized t)
421 (incf count)
422 (when (and (>= count *max-optimize-iterations*)
423 (not (component-reanalyze component))
424 (eq (component-reoptimize component) :maybe))
425 (maybe-mumble "*")
426 (event ir1-optimize-maxed-out)
427 (ir1-optimize-last-effort component)
428 (return)))
430 (return)))
431 (when (setq fastp (>= count *max-optimize-iterations*))
432 (ir1-optimize-last-effort component))
433 (maybe-mumble (if fastp "-" ".")))
434 (when cleared-reanalyze
435 (setf (component-reanalyze component) t))
436 (maybe-mumble " ")
437 reoptimized))
439 (defparameter *constraint-propagate* t)
441 (defevent reoptimize-maxed-out
442 "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
444 ;;; Iterate doing FIND-DFO until no new dead code is discovered.
445 (defun dfo-as-needed (component)
446 (declare (type component component))
447 (when (component-reanalyze component)
448 (maybe-mumble "DFO")
449 (loop
450 (find-dfo component)
451 (unless (component-reanalyze component)
452 (maybe-mumble " ")
453 (return))
454 (maybe-mumble "."))
457 (defparameter *reoptimize-limit* 10)
459 (defun ir1-optimize-phase-1 (component)
460 (let ((loop-count 0)
461 (constraint-propagate *constraint-propagate*)
462 reoptimized)
463 (tagbody
464 again
465 (loop
466 (setf reoptimized (ir1-optimize-until-done component))
467 (cond ((or (component-new-functionals component)
468 (component-reanalyze-functionals component))
469 (maybe-mumble "Locall ")
470 (locall-analyze-component component))
471 ((and (>= loop-count 1)
472 (not (component-reanalyze component))
473 (not reoptimized))
474 ;; Constraint propagation did something but that
475 ;; information didn't lead to any new optimizations.
476 ;; Don't run constraint-propagate again.
477 (return)))
478 (dfo-as-needed component)
479 (when constraint-propagate
480 (maybe-mumble "Constraint ")
481 (constraint-propagate component)
482 (when (retry-delayed-ir1-transforms :constraint)
483 (setf loop-count 0) ;; otherwise nothing may get retried
484 (maybe-mumble "Rtran ")))
485 (unless (or (component-reoptimize component)
486 (component-reanalyze component)
487 (component-new-functionals component)
488 (component-reanalyze-functionals component))
489 (return))
490 (when (> loop-count *reoptimize-limit*)
491 (maybe-mumble "[Reoptimize Limit]")
492 (event reoptimize-maxed-out)
493 (return))
494 (incf loop-count))
495 ;; Do it once more for the transforms that will produce code
496 ;; that loses some information for further optimizations and
497 ;; it's better to insert it at the last moment.
498 ;; Such code shouldn't need constraint propagation, the slowest
499 ;; part, so avoid it.
500 (when (retry-delayed-ir1-transforms :ir1-phases)
501 (setf loop-count 0
502 constraint-propagate nil)
503 (go again)))))
505 ;;; Do all the IR1 phases for a non-top-level component.
506 (defun ir1-phases (component)
507 (declare (type component component))
508 (aver-live-component component)
509 (let ((*constraint-universe* (make-array 64 ; arbitrary, but don't make this 0
510 :fill-pointer 0 :adjustable t))
511 (*delayed-ir1-transforms* nil))
512 (declare (special *constraint-universe* *delayed-ir1-transforms*))
513 (ir1-optimize-phase-1 component)
514 (loop while (progn
515 (maybe-mumble "Type ")
516 (generate-type-checks component))
518 (ir1-optimize-phase-1 component))
519 ;; Join the blocks that were generated by GENERATE-TYPE-CHECKS
520 ;; now that all the blocks have the same TYPE-CHECK attribute
521 (join-blocks-if-possible component))
523 (ir1-finalize component)
524 (values))
526 #-immobile-code
527 (defun component-mem-space (component)
528 (component-%mem-space component))
530 #+immobile-code
531 (progn
532 (defun component-mem-space (component)
533 (or (component-%mem-space component)
534 #-sb-xc-host
535 (setf (component-%mem-space component)
536 (if (fasl-output-p *compile-object*)
537 (and (eq *compile-file-to-memory-space* :immobile)
538 (neq (component-kind component) :toplevel)
539 (policy *lexenv* (/= sb-c:store-coverage-data 3))
540 :immobile)
541 (if (core-object-ephemeral *compile-object*)
542 :dynamic
543 *compile-to-memory-space*)))))
544 (defun code-immobile-p (thing)
545 #+sb-xc-host (declare (ignore thing)) #+sb-xc-host t
546 #-sb-xc-host
547 (let ((component (etypecase thing
548 (vop (node-component (vop-node thing)))
549 (node (node-component thing))
550 (component thing))))
551 (eq (component-mem-space component) :immobile))))
553 (defun %compile-component (component)
554 (maybe-mumble "GTN ")
555 (gtn-analyze component)
556 (maybe-mumble "LTN ")
557 (ltn-analyze component)
558 (dfo-as-needed component)
560 (maybe-mumble "Control ")
561 (control-analyze component)
563 (report-code-deletion)
565 (when (or (ir2-component-values-receivers (component-info component))
566 (ir2-component-stack-allocates-p (component-info component)))
567 (maybe-mumble "Stack ")
568 (stack-analyze component)
569 ;; Assign BLOCK-NUMBER for any cleanup blocks introduced by
570 ;; stack analysis. There shouldn't be any unreachable code after
571 ;; control, so this won't delete anything.
572 (dfo-as-needed component))
574 (maybe-mumble "IR2Tran ")
575 (entry-analyze component)
577 ;; For on-demand recalculation of dominators, the previously
578 ;; computed results may be stale.
580 (clear-dominators component)
582 (ir2-convert component)
584 (when (policy *lexenv* (>= speed compilation-speed))
585 (maybe-mumble "Copy ")
586 (copy-propagate component))
588 (ir2-optimize component)
590 (select-representations component)
592 (ir2-optimize component 'select-representations)
594 (when *check-consistency*
595 (maybe-mumble "Check2 ")
596 (check-ir2-consistency component))
598 (delete-unreferenced-tns component)
600 (maybe-mumble "Life ")
601 (lifetime-analyze component)
603 (when *compile-progress*
604 (compiler-mumble "") ; Sync before doing more output.
605 (pre-pack-tn-stats component *standard-output*))
607 (when *check-consistency*
608 (maybe-mumble "CheckL ")
609 (check-life-consistency component))
611 (maybe-mumble "Pack ")
612 (sb-regalloc:pack component)
614 (when *check-consistency*
615 (maybe-mumble "CheckP ")
616 (check-pack-consistency component))
618 (ir2-optimize component 'regalloc)
620 (when *compiler-trace-output*
621 (when (memq :ir1 *compile-trace-targets*)
622 (describe-component component *compiler-trace-output*))
623 (when (memq :ir2 *compile-trace-targets*)
624 (describe-ir2-component component *compiler-trace-output*)))
626 (maybe-mumble "Code ")
627 (multiple-value-bind (segment text-length fun-table
628 elsewhere-label fixup-notes alloc-points)
629 (let ((*compiler-trace-output*
630 (and (memq :vop *compile-trace-targets*)
631 *compiler-trace-output*)))
632 (generate-code component))
633 (declare (ignorable text-length fun-table))
635 (let ((bytes (sb-assem:segment-contents-as-vector segment))
636 (object *compile-object*)
637 (*elsewhere-label* elsewhere-label)) ; KLUDGE
638 #-sb-xc-host
639 (when (and *compiler-trace-output*
640 (memq :disassemble *compile-trace-targets*))
641 (let ((ranges
642 (maplist (lambda (list)
643 (cons (+ (car list)
644 (ash sb-vm:simple-fun-insts-offset
645 sb-vm:word-shift))
646 (or (cadr list) text-length)))
647 fun-table)))
648 (format *compiler-trace-output*
649 "~|~%Disassembly of code for ~S~2%" component)
650 (sb-disassem:disassemble-assem-segment
651 bytes ranges *compiler-trace-output*)))
653 (funcall (etypecase object
654 (fasl-output (maybe-mumble "FASL") #'fasl-dump-component)
655 #-sb-xc-host ; no compiling to core
656 (core-object (maybe-mumble "Core") #'make-core-component)
657 (null (lambda (&rest dummies)
658 (declare (ignore dummies)))))
659 component segment (length bytes)
660 fixup-notes alloc-points
661 object)))
663 ;; We're done, so don't bother keeping anything around.
664 (setf (component-info component) :dead)
666 (values))
668 ;;; Delete components with no external entry points before we try to
669 ;;; generate code. Unreachable closures can cause IR2 conversion to
670 ;;; puke on itself, since it is the reference to the closure which
671 ;;; normally causes the components to be combined.
672 (defun delete-if-no-entries (component)
673 (dolist (fun (component-lambdas component) (delete-component component))
674 (when (functional-has-external-references-p fun)
675 (return))
676 (functional-kind-case fun
677 (toplevel (return))
678 (external
679 (unless (every (lambda (ref)
680 (eq (node-component ref) component))
681 (leaf-refs fun))
682 (return))))))
684 (defvar *compile-component-hook* nil)
686 (defun compile-component (component)
687 (aver-live-component component)
688 (let* ((*component-being-compiled* component))
690 (when *compile-progress*
691 (compiler-mumble "~&")
692 (pprint-logical-block (*standard-output* nil :per-line-prefix "; ")
693 (compiler-mumble "Compiling ~A: " (component-name component))))
695 ;; Record xref information before optimization. This way the
696 ;; stored xref data reflects the real source as closely as
697 ;; possible.
698 (record-component-xrefs component)
700 (ir1-phases component)
702 ;; KLUDGE: We should instead set COMPONENT-REOPTIMIZE to T
703 ;; whenever a REF gets deleted so that DFO-AS-NEEDED kicks in only
704 ;; when needed, and we don't need this call to do a final
705 ;; unreachable entry point scan.
706 (find-dfo component)
708 (dfo-as-needed component)
709 (maybe-mumble "Dom ")
710 (find-dominators component)
711 (maybe-mumble "Loop ")
712 (loop-analyze component)
715 (when *compiler-trace-output*
716 (labels ((print-blocks (block)
717 (format *compiler-trace-output* " ~A~%" block)
718 (when (block-loop-next block)
719 (print-blocks (block-loop-next block))))
720 (print-loop (loop)
721 (format *compiler-trace-output* "loop=~A~%" loop)
722 (print-blocks (loop-blocks loop))
723 (dolist (l (loop-inferiors loop))
724 (print-loop l))))
725 (print-loop (component-outer-loop component))))
728 (maybe-mumble "Env ")
729 (environment-analyze component)
730 (dfo-as-needed component)
732 (delete-if-no-entries component)
734 (if (eq (block-next (component-head component))
735 (component-tail component))
736 (report-code-deletion)
737 (%compile-component component))
738 (when *compile-component-hook*
739 (funcall *compile-component-hook* component)))
741 (clear-constant-info)
742 (values))
744 ;;;; clearing global data structures
745 ;;;;
746 ;;;; FIXME: Is it possible to get rid of this stuff, getting rid of
747 ;;;; global data structures entirely when possible and consing up the
748 ;;;; others from scratch instead of clearing and reusing them?
750 ;;; Clear the INFO in constants in the *IR1-NAMESPACE*, etc. In
751 ;;; addition to allowing stuff to be reclaimed, this is required for
752 ;;; correct assignment of constant offsets, since we need to assign a
753 ;;; new offset for each component. We don't clear the FUNCTIONAL-INFO
754 ;;; slots, since they are used to keep track of functions across
755 ;;; component boundaries.
756 (defun clear-constant-info (&aux (ns *ir1-namespace*))
757 (maphash (lambda (k v)
758 (declare (ignore k))
759 (setf (leaf-info v) nil))
760 (eql-constants ns))
761 (maphash (lambda (k v)
762 (declare (ignore k))
763 (when (constant-p v)
764 (setf (leaf-info v) nil)))
765 (free-vars ns))
766 (values))
768 ;;; Blow away the REFS for all global variables, and let COMPONENT
769 ;;; be recycled.
770 (defun clear-ir1-info (component &aux (ns *ir1-namespace*))
771 (declare (type component component))
772 (labels ((blast (x)
773 (maphash (lambda (k v)
774 (declare (ignore k))
775 (when (leaf-p v)
776 (setf (leaf-refs v)
777 (delete-if #'here-p (leaf-refs v)))
778 (when (basic-var-p v)
779 (setf (basic-var-sets v)
780 (delete-if #'here-p (basic-var-sets v))))))
782 (here-p (x)
783 (eq (node-component x) component)))
784 (blast (free-vars ns))
785 (blast (free-funs ns))
786 ;; There can be more constants to blast when considering them by EQL rather
787 ;; than similarity. But it's totally OK to visit a #<CONSTANT> twice.
788 ;; Its refs will be scanned redundantly, which is harmless.
789 (blast (eql-constants ns)))
790 (values))
792 ;;; Clear the global hash tables held in IR1-NAMESPACE.
793 (defun clear-ir1-namespace ()
794 (when (boundp '*ir1-namespace*)
795 (let ((ir1-namespace *ir1-namespace*))
796 (clrhash (free-funs ir1-namespace))
797 (clrhash (free-vars ir1-namespace))
798 ;; FIXME: It would make sense to clear these tables on arm64 as
799 ;; well, but it relies on the constant for NIL to stay around in
800 ;; order to assign a wired TN to it. A possible fix is to give
801 ;; arm64 NULL-SC like on other platforms.
802 #-arm64
803 (progn
804 (clrhash (eql-constants ir1-namespace))
805 (clrhash (similar-constants ir1-namespace))))))
807 ;;;; trace output
809 ;;; Print out some useful info about COMPONENT to STREAM.
810 (defun describe-component (component *standard-output*)
811 (declare (type component component))
812 (format t "~|~%;;;; component: ~S~2%" (component-name component))
813 (print-all-blocks component)
814 (values))
816 (defun describe-ir2-component (component *standard-output*)
817 (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
818 (format t "entries:~%")
819 (dolist (entry (ir2-component-entries (component-info component)))
820 (format t "~4TL~D: ~S~:[~; [closure]~]~%"
821 (label-id (entry-info-offset entry))
822 (entry-info-name entry)
823 (entry-info-closure-tn entry)))
824 (terpri)
825 (pre-pack-tn-stats component *standard-output*)
826 (terpri)
827 (print-ir2-blocks component)
828 (terpri)
829 (values))
831 ;;; Leave this as NIL if you want modern, rational, correct, behavior,
832 ;;; or switch it to T for legacy (CLHS-specified) bullshit a la
833 ;;; "During a call to compile-file, *compile-file-pathname* is bound to the pathname
834 ;;; denoted by the first argument to compile-file, merged against the defaults"
835 ;;; The normal build sets it to T in make-target-2, despite that I think most people would
836 ;;; prefer the nonstandard behavior. The standard behavior makes stored pathnames all wrong
837 ;;; when files are physically moved. (Same problem as SBCL_HOME embedded into C pretty much)
838 (defglobal *merge-pathnames* nil)
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
844 ;; becomes *COMPILE-FILE-PATHNAME*
845 :pathname (if *merge-pathnames* (merge-pathnames file) file)
846 :external-format external-format
847 :subforms (if form-tracking-p (make-array 100 :fill-pointer 0 :adjustable t))
848 :write-date (file-write-date file))))
850 ;; LOAD-AS-SOURCE uses this.
851 (defun make-file-stream-source-info (file-stream)
852 (make-source-info
853 :file-info (make-file-info :truename (truename file-stream) ; FIXME: WHY USE TRUENAME???
854 ;; This T-L-P has been around since at least 2011.
855 ;; It's unclear why an LPN isn't good enough.
856 :pathname (translate-logical-pathname file-stream)
857 :external-format (stream-external-format file-stream)
858 :write-date (file-write-date file-stream))))
860 ;;; Return a SOURCE-INFO to describe the incremental compilation of FORM.
861 (defun make-lisp-source-info (form &key parent)
862 (make-source-info
863 :file-info (make-file-info :truename :lisp
864 :forms (vector form)
865 :positions '#(0))
866 :parent parent))
868 ;;; Walk up the SOURCE-INFO list until we either reach a SOURCE-INFO
869 ;;; with no parent (e.g., from a REPL evaluation) or until we reach a
870 ;;; SOURCE-INFO whose FILE-INFO denotes a file.
871 (defun get-toplevelish-file-info (&optional (source-info *source-info*))
872 (if source-info
873 (do* ((sinfo source-info (source-info-parent sinfo))
874 (finfo (source-info-file-info sinfo)
875 (source-info-file-info sinfo)))
876 ((or (not (source-info-p (source-info-parent sinfo)))
877 (pathnamep (file-info-truename finfo)))
878 finfo))))
880 ;;; If STREAM is present, return it, otherwise open a stream to the
881 ;;; current file. There must be a current file.
883 ;;; FIXME: This is probably an unnecessarily roundabout way to do
884 ;;; things now that we process a single file in COMPILE-FILE (unlike
885 ;;; the old CMU CL code, which accepted multiple files). Also, the old
886 ;;; comment said
887 ;;; When we open a new file, we also reset *PACKAGE* and policy.
888 ;;; This gives the effect of rebinding around each file.
889 ;;; which doesn't seem to be true now. Check to make sure that if
890 ;;; such rebinding is necessary, it's still done somewhere.
891 ;;; FIXME: We will want to have a way to process multiple files again
892 ;;; for the sake of block compilation.
893 (defun get-source-stream (info)
894 (declare (type source-info info))
895 (or (source-info-stream info)
896 (let* ((file-info (source-info-file-info info))
897 (pathname (file-info-pathname file-info))
898 (external-format (file-info-external-format file-info)))
899 (let ((stream
900 (open pathname
901 :direction :input
902 :external-format external-format
903 ;; SBCL stream classes aren't available in the host
904 #-sb-xc-host :class
905 #-sb-xc-host 'form-tracking-stream)))
906 ;; If you don't want merged pathnames embedded in your build artifacts,
907 ;; then you surely don't want them in *COMPILE-FILE-PATHNAME* either.
908 ;; [And can't we just bind this to PATHNAME is all cases? If anything,
909 ;; it seems to me that asking the stream for its name is expressly backwards]
910 (setf *compile-file-pathname* (if *merge-pathnames* (pathname stream) pathname)
911 *compile-file-truename* (truename stream)
912 (file-info-truename file-info) *compile-file-truename*)
913 (when (file-info-subforms file-info)
914 (setf (form-tracking-stream-observer stream)
915 (make-form-tracking-stream-observer file-info)))
916 (setf (source-info-stream info) stream)
917 ;; This used to happen before opening the file, which
918 ;; inhibited lazy computation of the truename, and was a
919 ;; minor time-of-check-vs-time-of-use mistake. It doesn't
920 ;; seem worthwhile to pass the verbose bit down from C-F,
921 ;; however.
922 (when *compile-verbose*
923 (print-compile-start-note info))
924 stream))))
926 ;;; Close the stream in INFO if it is open.
927 (defun close-source-info (info)
928 (declare (type source-info info))
929 (let ((stream (source-info-stream info)))
930 (when stream (close stream)))
931 (setf (source-info-stream info) nil)
932 (values))
934 ;; Loop over forms read from INFO's stream, calling FUNCTION with each.
935 ;; CONDITION-NAME is signaled if there is a reader error, and should be
936 ;; a subtype of not-so-aptly-named INPUT-ERROR-IN-COMPILE-FILE.
937 (defun %do-forms-from-info (function info condition-name)
938 (declare (function function))
939 (declare (dynamic-extent function))
940 (let* ((file-info (source-info-file-info info))
941 (stream (get-source-stream info))
942 (pos (file-position stream))
943 (form
944 ;; Return a form read from STREAM; or for EOF use the trick,
945 ;; popularized by Kent Pitman, of returning STREAM itself.
946 (handler-case
947 (progn
948 ;; Reset for a new toplevel form.
949 (when (form-tracking-stream-p stream)
950 (setf (form-tracking-stream-form-start-char-pos stream) nil))
951 (awhen (file-info-subforms file-info)
952 (setf (fill-pointer it) 0))
953 (read-preserving-whitespace stream nil stream))
954 (reader-error (condition)
955 (compiler-error condition-name
956 ;; We don't need to supply :POSITION here because
957 ;; READER-ERRORs already know their position in the file.
958 :condition condition
959 :stream stream))
960 ;; ANSI, in its wisdom, says that READ should return END-OF-FILE
961 ;; (and that this is not a READER-ERROR) when it encounters end of
962 ;; file in the middle of something it's trying to read,
963 ;; making it unfortunately indistinguishable from legal EOF.
964 ;; Were it not for that, it would be more elegant to just
965 ;; handle one more condition in the HANDLER-CASE.
966 ((or end-of-file error) (condition)
967 (compiler-error
968 condition-name
969 :condition condition
970 ;; We need to supply :POSITION here because the END-OF-FILE
971 ;; condition doesn't carry the position that the user
972 ;; probably cares about, where the failed READ began.
973 :position
974 (or (and (form-tracking-stream-p stream)
975 (form-tracking-stream-form-start-byte-pos stream))
976 pos)
977 :line/col
978 (and (form-tracking-stream-p stream)
979 (line/col-from-charpos
980 stream
981 (form-tracking-stream-form-start-char-pos stream)))
982 :stream stream)))))
983 (unless (eq form stream) ; not EOF
984 (funcall function form
985 :current-index
986 (let* ((forms (file-info-forms file-info))
987 (current-idx (fill-pointer forms)))
988 (vector-push-extend form forms)
989 (vector-push-extend pos (file-info-positions file-info))
990 current-idx))
991 (%do-forms-from-info function info condition-name))))
993 ;;; Loop over FORMS retrieved from INFO. Used by COMPILE-FILE and
994 ;;; LOAD when loading from a FILE-STREAM associated with a source
995 ;;; file. ON-ERROR is the name of a condition class that should
996 ;;; be signaled if anything goes wrong during a READ.
997 (defmacro do-forms-from-info (((form &rest keys) info
998 &optional (on-error ''input-error-in-load))
999 &body body)
1000 (aver (symbolp form))
1001 `(%do-forms-from-info (lambda (,form &key ,@keys &allow-other-keys)
1002 ,@body)
1003 ,info ,on-error))
1005 ;;; Return the INDEX'th source form read from INFO and the position
1006 ;;; where it was read.
1007 (defun find-source-root (index info)
1008 (declare (type index index) (type source-info info))
1009 (let ((file-info (source-info-file-info info)))
1010 (values (aref (file-info-forms file-info) index)
1011 (aref (file-info-positions file-info) index))))
1013 ;;;; processing of top level forms
1015 ;;; This is called by top level form processing when we are ready to
1016 ;;; actually compile something. If (BLOCK-COMPILE *COMPILATION*) is T,
1017 ;;; then we still convert the form, but delay compilation, pushing the result
1018 ;;; on (TOPLEVEL-LAMBDAS *COMPILATION*) instead.
1020 ;;; The policy at this time becomes the default policy for compiling
1021 ;;; the form. Any enclosed PROCLAIMs will affect only subsequent
1022 ;;; forms.
1023 (defun convert-and-maybe-compile (form path)
1024 (declare (list path))
1025 #+sb-xc-host
1026 (when sb-cold::*compile-for-effect-only*
1027 (return-from convert-and-maybe-compile))
1028 ;; Don't bother to compile simple objects that just sit there.
1029 (when (and form (or (symbolp form) (consp form)))
1030 (let* ((*lexenv* (make-lexenv
1031 :policy *policy*
1032 :handled-conditions *handled-conditions*
1033 :disabled-package-locks *disabled-package-locks*))
1034 (tll (ir1-toplevel form path nil)))
1035 (if (eq (block-compile *compilation*) t)
1036 (let ((compilation *compilation*))
1037 (push tll (toplevel-lambdas compilation))
1038 (when (package-environment-changed compilation)
1039 (finish-block-compilation)
1040 (setf (block-compile compilation) t)
1041 (setf (package-environment-changed compilation) nil)))
1042 (compile-toplevel (list tll) nil))
1043 nil)))
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*)))
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)))
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 (let* ((*lexenv* (process-decls decls vars funs))
1081 ;; FIXME: VALUES declaration
1083 ;; Binding *POLICY* is pretty much of a hack, since it
1084 ;; causes LOCALLY to "capture" enclosed proclamations. It
1085 ;; is necessary because CONVERT-AND-MAYBE-COMPILE uses the
1086 ;; value of *POLICY* as the policy. The need for this hack
1087 ;; is due to the quirk that there is no way to represent in
1088 ;; a POLICY that an optimize quality came from the default.
1090 ;; FIXME: Ideally, something should be done so that DECLAIM
1091 ;; inside LOCALLY works OK. Failing that, at least we could
1092 ;; issue a warning instead of silently screwing up.
1093 ;; Here's how to fix this: a POLICY object can in fact represent
1094 ;; absence of qualitities. Whenever we rebind *POLICY* (here and
1095 ;; elsewhere), it should be bound to a policy that expresses no
1096 ;; qualities. Proclamations should update SYMBOL-GLOBAL-VALUE of
1097 ;; *POLICY*, which can be seen irrespective of dynamic bindings,
1098 ;; and declarations should update the lexical policy.
1099 ;; The POLICY macro can be amended to merge the dynamic *POLICY*
1100 ;; (or whatever it came from, like a LEXENV) with the global
1101 ;; *POLICY*. COERCE-TO-POLICY can do the merge, employing a 1-line
1102 ;; cache so that repeated calls for any two fixed policy objects
1103 ;; return the identical value (since policies are immutable).
1104 (*policy* (lexenv-policy *lexenv*))
1105 ;; This is probably also a hack
1106 (*handled-conditions* (lexenv-handled-conditions *lexenv*))
1107 ;; ditto
1108 (*disabled-package-locks* (lexenv-disabled-package-locks *lexenv*)))
1109 (process-toplevel-progn forms path compile-time-too))))
1111 ;;; Parse an EVAL-WHEN situations list, returning three flags,
1112 ;;; (VALUES COMPILE-TOPLEVEL LOAD-TOPLEVEL EXECUTE), indicating
1113 ;;; the types of situations present in the list.
1114 (defun parse-eval-when-situations (situations)
1115 (when (or (not (listp situations))
1116 (set-difference situations
1117 '(:compile-toplevel
1118 compile
1119 :load-toplevel
1120 load
1121 :execute
1122 eval)))
1123 (compiler-error "bad EVAL-WHEN situation list: ~S" situations))
1124 (let ((deprecated-names (intersection situations '(compile load eval))))
1125 (when deprecated-names
1126 (style-warn "using deprecated EVAL-WHEN situation names~{ ~S~}"
1127 deprecated-names)))
1128 (values (intersection '(:compile-toplevel compile)
1129 situations)
1130 (intersection '(:load-toplevel load) situations)
1131 (intersection '(:execute eval) situations)))
1133 ;;; Print some noise about FORM if *COMPILE-PRINT* is true.
1134 (defun note-top-level-form (form)
1135 (when *compile-print*
1136 (let ((*print-length* 2)
1137 (*print-level* 2)
1138 (*print-pretty* nil))
1139 (with-compiler-io-syntax
1140 (compiler-mumble "~&; processing ~S" form)))))
1142 ;;; Handle the evaluation the a :COMPILE-TOPLEVEL body during
1143 ;;; compilation. Normally just evaluate in the appropriate
1144 ;;; environment, but also compile if outputting a CFASL.
1145 (defun eval-compile-toplevel (body path)
1146 (let ((*compile-time-eval* t))
1147 (flet ((frob ()
1148 (eval-tlf `(progn ,@body) (source-path-tlf-number path) *lexenv*)
1149 (awhen (compile-toplevel-object *compilation*)
1150 (let ((*compile-object* it))
1151 (convert-and-maybe-compile `(progn ,@body) path)))))
1152 (if (null *macro-policy*)
1153 (frob)
1154 ;; Macro policy is such a kludge. Most of the effect is conferred by
1155 ;; injecting declarations into any sexpr coming from MAKE-MACRO-LAMBDA.
1156 ;; But that's not enough - we need all code in EVAL-WHEN :COMPILE-TOPLEVEL
1157 ;; situations to run under the macro policy. This somewhat works by binding
1158 ;; *LEXENV*, but fails anywhere we use MAKE-NULL-LEXENV, which sees only
1159 ;; the policy in *POLICY* from the perspective of that lexenv.
1160 ;; So we have to change *POLICY* also, but without binding it, because
1161 ;; binding prevents toplevel DECLAIMs from taking effect. As a workaround,
1162 ;; we assign *POLICY* but restore the original qualities whose values
1163 ;; were present in the macro policy.
1164 ;; e.g:
1165 ;; - macro policy of (safety 3)
1166 ;; - global policy of (safety 0) and (store-coverage-data 3)
1167 ;; - some file wants to declaim (safety 1) (store-coverage-data 0)
1168 ;; So because the DECLAIM is an EVAL-WHEN :COMPILE-TOPLEVEL with a macro policy,
1169 ;; we would try to restore *POLICY* to (safety 0) (store-coverage-data 3)
1170 ;; immediately after eval'ing the DECLAIM, making it totally effectless.
1171 (let ((new-policy (process-optimize-decl
1172 `(optimize ,@(policy-to-decl-spec *macro-policy*))
1173 (lexenv-policy *lexenv*)))
1174 (old-policy *policy*))
1175 (unwind-protect
1176 (let ((*lexenv* (make-lexenv :policy new-policy :default *lexenv*)))
1177 (setf (saved-optimize-decls *compilation*) nil)
1178 (setq *policy* new-policy)
1179 (frob))
1180 ;; There are other ways to do this. e.g.: only save a declaim if it contained
1181 ;; a quality names intersecting with the ones in macro policy; then don't
1182 ;; restore everything to the start sate, merely undo changes from macro-policy,
1183 ;; but keeping the changes that were expressed by toplevel forms.
1184 ;; This is easiest and I really don't care to think about it.
1185 (let ((saved (saved-optimize-decls *compilation*)))
1186 (setf (saved-optimize-decls *compilation*) :none)
1187 (dolist (expr (nreverse saved)) ;; seldom anything here
1188 (setq old-policy (process-optimize-decl expr old-policy)))
1189 (setq *policy* old-policy))))))))
1191 ;;; Process a top level FORM with the specified source PATH.
1192 ;;; * If this is a magic top level form, then do stuff.
1193 ;;; * If this is a macro, then expand it.
1194 ;;; * Otherwise, just compile it.
1196 ;;; COMPILE-TIME-TOO is as defined in ANSI
1197 ;;; "3.2.3.1 Processing of Top Level Forms".
1198 (defun process-toplevel-form (form path compile-time-too)
1199 (declare (list path))
1201 (catch 'process-toplevel-form-error-abort
1202 (let* ((path (or (get-source-path form) (cons form path)))
1203 (*current-path* path)
1204 (*compiler-error-bailout*
1205 (lambda (&optional condition)
1206 (convert-and-maybe-compile
1207 (make-compiler-error-form condition form)
1208 path)
1209 (throw 'process-toplevel-form-error-abort nil)))
1210 (*top-level-form-p* t))
1211 (case (if (listp form) (car form))
1212 ((eval-when macrolet symbol-macrolet) ; things w/ 1 arg before body
1213 (unless (cdr form)
1214 (compiler-error "~S form is too short: ~S" (car form) form))
1215 (destructuring-bind (special-operator magic &rest body) form
1216 (ecase special-operator
1217 ((eval-when)
1218 ;; CT, LT, and E here are as in Figure 3-7 of ANSI
1219 ;; "3.2.3.1 Processing of Top Level Forms".
1220 (multiple-value-bind (ct lt e) (parse-eval-when-situations magic)
1221 (let ((new-compile-time-too (or ct (and compile-time-too e))))
1222 (cond (lt
1223 (process-toplevel-progn body path new-compile-time-too))
1224 (new-compile-time-too
1225 (eval-compile-toplevel body path))))))
1226 ((macrolet)
1227 (funcall-in-macrolet-lexenv
1228 magic
1229 (lambda (&optional funs)
1230 (process-toplevel-locally body path compile-time-too :funs funs))
1231 :compile))
1232 ((symbol-macrolet)
1233 (funcall-in-symbol-macrolet-lexenv
1234 magic
1235 (lambda (&optional vars)
1236 (process-toplevel-locally body path compile-time-too :vars vars))
1237 :compile)))))
1238 ((locally)
1239 (process-toplevel-locally (rest form) path compile-time-too))
1240 ((progn)
1241 (process-toplevel-progn (rest form) path compile-time-too))
1243 (let ((expanded (preprocessor-macroexpand-1 form)))
1244 (cond ((neq expanded form) ; macro -> take it from the top
1245 (process-toplevel-form expanded path compile-time-too))
1247 (when compile-time-too
1248 (eval-compile-toplevel (list form) path))
1249 (let (*top-level-form-p*)
1250 (convert-and-maybe-compile form path)))))))))
1252 (values))
1254 (defun copy-hash-table (hash-table)
1255 (let ((new (make-hash-table :test (hash-table-test hash-table)
1256 :size (hash-table-size hash-table))))
1257 (maphash (lambda (key value)
1258 (setf (gethash key new) value))
1259 hash-table)
1260 new))
1262 ;;;; load time value support
1263 ;;;;
1264 ;;;; (See EMIT-MAKE-LOAD-FORM.)
1266 ;;; Return T if we are currently producing a fasl file and hence
1267 ;;; constants need to be dumped carefully.
1268 (declaim (inline producing-fasl-file))
1269 (defun producing-fasl-file ()
1270 (fasl-output-p *compile-object*))
1272 ;;; Compile FORM and arrange for it to be called at load-time. Return
1273 ;;; the dumper handle and our best guess at the type of the object.
1274 ;;; TODO: We could use a bytecode compiler here to produce smaller
1275 ;;; code. Same goes for top level code.
1276 (defun compile-load-time-value (form)
1277 (let ((lambda (compile-load-time-stuff form t)))
1278 (values (fasl-dump-load-time-value-lambda lambda *compile-object*)
1279 (let ((type (leaf-type lambda)))
1280 (if (fun-type-p type)
1281 (single-value-type (fun-type-returns type))
1282 *wild-type*)))))
1284 ;;; Compile the FORMS and arrange for them to be called (for effect,
1285 ;;; not value) at load time.
1286 (defun compile-make-load-form-init-forms (forms)
1287 (let ((lambda (compile-load-time-stuff `(progn ,@forms) nil)))
1288 (fasl-dump-toplevel-lambda-call lambda *compile-object*)))
1290 ;;; Do the actual work of COMPILE-LOAD-TIME-VALUE or
1291 ;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS.
1292 (defun compile-load-time-stuff (form for-value)
1293 ;; We want to force top level lambdas before any recursive IR1
1294 ;; namespacing happens. Therefore, we need to force here as well as
1295 ;; in EMIT-MAKE-LOAD-FORMS, since we could enter recursive IR1
1296 ;; namespacing through either function.
1297 (compile-toplevel-lambdas () t)
1298 (with-ir1-namespace
1299 (let* ((*lexenv* (make-null-lexenv))
1300 (lambda (ir1-toplevel form *current-path* for-value nil)))
1301 (compile-toplevel (list lambda) t)
1302 lambda)))
1304 ;;; This is called by COMPILE-TOPLEVEL when it was passed T for
1305 ;;; LOAD-TIME-VALUE-P (which happens in COMPILE-LOAD-TIME-STUFF). We
1306 ;;; don't try to combine this component with anything else and frob
1307 ;;; the name. If not in a :TOPLEVEL component, then don't bother
1308 ;;; compiling, because it was merged with a run-time component.
1309 (defun compile-load-time-value-lambda (lambdas)
1310 (aver (null (cdr lambdas)))
1311 (let* ((lambda (car lambdas))
1312 (component (lambda-component lambda)))
1313 (when (eql (component-kind component) :toplevel)
1314 (setf (component-name component) (leaf-debug-name lambda))
1315 (compile-component component)
1316 (clear-ir1-info component))))
1319 ;;; The entry point for MAKE-LOAD-FORM support. When IR1 conversion
1320 ;;; finds a constant structure, it invokes this to arrange for proper
1321 ;;; dumping. If it turns out that the constant has already been
1322 ;;; dumped, then we don't need to do anything.
1324 ;;; If the constant hasn't been dumped, then we check to see whether
1325 ;;; we are in the process of creating it. We detect this by
1326 ;;; maintaining the special *CONSTANTS-BEING-CREATED* as a list of all
1327 ;;; the constants we are in the process of creating. Actually, each
1328 ;;; entry is a list of the constant and any init forms that need to be
1329 ;;; processed on behalf of that constant.
1331 ;;; It's not necessarily an error for this to happen. If we are
1332 ;;; processing the init form for some object that showed up *after*
1333 ;;; the original reference to this constant, then we just need to
1334 ;;; defer the processing of that init form. To detect this, we
1335 ;;; maintain *CONSTANTS-CREATED-SINCE-LAST-INIT* as a list of the
1336 ;;; constants created since the last time we started processing an
1337 ;;; init form. If the constant passed to emit-make-load-form shows up
1338 ;;; in this list, then there is a circular chain through creation
1339 ;;; forms, which is an error.
1341 ;;; If there is some intervening init form, then we blow out of
1342 ;;; processing it by throwing to the tag PENDING-INIT. The value we
1343 ;;; throw is the entry from *CONSTANTS-BEING-CREATED*. This is so the
1344 ;;; offending init form can be tacked onto the init forms for the
1345 ;;; circular object.
1347 ;;; If the constant doesn't show up in *CONSTANTS-BEING-CREATED*, then
1348 ;;; we have to create it. We call MAKE-LOAD-FORM and check if the
1349 ;;; result comes from MAKE-LOAD-FORM-SAVING-SLOTS, and if so we don't
1350 ;;; do anything. The dumper will eventually get its hands on the
1351 ;;; object and use the normal structure dumping noise on it.
1353 ;;; Otherwise, we bind *CONSTANTS-BEING-CREATED* and
1354 ;;; *CONSTANTS-CREATED-SINCE- LAST-INIT* and compile the creation form
1355 ;;; much the way LOAD-TIME-VALUE does. When this finishes, we tell the
1356 ;;; dumper to use that result instead whenever it sees this constant.
1358 ;;; Now we try to compile the init form. We bind
1359 ;;; *CONSTANTS-CREATED-SINCE-LAST-INIT* to NIL and compile the init
1360 ;;; form (and any init forms that were added because of circularity
1361 ;;; detection). If this works, great. If not, we add the init forms to
1362 ;;; the init forms for the object that caused the problems and let it
1363 ;;; deal with it.
1364 (defvar *constants-being-created*)
1365 (defvar *constants-created-since-last-init*)
1366 (defun emit-make-load-form (constant &aux (constants-being-created
1367 (if (boundp '*constants-being-created*)
1368 *constants-being-created*))
1369 (constants-created-since-last-init
1370 (if (boundp '*constants-created-since-last-init*)
1371 *constants-created-since-last-init*))
1372 (fasl *compile-object*))
1373 (aver (fasl-output-p fasl))
1374 (unless (fasl-constant-already-dumped-p constant fasl)
1375 (let ((circular-ref (assoc constant constants-being-created :test #'eq)))
1376 (when circular-ref
1377 (when (find constant constants-created-since-last-init :test #'eq)
1378 (throw constant t))
1379 (throw 'pending-init circular-ref)))
1380 (multiple-value-bind (creation-form init-form)
1381 (handler-case (make-load-form constant (make-null-lexenv))
1382 (error (condition) (sb-c:compiler-error condition)))
1383 (cond
1384 ;; Used mainly as an optimization to avoid dumping internal
1385 ;; compiler data structures (see :IGNORE-IT), and to avoid
1386 ;; unnecessary top level lambda forcing.
1387 ((and (null creation-form) (null init-form))
1388 (dump-fop 'fop-empty-list fasl)
1389 (fasl-note-handle-for-constant constant (dump-pop fasl) fasl)
1390 nil)
1391 ((and
1392 ;; MAKE-LOAD-FORM-SAVING-SLOTS on the cross-compiler needs
1393 ;; the type to be defined for the target.
1394 #+sb-xc-host
1395 (find-classoid (type-of constant) nil)
1396 (multiple-value-bind (ss-creation-form ss-init-form)
1397 (make-load-form-saving-slots constant)
1398 (cond
1399 ((and (typep constant 'structure-object)
1400 (equal creation-form ss-creation-form)
1401 (equal init-form ss-init-form))
1402 (fasl-validate-structure constant fasl)
1404 ((and (not (typep constant 'structure-object))
1405 (equal creation-form ss-creation-form)
1406 (subsetp (rest init-form) (rest ss-init-form) :test #'equal))
1407 (collect ((slot-names))
1408 (dolist (init (rest init-form))
1409 (when (eq (first init) 'setf)
1410 (destructuring-bind (slot-value object 'slot-name)
1411 (second init)
1412 (declare (ignore slot-value object quote))
1413 (slot-names slot-name))))
1414 (fasl-note-instance-saves-slots constant (slot-names) fasl))
1415 t)))))
1417 (compile-toplevel-lambdas () t)
1418 (when (fasl-constant-already-dumped-p constant fasl)
1419 (return-from emit-make-load-form nil))
1420 ;; Allow dumping objects that can't be printed
1421 ;; Non-invocation of PRINT-OBJECT is tested by 'mlf.impure-cload.lisp'.
1422 (let* ((name #+sb-xc-host 'blobby ; the name means nothing
1423 #-sb-xc-host
1424 (format nil "the-~A-formerly-known-as-~X"
1425 (type-of constant)
1426 (get-lisp-obj-address constant)))
1427 (info (if init-form
1428 (list constant name init-form)
1429 (list constant))))
1430 (let ((*constants-being-created* (cons info constants-being-created))
1431 (*constants-created-since-last-init*
1432 (cons constant constants-created-since-last-init)))
1433 (when
1434 (catch constant
1435 (fasl-note-handle-for-constant
1436 constant
1437 (compile-load-time-value creation-form)
1438 fasl)
1439 nil)
1440 (compiler-error "circular references in creation form for ~S"
1441 constant)))
1442 (when (cdr info)
1443 (let* ((*constants-created-since-last-init* nil)
1444 (circular-ref
1445 (catch 'pending-init
1446 (loop for (nil form) on (cdr info) by #'cddr
1447 collect form into forms
1448 finally (compile-make-load-form-init-forms forms))
1449 nil)))
1450 (when circular-ref
1451 (setf (cdr circular-ref)
1452 (append (cdr circular-ref) (cdr info)))))))
1453 nil)))))
1456 ;;;; COMPILE-FILE
1458 ;;; The maximum number of top-level lambdas we put in a single top-level
1459 ;;; component.
1460 (defparameter top-level-lambda-max 20)
1462 (defun object-call-toplevel-lambda (tll)
1463 (declare (type functional tll))
1464 (let ((object *compile-object*))
1465 (etypecase object
1466 (fasl-output (fasl-dump-toplevel-lambda-call tll object))
1467 #-sb-xc-host
1468 (core-object (core-call-toplevel-lambda tll object))
1469 (null))))
1471 ;;; Add LAMBDAS to the pending lambdas. If this leaves more than
1472 ;;; TOP-LEVEL-LAMBDA-MAX lambdas in the list, or if FORCE-P is true,
1473 ;;; then smash the lambdas into a single component, compile it, and
1474 ;;; arrange for the resulting function to be called.
1475 (defun sub-compile-toplevel-lambdas (lambdas force-p)
1476 (declare (list lambdas))
1477 (let ((compilation *compilation*))
1478 (setf (pending-toplevel-lambdas compilation)
1479 (append (pending-toplevel-lambdas compilation) lambdas))
1480 (let ((pending (pending-toplevel-lambdas compilation)))
1481 (when (and pending
1482 (or (> (length pending) top-level-lambda-max)
1483 force-p
1484 (package-environment-changed compilation)))
1485 (multiple-value-bind (component tll)
1486 (merge-toplevel-lambdas pending)
1487 (setf (pending-toplevel-lambdas compilation) ())
1488 (compile-component component)
1489 (clear-ir1-info component)
1490 (object-call-toplevel-lambda tll))
1491 (setf (package-environment-changed compilation) nil))))
1492 (values))
1494 ;;; Compile top level code and call the top level lambdas. We pick off
1495 ;;; top level lambdas in non-top-level components here, calling
1496 ;;; SUB-c-t-l-l on each subsequence of normal top level lambdas.
1497 (defun compile-toplevel-lambdas (lambdas force-p)
1498 (declare (list lambdas))
1499 (let ((len (length lambdas)))
1500 (flet ((loser (start)
1501 (or (position-if (lambda (x)
1502 (not (eq (component-kind
1503 (node-component (lambda-bind x)))
1504 :toplevel)))
1505 lambdas
1506 ;; this used to read ":start start", but
1507 ;; start can be greater than len, which
1508 ;; is an error according to ANSI - CSR,
1509 ;; 2002-04-25
1510 :start (min start len))
1511 len)))
1512 (do* ((start 0 (1+ loser))
1513 (loser (loser start) (loser start)))
1514 ((>= start len)
1515 (when force-p
1516 (sub-compile-toplevel-lambdas nil t)))
1517 (sub-compile-toplevel-lambdas (subseq lambdas start loser)
1518 (or force-p (/= loser len)))
1519 (unless (= loser len)
1520 (object-call-toplevel-lambda (elt lambdas loser))))))
1521 (values))
1523 ;;; Compile LAMBDAS (a list of CLAMBDAs for top level forms) into the
1524 ;;; object file. We loop doing local call analysis until it converges,
1525 ;;; since a single pass might miss something due to components being
1526 ;;; joined by let conversion.
1527 (defun compile-toplevel (lambdas load-time-value-p)
1528 (declare (list lambdas))
1530 (maybe-mumble "Locall ")
1531 (locall-analyze-clambdas-until-done lambdas)
1533 (maybe-mumble "IDFO ")
1534 (multiple-value-bind (components top-components)
1535 (find-initial-dfo lambdas)
1536 (when *check-consistency*
1537 (maybe-mumble "[Check]~%")
1538 (check-ir1-consistency (append components top-components)))
1540 (let ((top-level-closure nil))
1541 (dolist (component components)
1542 (compile-component component)
1543 (when (replace-toplevel-xeps component)
1544 (setq top-level-closure t)))
1546 (when *check-consistency*
1547 (maybe-mumble "[Check]~%")
1548 (check-ir1-consistency (append components top-components)))
1550 (if load-time-value-p
1551 (compile-load-time-value-lambda lambdas)
1552 (compile-toplevel-lambdas lambdas top-level-closure)))
1554 (clear-ir1-namespace))
1555 (values))
1557 ;;; Actually compile any stuff that has been queued up for block
1558 ;;; compilation.
1559 (defun finish-block-compilation ()
1560 (let ((compilation *compilation*))
1561 (when (block-compile compilation)
1562 (when (toplevel-lambdas compilation)
1563 (compile-toplevel (nreverse (toplevel-lambdas compilation)) nil)
1564 (setf (toplevel-lambdas compilation) nil))
1565 (setf (block-compile compilation) :specified)
1566 (setf (entry-points compilation) nil))))
1568 (declaim (ftype function handle-condition-p))
1569 (flet ((get-handled-conditions ()
1570 (if (boundp '*lexenv*)
1571 (let ((ctxt *compiler-error-context*))
1572 (etypecase ctxt
1573 (node
1574 (lexenv-handled-conditions (node-lexenv ctxt)))
1575 (lvar-annotation
1576 (lexenv-handled-conditions (lvar-annotation-lexenv ctxt)))
1577 (compiler-error-context
1578 (compiler-error-context-handled-conditions ctxt))
1579 ;; Is this right? I would think that if lexenv is null
1580 ;; we should look at *HANDLED-CONDITIONS*.
1581 ((or ctran list) (lexenv-handled-conditions *lexenv*))))
1582 *handled-conditions*))
1583 (handle-p (condition type)
1584 #+sb-xc-host (cl:typep condition type) ; TYPE is a sexpr
1585 #-sb-xc-host (%%typep condition type))) ; TYPE is a CTYPE
1586 (declare (inline handle-p))
1588 (defun handle-condition-p (condition)
1589 (dolist (muffle (get-handled-conditions) nil)
1590 (destructuring-bind (type . restart-name) muffle
1591 (when (and (handle-p condition type)
1592 (find-restart restart-name condition))
1593 (return t)))))
1595 (defun handle-condition-handler (condition)
1596 (let ((muffles (get-handled-conditions)))
1597 (aver muffles) ; FIXME: looks redundant with UNREACHABLE
1598 (dolist (muffle muffles (sb-impl::unreachable))
1599 (destructuring-bind (type . restart-name) muffle
1600 (when (handle-p condition type)
1601 (awhen (find-restart restart-name condition)
1602 (invoke-restart it)))))))
1604 ;; WOULD-MUFFLE-P is called (incorrectly) only by NOTE-UNDEFINED-REFERENCE.
1605 ;; It is not wrong per se, but as used, it is wrong, making it nearly
1606 ;; impossible to muffle a subset of undefind warnings whose NAME and KIND
1607 ;; slots match specific things tested by a user-defined predicate.
1608 ;; Attempting to do that might muffle everything, depending on how your
1609 ;; predicate responds to a vanilla WARNING. Consider e.g.
1610 ;; (AND WARNING (NOT (SATISFIES HAIRYFN)))
1611 ;; where HAIRYFN depends on the :FORMAT-CONTROL and :FORMAT-ARGUMENTS.
1612 (defun would-muffle-p (condition)
1613 (let ((ctype (rassoc 'muffle-warning
1614 (lexenv-handled-conditions *lexenv*))))
1615 (and ctype (handle-p condition (car ctype))))))
1617 ;;; Read all forms from INFO and compile them, with output to
1618 ;;; *COMPILE-OBJECT*. Return (VALUES ABORT-P WARNINGS-P FAILURE-P).
1619 (defun sub-compile-file (info cfasl)
1620 (declare (type source-info info))
1621 (let ((*package* (sane-package))
1622 (*readtable* *readtable*)
1623 (*compile-file-pathname* nil) ; set by GET-SOURCE-STREAM
1624 (*compile-file-truename* nil) ; "
1625 (*policy* *policy*)
1626 (*macro-policy* *macro-policy*)
1627 (*source-info* info)
1629 (*compilation*
1630 (make-compilation
1631 :coverage-metadata (cons (make-hash-table :test 'equal)
1632 (make-hash-table :test 'equal))
1633 ;; Whether to emit msan unpoisoning code depends on the runtime
1634 ;; value of the feature, not "#+msan", because we can use the target
1635 ;; compiler to compile code for itself which isn't sanitized,
1636 ;; *or* code for another image which is sanitized.
1637 ;; And we can also cross-compile assuming msan.
1638 :msan-unpoison (member :msan sb-xc:*features*)
1639 :block-compile *block-compile-argument*
1640 :entry-points *entry-points-argument*
1641 :compile-toplevel-object cfasl))
1643 (*handled-conditions* *handled-conditions*)
1644 (*disabled-package-locks* *disabled-package-locks*)
1645 (*lexenv* (make-null-lexenv))
1646 (*allow-instrumenting* nil)
1647 (*compiler-error-bailout*
1648 (lambda (&optional error)
1649 (declare (ignore error))
1650 (return-from sub-compile-file (values t t t))))
1651 (*current-path* nil)
1652 (sb-impl::*eval-source-info* nil)
1653 (sb-impl::*eval-tlf-index* nil)
1654 (sb-impl::*eval-source-context* nil))
1655 (handler-case
1656 (handler-bind (((satisfies handle-condition-p) 'handle-condition-handler))
1657 (with-compilation-values
1658 (with-compilation-unit ()
1659 (fasl-dump-partial-source-info info *compile-object*)
1660 (with-ir1-namespace
1661 (with-source-paths
1662 (do-forms-from-info ((form current-index) info
1663 'input-error-in-compile-file)
1664 (clrhash *source-paths*)
1665 (find-source-paths form current-index)
1666 (note-top-level-form form)
1667 (let ((*gensym-counter* 0))
1668 (process-toplevel-form
1669 form `(original-source-start 0 ,current-index) nil)))
1670 (finish-block-compilation)
1671 (compile-toplevel-lambdas () t)
1672 (let ((object *compile-object*))
1673 (etypecase object
1674 (fasl-output (fasl-dump-source-info info object))
1675 #-sb-xc-host
1676 (core-object (fix-core-source-info info object))
1677 (null)))))
1678 ;; FIXME: dump/restore "linkage" information, produce deferred warnings
1679 ;; (sb-fasl::dump-emitted-full-calls (emitted-full-calls *compilation*)
1680 ;; *compile-object*)
1681 (let ((code-coverage-records
1682 (code-coverage-records (coverage-metadata *compilation*))))
1683 (unless (zerop (hash-table-count code-coverage-records))
1684 ;; Dump the code coverage records into the fasl.
1685 (dump-code-coverage-records
1686 (loop for k being each hash-key of code-coverage-records
1687 collect k)
1688 *compile-object*)))
1689 nil)))
1690 ;; Some errors are sufficiently bewildering that we just fail
1691 ;; immediately, without trying to recover and compile more of
1692 ;; the input file.
1693 (fatal-compiler-error (condition)
1694 (signal condition)
1695 (fresh-line *error-output*)
1696 (pprint-logical-block (*error-output* nil :per-line-prefix "; ")
1697 (format *error-output*
1698 "~@<~@:_compilation aborted because of fatal error: ~2I~_~A~@:_~:>"
1699 (encapsulated-condition condition)))
1700 (finish-output *error-output*)
1701 (values t t t)))))
1703 ;;; Return a pathname for the named file. The file must exist.
1704 (defun verify-source-file (pathname-designator)
1705 (let* ((pathname (pathname pathname-designator))
1706 (default-host (make-pathname :host (pathname-host pathname))))
1707 (flet ((try-with-type (path type error-p)
1708 (let ((new (merge-pathnames
1709 path (make-pathname :type type
1710 :defaults default-host))))
1711 (if (probe-file new)
1713 (and error-p (truename new))))))
1714 (cond ((typep pathname 'logical-pathname)
1715 (try-with-type pathname "LISP" t))
1716 ((probe-file pathname) pathname)
1717 ((try-with-type pathname "lisp" nil))
1718 ((try-with-type pathname "lisp" t))))))
1720 (defun elapsed-time-to-string (internal-time-delta)
1721 (multiple-value-bind (tsec remainder)
1722 (truncate internal-time-delta internal-time-units-per-second)
1723 (let ((ms (truncate remainder (/ internal-time-units-per-second 1000))))
1724 (multiple-value-bind (tmin sec) (truncate tsec 60)
1725 (multiple-value-bind (thr min) (truncate tmin 60)
1726 (format nil "~D:~2,'0D:~2,'0D.~3,'0D" thr min sec ms))))))
1728 ;;; Print some junk at the beginning and end of compilation.
1729 (defun print-compile-start-note (source-info)
1730 (declare (type source-info source-info))
1731 (let ((file-info (source-info-file-info source-info)))
1732 #+sb-xc-host
1733 (compiler-mumble "~&; ~Aing file ~S:~%"
1734 (if sb-cold::*compile-for-effect-only* "load" "x-compil")
1735 (namestring (file-info-pathname file-info)))
1736 #-sb-xc-host
1737 (compiler-mumble "~&; compiling file ~S (written ~A):~%"
1738 (namestring (file-info-pathname file-info))
1739 (format-universal-time nil
1740 (file-info-write-date file-info)
1741 :style :government
1742 :print-weekday nil
1743 :print-timezone nil)))
1744 (values))
1746 (defun print-compile-end-note (source-info won)
1747 (declare (type source-info source-info))
1748 (compiler-mumble "~&; compilation ~:[aborted after~;finished in~] ~A~&"
1750 (elapsed-time-to-string
1751 (- (get-internal-real-time)
1752 (source-info-start-real-time source-info))))
1753 (values))
1755 (defglobal *compile-elapsed-time* 0) ; nanoseconds
1756 (defglobal *compile-file-elapsed-time* 0) ; nanoseconds
1757 (defun get-thread-virtual-time ()
1758 #+(and linux (not sb-xc-host)) (sb-unix:clock-gettime sb-unix:clock-thread-cputime-id)
1759 #-(and linux (not sb-xc-host)) (values 0 0))
1761 (defun accumulate-compiler-time (symbol start-sec start-nsec)
1762 (declare (ignorable symbol start-sec start-nsec))
1763 #+(and linux (not sb-xc-host))
1764 (multiple-value-bind (stop-sec stop-nsec) (get-thread-virtual-time)
1765 (let* ((sec-diff (- stop-sec start-sec))
1766 (nsec-diff (- stop-nsec start-nsec))
1767 (total-nsec-diff (+ (* sec-diff (* 1000 1000 1000))
1768 nsec-diff))
1769 (old (symbol-global-value symbol)))
1770 (loop
1771 ;; FIXME: should we define #'(CAS SYMBOL-GLOBAL-VALUE) ?
1772 ;; Probably want to get it working everywhere first.
1773 (let ((new (+ old total-nsec-diff)))
1774 (when (eq old (setq old
1775 #-x86-64
1776 (cas (symbol-value symbol) old new)
1777 #+x86-64
1778 (%cas-symbol-global-value symbol old new)))
1779 (return)))))))
1781 ;;; Open some files and call SUB-COMPILE-FILE. If something unwinds
1782 ;;; out of the compile, then abort the writing of the output file, so
1783 ;;; that we don't overwrite it with known garbage.
1784 (defun compile-file
1785 (input-file
1786 &key
1788 ;; ANSI options
1789 (output-file "" output-file-p)
1790 ;; We rebind the specials despite such behavior not being mentioned
1791 ;; in CLHS. Several other lisp implementations do this as well.
1792 ((:verbose *compile-verbose*) *compile-verbose*)
1793 ((:print *compile-print*) *compile-print*)
1794 (external-format :default)
1796 ;; extensions
1797 ((:progress *compile-progress*) *compile-progress*)
1798 (trace-file nil)
1799 ((:block-compile *block-compile-argument*)
1800 *block-compile-default*)
1801 ((:entry-points *entry-points-argument*) nil)
1802 (emit-cfasl *emit-cfasl*))
1803 "Compile INPUT-FILE, producing a corresponding fasl file and
1804 returning its filename.
1806 :OUTPUT-FILE
1807 The name of the FASL to output, NIL for none, T for the default.
1808 (Note the difference between the treatment of NIL :OUTPUT-FILE
1809 here and in COMPILE-FILE-PATHNAME.) The returned pathname of the
1810 output file may differ from the pathname of the :OUTPUT-FILE
1811 parameter, e.g. when the latter is a designator for a directory.
1813 :VERBOSE
1814 If true, information indicating what file is being compiled is printed
1815 to *STANDARD-OUTPUT*.
1817 :PRINT
1818 If true, each top level form in the file is printed to *STANDARD-OUTPUT*.
1820 :EXTERNAL-FORMAT
1821 The external format to use when opening the source file.
1823 :BLOCK-COMPILE {NIL | :SPECIFIED | T}
1824 Determines whether multiple functions are compiled together as a unit,
1825 resolving function references at compile time. NIL means that global
1826 function names are never resolved at compilation time. :SPECIFIED means
1827 that names are resolved at compile-time when convenient (as in a
1828 self-recursive call), but the compiler doesn't combine top-level DEFUNs.
1829 With :SPECIFIED, an explicit START-BLOCK declaration will enable block
1830 compilation. A value of T indicates that all forms in the file(s) should
1831 be compiled as a unit. The default is the value of
1832 SB-EXT:*BLOCK-COMPILE-DEFAULT*, which is initially NIL.
1834 :ENTRY-POINTS
1835 This specifies a list of function names for functions in the file(s) that
1836 must be given global definitions. This only applies to block
1837 compilation, and is useful mainly when :BLOCK-COMPILE T is specified on a
1838 file that lacks START-BLOCK declarations. If the value is NIL (the
1839 default) then all functions will be globally defined.
1841 :TRACE-FILE
1842 If given, internal data structures are dumped to the specified
1843 file, or if a value of T is given, to a file of *.trace type
1844 derived from the input file name. (non-standard)
1846 :EMIT-CFASL
1847 (Experimental). If true, outputs the toplevel compile-time effects
1848 of this file into a separate .cfasl file."
1849 (binding*
1850 ((output-file-pathname nil)
1851 (fasl-output nil)
1852 (cfasl-pathname nil)
1853 (cfasl-output nil)
1854 (abort-p t)
1855 (warnings-p nil)
1856 (failure-p t) ; T in case error keeps this from being set later
1857 ((start-sec start-nsec) (get-thread-virtual-time))
1858 (input-pathname (verify-source-file input-file))
1859 (source-info
1860 (make-file-source-info input-pathname external-format
1861 #-sb-xc-host t)) ; can't track, no SBCL streams
1862 (*last-message-count* (list* 0 nil nil))
1863 (*last-error-context* nil)
1864 (*compiler-trace-output* nil)) ; might be modified below
1866 (unwind-protect
1867 (progn
1868 ;; To avoid passing "" as OUTPUT-FILE when unsupplied, we exploit the fact
1869 ;; that COMPILE-FILE-PATHNAME allows random &KEY args.
1870 (setq output-file-pathname
1871 (compile-file-pathname input-file (when output-file-p :output-file) output-file)
1872 fasl-output (open-fasl-output output-file-pathname
1873 (namestring input-pathname)))
1874 (when emit-cfasl
1875 (setq cfasl-pathname (make-pathname :type "cfasl" :defaults output-file-pathname))
1876 (setq cfasl-output (open-fasl-output cfasl-pathname (namestring input-pathname))))
1877 (when trace-file
1878 (setf *compiler-trace-output*
1879 (if (streamp trace-file)
1880 trace-file
1881 (open (merge-pathnames
1882 (if (eql trace-file t) "" trace-file)
1883 (make-pathname :type "trace" :defaults
1884 (fasl-output-stream fasl-output)))
1885 :if-exists :supersede :direction :output))))
1887 (let ((*compile-object* fasl-output))
1888 (setf (values abort-p warnings-p failure-p)
1889 (sub-compile-file source-info cfasl-output))))
1891 (close-source-info source-info)
1893 (when fasl-output
1894 (close-fasl-output fasl-output abort-p)
1895 ;; There was an assignment here
1896 ;; (setq fasl-pathname (pathname (fasl-output-stream fasl-output)))
1897 ;; which seems pretty bogus, because we've computed the fasl-pathname,
1898 ;; and should return exactly what was computed so that it 100% agrees
1899 ;; with what COMPILE-FILE-PATHNAME said we would write into.
1900 ;; A distorted variation of the name coming from the stream is just wrong,
1901 ;; because do not support versioned pathnames.
1902 (when (and (not abort-p) *compile-verbose*)
1903 (compiler-mumble "~2&; wrote ~A~%" (namestring output-file-pathname))))
1905 (when cfasl-output
1906 (close-fasl-output cfasl-output abort-p)
1907 (when (and (not abort-p) *compile-verbose*)
1908 (compiler-mumble "; wrote ~A~%" (namestring cfasl-pathname))))
1910 (when *compile-verbose*
1911 (print-compile-end-note source-info (not abort-p)))
1913 ;; Don't nuke stdout if you use :trace-file *standard-output*
1914 (when (and trace-file (not (streamp trace-file)))
1915 (close *compiler-trace-output*)))
1917 (accumulate-compiler-time '*compile-file-elapsed-time* start-sec start-nsec)
1919 ;; CLHS says that the first value is NIL if the "file could not
1920 ;; be created". We interpret this to mean "a valid fasl could not
1921 ;; be created" -- which can happen if the compilation is aborted
1922 ;; before the whole file has been processed, due to eg. a reader
1923 ;; error.
1924 (values (when (and (not abort-p) output-file)
1925 ;; Again, more bogosity. Why do PROBE-FILE here
1926 ;; when it achieves nothing other than to potentially disagree
1927 ;; with what COMPILE-FILE-PATHNAME returned.
1928 ;; I would guess that the intent of the spec was to not return
1929 ;; pathnames with a wild version component, but it never anticipated
1930 ;; that content-addressable storage would be a thing.
1931 ;; Unfortunately there's no way to give lossless information here
1932 ;; while remaining ANSI-compliant. So let's repurpose the secret
1933 ;; *MERGE-PATHNAMES* option to return pathnames that don't suck.
1934 (or (and *merge-pathnames* (probe-file output-file-pathname))
1935 output-file-pathname))
1936 warnings-p
1937 failure-p)))
1939 ;;; KLUDGE: Part of the ANSI spec for this seems contradictory:
1940 ;;; If INPUT-FILE is a logical pathname and OUTPUT-FILE is unsupplied,
1941 ;;; the result is a logical pathname. If INPUT-FILE is a logical
1942 ;;; pathname, it is translated into a physical pathname as if by
1943 ;;; calling TRANSLATE-LOGICAL-PATHNAME.
1944 ;;; So I haven't really tried to make this precisely ANSI-compatible
1945 ;;; at the level of e.g. whether it returns logical pathname or a
1946 ;;; physical pathname. Patches to make it more correct are welcome.
1947 ;;; -- WHN 2000-12-09
1949 ;;; Issues of logical-pathname handling aside, I checked some other lisps
1950 ;;; to see what they do with the following two examples:
1951 ;;; (COMPILE-FILE "a/b/file.lisp :output-file "x/y/z/")
1952 ;;; (COMPILE-FILE "a/b/file.lisp :output-file "x/y/out")
1953 ;;; and it turns out that they don't implement the spirit of the law,
1954 ;;; forget about the letter of the law. The spirit (intent) is that regardless
1955 ;;; of how pathnames are handled, COMPILE-FILE-PATHNAME should tell you exactly
1956 ;;; what pathname the compiler would write into given the input and output to
1957 ;;; COMPILE-FILE. But they can't even do that much correctly.
1958 ;;; So forget about how merging "should" work - it's a crap shoot at best.
1960 ;;; Clozure 1.10-r16196
1961 ;;; -------------------
1962 ;;; ? (COMPILE-FILE-PATHNAME "a/b/file.lisp" :output-file #p"x/y/z/")
1963 ;;; => #P"a/b/x/y/z/file.lx64fsl" ; ok, so it thinks it merges input and output dirs
1964 ;;; let's confirm by actually compiling:
1965 ;;; ? (COMPILE-FILE "a/b/file.lisp" :output-file #p"x/y/z/")
1966 ;;; #P"/tmp/sbcl/x/y/z/file.lx64fsl" ; no, it didn't actually. it's what I want though
1968 ;;; ECL 16.1.3
1969 ;;; ----------
1970 ;;; (compile-file-pathname "a/b/file.lisp" :output-file #p"x/y/z/")
1971 ;;; #P"x/y/z/" ; ok, maybe it will do additional defaulting to get the name and type?
1972 ;;; (compile-file "a/b/file.lisp" :output-file #p"x/y/z/")
1973 ;;; Internal error:
1974 ;;; ** Pathname without a physical namestring:
1975 ;;; Nope, it won't default them. However:
1976 ;;; (compile-file "a/b/file.lisp" :output-file #p"x/y/z/out")
1977 ;;; => #P"/tmp/sbcl/x/y/z/out"
1978 ;;; so it worked, but it failed to default the file type to '.fas'
1979 ;;; which it would have if nothing were specified.
1981 ;;; ABCL 1.7.1
1982 ;;; ----------
1983 ;;; (compile-file-pathname "a/b/file.lisp" :output-file #p"x/y/z/")
1984 ;;; #P"/tmp/sbcl/a/b/x/y/z/file.lisp" ; OK, so it says it merged input + output dirs
1985 ;;; but it didn't stick on a pathname-type. However
1986 ;;; (compile-file "a/b/file.lisp" :output-file #p"x/y/z/")
1987 ;;; ; Compiling /tmp/sbcl/a/b/file.lisp ...
1988 ;;; #<THREAD "interpreter" {E2B80EB}>: Debugger invoked on condition of type SIMPLE-ERROR
1989 ;;; Pathname has no namestring:
1990 ;;; And now:
1991 ;;; (compile-file "a/b/file.lisp" :output-file #p"x/y/z/out.abcl")
1992 ;;; => #P"/tmp/sbcl/x/y/z/out.abcl" ; so it *didn't* actually merge dirs, which is fine
1994 ;;; But we try our best to give somewhat understandable semantics:
1995 ;;; * strongly prefer that all fasls have a pathname-type
1996 ;;; whether or not the output was specified. However, if you are sadistic
1997 ;;; (and/or enjoy being confusing to others), then :OUTPUT-FILE is permitted
1998 ;;; to have :UNSPECIFIC as the type, and it will lack the '.fasl' suffix.
1999 ;;; * we can accept just a directory for the output (a namestring ending in "/"
2000 ;;; on Unix) and will take the pathname-name from the input
2001 ;;; * we will never merge directories from the input to output
2003 ;;; It is unclear what should happen with
2004 ;;; (compile-file "sys:contrib;foo.lisp" :output-file "obj")
2005 ;;; Is "obj" on the logical host or the physical host?
2007 (defun compile-file-pathname (input-file &key (output-file nil output-file-p)
2008 &allow-other-keys)
2009 "Return a pathname describing what file COMPILE-FILE would write to given
2010 these arguments."
2011 ;; ANSI: The defaults for the OUTPUT-FILE are taken from the pathname
2012 ;; that results from merging the INPUT-FILE with the value of
2013 ;; *DEFAULT-PATHNAME-DEFAULTS*, except that the type component should
2014 ;; default to the appropriate implementation-defined default type for
2015 ;; compiled files.
2016 (let* ((input (pathname input-file))
2017 (output (if output-file-p (pathname output-file)))
2018 (host/dev/dir
2019 (if (or (not output) (memq (pathname-directory output) '(nil :unspecific)))
2020 input output)))
2021 ;; Merging *D-P-D* here is ridiculous, because every pathname is eventually
2022 ;; merged against it.
2023 ;; Users can set it to #P"" around calling this to obtain a lossless answer.
2024 (merge-pathnames
2025 (flet ((pick (slot default &aux (specified (if output (funcall slot output))))
2026 ;; :unspecific is left alone, "as if the field were 'filled'"
2027 ;; (http://www.lispworks.com/documentation/HyperSpec/Body/19_bbbca.htm)
2028 ;; which makes little to zero sense at all for the PATHNAME-NAME
2029 ;; of a fasl file, but is allowable for its PATHNAME-TYPE.
2030 (cond ((or (not specified)
2031 (and (eq specified :unspecific) (eq slot 'pathname-name)))
2032 default)
2034 specified))))
2035 (make-pathname :host (pathname-host host/dev/dir)
2036 :device (pathname-device host/dev/dir)
2037 :directory (pathname-directory host/dev/dir)
2038 :name (pick 'pathname-name (pathname-name input))
2039 :type (pick 'pathname-type *fasl-file-type*))))))
2041 ;;; FIXME: find a better place for this.
2042 (defun always-boundp (name)
2043 (case (info :variable :always-bound name)
2044 (:always-bound t)
2045 ;; Compiling to fasl considers a symbol always-bound if its
2046 ;; :always-bound info value is now T or will eventually be T.
2047 (:eventually (producing-fasl-file))))