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