main.lisp 62.1 KB
Newer Older
wlott's avatar
wlott committed
1
2
3
;;; -*- Package: C; Log: C.Log -*-
;;;
;;; **********************************************************************
ram's avatar
ram committed
4
5
6
7
8
9
;;; This code was written as part of the CMU Common Lisp project at
;;; Carnegie Mellon University, and has been placed in the public domain.
;;; If you want to use this code or any part of CMU Common Lisp, please contact
;;; Scott Fahlman or slisp-group@cs.cmu.edu.
;;;
(ext:file-comment
10
  "$Header: /Volumes/share2/src/cmucl/cvs2git/cvsroot/src/compiler/main.lisp,v 1.97 1993/08/20 00:18:29 ram Exp $")
ram's avatar
ram committed
11
;;;
wlott's avatar
wlott committed
12
13
14
15
16
17
;;; **********************************************************************
;;;
;;;    This file contains the top-level interfaces to the compiler.
;;; 
;;; Written by Rob MacLachlan
;;;
ram's avatar
ram committed
18
(in-package "C")
19
(in-package "EXTENSIONS")
20
(export '(*compile-progress* compile-from-stream *block-compile-default*
21
22
23
			     start-block end-block
			     *byte-compile-default*
			     *byte-compile-top-level*))
24
25
(in-package "LISP")
(export '(*compile-verbose* *compile-print* *compile-file-pathname*
ram's avatar
ram committed
26
27
			    *compile-file-truename*
			    compile-file-pathname))
28
(in-package "C")
wlott's avatar
wlott committed
29
30
31

(proclaim '(special *constants* *free-variables* *compile-component*
		    *code-vector* *next-location* *result-fixups*
ram's avatar
ram committed
32
		    *free-functions* *source-paths*
wlott's avatar
wlott committed
33
34
35
		    *seen-blocks* *seen-functions* *list-conflicts-table*
		    *continuation-number* *continuation-numbers*
		    *number-continuations* *tn-id* *tn-ids* *id-tns*
36
		    *label-ids* *label-id* *id-labels*
ram's avatar
ram committed
37
		    *undefined-warnings* *compiler-error-count*
wlott's avatar
wlott committed
38
39
40
41
42
		    *compiler-warning-count* *compiler-note-count*
		    *compiler-error-output* *compiler-error-bailout*
		    *compiler-trace-output*
		    *last-source-context* *last-original-source*
		    *last-source-form* *last-format-string* *last-format-args*
43
		    *last-message-count* *lexical-environment*))
wlott's avatar
wlott committed
44

45
;;; Exported:
46
47
(defvar *block-compile-default* :specified
  "The default value for the :Block-Compile argument to COMPILE-FILE.")
48
49
50
51
52
53
54
55
56
(declaim (type (member t nil :specified) *block-compile-default*))

;;; Exported:
(defvar *byte-compile-default* :maybe
  "The default value for the :Byte-Compile argument to COMPILE-FILE.")

;;; Exported:
(defvar *byte-compile-top-level* t
  "Similar to *BYTE-COMPILE-DEFAULT*, but controls the compilation of top-level
57
58
   forms (evaluated at load-time) when the :BYTE-COMPILE argument is :MAYBE
   (the default.)  When true, we decide to byte-compile.")
59
60
61
62
63

;;; Value of the :byte-compile argument to the compiler.
(defvar *byte-compile* :maybe)

;;; Bound by COMPILE-COMPONENT to T when byte-compiling, and NIL when
ram's avatar
ram committed
64
65
;;; native compiling.  During IR1 conversion this can also be :MAYBE, in which
;;; case we must look at the policy, see (byte-compiling).
66
;;;
ram's avatar
ram committed
67
68
69
(defvar *byte-compiling* :maybe)
(declaim (type (member t nil :maybe) *byte-compile* *byte-compiling*
	       *byte-compile-default*))
70

71
(defvar compiler-version "1.0")
ram's avatar
ram committed
72
73
74
75
76
(pushnew :python *features*)
(setf (getf ext:*herald-items* :python)
      `("    Python " ,compiler-version ", target "
	,#'(lambda (stream)
	     (write-string (backend-version *backend*) stream))))
wlott's avatar
wlott committed
77

78
(defvar *check-consistency* nil)
wlott's avatar
wlott committed
79
80
(defvar *all-components*)

81
82
83
;;; The current block compilation state.  These are initialized to the 
;;; :Block-Compile and :Entry-Points arguments that COMPILE-FILE was called
;;; with.  Subsequent START-BLOCK or END-BLOCK declarations alter the values.
wlott's avatar
wlott committed
84
85
;;;
(defvar *block-compile*)
86
87
88
(declaim (type (member nil t :specified) *block-compile*))
(defvar *entry-points*)
(declaim (list *entry-points*))
wlott's avatar
wlott committed
89
90
91
92
93

;;; When block compiling, used by PROCESS-FORM to accumulate top-level lambdas
;;; resulting from compiling subforms.  (In reverse order.)
;;;
(defvar *top-level-lambdas*)
94
(declaim (list *top-level-lambdas*))
wlott's avatar
wlott committed
95

96
97
98
99
100
101
102
103
(defvar *compile-verbose* t
  "The default for the :VERBOSE argument to COMPILE-FILE.")
(defvar *compile-print* t
  "The default for the :PRINT argument to COMPILE-FILE.")
(defvar *compile-progress* nil
  "The default for the :PROGRESS argument to COMPILE-FILE.")

(defvar *compile-file-pathname* nil
ram's avatar
ram committed
104
  "The defaulted pathname of the file currently being compiled, or NIL if not
105
106
  compiling.")
(defvar *compile-file-truename* nil
ram's avatar
ram committed
107
  "The TRUENAME of the file currently being compiled, or NIL if not
108
109
110
111
  compiling.")

(declaim (type (or pathname null) *compile-file-pathname*
	       *compile-file-truename*))
wlott's avatar
wlott committed
112

113
;;; The values of *Package* and policy when compilation started.
wlott's avatar
wlott committed
114
115
116
;;;
(defvar *initial-package*)
(defvar *initial-cookie*)
117
(defvar *initial-interface-cookie*)
wlott's avatar
wlott committed
118
119
120
121
122
123
124
125
126
127

;;; 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)


;;; Maybe-Mumble  --  Internal
;;;
128
;;;    Mumble conditional on *compile-progress*.
wlott's avatar
wlott committed
129
130
;;;
(defun maybe-mumble (&rest foo)
131
  (when *compile-progress*
wlott's avatar
wlott committed
132
133
    (apply #'compiler-mumble foo)))

134

wlott's avatar
wlott committed
135
136
(deftype object () '(or fasl-file core-object null))

137
138
139
140
(defvar *compile-object* nil)
(declaim (type object *compile-object*))


wlott's avatar
wlott committed
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

;;;; Component compilation:

(defparameter max-optimize-iterations 3
  "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.")

;;; IR1-Optimize-Until-Done  --  Internal
;;;
;;;    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 following 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))
    (loop
      (when (component-reanalyze component)
	(setq count 0)
	(setq cleared-reanalyze t)
	(setf (component-reanalyze component) nil))
      (setf (component-reoptimize component) nil)
      (ir1-optimize component)
      (unless (component-reoptimize component)
	(maybe-mumble " ")
	(return))
      (incf count)
      (when (= count max-optimize-iterations)
	(event ir1-optimize-maxed-out)
	(maybe-mumble "* ")
	(setf (component-reoptimize component) nil)
	(do-blocks (block component)
	  (setf (block-reoptimize block) nil))
	(return))
      (maybe-mumble "."))
    (when cleared-reanalyze
      (setf (component-reanalyze component) t)))
  (undefined-value))

188
189
190
191
192
(defparameter *constraint-propagate* t)
(defparameter *reoptimize-after-type-check-max* 5)

(defevent reoptimize-maxed-out
  "*REOPTIMIZE-AFTER-TYPE-CHECK-MAX* exceeded.")
wlott's avatar
wlott committed
193

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211

;;; DFO-AS-NEEDED  --  Internal
;;;
;;;    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 ".")))
  (undefined-value))


wlott's avatar
wlott committed
212
213
214
215
216
217
;;; IR1-Phases  --  Internal
;;;
;;;    Do all the IR1 phases for a non-top-level component.
;;;
(defun ir1-phases (component)
  (declare (type component component))
218
219
  (let ((*constraint-number* 0)
	(loop-count 1))
wlott's avatar
wlott committed
220
    (declare (special *constraint-number*))
221
    (loop
wlott's avatar
wlott committed
222
      (ir1-optimize-until-done component)
223
224
225
      (when (component-reanalyze-functions component)
	(maybe-mumble "Locall ")
	(local-call-analyze component))
226
      (dfo-as-needed component)
wlott's avatar
wlott committed
227
228
229
230
231
232
      (when *constraint-propagate*
	(maybe-mumble "Constraint ")
	(constraint-propagate component))
      (maybe-mumble "Type ")
      (generate-type-checks component)
      (unless (or (component-reoptimize component)
233
234
		  (component-reanalyze component)
		  (component-reanalyze-functions component))
235
236
237
238
239
240
	(return))
      (when (>= loop-count *reoptimize-after-type-check-max*)
	(maybe-mumble "[Reoptimize Limit]")
	(event reoptimize-maxed-out)
	(return))
      (incf loop-count)))
241
242

  (ir1-finalize component)
243
  (undefined-value))
wlott's avatar
wlott committed
244
245


246
;;; Native-Compile-Component  --  Internal
wlott's avatar
wlott committed
247
;;;
248
249
(defun native-compile-component (component)
  (let ((*code-segment* nil)
wlott's avatar
wlott committed
250
	(*elsewhere* nil))
wlott's avatar
wlott committed
251
252
253
254
    (maybe-mumble "GTN ")
    (gtn-analyze component)
    (maybe-mumble "LTN ")
    (ltn-analyze component)
255
    (dfo-as-needed component)
ram's avatar
ram committed
256
    (maybe-mumble "Control ")
257
    (control-analyze component #'make-ir2-block)
wlott's avatar
wlott committed
258
259
260

    (when (ir2-component-values-receivers (component-info component))
      (maybe-mumble "Stack ")
261
262
263
264
265
266
      (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))
wlott's avatar
wlott committed
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
    (unwind-protect
	(progn
	  (maybe-mumble "IR2Tran ")
	  (init-assembler)
	  (entry-analyze component)
	  (ir2-convert component)
	  
	  (when (policy nil (>= speed cspeed))
	    (maybe-mumble "Copy ")
	    (copy-propagate component))
	  
	  (select-representations component)
	  
	  (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 random output.
	    (pre-pack-tn-stats component *compiler-error-output*))
	  
	  (when *check-consistency*
	    (maybe-mumble "CheckL ")
	    (check-life-consistency component))
	  
	  (maybe-mumble "Pack ")
	  (pack component)
	  
	  (when *check-consistency*
	    (maybe-mumble "CheckP ")
	    (check-pack-consistency component))
	  
	  (when *compiler-trace-output*
306
307
	    (describe-component component *compiler-trace-output*)
	    (describe-ir2-component component *compiler-trace-output*))
308
309
310
311
312
313
	  
	  (maybe-mumble "Code ")
	  (multiple-value-bind
	      (length trace-table fixups)
	      (generate-code component)
	    
314
315
	    (when (and *compiler-trace-output*
		       (backend-disassem-params *backend*))
316
317
	      (format *compiler-trace-output*
		      "~|~%Disassembly of code for ~S~2%" component)
318
319
320
	      (disassem:disassemble-assem-segment *code-segment*
						  *compiler-trace-output*
						  *backend*))
321

322
323
324
325
326
327
328
329
330
	    (etypecase *compile-object*
	      (fasl-file
	       (maybe-mumble "FASL")
	       (fasl-dump-component component *code-segment*
				    length trace-table fixups
				    *compile-object*))
	      (core-object
	       (maybe-mumble "Core")
	       (make-core-component component *code-segment*
331
332
				    length trace-table fixups
				    *compile-object*))
333
334
	      (null))))
	    
wlott's avatar
wlott committed
335
336
337
338
      (when *code-segment*
	(new-assem:release-segment *code-segment*))
      (when *elsewhere*
	(new-assem:release-segment *elsewhere*))))
wlott's avatar
wlott committed
339

340
  ;; We are done, so don't bother keeping anything around.
341
342
  (nuke-ir2-component component)
  (setf (component-info component) nil)
343
344
345
346
  
  (undefined-value))


ram's avatar
ram committed
347
348
349
350
351
352
353
354
355
;;; BYTE-COMPILING  --  Interface
;;;
;;;    Return our best guess for whether we will byte compile code currently
;;; being IR1 converted.  Only a guess because the decision is made on a
;;; per-component basis.
;;;
(defun byte-compiling ()
  (if (eq *byte-compiling* :maybe)
      (policy nil (zerop speed) (<= debug 1))
356
      (and *byte-compile* *byte-compiling*)))
ram's avatar
ram committed
357
358

  
359
360
361
;;; COMPILE-COMPONENT -- internal.
;;;
(defun compile-component (component)
362
  (let* ((*compile-component* component)
ram's avatar
ram committed
363
	 (*byte-compiling*
364
365
366
367
	  (ecase *byte-compile*
	    ((t) t)
	    ((nil) nil)
	    (:maybe
368
369
	     (dolist (fun (component-lambdas component) t)
	       (unless (policy (lambda-bind fun)
370
			       (zerop speed) (<= debug 1))
371
372
		 (return nil)))))))

373
    (when *compile-print*
374
375
376
      (compiler-mumble "~&~:[~;Byte ~]Compiling ~A: "
		       *byte-compiling*
		       (component-name component)))
377
378
379
380
381
382
383
384
385
386
387
388
389
390

    (ir1-phases component)

    #|
    (maybe-mumble "Dom ")
    (find-dominators component)
    (maybe-mumble "Loop ")
    (loop-analyze component)
    |#

    (maybe-mumble "Env ")
    (environment-analyze component)
    (dfo-as-needed component)

ram's avatar
ram committed
391
392
393
394
395
    (unless (eq (block-next (component-head component))
		(component-tail component))
      (if *byte-compiling*
	  (byte-compile-component component)
	  (native-compile-component component))))
396

397
398
  (clear-constant-info)

399
400
401
  (when *compile-print*
    (compiler-mumble "~&"))

wlott's avatar
wlott committed
402
403
404
405
406
  (undefined-value))


;;;; Clearing global data structures:

407
;;; CLEAR-CONSTANT-INFO  --  Internal
wlott's avatar
wlott committed
408
;;;
409
410
411
412
413
;;;    Clear the INFO in constants in the *FREE-VARIABLES*, 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.
wlott's avatar
wlott committed
414
;;;
415
(defun clear-constant-info ()
wlott's avatar
wlott committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
  (maphash #'(lambda (k v)
	       (declare (ignore k))
	       (setf (leaf-info v) nil))
	   *constants*)

  (maphash #'(lambda (k v)
	       (declare (ignore k))
	       (when (constant-p v)
		 (setf (leaf-info v) nil)))
	   *free-variables*)

  (undefined-value))


430
431
432
433
434
435
436
;;; CLEAR-IR1-INFO  --  Internal
;;;
;;;    Blow away the REFS for all global variables, and recycle the IR1 for
;;; Component.
;;;
(defun clear-ir1-info (component)
  (declare (type component component))
437
438
439
  (labels ((blast (x)
	     (maphash #'(lambda (k v)
			  (declare (ignore k))
wlott's avatar
wlott committed
440
441
442
443
444
445
			  (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))))))
446
447
448
		      x))
	   (here-p (x)
	     (eq (block-component (node-block x)) component)))
449
450
451
452
453
454
455
    (blast *free-variables*)
    (blast *free-functions*)
    (blast *constants*))
  (macerate-ir1-component component)
  (undefined-value))


456
;;; CLEAR-STUFF  --  Interface
457
458
;;;
;;;    Clear all the global variables used by the compiler.
wlott's avatar
wlott committed
459
;;;
460
(defun clear-stuff (&optional (debug-too t))
wlott's avatar
wlott committed
461
462
  ;;
  ;; Clear global tables.
463
464
465
466
  (when (boundp '*free-functions*)
    (clrhash *free-functions*)
    (clrhash *free-variables*)
    (clrhash *constants*))
wlott's avatar
wlott committed
467
468
469
470
471
  ;;
  ;; Clear debug counters and tables.
  (clrhash *seen-blocks*)
  (clrhash *seen-functions*)
  (clrhash *list-conflicts-table*)
472
473
474
475
476
477
478
479
480
481

  (when debug-too
    (clrhash *continuation-numbers*)
    (clrhash *number-continuations*)
    (setq *continuation-number* 0)
    (clrhash *tn-ids*)
    (clrhash *id-tns*)
    (setq *tn-id* 0)
    (clrhash *label-ids*)
    (clrhash *id-labels*)
482
483
484
485
486
487
488
    (setq *label-id* 0)
    ;;
    ;; Clear some Pack data structures (for GC purposes only.)
    (assert (not *in-pack*))
    (dolist (sb (backend-sb-list *backend*))
      (when (finite-sb-p sb)
	(fill (finite-sb-live-tns sb) nil))))
wlott's avatar
wlott committed
489
490
  ;;
  ;; Reset Gensym.
491
492
493
  (setq lisp:*gensym-counter* 0)

  (values))
wlott's avatar
wlott committed
494

495

wlott's avatar
wlott committed
496
497
498
499
500
501
502
503
504
505
;;; PRINT-SUMMARY  --  Interface
;;;
;;;    This function is called by WITH-COMPILATION-UNIT at the end of a
;;; compilation unit.  It prints out any residual unknown function warnings and
;;; 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 print-summary (abort-p abort-count)
  (unless abort-p
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
    (handler-bind ((warning #'compiler-warning-handler))
      (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)))))))
	(unless *converting-for-interpreter*
	  (dolist (undef undefs)
	    (let ((name (undefined-warning-name undef))
		  (kind (undefined-warning-kind undef))
		  (warnings (undefined-warning-warnings undef))
		  (count (undefined-warning-count undef)))
	      (dolist (*compiler-error-context* warnings)
		(compiler-warning "Undefined ~(~A~): ~S" kind name))
	      
	      (let ((warn-count (length warnings)))
		(when (and warnings (> count warn-count))
		  (let ((more (- count warn-count)))
		    (compiler-warning "~D more use~:P of undefined ~(~A~) ~S."
				      more kind name)))))))
	
	(dolist (kind '(:variable :function :type))
	  (let ((summary (mapcar #'undefined-warning-name
				 (remove kind undefs :test-not #'eq
					 :key #'undefined-warning-kind))))
	    (when summary
	      (compiler-warning
	       "~:[This ~(~A~) is~;These ~(~A~)s are~] undefined:~
		~%  ~{~<~%  ~1:;~S~>~^ ~}"
	       (cdr summary) kind summary)))))))
537
  
538
539
540
541
542
  (unless (or *converting-for-interpreter*
	      (and (not abort-p) (zerop abort-count)
		   (zerop *compiler-error-count*)
		   (zerop *compiler-warning-count*)
		   (zerop *compiler-note-count*)))
543
544
545
546
547
548
549
550
551
552
553
    (compiler-mumble
     "~2&Compilation unit ~:[finished~;aborted~].~
      ~[~:;~:*~&  ~D fatal error~:P~]~
      ~[~:;~:*~&  ~D error~:P~]~
      ~[~:;~:*~&  ~D warning~:P~]~
      ~[~:;~:*~&  ~D note~:P~]~2%"
     abort-p
     abort-count
     *compiler-error-count*
     *compiler-warning-count*
     *compiler-note-count*)))
554

555
   
556
557
;;;; Trace output:

wlott's avatar
wlott committed
558
559
560
561
;;; Describe-Component  --  Internal
;;;
;;;    Print out some useful info about Component to Stream.
;;;
562
(defun describe-component (component *standard-output*)
563
  (declare (type component component))
wlott's avatar
wlott committed
564
  (format t "~|~%;;;; Component: ~S~2%" (component-name component))
565
566
567
568
569
570
  (print-blocks component)  
  (undefined-value))


(defun describe-ir2-component (component *standard-output*)
  (format t "~%~|~%;;;; IR2 component: ~S~2%" (component-name component))
wlott's avatar
wlott committed
571
  
572
573
574
575
576
577
  (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-p entry)))
wlott's avatar
wlott committed
578
  
579
580
581
582
583
  (terpri)
  (pre-pack-tn-stats component *standard-output*)
  (terpri)
  (print-ir2-blocks component)
  (terpri)
wlott's avatar
wlott committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
  (undefined-value))


;;;; File reading:
;;;
;;;    When reading from a file, we have to keep track of some source
;;; information.  We also exploit our ability to back up for printing the error
;;; context and for recovering from errors.
;;;
;;; The interface we provide to this stuff is the stream-oid Source-Info
;;; structure.  The bookkeeping is done as a side-effect of getting the next
;;; source form.


;;; The File-Info structure holds all the source information for a given file.
;;;
(defstruct file-info
  ;;
  ;; If a file, the truename of the corresponding source file.  If from a Lisp
  ;; form, :LISP, if from a stream, :STREAM.
604
  (name (required-argument) :type (or pathname (member :lisp :stream)))
wlott's avatar
wlott committed
605
  ;;
606
  ;; The defaulted, but not necessarily absolute file name (i.e. prior to
607
608
609
  ;; TRUENAME call.)  Null if not a file.  This is used to set
  ;; *COMPILE-FILE-PATHNAME*, and if absolute, is dumped in the debug-info.
  (untruename nil :type (or pathname null))
610
  ;;
wlott's avatar
wlott committed
611
612
613
  ;; The file's write date (if relevant.)
  (write-date nil :type (or unsigned-byte null))
  ;;
ram's avatar
ram committed
614
615
616
  ;; This file's FILE-COMMENT, or NIL if none.
  (comment nil :type (or simple-string null))
  ;;
wlott's avatar
wlott committed
617
618
619
620
621
622
623
  ;; The source path root number of the first form in this file (i.e. the
  ;; total number of forms converted previously in this compilation.)
  (source-root 0 :type unsigned-byte)
  ;;
  ;; Parallel vectors containing the forms read out of the file and the file
  ;; positions that reading of each form started at (i.e. the end of the
  ;; previous form.)
624
  (forms (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t))
625
626
627
628
  (positions (make-array 10 :fill-pointer 0 :adjustable t) :type (vector t))
  ;;
  ;; Language to use.  Normally Lisp, but sometimes Dylan.
  (language :lisp :type (member :lisp :dylan)))
wlott's avatar
wlott committed
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

;;; The Source-Info structure provides a handle on all the source information
;;; for an entire compilation.
;;;
(defstruct (source-info
	    (:print-function
	     (lambda (s stream d)
	       (declare (ignore s d))
	       (format stream "#<Source-Info>"))))
  ;;
  ;; The UT that compilation started at.
  (start-time (get-universal-time) :type unsigned-byte)
  ;;
  ;; A list of the file-info structures for this compilation.
  (files nil :type list)
  ;;
  ;; The tail of the Files for the file we are currently reading.
  (current-file nil :type list)
  ;;
  ;; The stream that we are using to read the Current-File.  Null if no stream
  ;; has been opened yet.
  (stream nil :type (or stream null)))


;;; Make-File-Source-Info  --  Internal
;;;
;;;    Given a list of pathnames, return a Source-Info structure.
;;;
(defun make-file-source-info (files)
  (declare (list files))
  (let ((file-info
	 (mapcar #'(lambda (x)
ram's avatar
ram committed
661
		     (make-file-info :name (truename x)
662
				     :untruename x
663
664
665
666
667
668
				     :write-date (file-write-date x)
				     :language
				     (if (string-equal (pathname-type x)
						       "dylan")
					 :dylan
					 :lisp)))
wlott's avatar
wlott committed
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
		 files)))

    (make-source-info :files file-info
		      :current-file file-info)))


;;; MAKE-LISP-SOURCE-INFO  --  Interface
;;;
;;;    Return a SOURCE-INFO to describe the incremental compilation of Form.
;;; Also used by EVAL:INTERNAL-EVAL.
;;;
(defun make-lisp-source-info (form)
  (make-source-info
   :start-time (get-universal-time)
   :files (list (make-file-info :name :lisp
				:forms (vector form)
				:positions '#(0)))))


;;; MAKE-STREAM-SOURCE-INFO  --  Internal
;;;
;;;    Return a SOURCE-INFO which will read from Stream.
;;;
692
693
694
(defun make-stream-source-info (stream language)
  (declare (type (member :lisp :dylan) language))
  (let ((files (list (make-file-info :name :stream :language language))))
wlott's avatar
wlott committed
695
696
697
698
699
700
701
702
703
704
705
706
707
708
    (make-source-info
     :files files
     :current-file files
     :stream stream)))


;;; Normal-Read-Error  --  Internal
;;;
;;;    Print an error message for a non-EOF error on Stream.  Old-Pos is a
;;; preceding file position that hopefully comes before the beginning of the
;;; line.  Of course, this only works on streams that support the file-position
;;; operation.
;;;
(defun normal-read-error (stream old-pos condition)
709
  (declare (type stream stream) (type unsigned-byte old-pos))
wlott's avatar
wlott committed
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
  (let ((pos (file-position stream)))
    (file-position stream old-pos)
    (let ((start old-pos))
      (loop
	(let ((line (read-line stream nil))
	      (end (file-position stream)))
	  (when (>= end pos)
	    (compiler-error-message
	     "Read error at ~D:~% \"~A/\\~A\"~%~A"
	     pos
	     (string-left-trim " 	"
			       (subseq line 0 (- pos start)))
	     (subseq line (- pos start))
	     condition)
	    (return))
	  (setq start end)))))
  (undefined-value))


;;; Ignore-Error-Form  --  Internal
;;;
;;;    Back Stream up to the position Pos, then read a form with
;;; *Read-Suppress* on, discarding the result.  If an error happens during this
;;; read, then bail out using Compiler-Error (fatal in this context).
;;;
735
(defun ignore-error-form (stream pos)
wlott's avatar
wlott committed
736
737
  (declare (type stream stream) (type unsigned-byte pos))
  (file-position stream pos)
738
739
  (handler-case (let ((*read-suppress* t)
		      (*features* (backend-features *target-backend*)))
740
		  (read stream))
wlott's avatar
wlott committed
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
    (error (condition)
      (declare (ignore condition))
      (compiler-error "Unable to recover from read error."))))


;;; Unexpected-EOF-Error  --  Internal
;;;
;;;    Print an error message giving some context for an EOF error.  We print
;;; the first line after Pos that contains #\" or #\(, or lacking that, the
;;; first non-empty line.
;;;
(defun unexpected-eof-error (stream pos condition)
  (declare (type stream stream) (type unsigned-byte pos))
  (let ((res nil))
    (file-position stream pos)
    (loop
      (let ((line (read-line stream nil nil))) 
	(unless line (return))
	(when (or (find #\" line) (find #\( line))
	  (setq res line)
	  (return))
	(unless (or res (zerop (length line)))
	  (setq res line))))

    (compiler-error-message
     "Read error in form starting at ~D:~%~@[ \"~A\"~%~]~A"
     pos res condition))

  (file-position stream (file-length stream))
  (undefined-value))


;;; Careful-Read  --  Internal
;;;
;;;    Read a form from Stream, returning EOF at EOF.  If a read error happens,
;;; then attempt to recover if possible, returing a proxy error form.
;;;
778
(defun careful-read (stream eof pos)
779
  (handler-case (let ((*features* (backend-features *target-backend*)))
780
		  (read stream nil eof))
wlott's avatar
wlott committed
781
782
783
784
785
786
    (error (condition)
      (let ((new-pos (file-position stream)))
	(cond ((= new-pos (file-length stream))
	       (unexpected-eof-error stream pos condition))
	      (t
	       (normal-read-error stream pos condition)
787
	       (ignore-error-form stream pos))))
788
789
      '(cerror "Skip this form."
	       "Attempt to load a file having a compile-time read error."))))
wlott's avatar
wlott committed
790
791
792
793
794
795


;;; Get-Source-Stream  --  Internal
;;;
;;;    If Stream is present, return it, otherwise open a stream to the current
;;; file.  There must be a current file.  When we open a new file, we also
796
;;; reset *Package* and policy.  This gives the effect of rebinding
wlott's avatar
wlott committed
797
798
799
800
801
802
803
804
;;; around each file.
;;;
(defun get-source-stream (info)
  (declare (type source-info info))
  (cond ((source-info-stream info))
	(t
	 (setq *package* *initial-package*)
	 (setq *default-cookie* (copy-cookie *initial-cookie*))
805
806
	 (setq *default-interface-cookie*
	       (copy-cookie *initial-interface-cookie*))
807
808
	 (let* ((finfo (first (source-info-current-file info)))
		(name (file-info-name finfo)))
809
810
	   (setq *compile-file-truename* name)
	   (setq *compile-file-pathname* (file-info-untruename finfo))
811
812
	   (setf (source-info-stream info)
		 (open name :direction :input))))))
wlott's avatar
wlott committed
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

;;; CLOSE-SOURCE-INFO  --  Internal
;;;
;;;    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)
  (undefined-value))


;;; Advance-Source-File  --  Internal
;;;
;;;    Advance Info to the next source file.  If none, return NIL, otherwise T.
;;;
(defun advance-source-file (info)
  (declare (type source-info info))
  (close-source-info info)
  (let ((prev (pop (source-info-current-file info))))
    (if (source-info-current-file info)
	(let ((current (first (source-info-current-file info))))
	  (setf (file-info-source-root current)
		(+ (file-info-source-root prev)
		   (length (file-info-forms prev))))
	  t)
	nil)))

842
;;; PROCESS-SOURCES -- internal.
wlott's avatar
wlott committed
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
;;; Read the sources from the source files and process them.
;;; 
(defun process-sources (info)
  (let* ((file (first (source-info-current-file info)))
	 (language (file-info-language file))
	 (stream (get-source-stream info)))
    (ecase language
      (:lisp
       (loop
	 (let* ((pos (file-position stream))
		(eof '(*eof*))
		(form (careful-read stream eof pos)))
	   (if (eq form eof)
	       (return)
	       (let* ((forms (file-info-forms file))
		      (current-idx (+ (fill-pointer forms)
				      (file-info-source-root file))))
		 (vector-push-extend form forms)
		 (vector-push-extend pos (file-info-positions file))
		 (clrhash *source-paths*)
		 (find-source-paths form current-idx)
		 (process-form form
			       `(original-source-start 0 ,current-idx)))))))
      (:dylan
       (let ((*error-output* *compiler-error-output*))
	 (dylan::parse-and-convert
	  stream
	  #'(lambda (form start-position)
	      (let* ((forms (file-info-forms file))
		     (current-idx (+ (fill-pointer forms)
				     (file-info-source-root file))))
		(vector-push-extend form forms)
		(vector-push-extend start-position (file-info-positions file))
		(clrhash *source-paths*)
		(process-form form
			      `(original-source-start 0 ,current-idx))))))))
    (when (advance-source-file info)
      (process-sources info))))
wlott's avatar
wlott committed
882
883


884
885
886
887
888
889
890
891
892
893
894
895
896
897
;;; FIND-FILE-INFO  --  Interface
;;;
;;;    Return the File-Info describing the Index'th form.
;;;
(defun find-file-info (index info)
  (declare (type index index) (type source-info info))
  (dolist (file (source-info-files info))
    (when (> (+ (length (file-info-forms file))
		(file-info-source-root file))
	     index)
      (return file))))


;;; FIND-SOURCE-ROOT  --  Interface
wlott's avatar
wlott committed
898
899
900
901
902
;;;
;;;    Return the Index'th source form read from Info and the position that it
;;; was read at.
;;;
(defun find-source-root (index info)
903
904
905
906
907
  (declare (type source-info info) (type index index))
  (let* ((file (find-file-info index info))
	 (idx (- index (file-info-source-root file))))
    (values (aref (file-info-forms file) idx)
	    (aref (file-info-positions file) idx))))
wlott's avatar
wlott committed
908
909
910
911
912
913

;;;; Top-level form processing:

;;; CONVERT-AND-MAYBE-COMPILE  --  Internal
;;;
;;;    Called by top-level form processing when we are ready to actually
914
;;; compile something.  If *BLOCK-COMPILE* is T, then we still convert the
wlott's avatar
wlott committed
915
916
;;; form, but delay compilation, pushing the result on *TOP-LEVEL-LAMBDAS*
;;; instead.
917
;;;
918
919
920
;;;   The cookies at this time becomes the default policy for compiling the
;;; form.  Any enclosed PROCLAIMs will affect only subsequent forms.
;;;
921
922
(defun convert-and-maybe-compile (form path)
  (declare (list path))
923
924
925
926
927
928
929
930
931
932
933
934
  (let ((orig (bytes-consed-between-gcs)))
    (unwind-protect
	(progn
	  (setf (bytes-consed-between-gcs) (* orig 4))
	  (let* ((*lexical-environment*
		  (make-lexenv :cookie *default-cookie*
			       :interface-cookie *default-interface-cookie*))
		 (tll (ir1-top-level form path nil)))
	    (cond ((eq *block-compile* t) (push tll *top-level-lambdas*))
		  (t
		   (compile-top-level (list tll) nil)))))
      (setf (bytes-consed-between-gcs) orig))))
wlott's avatar
wlott committed
935
936
937
938

;;; PROCESS-PROGN  --  Internal
;;;
;;;    Process a PROGN-like portion of a top-level form.  Forms is a list of
939
;;; the forms, and Path is source path of the form they came out of.
wlott's avatar
wlott committed
940
;;;
941
942
(defun process-progn (forms path)
  (declare (list forms) (list path))
943
  (dolist (form forms)
944
    (process-form form path)))
wlott's avatar
wlott committed
945
946


947
948
;;; PREPROCESSOR-MACROEXPAND  --  Internal
;;;
949
950
951
;;;    Macroexpand form in the current environment with an error handler.  We
;;; only expand one level, so that we retain all the intervening forms in the
;;; source path.
952
953
;;;
(defun preprocessor-macroexpand (form)
954
  (handler-case (macroexpand-1 form *lexical-environment*)
955
    (error (condition)
956
       (compiler-error "(during macroexpansion)~%~A" condition))))
957
958


959
960
961
962
963
;;; PROCESS-LOCALLY  --  Internal
;;;
;;;    Process a top-level use of LOCALLY.  We parse declarations and then
;;; recursively process the body.
;;;
964
;;;    Binding *DEFAULT-xxx-COOKIE* is pretty much of a hack, since it causes
965
966
967
968
969
;;; LOCALLY to "capture" enclosed proclamations.  It is necessary because
;;; CONVERT-AND-MAYBE-COMPILE uses the value of *DEFAULT-COOKIE* as the policy.
;;; The need for this hack is due to the quirk that there is no way to
;;; represent in a cookie that an optimize quality came from the default.
;;;
970
971
(defun process-locally (form path)
  (declare (list path))
972
973
974
975
976
  (multiple-value-bind
      (body decls)
      (system:parse-body (cdr form) *lexical-environment* nil)
    (let* ((*lexical-environment*
	    (process-declarations decls nil nil (make-continuation)))
977
978
979
	   (*default-cookie* (lexenv-cookie *lexical-environment*))
	   (*default-interface-cookie*
	    (lexenv-interface-cookie *lexical-environment*)))
980
      (process-progn body path))))
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999


;;; PROCESS-FILE-COMMENT  --  Internal
;;;
;;;    Stash file comment in the file-info structure.
;;;
(defun process-file-comment (form)
  (unless (and (= (length form) 2) (stringp (second form)))
    (compiler-error "Bad FILE-COMMENT form: ~S." form))
  (let ((file (first (source-info-current-file *source-info*))))
    (cond ((file-info-comment file)
	   (compiler-warning "Ignoring extra file comment:~%  ~S." form))
	  (t
	   (let ((comment (coerce (second form) 'simple-string)))
	     (setf (file-info-comment file) comment)
	     (when *compile-verbose*
	       (compiler-mumble "~&Comment: ~A~2&" comment)))))))


1000
;;; PROCESS-COLD-LOAD-FORM  --  Internal
1001
1002
;;;
;;;    Force any pending top-level forms to be compiled and dumped so that they
1003
1004
;;; will be evaluated in the correct package environment.  Eval the form if
;;; Eval is true, then dump the form to evaled at (cold) load time.
1005
;;;
1006
1007
1008
1009
(defun process-cold-load-form (form path eval)
  (let ((object *compile-object*))
    (etypecase object
      (fasl-file
1010
       (compile-top-level-lambdas () t)
1011
1012
       (fasl-dump-cold-load-form form object))
      ((or null core-object)
1013
1014
       (convert-and-maybe-compile form path)))
    (when eval (eval form))))
1015
1016
1017
1018
1019


;;; PROCESS-PROCLAIM  --  Internal
;;;
;;;    If a special block compilation delimiter, then start or end the block as
1020
1021
;;; appropriate.  Otherwise, just convert-and-maybe-compile the form.  If
;;; *BLOCK-COMPILE* is NIL, then we ignore block declarations.
1022
;;;
1023
(defun process-proclaim (form path)
1024
1025
1026
1027
1028
  (if (and (eql (length form) 2) (constantp (cadr form)))
      (let ((spec (eval (cadr form))))
	(if (consp spec)
	    (case (first spec)
	      (start-block
1029
	       (when *block-compile*
1030
		 (finish-block-compilation)
1031
1032
1033
		 (setq *block-compile* t)
		 (setq *entry-points* (rest spec))))
	      (end-block
1034
	       (finish-block-compilation))
1035
	      (t
1036
1037
1038
	       (convert-and-maybe-compile form path)))
	    (convert-and-maybe-compile form path)))
      (convert-and-maybe-compile form path)))
1039
1040


wlott's avatar
wlott committed
1041
1042
1043
1044
1045
(proclaim '(special *compiler-error-bailout*))

;;; PROCESS-FORM  --  Internal
;;;
;;;    Process a top-level Form with the specified source Path and output to
ram's avatar
ram committed
1046
1047
1048
1049
;;; Object.
;;; -- If this is a magic top-level form, then do stuff.
;;; -- If it is a macro expand it.
;;; -- Otherwise, just compile it.
wlott's avatar
wlott committed
1050
;;;
1051
1052
(defun process-form (form path)
  (declare (list path))
wlott's avatar
wlott committed
1053
  (catch 'process-form-error-abort
1054
1055
    (let* ((path (or (gethash form *source-paths*) (cons form path)))
	   (*compiler-error-bailout*
1056
1057
1058
1059
	    #'(lambda ()
		(convert-and-maybe-compile
		 `(error "Execution of a form compiled with errors:~% ~S"
			 ',form)
1060
		 path)
1061
		(throw 'process-form-error-abort nil))))
wlott's avatar
wlott committed
1062
      (if (atom form)
1063
	  (convert-and-maybe-compile form path)
wlott's avatar
wlott committed
1064
	  (case (car form)
1065
1066
1067
	    ((make-package shadow shadowing-import export
	      unexport use-package unuse-package import
	      old-in-package %in-package)
1068
	     (process-cold-load-form form path t))
1069
	    ((error cerror break signal)
1070
	     (process-cold-load-form form path nil))
1071
1072
1073
	    (kernel:%compiler-defstruct
	     (convert-and-maybe-compile form path)
	     (compile-top-level-lambdas () t))
wlott's avatar
wlott committed
1074
1075
1076
1077
1078
1079
	    ((eval-when)
	     (unless (>= (length form) 2)
	       (compiler-error "EVAL-WHEN form is too short: ~S." form))
	     (do-eval-when-stuff
	      (cadr form) (cddr form)
	      #'(lambda (forms)
1080
		  (process-progn forms path))))
wlott's avatar
wlott committed
1081
1082
1083
1084
1085
1086
	    ((macrolet)
	     (unless (>= (length form) 2)
	       (compiler-error "MACROLET form is too short: ~S." form))
	     (do-macrolet-stuff
	      (cadr form)
	      #'(lambda ()
1087
1088
1089
		  (process-progn (cddr form) path))))
	    (locally (process-locally form path))
	    (progn (process-progn (cdr form) path))
1090
	    (file-comment (process-file-comment form))
1091
	    (proclaim (process-proclaim form path))
wlott's avatar
wlott committed
1092
	    (t
ram's avatar
ram committed
1093
1094
	     (let ((exp (preprocessor-macroexpand form)))
	       (if (eq exp form)
1095
1096
		   (convert-and-maybe-compile form path)
		   (process-form exp path))))))))
wlott's avatar
wlott committed
1097
1098
1099
      
  (undefined-value))

1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119

;;;; Load time value support.

;;; PRODUCING-FASL-FILE  --  interface.
;;;
;;; Returns T iff we are currently producing a fasl-file and hence constants
;;; need to be dumped carfully.
;;; 
(defun producing-fasl-file ()
  (unless *converting-for-interpreter*
    (fasl-file-p *compile-object*)))

;;; COMPILE-LOAD-TIME-VALUE  --  interface.
;;;
;;; Compile FORM and arrange for it to be called at load-time.  Returns the
;;; dumper handle and our best guess at the type of the object.
;;; 
(defun compile-load-time-value
       (form &optional
	     (name (let ((*print-level* 2) (*print-length* 3))
1120
1121
1122
1123
1124
		     (format nil "Load Time Value of ~S"
			     (if (and (listp form)
				      (eq (car form) 'make-value-cell))
				 (second form)
				 form)))))
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
  (let ((lambda (compile-load-time-stuff form name t)))
    (values
     (fasl-dump-load-time-value-lambda lambda *compile-object*)
     (let ((type (leaf-type lambda)))
       (if (function-type-p type)
	   (single-value-type (function-type-returns type))
	   *wild-type*)))))

;;; COMPILE-MAKE-LOAD-FORM-INIT-FORMS  --  internal.
;;;
;;; Compile the FORMS and arrange for them to be called (for effect, not value)
;;; at load-time.
;;; 
(defun compile-make-load-form-init-forms (forms name)
  (let ((lambda (compile-load-time-stuff `(progn ,@forms) name nil)))
    (fasl-dump-top-level-lambda-call lambda *compile-object*)))

;;; COMPILE-LOAD-TIME-STUFF  --  internal.
;;;
;;; Does the actual work of COMPILE-LOAD-TIME-VALUE or COMPILE-MAKE-LOAD-FORM-
;;; INIT-FORMS.
;;; 
(defun compile-load-time-stuff (form name for-value)
  (compile-top-level-lambdas () t)
  (with-ir1-namespace
   (let* ((*lexical-environment* (make-null-environment))
	  (lambda (ir1-top-level form *current-path* for-value)))
     (setf (leaf-name lambda) name)
     (compile-top-level (list lambda) t)
     lambda)))

;;; COMPILE-LOAD-TIME-VALUE-LAMBDA  --  internal.
;;;
;;; Called by COMPILE-TOP-LEVEL when it was pased T for LOAD-TIME-VALUE-P
;;; (which happens in COMPILE-LOAD-TIME-STUFF).  We don't try to combine
1160
1161
1162
;;; this component with anything else and frob the name.  If not in a
;;; :TOP-LEVEL component, then don't bother compiling, because it was merged
;;; with a run-time component.
1163
1164
1165
1166
1167
;;; 
(defun compile-load-time-value-lambda (lambdas)
  (assert (null (cdr lambdas)))
  (let* ((lambda (car lambdas))
	 (component (block-component (node-block (lambda-bind lambda)))))
1168
1169
1170
1171
    (when (eq (component-kind component) :top-level)
      (setf (component-name component) (leaf-name lambda))
      (compile-component component)
      (clear-ir1-info component))))
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222


;;; EMIT-MAKE-LOAD-FORM  --  interface.
;;;
;;; The entry point for MAKE-LOAD-FORM support.  When IR1 conversion finds a
;;; constant structure, it invokes this to arrange for proper dumping.  If it
;;; turns out that the constant has already been dumped, then we don't need
;;; to do anything.
;;;
;;; If the constant hasn't been dumped, then we check to see if we are in the
;;; process of creating it.  We detect this by maintaining the special
;;; *constants-being-created* as a list of all the constants we are in the
;;; process of creating.  Actually, each entry is a list of the constant and
;;; any init forms that need to be processed on behalf of that constant.
;;;
;;; It's not necessarily an error for this to happen.  If we are processing the
;;; init form for some object that showed up *after* the original reference
;;; to this constant, then we just need to defer the processing of that init
;;; form.  To detect this, we maintain *constants-created-sense-last-init* as
;;; a list of the constants created sense the last time we started processing
;;; an init form.  If the constant passed to emit-make-load-form shows up in
;;; this list, then there is a circular chain through creation forms, which is
;;; an error.
;;;
;;; If there is some intervening init form, then we blow out of processing it
;;; by throwing to the tag PENDING-INIT.  The value we throw is the entry from
;;; *constants-being-created*.  This is so the offending init form can be
;;; tacked onto the init forms for the circular object.
;;;
;;; If the constant doesn't show up in *constants-being-created*, then we have
;;; to create it.  We call MAKE-LOAD-FORM and check to see if the creation
;;; form is the magic value :just-dump-it-normally.  If it is, then we don't
;;; do anything.  The dumper will eventually get it's hands on the object
;;; and use the normal structure dumping noise on it.
;;;
;;; Otherwise, we bind *constants-being-created* and *constants-created-sense-
;;; last-init* and compile the creation form a la load-time-value.  When this
;;; finishes, we tell the dumper to use that result instead whenever it sees
;;; this constant.
;;;
;;; Now we try to compile the init form.  We bind *constants-created-sense-
;;; last-init* to NIL and compile the init form (and any init forms that were
;;; added because of circularity detection).  If this works, great.  If not,
;;; we add the init forms to the init forms for the object that caused the
;;; problems and let it deal with it.
;;; 
(defvar *constants-being-created* nil)
(defvar *constants-created-sense-last-init* nil)
;;;
(defun emit-make-load-form (constant)
  (assert (fasl-file-p *compile-object*))
1223
  (unless (fasl-constant-already-dumped constant *compile-object*)
1224
1225
1226
1227
1228
1229
1230
    (let ((circular-ref (assoc constant *constants-being-created* :test #'eq)))
      (when circular-ref
	(when (find constant *constants-created-sense-last-init* :test #'eq)
	  (throw constant t))
	(throw 'pending-init circular-ref)))
    (multiple-value-bind
	(creation-form init-form)
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
	(handler-case
	    (if (fboundp 'lisp::make-load-form)
		(locally
		 (declare (optimize (inhibit-warnings 3)))
		 (lisp::make-load-form constant (make-null-environment)))
		(make-structure-load-form constant))
	  (error (condition)
		 (compiler-error "(while making load form for ~S)~%~A"
				 constant condition)))
      (case creation-form
	(:just-dump-it-normally
	 (fasl-validate-structure constant *compile-object*)
	 t)
	(:ignore-it
	 nil)
	(t
	 (let* ((name (let ((*print-level* 1) (*print-length* 2))
			(with-output-to-string (stream)
			  (write constant :stream stream))))
		(info (if init-form
			  (list constant name init-form)
			  (list constant))))
	   (let ((*constants-being-created*
		  (cons info *constants-being-created*))
		 (*constants-created-sense-last-init*
		  (cons constant *constants-created-sense-last-init*)))
	     (when
		 (catch constant
		   (fasl-note-handle-for-constant
		    constant
		    (compile-load-time-value
		     creation-form
		     (format nil "Creation Form for ~A" name))
		    *compile-object*)
		   nil)
	       (compiler-error "Circular references in creation form for ~S"
			       constant)))
	   (when (cdr info)
	     (let* ((*constants-created-sense-last-init* nil)
		    (circular-ref
		     (catch 'pending-init
		       (loop for (name form) on (cdr info) by #'cddr
			 collect name into names
			 collect form into forms
			 finally do
			 (compile-make-load-form-init-forms
			  forms
			  (format nil "Init Form~:[~;s~] for ~{~A~^, ~}"
				  (cdr forms) names)))
		       nil)))
	       (when circular-ref
		 (setf (cdr circular-ref)
		       (append (cdr circular-ref) (cdr info))))))))))))
1284
1285


wlott's avatar
wlott committed
1286
1287
1288

;;;; COMPILE-FILE and COMPILE-FROM-STREAM: 

1289
1290
1291
1292
1293
1294
1295
1296
;;; We build a list of top-level lambdas, and then periodically smash them
;;; together into a single component and compile it.
;;;
(defvar *pending-top-level-lambdas*)

;;; The maximum number of top-level lambdas we put in a single top-level
;;; component.
;;;
1297
(defparameter top-level-lambda-max 10)
1298
1299


1300
1301
;;; OBJECT-CALL-TOP-LEVEL-LAMBDA  --  Internal
;;;
1302
1303
1304
1305
1306
1307
1308
1309
1310
(defun object-call-top-level-lambda (tll)
  (declare (type functional tll))
  (let ((object *compile-object*))
    (etypecase object
      (fasl-file
       (fasl-dump-top-level-lambda-call tll object))
      (core-object
       (core-call-top-level-lambda tll object))
      (null))))
1311
1312
1313


;;; SUB-COMPILE-TOP-LEVEL-LAMBDAS  --  Internal
1314
1315
1316
1317
1318
1319
;;;
;;;    Add Lambdas to the pending lambdas.  If this leaves more than
;;; TOP-LEVEL-LAMBDA-MAX lambdas in the list, or if Force-P is true, then smash
;;; the lambdas into a single component, compile it, and call the resulting
;;; function.
;;;
1320
1321
(defun sub-compile-top-level-lambdas (lambdas force-p)
  (declare (list lambdas))
1322
1323
1324
1325
1326
1327
1328
1329
1330
  (setq *pending-top-level-lambdas*
	(append *pending-top-level-lambdas* lambdas))
  (let ((pending *pending-top-level-lambdas*))
    (when (and pending
	       (or (> (length pending) top-level-lambda-max)
		   force-p))
      (multiple-value-bind (component tll)
			   (merge-top-level-lambdas pending)
	(setq *pending-top-level-lambdas* ())
1331
1332
1333
	(let ((*byte-compile* (if (eq *byte-compile* :maybe)
				  *byte-compile-top-level*
				  *byte-compile*)))
1334
	  (compile-component component))
1335
	(clear-ir1-info component)
1336
	(object-call-top-level-lambda tll))))
1337
1338
1339
1340
1341
1342
1343
1344
1345
  (undefined-value))


;;; COMPILE-TOP-LEVEL-LAMBDAS  --  Internal
;;;
;;;    Compile top-level code and call the Top-Level lambdas.  We pick off
;;; top-level lambdas in non-top-level components here, calling SUB-c-t-l-l on
;;; each subsequence of normal top-level lambdas.
;;;
1346
1347
(defun compile-top-level-lambdas (lambdas force-p)
  (declare (list lambdas))
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
  (let ((len (length lambdas)))
    (flet ((loser (start)
	     (or (position-if #'(lambda (x)
				  (not (eq (component-kind
					    (block-component
					     (node-block
					      (lambda-bind x))))
					   :top-level)))
			      lambdas
			      :start start)
		 len)))
      (do* ((start 0 (1+ loser))
	    (loser (loser start) (loser start)))
	   ((>= start len)
	    (when force-p
1363
	      (sub-compile-top-level-lambdas nil t)))
1364
	(sub-compile-top-level-lambdas (subseq lambdas start loser)
1365
				       (or force-p (/= loser len)))
1366
	(unless (= loser len)
1367
	  (object-call-top-level-lambda (elt lambdas loser))))))
1368
1369
1370
1371
1372
1373
  (undefined-value))


;;; Compile-Top-Level  --  Internal
;;;
;;;    Compile Lambdas (a list of the lambdas for top-level forms) into the
1374
1375
1376
;;; Object file.  We loop doing local call analysis until it converges, since a
;;; single pass might miss something due to components being joined by let
;;; conversion.
1377
;;;
1378
1379
(defun compile-top-level (lambdas load-time-value-p)
  (declare (list lambdas))
1380
  (maybe-mumble "Locall ")
1381
1382
1383
1384
1385
1386
1387
1388
1389
  (loop
    (let ((did-something nil))
      (dolist (lambda lambdas)
	(let* ((component (block-component (node-block (lambda-bind lambda))))
	       (*all-components* (list component)))
	  (when (component-new-functions component)
	    (setq did-something t)
	    (local-call-analyze component))))
      (unless did-something (return))))
1390
  
1391
  (maybe-mumble "IDFO ")
1392
  (multiple-value-bind (components top-components hairy-top)
1393
		       (find-initial-dfo lambdas)
1394
1395
    (let ((*all-components* (append components top-components))
	  (top-level-closure nil))
1396
1397
1398
1399
      (when *check-consistency*
	(maybe-mumble "[Check]~%")
	(check-ir1-consistency *all-components*))
      
1400
      (dolist (component (append hairy-top top-components))
1401
	(when (pre-environment-analyze-top-level component)
ram's avatar
ram committed
1402
	  (setq top-level-closure t)))
1403
1404
1405
1406
1407
1408
1409
1410

      (let ((*byte-compile*
	     (if (and top-level-closure (eq *byte-compile* :maybe))
		 nil
		 *byte-compile*)))
	(dolist (component components)
	  (compile-component component)
	  (when (replace-top-level-xeps component)
1411
1412
1413
1414
1415
1416
1417
1418
1419
	    (setq top-level-closure t)))
	
	(when *check-consistency*
	  (maybe-mumble "[Check]~%")
	  (check-ir1-consistency *all-components*))
	
	(if load-time-value-p
	    (compile-load-time-value-lambda lambdas)
	    (compile-top-level-lambdas lambdas top-level-closure)))
1420

1421
1422
1423
      (dolist (component components)
	(clear-ir1-info component))
      (clear-stuff)))
1424
1425
1426
  (undefined-value))


1427
1428
1429
1430
1431
;;; FINISH-BLOCK-COMPILATION  --  Internal
;;;
;;;    Actually compile any stuff that has been queued up for block
;;; compilation.
;;;
1432
(defun finish-block-compilation ()
1433
1434
  (when *block-compile*
    (when *top-level-lambdas*
1435
      (compile-top-level (nreverse *top-level-lambdas*) nil)
1436
1437
1438
      (setq *top-level-lambdas* ()))
    (setq *block-compile* :specified)
    (setq *entry-points* nil)))
1439
1440


wlott's avatar
wlott committed
1441
1442
;;; Sub-Compile-File  --  Internal
;;;
1443
1444
1445
;;;    Read all forms from Info and compile them, with output to Object.  We
;;; return :ERROR, :WARNING, :NOTE or NIL to indicate the most severe kind of
;;; compiler diagnostic emitted.
wlott's avatar
wlott committed
1446
;;;
1447
1448
(defun sub-compile-file (info &optional d-s-info)
  (declare (type source-info info))
ram's avatar
ram committed
1449
1450
1451
1452
1453
1454
1455
  (with-ir1-namespace
    (let* ((start-errors *compiler-error-count*)
	   (start-warnings *compiler-warning-count*)
	   (start-notes *compiler-note-count*)
	   (*package* *package*)
	   (*initial-package* *package*)
	   (*initial-cookie* *default-cookie*)
1456