0.6.9.8:
[sbcl.git] / src / code / load.lisp
1 ;;;; parts of the loader which make sense in the cross-compilation
2 ;;;; host (and which are useful in the host, because they're used by
3 ;;;; GENESIS)
4 ;;;;
5 ;;;; based on the CMU CL load.lisp code, written by Skef Wholey and
6 ;;;; Rob Maclachlan
7
8 ;;;; This software is part of the SBCL system. See the README file for
9 ;;;; more information.
10 ;;;;
11 ;;;; This software is derived from the CMU CL system, which was
12 ;;;; written at Carnegie Mellon University and released into the
13 ;;;; public domain. The software is in the public domain and is
14 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
15 ;;;; files for more information.
16
17 (in-package "SB!IMPL")
18 \f
19 ;;;; variables
20
21 ;;; FIXME: It's awkward having LOAD stuff in SB!IMPL and dump stuff in
22 ;;; SB!C. Among other things, it makes it hard to figure out where
23 ;;; *FASL-HEADER-STRING-START-STRING* and
24 ;;; *FASL-HEADER-STRING-STOP-CHAR-CODE* should go. Perhaps we should
25 ;;; make a package called SB-DUMP or SB-LD which includes all
26 ;;; knowledge of both loading and dumping.
27
28 ;;; This value is used to identify fasl files. Even though this is not
29 ;;; declared as a constant (because ANSI Common Lisp has no facility
30 ;;; for declaring values which are constant under EQUAL but not EQL),
31 ;;; obviously you shouldn't mess with it lightly. If you do set a new
32 ;;; value for some reason, keep these things in mind:
33 ;;; * To avoid confusion with the similar but incompatible CMU CL
34 ;;;   fasl file format, the value should not be "FASL FILE", which
35 ;;;   is what CMU CL used for the same purpose.
36 ;;; * Since its presence at the head of a file is used by LOAD to
37 ;;;   decide whether a file is to be fasloaded or sloloaded, the value
38 ;;;   should be something which can't legally appear at the head of a
39 ;;;   Lisp source file.
40 ;;; * The value should not contain any line-terminating characters,
41 ;;;   because they're hard to express portably and because the LOAD
42 ;;;   code might reasonably use READ-LINE to get the value to compare
43 ;;;   against.
44 (defparameter sb!c:*fasl-header-string-start-string* "# FASL"
45   #!+sb-doc
46   "a string which appears at the start of a fasl file header")
47
48 (defparameter sb!c:*fasl-header-string-stop-char-code* 255
49   #!+sb-doc
50   "the code for a character which terminates a fasl file header")
51
52 (defvar *load-depth* 0
53   #!+sb-doc
54   "the current number of recursive loads")
55 (declaim (type index *load-depth*))
56
57 ;;; the FASL file we're reading from
58 (defvar *fasl-file*)
59 (declaim (type lisp-stream fasl-file))
60
61 (defvar *load-print* nil
62   #!+sb-doc
63   "the default for the :PRINT argument to LOAD")
64 (defvar *load-verbose* nil
65   ;; Note that CMU CL's default for this was T, and ANSI says it's
66   ;; implementation-dependent. We choose NIL on the theory that it's
67   ;; a nicer default behavior for Unix programs.
68   #!+sb-doc
69   "the default for the :VERBOSE argument to LOAD")
70 \f
71 ;;;; miscellaneous load utilities
72
73 ;;; Output the current number of semicolons after a fresh-line.
74 ;;; FIXME: non-mnemonic name
75 (defun load-fresh-line ()
76   (fresh-line)
77   (let ((semicolons ";;;;;;;;;;;;;;;;"))
78     (do ((count *load-depth* (- count (length semicolons))))
79         ((< count (length semicolons))
80          (write-string semicolons *standard-output* :end count))
81       (declare (fixnum count))
82       (write-string semicolons))
83     (write-char #\space)))
84
85 ;;; If VERBOSE, output (to *STANDARD-OUTPUT*) a message about how we're
86 ;;; loading from STREAM-WE-ARE-LOADING-FROM.
87 ;;; FIXME: non-mnemonic name
88 (defun do-load-verbose (stream-we-are-loading-from verbose)
89   (when verbose
90     (load-fresh-line)
91     (let ((name #-sb-xc-host (file-name stream-we-are-loading-from)
92                 #+sb-xc-host nil))
93       (if name
94           (format t "loading ~S~%" name)
95           (format t "loading stuff from ~S~%" stream-we-are-loading-from)))))
96 \f
97 ;;;; utilities for reading from fasl files
98
99 #!-sb-fluid (declaim (inline read-byte))
100
101 ;;;    Expands into code to read an N-byte unsigned integer using
102 ;;; fast-read-byte.
103 (defmacro fast-read-u-integer (n)
104   (declare (optimize (speed 0)))
105   (do ((res '(fast-read-byte)
106             `(logior (fast-read-byte)
107                      (ash ,res 8)))
108        (cnt 1 (1+ cnt)))
109       ((>= cnt n) res)))
110
111 ;;; Like Fast-Read-U-Integer, but the size may be determined at run time.
112 (defmacro fast-read-variable-u-integer (n)
113   (let ((n-pos (gensym))
114         (n-res (gensym))
115         (n-cnt (gensym)))
116     `(do ((,n-pos 8 (+ ,n-pos 8))
117           (,n-cnt (1- ,n) (1- ,n-cnt))
118           (,n-res
119            (fast-read-byte)
120            (dpb (fast-read-byte) (byte 8 ,n-pos) ,n-res)))
121          ((zerop ,n-cnt) ,n-res)
122        (declare (type index ,n-pos ,n-cnt)))))
123
124 ;;; Read a signed integer.
125 (defmacro fast-read-s-integer (n)
126   (declare (optimize (speed 0)))
127   (let ((n-last (gensym)))
128     (do ((res `(let ((,n-last (fast-read-byte)))
129                  (if (zerop (logand ,n-last #x80))
130                      ,n-last
131                      (logior ,n-last #x-100)))
132               `(logior (fast-read-byte)
133                        (ash (the (signed-byte ,(* cnt 8)) ,res) 8)))
134          (cnt 1 (1+ cnt)))
135         ((>= cnt n) res))))
136
137 ;;; Read an N-byte unsigned integer from the *FASL-FILE*
138 (defmacro read-arg (n)
139   (declare (optimize (speed 0)))
140   (if (= n 1)
141       `(the (unsigned-byte 8) (read-byte *fasl-file*))
142       `(prepare-for-fast-read-byte *fasl-file*
143          (prog1
144           (fast-read-u-integer ,n)
145           (done-with-fast-read-byte)))))
146 ;;; FIXME: This deserves a more descriptive name, and should probably
147 ;;; be implemented as an ordinary function, not a macro.
148 ;;;
149 ;;; (for the names: There seem to be only two cases, so it could be
150 ;;; named READ-U-INTEGER-8 and READ-U-INTEGER-32 or something.)
151 \f
152 ;;;; the fop table
153
154 ;;; The table is implemented as a simple-vector indexed by the table
155 ;;; offset. We may need to have several, since LOAD can be called
156 ;;; recursively.
157
158 (defvar *free-fop-tables* (list (make-array 1000))
159   #!+sb-doc
160   "List of free fop tables for the fasloader.")
161
162 ;;; the current fop table
163 (defvar *current-fop-table*)
164 (declaim (simple-vector *current-fop-table*))
165
166 ;;; the length of the current fop table
167 (defvar *current-fop-table-size*)
168 (declaim (type index *current-fop-table-size*))
169
170 ;;; the index in the fop-table of the next entry to be used
171 (defvar *current-fop-table-index*)
172 (declaim (type index *current-fop-table-index*))
173
174 (defun grow-fop-table ()
175   (let* ((new-size (* *current-fop-table-size* 2))
176          (new-table (make-array new-size)))
177     (declare (fixnum new-size) (simple-vector new-table))
178     (replace new-table (the simple-vector *current-fop-table*))
179     (setq *current-fop-table* new-table)
180     (setq *current-fop-table-size* new-size)))
181
182 (defmacro push-fop-table (thing)
183   (let ((n-index (gensym)))
184     `(let ((,n-index *current-fop-table-index*))
185        (declare (fixnum ,n-index))
186        (when (= ,n-index (the fixnum *current-fop-table-size*))
187          (grow-fop-table))
188        (setq *current-fop-table-index* (1+ ,n-index))
189        (setf (svref *current-fop-table* ,n-index) ,thing))))
190 \f
191 ;;;; the fop stack
192
193 ;;; (This is in a simple-vector, but it grows down, since it is
194 ;;; somewhat cheaper to test for overflow that way.)
195 (defvar *fop-stack* (make-array 100)
196   #!+sb-doc
197   "The fop stack (we only need one!).")
198 (declaim (simple-vector *fop-stack*))
199
200 ;;; the index of the most recently pushed item on the fop-stack
201 (defvar *fop-stack-pointer* 100)
202
203 ;;; the current index into the fop stack when we last recursively
204 ;;; entered LOAD
205 (defvar *fop-stack-pointer-on-entry*)
206 (declaim (type index *fop-stack-pointer* *fop-stack-pointer-on-entry*))
207
208 (defun grow-fop-stack ()
209   (let* ((size (length (the simple-vector *fop-stack*)))
210          (new-size (* size 2))
211          (new-stack (make-array new-size)))
212     (declare (fixnum size new-size) (simple-vector new-stack))
213     (replace new-stack (the simple-vector *fop-stack*) :start1 size)
214     (incf *fop-stack-pointer-on-entry* size)
215     (setq *fop-stack-pointer* size)
216     (setq *fop-stack* new-stack)))
217
218 ;;; Cache information about the fop-stack in local variables. Define a
219 ;;; local macro to pop from the stack. Push the result of evaluation
220 ;;; if specified.
221 (defmacro with-fop-stack (pushp &body forms)
222   (check-type pushp (member nil t :nope))
223   (let ((n-stack (gensym))
224         (n-index (gensym))
225         (n-res (gensym)))
226     `(let ((,n-stack *fop-stack*)
227            (,n-index *fop-stack-pointer*))
228        (declare (simple-vector ,n-stack) (type index ,n-index))
229        (macrolet ((pop-stack ()
230                     `(prog1
231                       (svref ,',n-stack ,',n-index)
232                       (incf ,',n-index)))
233                   (call-with-popped-things (fun n)
234                     (let ((n-start (gensym)))
235                       `(let ((,n-start (+ ,',n-index ,n)))
236                          (declare (type index ,n-start))
237                          (setq ,',n-index ,n-start)
238                          (,fun ,@(make-list n :initial-element
239                                             `(svref ,',n-stack
240                                                     (decf ,n-start))))))))
241          ,(if pushp
242               `(let ((,n-res (progn ,@forms)))
243                  (when (zerop ,n-index)
244                    (grow-fop-stack)
245                    (setq ,n-index *fop-stack-pointer*
246                          ,n-stack *fop-stack*))
247                  (decf ,n-index)
248                  (setq *fop-stack-pointer* ,n-index)
249                  (setf (svref ,n-stack ,n-index) ,n-res))
250               `(prog1
251                 (progn ,@forms)
252                 (setq *fop-stack-pointer* ,n-index)))))))
253 \f
254 ;;;; FASLOAD
255 ;;;;
256 ;;;; Note: FASLOAD is used not only by LOAD, but also (after suitable
257 ;;;; modification of the fop table) in genesis. Therefore, it's needed
258 ;;;; not only in the target Lisp, but also in the cross-compilation
259 ;;;; host.
260
261 ;;; a helper function for LOAD-FASL-GROUP
262 ;;;
263 ;;; Return true if we successfully read a FASL header from the stream,
264 ;;; or NIL if EOF was hit before anything was read. Signal an error if
265 ;;; we encounter garbage.
266 (defun check-fasl-header (stream)
267
268   (let ((byte (read-byte stream nil)))
269     (when byte
270
271       ;; Read the string part of the fasl header, or die.
272       (let* ((fhsss sb!c:*fasl-header-string-start-string*)
273              (fhsss-length (length fhsss)))
274         (unless (= byte (char-code (schar fhsss 0)))
275           (error "illegal fasl file header"))
276         (do ((byte (read-byte stream) (read-byte stream))
277              (count 1 (1+ count)))
278             ((= byte sb!c:*fasl-header-string-stop-char-code*)
279              t)
280           (declare (fixnum byte count))
281           (when (and (< count fhsss-length)
282                      (not (eql byte (char-code (schar fhsss count)))))
283             (error "illegal fasl file header"))))
284
285       ;; Read and validate implementation and version, or die.
286       (let* ((implementation-length (read-arg 4))
287              (implementation-string (make-string implementation-length))
288              (ignore (read-string-as-bytes stream implementation-string))
289              (implementation (keywordicate implementation-string))
290              ;; FIXME: The logic above to read a keyword from the fasl file
291              ;; could probably be shared with the read-a-keyword fop.
292              (version (read-arg 4)))
293         (declare (ignore ignore))
294         (flet ((check-version (variant possible-implementation needed-version)
295                  (when (string= possible-implementation implementation)
296                    (unless (= version needed-version)
297                      (error "~S was compiled for ~A fasl file format version ~
298                              ~S, but we need version ~S."
299                             stream
300                             variant
301                             version
302                             needed-version))
303                    t)))
304           (or (check-version "native code"
305                              #.sb!c:*backend-fasl-file-implementation*
306                              #.sb!c:*backend-fasl-file-version*)
307               (check-version "byte code"
308                              #.(sb!c:backend-byte-fasl-file-implementation)
309                              sb!c:byte-fasl-file-version)
310               (error "~S was compiled for implementation ~A, but this is a ~A."
311                      stream
312                      implementation
313                      sb!c:*backend-fasl-file-implementation*)))))))
314
315 ;; Setting this variable gives you a trace of fops as they are loaded and
316 ;; executed.
317 #!+sb-show
318 (defvar *show-fops-p* nil)
319
320 ;;; a helper function for FASLOAD
321 ;;;
322 ;;; Return true if we successfully load a group from the stream, or NIL if EOF
323 ;;; was encountered while trying to read from the stream. Dispatch to the right
324 ;;; function for each fop. Special-case FOP-BYTE-PUSH since it is real common.
325 (defun load-fasl-group (stream)
326   (when (check-fasl-header stream)
327     (catch 'fasl-group-end
328       (let ((*current-fop-table-index* 0))
329         (loop
330           (let ((byte (read-byte stream)))
331
332             ;; Do some debugging output.
333             #!+sb-show
334             (when *show-fops-p*
335               (let ((ptr *fop-stack-pointer*)
336                     (stack *fop-stack*))
337                 (fresh-line *trace-output*)
338                 ;; The FOP operations are stack based, so it's sorta
339                 ;; logical to display the operand before the operator.
340                 ;; ("reverse Polish notation")
341                 (unless (= ptr (length stack))
342                   (write-char #\space *trace-output*)
343                   (prin1 (svref stack ptr) *trace-output*)
344                   (terpri *trace-output*))
345                 ;; Display the operator.
346                 (format *trace-output*
347                         "~&~S (#X~X at ~D) (~S)~%"
348                         (svref *fop-names* byte)
349                         byte
350                         (1- (file-position stream))
351                         (svref *fop-functions* byte))))
352
353             ;; Actually execute the fop.
354             (if (eql byte 3)
355               ;; FIXME: This is the special case for FOP-BYTE-PUSH.
356               ;; Benchmark to see whether it's really worth special
357               ;; casing it. If it is, at least express the test in
358               ;; terms of a symbolic name for the FOP-BYTE-PUSH code,
359               ;; not a bare '3' (!). Failing that, remove the special
360               ;; case (and the comment at the head of this function
361               ;; which mentions it).
362               (let ((index *fop-stack-pointer*))
363                 (declare (type index index))
364                 (when (zerop index)
365                   (grow-fop-stack)
366                   (setq index *fop-stack-pointer*))
367                 (decf index)
368                 (setq *fop-stack-pointer* index)
369                 (setf (svref *fop-stack* index)
370                       (svref *current-fop-table* (read-byte stream))))
371               (funcall (the function (svref *fop-functions* byte))))))))))
372
373 (defun fasload (stream verbose print)
374   ;; KLUDGE: ANSI says it's good to do something with the :PRINT
375   ;; argument to LOAD when we're fasloading a file, but currently we
376   ;; don't. (CMU CL did, but implemented it in a non-ANSI way, and I
377   ;; just disabled that instead of rewriting it.) -- WHN 20000131
378   (declare (ignore print))
379   (when (zerop (file-length stream))
380     (error "attempt to load an empty FASL file:~%  ~S" (namestring stream)))
381   (do-load-verbose stream verbose)
382   (let* ((*fasl-file* stream)
383          (*current-fop-table* (or (pop *free-fop-tables*) (make-array 1000)))
384          (*current-fop-table-size* (length *current-fop-table*))
385          (*fop-stack-pointer-on-entry* *fop-stack-pointer*))
386     (unwind-protect
387         ;; FIXME: This should probably become
388         ;;   (LOOP WHILE (LOAD-FASL-GROUP-STREAM))
389         ;; but as a LOOP newbie I don't want to do that until I can
390         ;; test it.
391         (do ((loaded-group (load-fasl-group stream) (load-fasl-group stream)))
392             ((not loaded-group)))
393       (setq *fop-stack-pointer* *fop-stack-pointer-on-entry*)
394       (push *current-fop-table* *free-fop-tables*)
395       ;; NIL out the stack and table, so that we don't hold onto garbage.
396       ;;
397       ;; FIXME: Couldn't we just get rid of the free fop table pool so
398       ;; that some of this NILing out would go away?
399       (fill *fop-stack* nil :end *fop-stack-pointer-on-entry*)
400       (fill *current-fop-table* nil)))
401   t)
402 \f
403 ;;;; stuff for debugging/tuning by collecting statistics on FOPs (?)
404
405 #|
406 (defvar *fop-counts* (make-array 256 :initial-element 0))
407 (defvar *fop-times* (make-array 256 :initial-element 0))
408 (defvar *print-fops* nil)
409
410 (defun clear-counts ()
411   (fill (the simple-vector *fop-counts*) 0)
412   (fill (the simple-vector *fop-times*) 0)
413   t)
414
415 (defun analyze-counts ()
416   (let ((counts ())
417         (total-count 0)
418         (times ())
419         (total-time 0))
420     (macrolet ((breakdown (lvar tvar vec)
421                  `(progn
422                    (dotimes (i 255)
423                      (declare (fixnum i))
424                      (let ((n (svref ,vec i)))
425                        (push (cons (svref *fop-names* i) n) ,lvar)
426                        (incf ,tvar n)))
427                    (setq ,lvar (subseq (sort ,lvar #'(lambda (x y)
428                                                        (> (cdr x) (cdr y))))
429                                        0 10)))))
430
431       (breakdown counts total-count *fop-counts*)
432       (breakdown times total-time *fop-times*)
433       (format t "Total fop count is ~D~%" total-count)
434       (dolist (c counts)
435         (format t "~30S: ~4D~%" (car c) (cdr c)))
436       (format t "~%Total fop time is ~D~%" (/ (float total-time) 60.0))
437       (dolist (m times)
438         (format t "~30S: ~6,2F~%" (car m) (/ (float (cdr m)) 60.0))))))
439 |#
440