/
main.lisp
2048 lines (1862 loc) · 91.6 KB
/
main.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;;; the top level interfaces to the compiler
;;;; This software is part of the SBCL system. See the README file for
;;;; more information.
;;;;
;;;; This software is derived from the CMU CL system, which was
;;;; written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-C")
(defvar *block-compile-default* nil
"The default value for the :Block-Compile argument to COMPILE-FILE.")
;;; *BLOCK-COMPILE-ARGUMENT* holds the original value of the :BLOCK-COMPILE
;;; argument, which overrides any internal declarations.
(defvar *block-compile-argument*)
(declaim (type (member nil t :specified)
*block-compile-default* *block-compile-argument*))
(defvar *entry-points-argument*)
(declaim (type list *entry-points-argument*))
(defvar *check-consistency* nil)
(defvar *compile-verbose* t
"The default for the :VERBOSE argument to COMPILE-FILE.")
(defvar *compile-print* nil
"The default for the :PRINT argument to COMPILE-FILE.")
(defvar *compile-progress* nil
"When this is true, the compiler prints to *STANDARD-OUTPUT* progress
information about the phases of compilation of each function. (This
is useful mainly in large block compilations.)")
(defvar *compile-file-pathname* nil
"The defaulted pathname of the file currently being compiled, or NIL if not
compiling.")
(defvar *compile-file-truename* nil
"The TRUENAME of the file currently being compiled, or NIL if not
compiling.")
(declaim (type (or pathname null)
*compile-file-pathname*
*compile-file-truename*))
;;; the SOURCE-INFO structure for the current compilation. This is
;;; null globally to indicate that we aren't currently in any
;;; identifiable compilation.
(defvar *source-info* nil)
;;; This is true if we are within a WITH-COMPILATION-UNIT form (which
;;; normally causes nested uses to be no-ops).
(defvar *in-compilation-unit* nil)
;;; Count of the number of compilation units dynamically enclosed by
;;; the current active WITH-COMPILATION-UNIT that were unwound out of.
(defvar *aborted-compilation-unit-count*)
;;; Mumble conditional on *COMPILE-PROGRESS*.
(defun maybe-mumble (&rest foo)
(when *compile-progress*
(apply #'compiler-mumble foo)))
(deftype object () '(or fasl-output #-sb-xc-host core-object null))
(defvar *compile-object* nil)
(declaim (type object *compile-object*))
(defvar *emit-cfasl* nil)
(declaim (inline code-coverage-records code-coverage-blocks))
;; Used during compilation to map code paths to the matching
;; instrumentation conses.
(defun code-coverage-records (x) (car x))
;; Used during compilation to keep track of with source paths have been
;; instrumented in which blocks.
(defun code-coverage-blocks (x) (cdr x))
;;;; WITH-COMPILATION-UNIT and WITH-COMPILATION-VALUES
(defmacro with-compilation-unit (options &body body)
"Affects compilations that take place within its dynamic extent. It is
intended to be eg. wrapped around the compilation of all files in the same system.
Following options are defined:
:OVERRIDE Boolean-Form
One of the effects of this form is to delay undefined warnings until the
end of the form, instead of giving them at the end of each compilation.
If OVERRIDE is NIL (the default), then the outermost
WITH-COMPILATION-UNIT form grabs the undefined warnings. Specifying
OVERRIDE true causes that form to grab any enclosed warnings, even if it
is enclosed by another WITH-COMPILATION-UNIT.
:POLICY Optimize-Declaration-Form
Provides dynamic scoping for global compiler optimization qualities and
restrictions, limiting effects of subsequent OPTIMIZE proclamations and
calls to SB-EXT:RESTRICT-COMPILER-POLICY to the dynamic scope of BODY.
If OVERRIDE is false, specified POLICY is merged with current global
policy. If OVERRIDE is true, current global policy, including any
restrictions, is discarded in favor of the specified POLICY.
Supplying POLICY NIL is equivalent to the option not being supplied at
all, ie. dynamic scoping of policy does not take place.
This option is an SBCL-specific experimental extension: Interface
subject to change.
:SOURCE-NAMESTRING Namestring-Form
Attaches the value returned by the Namestring-Form to the internal
debug-source information as the namestring of the source file. Normally
the namestring of the input-file for COMPILE-FILE is used: this option
can be used to provide source-file information for functions compiled
using COMPILE, or to override the input-file of COMPILE-FILE.
If both an outer and an inner WITH-COMPILATION-UNIT provide a
SOURCE-NAMESTRING, the inner one takes precedence. Unaffected
by :OVERRIDE.
This is an SBCL-specific extension.
:SOURCE-PLIST Plist-Form
Attaches the value returned by the Plist-Form to internal debug-source
information of functions compiled in within the dynamic extent of BODY.
Primarily for use by development environments, in order to eg. associate
function definitions with editor-buffers. Can be accessed using
SB-INTROSPECT:DEFINITION-SOURCE-PLIST.
If an outer WITH-COMPILATION-UNIT form also provide a SOURCE-PLIST, it
is appended to the end of the provided SOURCE-PLIST. Unaffected
by :OVERRIDE.
This is an SBCL-specific extension.
Examples:
;; Prevent proclamations from the file leaking, and restrict
;; SAFETY to 3 -- otherwise uses the current global policy.
(with-compilation-unit (:policy '(optimize))
(restrict-compiler-policy 'safety 3)
(load \"foo.lisp\"))
;; Using default policy instead of the current global one,
;; except for DEBUG 3.
(with-compilation-unit (:policy '(optimize debug)
:override t)
(load \"foo.lisp\"))
;; Same as if :POLICY had not been specified at all: SAFETY 3
;; proclamation leaks out from WITH-COMPILATION-UNIT.
(with-compilation-unit (:policy nil)
(declaim (optimize safety))
(load \"foo.lisp\"))
"
`(%with-compilation-unit (lambda () ,@body) ,@options))
(defvar *source-plist* nil)
(defvar *source-namestring* nil)
(defun %with-compilation-unit (fn &key override policy source-plist source-namestring)
(declare (type function fn))
(declare (dynamic-extent fn))
(flet ((with-it ()
(let ((succeeded-p nil)
(*source-plist* (append source-plist *source-plist*))
(*source-namestring*
(awhen (or source-namestring *source-namestring*)
(possibly-base-stringize it))))
(if (and *in-compilation-unit* (not override))
;; Inside another WITH-COMPILATION-UNIT, a WITH-COMPILATION-UNIT is
;; ordinarily (unless OVERRIDE) basically a no-op.
(unwind-protect
(multiple-value-prog1 (funcall fn) (setf succeeded-p t))
(unless succeeded-p
(incf *aborted-compilation-unit-count*)))
(let ((*aborted-compilation-unit-count* 0)
(*compiler-error-count* 0)
(*compiler-warning-count* 0)
(*compiler-style-warning-count* 0)
(*compiler-note-count* 0)
(*undefined-warnings* nil)
*argument-mismatch-warnings*
*methods-in-compilation-unit*
(*in-compilation-unit* t))
(handler-bind ((parse-unknown-type
(lambda (c)
(note-undefined-reference
(parse-unknown-type-specifier c)
:type))))
(unwind-protect
(multiple-value-prog1 (funcall fn) (setf succeeded-p t))
(unless succeeded-p
(incf *aborted-compilation-unit-count*))
(summarize-compilation-unit (not succeeded-p)))))))))
(if policy
(let ((*policy* (process-optimize-decl policy (unless override *policy*)))
(*policy-min* (unless override *policy-min*))
(*policy-max* (unless override *policy-max*)))
(with-it))
(with-it))))
;;; Is NAME something that no conforming program can rely on
;;; defining?
(defun name-reserved-by-ansi-p (name kind)
(declare (ignorable name kind))
#-sb-xc-host ; always return NIL in the cross-compiler
(ecase kind
(:function
(eq (sb-xc:symbol-package (fun-name-block-name name))
*cl-package*))
(:type
(let ((symbol (typecase name
(symbol name)
((cons symbol) (car name))
(t (return-from name-reserved-by-ansi-p nil)))))
(eq (sb-xc:symbol-package symbol) *cl-package*)))))
;;; This is to be called at the end of a compilation unit. It signals
;;; any residual warnings about unknown stuff, then prints the total
;;; error counts. ABORT-P should be true when the compilation unit was
;;; aborted by throwing out. ABORT-COUNT is the number of dynamically
;;; enclosed nested compilation units that were aborted.
(defun summarize-compilation-unit (abort-p)
(let (summary)
(unless abort-p
(let ((undefs (sort *undefined-warnings* #'string<
:key (lambda (x)
(let ((x (undefined-warning-name x)))
(if (symbolp x)
(symbol-name x)
(prin1-to-string x))))))
(*last-message-count* (list* 0 nil nil))
(*last-error-context* nil))
(handler-bind ((style-warning #'compiler-style-warning-handler)
(warning #'compiler-warning-handler))
(report-key-arg-mismatches)
(dolist (kind '(:variable :function :type))
(let ((names (mapcar #'undefined-warning-name
(remove kind undefs :test #'neq
:key #'undefined-warning-kind))))
(when names (push (cons kind names) summary))))
(dolist (undef undefs)
(let ((name (undefined-warning-name undef))
(kind (undefined-warning-kind undef))
(warnings (undefined-warning-warnings undef))
(undefined-warning-count (undefined-warning-count undef)))
(dolist (*compiler-error-context* warnings)
(if (and (member kind '(:function :type))
(name-reserved-by-ansi-p name kind))
(ecase kind
(:function
(compiler-warn
"~@<The function ~S is undefined, and its name is ~
reserved by ANSI CL so that even if it were ~
defined later, the code doing so would not be ~
portable.~:@>" name))
(:type
(if (and (consp name) (eq 'quote (car name)))
(compiler-warn
"~@<Undefined type ~S. The name starts with ~S: ~
probably use of a quoted type name in a context ~
where the name is not evaluated.~:@>"
name 'quote)
(compiler-warn
"~@<Undefined type ~S. Note that name ~S is ~
reserved by ANSI CL, so code defining a type with ~
that name would not be portable.~:@>" name
name))))
(funcall
(if (eq kind :variable) #'compiler-warn #'compiler-style-warn)
(sb-format:tokens "undefined ~(~A~): ~/sb-ext:print-symbol-with-prefix/")
kind name)))
(let ((warn-count (length warnings)))
(when (and warnings (> undefined-warning-count warn-count))
(let ((more (- undefined-warning-count warn-count)))
(if (eq kind :variable)
(compiler-warn
"~W more use~:P of undefined ~(~A~) ~S"
more kind name)
(compiler-style-warn
"~W more use~:P of undefined ~(~A~) ~S"
more kind name))))))))))
(unless (and (not abort-p)
(zerop *aborted-compilation-unit-count*)
(zerop *compiler-error-count*)
(zerop *compiler-warning-count*)
(zerop *compiler-style-warning-count*)
(zerop *compiler-note-count*))
(fresh-line *error-output*)
(pprint-logical-block (*error-output* nil :per-line-prefix "; ")
(format *error-output* "~&compilation unit ~:[finished~;aborted~]"
abort-p)
(dolist (cell summary)
(destructuring-bind (kind &rest names) cell
(format *error-output*
"~& Undefined ~(~A~)~p:~
~% ~{~<~% ~1:;~S~>~^ ~}"
kind (length names) names)))
(format *error-output* "~[~:;~:*~& caught ~W fatal ERROR condition~:P~]~
~[~:;~:*~& caught ~W ERROR condition~:P~]~
~[~:;~:*~& caught ~W WARNING condition~:P~]~
~[~:;~:*~& caught ~W STYLE-WARNING condition~:P~]~
~[~:;~:*~& printed ~W note~:P~]"
*aborted-compilation-unit-count*
*compiler-error-count*
*compiler-warning-count*
*compiler-style-warning-count*
*compiler-note-count*))
(terpri *error-output*)
(force-output *error-output*))))
;;; Evaluate BODY, then return (VALUES BODY-VALUE WARNINGS-P
;;; FAILURE-P), where BODY-VALUE is the first value of the body, and
;;; WARNINGS-P and FAILURE-P are as in CL:COMPILE or CL:COMPILE-FILE.
(defmacro with-compilation-values (&body body)
`(let ((*finite-sbs*
(vector
,@(loop for sb across *backend-sbs*
unless (eq (sb-kind sb) :non-packed)
collect
(let ((size (sb-size sb)))
`(make-finite-sb
:conflicts (make-array ,size :initial-element #())
:always-live (make-array ,size :initial-element #*)
:live-tns (make-array ,size :initial-element nil)))))))
(let ((*warnings-p* nil)
(*failure-p* nil))
(handler-bind ((compiler-error #'compiler-error-handler)
(style-warning #'compiler-style-warning-handler)
(warning #'compiler-warning-handler))
(values (progn ,@body) *warnings-p* *failure-p*)))))
;;; THING is a kind of thing about which we'd like to issue a warning,
;;; but showing at most one warning for a given set of <THING,FMT,ARGS>.
;;; The compiler does a good job of making sure not to print repetitive
;;; warnings for code that it compiles, but this solves a different problem.
;;; Specifically, for a warning from PARSE-LAMBDA-LIST, there are three calls:
;;; - once in the expander for defmacro itself, as it calls MAKE-MACRO-LAMBDA
;;; which calls PARSE-LAMBDA-LIST. This is the toplevel form processing.
;;; - again for :compile-toplevel, where the DS-BIND calls PARSE-LAMBDA-LIST.
;;; If compiling in compile-toplevel, then *COMPILE-OBJECT* is a core object,
;;; but if interpreting, then it is still a fasl.
;;; - once for compiling to fasl. *COMPILE-OBJECT* is a fasl.
;;; I'd have liked the data to be associated with the fasl, except that
;;; as indicated above, the second line hides some information.
(defun style-warn-once (thing fmt-or-condition &rest args)
(declare (notinline style-warn)) ; See COMPILER-STYLE-WARN for rationale
(let* ((source-info *source-info*)
(file-info (and (source-info-p source-info)
(source-info-file-info source-info)))
(file-compiling-p (file-info-p file-info)))
(flet ((match-p (entry)
(destructuring-bind (entry-thing entry-fmt &rest entry-args) entry
;; THING is compared by EQ, FMT mostly by STRING=.
(and (eq entry-thing thing)
(cond ((typep entry-fmt 'condition)
(and (typep fmt-or-condition 'condition)
(string= (princ-to-string entry-fmt)
(princ-to-string fmt-or-condition))))
((typep fmt-or-condition 'condition)
nil)
;; If at least one is a FMT-CONTROL-PROXY
;; the two should be either EQ or a
;; mismatch.
((not (stringp entry-fmt))
(and (not (stringp fmt-or-condition))
(eq entry-fmt fmt-or-condition)))
((string= entry-fmt fmt-or-condition)))
;; We don't want to walk into default values,
;; e.g. (&optional (b #<insane-struct))
;; because #<insane-struct> might be circular.
(list-elts-eq entry-args args)))))
(unless (and file-compiling-p
(find-if #'match-p
(file-info-style-warning-tracker file-info)))
(when file-compiling-p
(push (list* thing fmt-or-condition args)
(file-info-style-warning-tracker file-info)))
(apply 'style-warn fmt-or-condition args)))))
;;;; component compilation
(defparameter *max-optimize-iterations* 3 ; ARB
"The upper limit on the number of times that we will consecutively do IR1
optimization that doesn't introduce any new code. A finite limit is
necessary, since type inference may take arbitrarily long to converge.")
(defevent ir1-optimize-until-done "IR1-OPTIMIZE-UNTIL-DONE called")
(defevent ir1-optimize-maxed-out "hit *MAX-OPTIMIZE-ITERATIONS* limit")
;;; Repeatedly optimize COMPONENT until no further optimizations can
;;; be found or we hit our iteration limit. When we hit the limit, we
;;; clear the component and block REOPTIMIZE flags to discourage the
;;; next optimization attempt from pounding on the same code.
(defun ir1-optimize-until-done (component)
(declare (type component component))
(maybe-mumble "Opt")
(event ir1-optimize-until-done)
(let ((count 0)
(cleared-reanalyze nil)
(fastp nil)
reoptimized)
(loop
(when (component-reanalyze component)
(setf count 0
fastp nil
cleared-reanalyze t
(component-reanalyze component) nil))
(setf (component-reoptimize component) nil)
(ir1-optimize component fastp)
(cond ((component-reoptimize component)
(setf reoptimized t)
(incf count)
(when (and (>= count *max-optimize-iterations*)
(not (component-reanalyze component))
(eq (component-reoptimize component) :maybe))
(maybe-mumble "*")
(event ir1-optimize-maxed-out)
(ir1-optimize-last-effort component)
(return)))
(t
(return)))
(when (setq fastp (>= count *max-optimize-iterations*))
(ir1-optimize-last-effort component))
(maybe-mumble (if fastp "-" ".")))
(when cleared-reanalyze
(setf (component-reanalyze component) t))
(maybe-mumble " ")
reoptimized))
(defparameter *constraint-propagate* t)
(defevent reoptimize-maxed-out
"*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
;;; Iterate doing FIND-DFO until no new dead code is discovered.
(defun dfo-as-needed (component)
(declare (type component component))
(when (component-reanalyze component)
(maybe-mumble "DFO")
(loop
(find-dfo component)
(unless (component-reanalyze component)
(maybe-mumble " ")
(return))
(maybe-mumble "."))
t))
(defparameter *reoptimize-limit* 10)
(defun ir1-optimize-phase-1 (component)
(let ((loop-count 0)
(constraint-propagate *constraint-propagate*)
reoptimized)
(tagbody
again
(loop
(setf reoptimized (ir1-optimize-until-done component))
(cond ((or (component-new-functionals component)
(component-reanalyze-functionals component))
(maybe-mumble "Locall ")
(locall-analyze-component component))
((and (>= loop-count 1)
(not (component-reanalyze component))
(not reoptimized))
;; Constraint propagation did something but that
;; information didn't lead to any new optimizations.
;; Don't run constraint-propagate again.
(return)))
(dfo-as-needed component)
(when constraint-propagate
(maybe-mumble "Constraint ")
(constraint-propagate component)
(when (retry-delayed-ir1-transforms :constraint)
(setf loop-count 0) ;; otherwise nothing may get retried
(maybe-mumble "Rtran ")))
(unless (or (component-reoptimize component)
(component-reanalyze component)
(component-new-functionals component)
(component-reanalyze-functionals component))
(return))
(when (> loop-count *reoptimize-limit*)
(maybe-mumble "[Reoptimize Limit]")
(event reoptimize-maxed-out)
(return))
(incf loop-count))
;; Do it once more for the transforms that will produce code
;; that loses some information for further optimizations and
;; it's better to insert it at the last moment.
;; Such code shouldn't need constraint propagation, the slowest
;; part, so avoid it.
(when (retry-delayed-ir1-transforms :ir1-phases)
(setf loop-count 0
constraint-propagate nil)
(go again)))))
;;; Do all the IR1 phases for a non-top-level component.
(defun ir1-phases (component)
(declare (type component component))
(aver-live-component component)
(let ((*constraint-universe* (make-array 64 ; arbitrary, but don't make this 0
:fill-pointer 0 :adjustable t))
(*delayed-ir1-transforms* nil))
(declare (special *constraint-universe* *delayed-ir1-transforms*))
(ir1-optimize-phase-1 component)
(loop while (progn
(maybe-mumble "Type ")
(generate-type-checks component))
do
(ir1-optimize-phase-1 component))
;; Join the blocks that were generated by GENERATE-TYPE-CHECKS
;; now that all the blocks have the same TYPE-CHECK attribute
(join-blocks-if-possible component))
(ir1-finalize component)
(values))
#-immobile-code
(defun component-mem-space (component)
(component-%mem-space component))
#+immobile-code
(progn
(defun component-mem-space (component)
(or (component-%mem-space component)
#-sb-xc-host
(setf (component-%mem-space component)
(if (fasl-output-p *compile-object*)
(and (eq *compile-file-to-memory-space* :immobile)
(neq (component-kind component) :toplevel)
(policy *lexenv* (/= sb-c:store-coverage-data 3))
:immobile)
(if (core-object-ephemeral *compile-object*)
:dynamic
*compile-to-memory-space*)))))
(defun code-immobile-p (thing)
#+sb-xc-host (declare (ignore thing)) #+sb-xc-host t
#-sb-xc-host
(let ((component (etypecase thing
(vop (node-component (vop-node thing)))
(node (node-component thing))
(component thing))))
(eq (component-mem-space component) :immobile))))
(defun %compile-component (component)
(maybe-mumble "GTN ")
(gtn-analyze component)
(maybe-mumble "LTN ")
(ltn-analyze component)
(dfo-as-needed component)
(maybe-mumble "Control ")
(control-analyze component)
(report-code-deletion)
(when (or (ir2-component-values-receivers (component-info component))
(ir2-component-stack-allocates-p (component-info component)))
(maybe-mumble "Stack ")
(stack-analyze component)
;; Assign BLOCK-NUMBER for any cleanup blocks introduced by
;; stack analysis. There shouldn't be any unreachable code after
;; control, so this won't delete anything.
(dfo-as-needed component))
(maybe-mumble "IR2Tran ")
(entry-analyze component)
;; For on-demand recalculation of dominators, the previously
;; computed results may be stale.
(clear-dominators component)
(ir2-convert component)
(when (policy *lexenv* (>= speed compilation-speed))
(maybe-mumble "Copy ")
(copy-propagate component))
(ir2-optimize component)
(select-representations component)
(ir2-optimize component 'select-representations)
(when *check-consistency*
(maybe-mumble "Check2 ")
(check-ir2-consistency component))
(delete-unreferenced-tns component)
(maybe-mumble "Life ")
(lifetime-analyze component)
(when *compile-progress*
(compiler-mumble "") ; Sync before doing more output.
(pre-pack-tn-stats component *standard-output*))
(when *check-consistency*
(maybe-mumble "CheckL ")
(check-life-consistency component))
(maybe-mumble "Pack ")
(sb-regalloc:pack component)
(when *check-consistency*
(maybe-mumble "CheckP ")
(check-pack-consistency component))
(ir2-optimize component 'regalloc)
(when *compiler-trace-output*
(when (memq :ir1 *compile-trace-targets*)
(describe-component component *compiler-trace-output*))
(when (memq :ir2 *compile-trace-targets*)
(describe-ir2-component component *compiler-trace-output*)))
(maybe-mumble "Code ")
(multiple-value-bind (segment text-length fun-table
elsewhere-label fixup-notes alloc-points)
(let ((*compiler-trace-output*
(and (memq :vop *compile-trace-targets*)
*compiler-trace-output*)))
(generate-code component))
(declare (ignorable text-length fun-table))
(let ((bytes (sb-assem:segment-contents-as-vector segment))
(object *compile-object*)
(*elsewhere-label* elsewhere-label)) ; KLUDGE
#-sb-xc-host
(when (and *compiler-trace-output*
(memq :disassemble *compile-trace-targets*))
(let ((ranges
(maplist (lambda (list)
(cons (+ (car list)
(ash sb-vm:simple-fun-insts-offset
sb-vm:word-shift))
(or (cadr list) text-length)))
fun-table)))
(format *compiler-trace-output*
"~|~%Disassembly of code for ~S~2%" component)
(sb-disassem:disassemble-assem-segment
bytes ranges *compiler-trace-output*)))
(funcall (etypecase object
(fasl-output (maybe-mumble "FASL") #'fasl-dump-component)
#-sb-xc-host ; no compiling to core
(core-object (maybe-mumble "Core") #'make-core-component)
(null (lambda (&rest dummies)
(declare (ignore dummies)))))
component segment (length bytes)
fixup-notes alloc-points
object)))
;; We're done, so don't bother keeping anything around.
(setf (component-info component) :dead)
(values))
;;; Delete components with no external entry points before we try to
;;; generate code. Unreachable closures can cause IR2 conversion to
;;; puke on itself, since it is the reference to the closure which
;;; normally causes the components to be combined.
(defun delete-if-no-entries (component)
(dolist (fun (component-lambdas component) (delete-component component))
(when (functional-has-external-references-p fun)
(return))
(functional-kind-case fun
(toplevel (return))
(external
(unless (every (lambda (ref)
(eq (node-component ref) component))
(leaf-refs fun))
(return))))))
(defvar *compile-component-hook* nil)
(defun compile-component (component)
(aver-live-component component)
(let* ((*component-being-compiled* component))
(when *compile-progress*
(compiler-mumble "~&")
(pprint-logical-block (*standard-output* nil :per-line-prefix "; ")
(compiler-mumble "Compiling ~A: " (component-name component))))
;; Record xref information before optimization. This way the
;; stored xref data reflects the real source as closely as
;; possible.
(record-component-xrefs component)
(ir1-phases component)
;; KLUDGE: We should instead set COMPONENT-REOPTIMIZE to T
;; whenever a REF gets deleted so that DFO-AS-NEEDED kicks in only
;; when needed, and we don't need this call to do a final
;; unreachable entry point scan.
(find-dfo component)
(dfo-as-needed component)
(maybe-mumble "Dom ")
(find-dominators component)
(maybe-mumble "Loop ")
(loop-analyze component)
#|
(when *compiler-trace-output*
(labels ((print-blocks (block)
(format *compiler-trace-output* " ~A~%" block)
(when (block-loop-next block)
(print-blocks (block-loop-next block))))
(print-loop (loop)
(format *compiler-trace-output* "loop=~A~%" loop)
(print-blocks (loop-blocks loop))
(dolist (l (loop-inferiors loop))
(print-loop l))))
(print-loop (component-outer-loop component))))
|#
(maybe-mumble "Env ")
(environment-analyze component)
(dfo-as-needed component)
(delete-if-no-entries component)
(if (eq (block-next (component-head component))
(component-tail component))
(report-code-deletion)
(%compile-component component))
(when *compile-component-hook*
(funcall *compile-component-hook* component)))
(clear-constant-info)
(values))
;;;; clearing global data structures
;;;;
;;;; FIXME: Is it possible to get rid of this stuff, getting rid of
;;;; global data structures entirely when possible and consing up the
;;;; others from scratch instead of clearing and reusing them?
;;; Clear the INFO in constants in the *IR1-NAMESPACE*, etc. In
;;; addition to allowing stuff to be reclaimed, this is required for
;;; correct assignment of constant offsets, since we need to assign a
;;; new offset for each component. We don't clear the FUNCTIONAL-INFO
;;; slots, since they are used to keep track of functions across
;;; component boundaries.
(defun clear-constant-info (&aux (ns *ir1-namespace*))
(maphash (lambda (k v)
(declare (ignore k))
(setf (leaf-info v) nil))
(eql-constants ns))
(maphash (lambda (k v)
(declare (ignore k))
(when (constant-p v)
(setf (leaf-info v) nil)))
(free-vars ns))
(values))
;;; Blow away the REFS for all global variables, and let COMPONENT
;;; be recycled.
(defun clear-ir1-info (component &aux (ns *ir1-namespace*))
(declare (type component component))
(labels ((blast (x)
(maphash (lambda (k v)
(declare (ignore k))
(when (leaf-p v)
(setf (leaf-refs v)
(delete-if #'here-p (leaf-refs v)))
(when (basic-var-p v)
(setf (basic-var-sets v)
(delete-if #'here-p (basic-var-sets v))))))
x))
(here-p (x)
(eq (node-component x) component)))
(blast (free-vars ns))
(blast (free-funs ns))
;; There can be more constants to blast when considering them by EQL rather
;; than similarity. But it's totally OK to visit a #<CONSTANT> twice.
;; Its refs will be scanned redundantly, which is harmless.
(blast (eql-constants ns)))
(values))
;;; Clear the global hash tables held in IR1-NAMESPACE.
(defun clear-ir1-namespace ()
(when (boundp '*ir1-namespace*)
(let ((ir1-namespace *ir1-namespace*))
(clrhash (free-funs ir1-namespace))
(clrhash (free-vars ir1-namespace))
;; FIXME: It would make sense to clear these tables on arm64 as
;; well, but it relies on the constant for NIL to stay around in
;; order to assign a wired TN to it. A possible fix is to give
;; arm64 NULL-SC like on other platforms.
#-arm64
(progn
(clrhash (eql-constants ir1-namespace))
(clrhash (similar-constants ir1-namespace))))))
;;;; trace output
;;; Print out some useful info about COMPONENT to STREAM.
(defun describe-component (component *standard-output*)
(declare (type component component))
(format t "~|~%;;;; component: ~S~2%" (component-name component))
(print-all-blocks component)
(values))
(defun describe-ir2-component (component *standard-output*)
(format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
(format t "entries:~%")
(dolist (entry (ir2-component-entries (component-info component)))
(format t "~4TL~D: ~S~:[~; [closure]~]~%"
(label-id (entry-info-offset entry))
(entry-info-name entry)
(entry-info-closure-tn entry)))
(terpri)
(pre-pack-tn-stats component *standard-output*)
(terpri)
(print-ir2-blocks component)
(terpri)
(values))
;;; Leave this as NIL if you want modern, rational, correct, behavior,
;;; or switch it to T for legacy (CLHS-specified) bullshit a la
;;; "During a call to compile-file, *compile-file-pathname* is bound to the pathname
;;; denoted by the first argument to compile-file, merged against the defaults"
;;; The normal build sets it to T in make-target-2, despite that I think most people would
;;; prefer the nonstandard behavior. The standard behavior makes stored pathnames all wrong
;;; when files are physically moved. (Same problem as SBCL_HOME embedded into C pretty much)
(defglobal *merge-pathnames* nil)
;;; Given a pathname, return a SOURCE-INFO structure.
(defun make-file-source-info (file external-format &optional form-tracking-p)
(make-source-info
:file-info (make-file-info
;; becomes *COMPILE-FILE-PATHNAME*
:pathname (if *merge-pathnames* (merge-pathnames file) file)
:external-format external-format
:subforms (if form-tracking-p (make-array 100 :fill-pointer 0 :adjustable t))
:write-date (file-write-date file))))
;; LOAD-AS-SOURCE uses this.
(defun make-file-stream-source-info (file-stream)
(make-source-info
:file-info (make-file-info :truename (truename file-stream) ; FIXME: WHY USE TRUENAME???
;; This T-L-P has been around since at least 2011.
;; It's unclear why an LPN isn't good enough.
:pathname (translate-logical-pathname file-stream)
:external-format (stream-external-format file-stream)
:write-date (file-write-date file-stream))))
;;; Return a SOURCE-INFO to describe the incremental compilation of FORM.
(defun make-lisp-source-info (form &key parent)
(make-source-info
:file-info (make-file-info :truename :lisp
:forms (vector form)
:positions '#(0))
:parent parent))
;;; Walk up the SOURCE-INFO list until we either reach a SOURCE-INFO
;;; with no parent (e.g., from a REPL evaluation) or until we reach a
;;; SOURCE-INFO whose FILE-INFO denotes a file.
(defun get-toplevelish-file-info (&optional (source-info *source-info*))
(if source-info
(do* ((sinfo source-info (source-info-parent sinfo))
(finfo (source-info-file-info sinfo)
(source-info-file-info sinfo)))
((or (not (source-info-p (source-info-parent sinfo)))
(pathnamep (file-info-truename finfo)))
finfo))))
;;; If STREAM is present, return it, otherwise open a stream to the
;;; current file. There must be a current file.
;;;
;;; FIXME: This is probably an unnecessarily roundabout way to do
;;; things now that we process a single file in COMPILE-FILE (unlike
;;; the old CMU CL code, which accepted multiple files). Also, the old
;;; comment said
;;; When we open a new file, we also reset *PACKAGE* and policy.
;;; This gives the effect of rebinding around each file.
;;; which doesn't seem to be true now. Check to make sure that if
;;; such rebinding is necessary, it's still done somewhere.
;;; FIXME: We will want to have a way to process multiple files again
;;; for the sake of block compilation.
(defun get-source-stream (info)
(declare (type source-info info))
(or (source-info-stream info)
(let* ((file-info (source-info-file-info info))
(pathname (file-info-pathname file-info))
(external-format (file-info-external-format file-info)))
(let ((stream
(open pathname
:direction :input
:external-format external-format
;; SBCL stream classes aren't available in the host
#-sb-xc-host :class
#-sb-xc-host 'form-tracking-stream)))
;; If you don't want merged pathnames embedded in your build artifacts,
;; then you surely don't want them in *COMPILE-FILE-PATHNAME* either.
;; [And can't we just bind this to PATHNAME is all cases? If anything,
;; it seems to me that asking the stream for its name is expressly backwards]
(setf *compile-file-pathname* (if *merge-pathnames* (pathname stream) pathname)
*compile-file-truename* (truename stream)
(file-info-truename file-info) *compile-file-truename*)
(when (file-info-subforms file-info)
(setf (form-tracking-stream-observer stream)
(make-form-tracking-stream-observer file-info)))
(setf (source-info-stream info) stream)
;; This used to happen before opening the file, which
;; inhibited lazy computation of the truename, and was a
;; minor time-of-check-vs-time-of-use mistake. It doesn't
;; seem worthwhile to pass the verbose bit down from C-F,
;; however.
(when *compile-verbose*
(print-compile-start-note info))
stream))))
;;; Close the stream in INFO if it is open.
(defun close-source-info (info)
(declare (type source-info info))
(let ((stream (source-info-stream info)))
(when stream (close stream)))
(setf (source-info-stream info) nil)
(values))
;; Loop over forms read from INFO's stream, calling FUNCTION with each.
;; CONDITION-NAME is signaled if there is a reader error, and should be
;; a subtype of not-so-aptly-named INPUT-ERROR-IN-COMPILE-FILE.
(defun %do-forms-from-info (function info condition-name)
(declare (function function))
(declare (dynamic-extent function))
(let* ((file-info (source-info-file-info info))
(stream (get-source-stream info))
(pos (file-position stream))
(form
;; Return a form read from STREAM; or for EOF use the trick,
;; popularized by Kent Pitman, of returning STREAM itself.
(handler-case
(progn
;; Reset for a new toplevel form.
(when (form-tracking-stream-p stream)
(setf (form-tracking-stream-form-start-char-pos stream) nil))
(awhen (file-info-subforms file-info)
(setf (fill-pointer it) 0))
(read-preserving-whitespace stream nil stream))
(reader-error (condition)
(compiler-error condition-name
;; We don't need to supply :POSITION here because
;; READER-ERRORs already know their position in the file.
:condition condition
:stream stream))
;; ANSI, in its wisdom, says that READ should return END-OF-FILE
;; (and that this is not a READER-ERROR) when it encounters end of
;; file in the middle of something it's trying to read,
;; making it unfortunately indistinguishable from legal EOF.
;; Were it not for that, it would be more elegant to just
;; handle one more condition in the HANDLER-CASE.
((or end-of-file error) (condition)
(compiler-error
condition-name
:condition condition
;; We need to supply :POSITION here because the END-OF-FILE
;; condition doesn't carry the position that the user
;; probably cares about, where the failed READ began.
:position
(or (and (form-tracking-stream-p stream)
(form-tracking-stream-form-start-byte-pos stream))
pos)
:line/col
(and (form-tracking-stream-p stream)
(line/col-from-charpos
stream
(form-tracking-stream-form-start-char-pos stream)))
:stream stream)))))
(unless (eq form stream) ; not EOF
(funcall function form
:current-index
(let* ((forms (file-info-forms file-info))
(current-idx (fill-pointer forms)))
(vector-push-extend form forms)
(vector-push-extend pos (file-info-positions file-info))
current-idx))
(%do-forms-from-info function info condition-name))))
;;; Loop over FORMS retrieved from INFO. Used by COMPILE-FILE and
;;; LOAD when loading from a FILE-STREAM associated with a source
;;; file. ON-ERROR is the name of a condition class that should
;;; be signaled if anything goes wrong during a READ.
(defmacro do-forms-from-info (((form &rest keys) info
&optional (on-error ''input-error-in-load))
&body body)
(aver (symbolp form))