4f81df1d0bee13f2aaa92bb414d090cb60fde512
[sbcl.git] / src / code / room.lisp
1 ;;;; heap-grovelling memory usage stuff
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!VM")
13
14 (declaim (special sb!vm:*read-only-space-free-pointer*
15                   sb!vm:*static-space-free-pointer*))
16 \f
17 ;;;; type format database
18
19 (eval-when (:compile-toplevel :load-toplevel :execute)
20   (def!struct (room-info (:make-load-form-fun just-dump-it-normally))
21     ;; the name of this type
22     (name nil :type symbol)
23     ;; kind of type (how we determine length)
24     (kind (missing-arg)
25           :type (member :lowtag :fixed :header :vector
26                         :string :code :closure :instance))
27     ;; length if fixed-length, shift amount for element size if :VECTOR
28     (length nil :type (or fixnum null))))
29
30 (eval-when (:compile-toplevel :execute)
31
32 (defvar *meta-room-info* (make-array 256 :initial-element nil))
33
34 (dolist (obj *primitive-objects*)
35   (let ((widetag (primitive-object-widetag obj))
36         (lowtag (primitive-object-lowtag obj))
37         (name (primitive-object-name obj))
38         (variable (primitive-object-variable-length-p obj))
39         (size (primitive-object-size obj)))
40     (cond
41      ((not lowtag))
42      ((not widetag)
43       (let ((info (make-room-info :name name
44                                   :kind :lowtag))
45             (lowtag (symbol-value lowtag)))
46         (declare (fixnum lowtag))
47         (dotimes (i 32)
48           (setf (svref *meta-room-info* (logior lowtag (ash i 3))) info))))
49      (variable)
50      (t
51       (setf (svref *meta-room-info* (symbol-value widetag))
52             (make-room-info :name name
53                             :kind :fixed
54                             :length size))))))
55
56 (dolist (code (list #!+sb-unicode complex-character-string-widetag
57                     complex-base-string-widetag simple-array-widetag
58                     complex-bit-vector-widetag complex-vector-widetag
59                     complex-array-widetag complex-vector-nil-widetag))
60   (setf (svref *meta-room-info* code)
61         (make-room-info :name 'array-header
62                         :kind :header)))
63
64 (setf (svref *meta-room-info* bignum-widetag)
65       (make-room-info :name 'bignum
66                       :kind :header))
67
68 (setf (svref *meta-room-info* closure-header-widetag)
69       (make-room-info :name 'closure
70                       :kind :closure))
71
72 ;; FIXME: This looks rather brittle. Can we get more of these numbers
73 ;; from somewhere sensible?
74 (dolist (stuff '((simple-bit-vector-widetag . -3)
75                  (simple-vector-widetag . #.sb!vm:word-shift)
76                  (simple-array-unsigned-byte-2-widetag . -2)
77                  (simple-array-unsigned-byte-4-widetag . -1)
78                  (simple-array-unsigned-byte-7-widetag . 0)
79                  (simple-array-unsigned-byte-8-widetag . 0)
80                  (simple-array-unsigned-byte-15-widetag . 1)
81                  (simple-array-unsigned-byte-16-widetag . 1)
82                  (simple-array-unsigned-byte-31-widetag . 2)
83                  (simple-array-unsigned-byte-32-widetag . 2)
84                  (simple-array-unsigned-fixnum-widetag . #.sb!vm:word-shift)
85                  (simple-array-unsigned-byte-63-widetag . 3)
86                  (simple-array-unsigned-byte-64-widetag . 3)
87                  (simple-array-signed-byte-8-widetag . 0)
88                  (simple-array-signed-byte-16-widetag . 1)
89                  (simple-array-fixnum-widetag . #.sb!vm:word-shift)
90                  (simple-array-signed-byte-32-widetag . 2)
91                  (simple-array-signed-byte-64-widetag . 3)
92                  (simple-array-single-float-widetag . 2)
93                  (simple-array-double-float-widetag . 3)
94                  (simple-array-complex-single-float-widetag . 3)
95                  (simple-array-complex-double-float-widetag . 4)))
96   (let* ((name (car stuff))
97          (size (cdr stuff))
98          (sname (string name)))
99     (when (boundp name)
100       (setf (svref *meta-room-info* (symbol-value name))
101             (make-room-info :name (intern (subseq sname
102                                                   0
103                                                   (mismatch sname "-WIDETAG"
104                                                             :from-end t)))
105                             :kind :vector
106                             :length size)))))
107
108 (setf (svref *meta-room-info* simple-base-string-widetag)
109       (make-room-info :name 'simple-base-string
110                       :kind :string
111                       :length 0))
112
113 #!+sb-unicode
114 (setf (svref *meta-room-info* simple-character-string-widetag)
115       (make-room-info :name 'simple-character-string
116                       :kind :string
117                       :length 2))
118
119 (setf (svref *meta-room-info* simple-array-nil-widetag)
120       (make-room-info :name 'simple-array-nil
121                       :kind :fixed
122                       :length 2))
123
124 (setf (svref *meta-room-info* code-header-widetag)
125       (make-room-info :name 'code
126                       :kind :code))
127
128 (setf (svref *meta-room-info* instance-header-widetag)
129       (make-room-info :name 'instance
130                       :kind :instance))
131
132 ) ; EVAL-WHEN
133
134 (defparameter *room-info* '#.*meta-room-info*)
135 (deftype spaces () '(member :static :dynamic :read-only))
136 \f
137 ;;;; MAP-ALLOCATED-OBJECTS
138
139 ;;; Since they're represented as counts of words, we should never
140 ;;; need bignums to represent these:
141 (declaim (type fixnum
142                *static-space-free-pointer*
143                *read-only-space-free-pointer*))
144
145 (defun space-bounds (space)
146   (declare (type spaces space))
147   (ecase space
148     (:static
149      (values (int-sap static-space-start)
150              (int-sap (ash *static-space-free-pointer* n-fixnum-tag-bits))))
151     (:read-only
152      (values (int-sap read-only-space-start)
153              (int-sap (ash *read-only-space-free-pointer* n-fixnum-tag-bits))))
154     (:dynamic
155      (values (int-sap (current-dynamic-space-start))
156              (dynamic-space-free-pointer)))))
157
158 ;;; Return the total number of bytes used in SPACE.
159 (defun space-bytes (space)
160   (multiple-value-bind (start end) (space-bounds space)
161     (- (sap-int end) (sap-int start))))
162
163 ;;; Round SIZE (in bytes) up to the next dualword boundary. A dualword
164 ;;; is eight bytes on platforms with 32-bit word size and 16 bytes on
165 ;;; platforms with 64-bit word size.
166 #!-sb-fluid (declaim (inline round-to-dualword))
167 (defun round-to-dualword (size)
168   (logand (the word (+ size lowtag-mask)) (lognot lowtag-mask)))
169
170 ;;; Return the total size of a vector in bytes, including any pad.
171 #!-sb-fluid (declaim (inline vector-total-size))
172 (defun vector-total-size (obj info)
173   (let ((shift (room-info-length info))
174         (len (+ (length (the (simple-array * (*)) obj))
175                 (ecase (room-info-kind info)
176                   (:vector 0)
177                   (:string 1)))))
178     (round-to-dualword
179      (+ (* vector-data-offset n-word-bytes)
180         (if (minusp shift)
181             (ash (+ len (1- (ash 1 (- shift))))
182                  shift)
183             (ash len shift))))))
184
185 ;;; Access to the GENCGC page table for better precision in
186 ;;; MAP-ALLOCATED-OBJECTS
187 #!+gencgc
188 (progn
189   (define-alien-type (struct page)
190       (struct page
191               (start long)
192               ;; On platforms with small enough GC pages, this field
193               ;; will be a short. On platforms with larger ones, it'll
194               ;; be an int.
195               (bytes-used (unsigned
196                            #.(if (typep sb!vm:gencgc-card-bytes
197                                         '(unsigned-byte 16))
198                                  16
199                                  32)))
200               (flags (unsigned 8))
201               (gen (signed 8))))
202   (declaim (inline find-page-index))
203   (define-alien-routine "find_page_index" long (index long))
204   (define-alien-variable "page_table" (* (struct page))))
205
206 ;;; Iterate over all the objects allocated in SPACE, calling FUN with
207 ;;; the object, the object's type code, and the object's total size in
208 ;;; bytes, including any header and padding. CAREFUL makes
209 ;;; MAP-ALLOCATED-OBJECTS slightly more accurate, but a lot slower: it
210 ;;; is intended for slightly more demanding uses of heap groveling
211 ;;; then ROOM.
212 #!-sb-fluid (declaim (maybe-inline map-allocated-objects))
213 (defun map-allocated-objects (fun space &optional careful)
214   (declare (type function fun) (type spaces space))
215   (flet ((make-obj (tagged-address)
216            (if careful
217                (make-lisp-obj tagged-address nil)
218                (values (%make-lisp-obj tagged-address) t))))
219     ;; Inlining MAKE-OBJ reduces consing on platforms where dynamic
220     ;; space extends past fixnum range.
221     (declare (inline make-obj))
222     (without-gcing
223       (multiple-value-bind (start end) (space-bounds space)
224         (declare (type system-area-pointer start end))
225         (declare (optimize (speed 3)))
226         (let ((current start)
227               #!+gencgc
228               (skip-tests-until-addr 0))
229           (labels ((maybe-finish-mapping ()
230                      (unless (sap< current end)
231                        (aver (sap= current end))
232                        (return-from map-allocated-objects)))
233                    ;; GENCGC doesn't allocate linearly, which means that the
234                    ;; dynamic space can contain large blocks zeros that get
235                    ;; accounted as conses in ROOM (and slow down other
236                    ;; applications of MAP-ALLOCATED-OBJECTS). To fix this
237                    ;; check the GC page structure for the current address.
238                    ;; If the page is free or the address is beyond the page-
239                    ;; internal allocation offset (bytes-used) skip to the
240                    ;; next page immediately.
241                    (maybe-skip-page ()
242                      #!+gencgc
243                      (when (eq space :dynamic)
244                        (loop with page-mask = #.(1- sb!vm:gencgc-card-bytes)
245                              for addr of-type sb!vm:word = (sap-int current)
246                              while (>= addr skip-tests-until-addr)
247                              do
248                              ;; For some reason binding PAGE with LET
249                              ;; conses like mad (but gives no compiler notes...)
250                              ;; Work around the problem with SYMBOL-MACROLET
251                              ;; instead of trying to figure out the real
252                              ;; issue. -- JES, 2005-05-17
253                              (symbol-macrolet
254                                  ((page (deref page-table
255                                                (find-page-index addr))))
256                                ;; Don't we have any nicer way to access C struct
257                                ;; bitfields?
258                                (let ((alloc-flag (ldb (byte 3 2)
259                                                       (slot page 'flags)))
260                                      (bytes-used (slot page 'bytes-used)))
261                                  ;; If the page is not free and the current
262                                  ;; pointer is still below the allocation offset
263                                  ;; of the page
264                                  (when (and (not (zerop alloc-flag))
265                                             (< (logand page-mask addr)
266                                                bytes-used))
267                                    ;; Don't bother testing again until we
268                                    ;; get past that allocation offset
269                                    (setf skip-tests-until-addr
270                                          (+ (logandc2 addr page-mask) bytes-used))
271                                    ;; And then continue with the
272                                    ;; scheduled mapping
273                                    (return-from maybe-skip-page))
274                                  ;; Move CURRENT to start of next page.
275                                  (setf current (int-sap (+ (logandc2 addr page-mask)
276                                                            sb!vm:gencgc-card-bytes)))
277                                  (maybe-finish-mapping))))))
278                    (maybe-map (obj obj-tag n-obj-bytes &optional (ok t))
279                      (let ((next (typecase n-obj-bytes
280                                    (fixnum (sap+ current n-obj-bytes))
281                                    (integer (sap+ current n-obj-bytes)))))
282                        ;; If this object would take us past END, it must
283                        ;; be either bogus, or it has been allocated after
284                        ;; the call to M-A-O.
285                        (cond ((and ok next (sap<= next end))
286                               (funcall fun obj obj-tag n-obj-bytes)
287                               (setf current next))
288                              (t
289                               (setf current (sap+ current n-word-bytes)))))))
290             (declare (inline maybe-finish-mapping maybe-skip-page maybe-map))
291             (loop
292               (maybe-finish-mapping)
293               (maybe-skip-page)
294               (let* ((header (sap-ref-word current 0))
295                      (header-widetag (logand header #xFF))
296                      (info (svref *room-info* header-widetag)))
297                 (cond
298                   ((or (not info)
299                        (eq (room-info-kind info) :lowtag))
300                    (multiple-value-bind (obj ok)
301                        (make-obj (logior (sap-int current) list-pointer-lowtag))
302                      (maybe-map obj
303                                 list-pointer-lowtag
304                                 (* cons-size n-word-bytes)
305                                 ok)))
306                   ((eql header-widetag closure-header-widetag)
307                    (let* ((obj (%make-lisp-obj (logior (sap-int current)
308                                                        fun-pointer-lowtag)))
309                           (size (round-to-dualword
310                                  (* (the fixnum (1+ (get-closure-length obj)))
311                                     n-word-bytes))))
312                      (maybe-map obj header-widetag size)))
313                   ((eq (room-info-kind info) :instance)
314                    (let* ((obj (%make-lisp-obj
315                                 (logior (sap-int current) instance-pointer-lowtag)))
316                           (size (round-to-dualword
317                                  (* (+ (%instance-length obj) 1) n-word-bytes))))
318                      (aver (zerop (logand size lowtag-mask)))
319                      (maybe-map obj header-widetag size)))
320                   (t
321                    (multiple-value-bind (obj ok)
322                        (make-obj (logior (sap-int current) other-pointer-lowtag))
323                      (let ((size (when ok
324                                    (ecase (room-info-kind info)
325                                      (:fixed
326                                       (aver (or (eql (room-info-length info)
327                                                      (1+ (get-header-data obj)))
328                                                 (floatp obj)
329                                                 (simple-array-nil-p obj)))
330                                       (round-to-dualword
331                                        (* (room-info-length info) n-word-bytes)))
332                                      ((:vector :string)
333                                       (vector-total-size obj info))
334                                      (:header
335                                       (round-to-dualword
336                                        (* (1+ (get-header-data obj)) n-word-bytes)))
337                                      (:code
338                                       (+ (the fixnum
339                                            (* (get-header-data obj) n-word-bytes))
340                                          (round-to-dualword
341                                           (* (the fixnum (%code-code-size obj))
342                                              n-word-bytes))))))))
343                        (macrolet ((frob ()
344                                     '(progn
345                                       (when size (aver (zerop (logand size lowtag-mask))))
346                                       (maybe-map obj header-widetag size))))
347                          (typecase size
348                            (fixnum (frob))
349                            (word (frob))
350                            (null (frob))))))))))))))))
351
352 \f
353 ;;;; MEMORY-USAGE
354
355 ;;; Return a list of 3-lists (bytes object type-name) for the objects
356 ;;; allocated in Space.
357 (defun type-breakdown (space)
358   (let ((sizes (make-array 256 :initial-element 0 :element-type '(unsigned-byte #.sb!vm:n-word-bits)))
359         (counts (make-array 256 :initial-element 0 :element-type '(unsigned-byte #.sb!vm:n-word-bits))))
360     (map-allocated-objects
361      (lambda (obj type size)
362        (declare (word size) (optimize (speed 3)) (ignore obj))
363        (incf (aref sizes type) size)
364        (incf (aref counts type)))
365      space)
366
367     (let ((totals (make-hash-table :test 'eq)))
368       (dotimes (i 256)
369         (let ((total-count (aref counts i)))
370           (unless (zerop total-count)
371             (let* ((total-size (aref sizes i))
372                    (name (room-info-name (aref *room-info* i)))
373                    (found (gethash name totals)))
374               (cond (found
375                      (incf (first found) total-size)
376                      (incf (second found) total-count))
377                     (t
378                      (setf (gethash name totals)
379                            (list total-size total-count name))))))))
380
381       (collect ((totals-list))
382         (maphash (lambda (k v)
383                    (declare (ignore k))
384                    (totals-list v))
385                  totals)
386         (sort (totals-list) #'> :key #'first)))))
387
388 ;;; Handle the summary printing for MEMORY-USAGE. Totals is a list of lists
389 ;;; (space-name . totals-for-space), where totals-for-space is the list
390 ;;; returned by TYPE-BREAKDOWN.
391 (defun print-summary (spaces totals)
392   (let ((summary (make-hash-table :test 'eq)))
393     (dolist (space-total totals)
394       (dolist (total (cdr space-total))
395         (push (cons (car space-total) total)
396               (gethash (third total) summary))))
397
398     (collect ((summary-totals))
399       (maphash (lambda (k v)
400                  (declare (ignore k))
401                  (let ((sum 0))
402                    (declare (unsigned-byte sum))
403                    (dolist (space-total v)
404                      (incf sum (first (cdr space-total))))
405                    (summary-totals (cons sum v))))
406                summary)
407
408       (format t "~2&Summary of spaces: ~(~{~A ~}~)~%" spaces)
409       (let ((summary-total-bytes 0)
410             (summary-total-objects 0))
411         (declare (unsigned-byte summary-total-bytes summary-total-objects))
412         (dolist (space-totals
413                  (mapcar #'cdr (sort (summary-totals) #'> :key #'car)))
414           (let ((total-objects 0)
415                 (total-bytes 0)
416                 name)
417             (declare (unsigned-byte total-objects total-bytes))
418             (collect ((spaces))
419               (dolist (space-total space-totals)
420                 (let ((total (cdr space-total)))
421                   (setq name (third total))
422                   (incf total-bytes (first total))
423                   (incf total-objects (second total))
424                   (spaces (cons (car space-total) (first total)))))
425               (format t "~%~A:~%    ~:D bytes, ~:D object~:P"
426                       name total-bytes total-objects)
427               (dolist (space (spaces))
428                 (format t ", ~W% ~(~A~)"
429                         (round (* (cdr space) 100) total-bytes)
430                         (car space)))
431               (format t ".~%")
432               (incf summary-total-bytes total-bytes)
433               (incf summary-total-objects total-objects))))
434         (format t "~%Summary total:~%    ~:D bytes, ~:D objects.~%"
435                 summary-total-bytes summary-total-objects)))))
436
437 ;;; Report object usage for a single space.
438 (defun report-space-total (space-total cutoff)
439   (declare (list space-total) (type (or single-float null) cutoff))
440   (format t "~2&Breakdown for ~(~A~) space:~%" (car space-total))
441   (let* ((types (cdr space-total))
442          (total-bytes (reduce #'+ (mapcar #'first types)))
443          (total-objects (reduce #'+ (mapcar #'second types)))
444          (cutoff-point (if cutoff
445                            (truncate (* (float total-bytes) cutoff))
446                            0))
447          (reported-bytes 0)
448          (reported-objects 0))
449     (declare (unsigned-byte total-objects total-bytes cutoff-point reported-objects
450                             reported-bytes))
451     (loop for (bytes objects name) in types do
452       (when (<= bytes cutoff-point)
453         (format t "  ~10:D bytes for ~9:D other object~2:*~P.~%"
454                 (- total-bytes reported-bytes)
455                 (- total-objects reported-objects))
456         (return))
457       (incf reported-bytes bytes)
458       (incf reported-objects objects)
459       (format t "  ~10:D bytes for ~9:D ~(~A~) object~2:*~P.~%"
460               bytes objects name))
461     (format t "  ~10:D bytes for ~9:D ~(~A~) object~2:*~P (space total.)~%"
462             total-bytes total-objects (car space-total))))
463
464 ;;; Print information about the heap memory in use. PRINT-SPACES is a
465 ;;; list of the spaces to print detailed information for.
466 ;;; COUNT-SPACES is a list of the spaces to scan. For either one, T
467 ;;; means all spaces (i.e. :STATIC, :DYNAMIC and :READ-ONLY.) If
468 ;;; PRINT-SUMMARY is true, then summary information will be printed.
469 ;;; The defaults print only summary information for dynamic space. If
470 ;;; true, CUTOFF is a fraction of the usage in a report below which
471 ;;; types will be combined as OTHER.
472 (defun memory-usage (&key print-spaces (count-spaces '(:dynamic))
473                           (print-summary t) cutoff)
474   (declare (type (or single-float null) cutoff))
475   (let* ((spaces (if (eq count-spaces t)
476                      '(:static :dynamic :read-only)
477                      count-spaces))
478          (totals (mapcar (lambda (space)
479                            (cons space (type-breakdown space)))
480                          spaces)))
481
482     (dolist (space-total totals)
483       (when (or (eq print-spaces t)
484                 (member (car space-total) print-spaces))
485         (report-space-total space-total cutoff)))
486
487     (when print-summary (print-summary spaces totals)))
488
489   (values))
490 \f
491 ;;; Print info about how much code and no-ops there are in SPACE.
492 (defun count-no-ops (space)
493   (declare (type spaces space))
494   (let ((code-words 0)
495         (no-ops 0)
496         (total-bytes 0))
497     (declare (fixnum code-words no-ops)
498              (type unsigned-byte total-bytes))
499     (map-allocated-objects
500      (lambda (obj type size)
501        (when (eql type code-header-widetag)
502          (let ((words (truly-the fixnum (%code-code-size obj)))
503                (sap (%primitive code-instructions obj))
504                (size size))
505            (declare (fixnum size))
506            (incf total-bytes size)
507            (incf code-words words)
508            (dotimes (i words)
509              (when (zerop (sap-ref-word sap (* i n-word-bytes)))
510                (incf no-ops))))))
511      space)
512
513     (format t
514             "~:D code-object bytes, ~:D code words, with ~:D no-ops (~D%).~%"
515             total-bytes code-words no-ops
516             (round (* no-ops 100) code-words)))
517
518   (values))
519 \f
520 (defun descriptor-vs-non-descriptor-storage (&rest spaces)
521   (let ((descriptor-words 0)
522         (non-descriptor-headers 0)
523         (non-descriptor-bytes 0))
524     (declare (type unsigned-byte descriptor-words non-descriptor-headers
525                    non-descriptor-bytes))
526     (dolist (space (or spaces '(:read-only :static :dynamic)))
527       (declare (inline map-allocated-objects))
528       (map-allocated-objects
529        (lambda (obj type size)
530          (case type
531            (#.code-header-widetag
532             (let ((inst-words (truly-the fixnum (%code-code-size obj)))
533                   (size size))
534               (declare (type fixnum size inst-words))
535               (incf non-descriptor-bytes (* inst-words n-word-bytes))
536               (incf descriptor-words
537                     (- (truncate size n-word-bytes) inst-words))))
538            ((#.bignum-widetag
539              #.single-float-widetag
540              #.double-float-widetag
541              #.simple-base-string-widetag
542              #!+sb-unicode #.simple-character-string-widetag
543              #.simple-array-nil-widetag
544              #.simple-bit-vector-widetag
545              #.simple-array-unsigned-byte-2-widetag
546              #.simple-array-unsigned-byte-4-widetag
547              #.simple-array-unsigned-byte-8-widetag
548              #.simple-array-unsigned-byte-16-widetag
549              #.simple-array-unsigned-byte-32-widetag
550              #.simple-array-signed-byte-8-widetag
551              #.simple-array-signed-byte-16-widetag
552              #.simple-array-signed-byte-32-widetag
553              #.simple-array-single-float-widetag
554              #.simple-array-double-float-widetag
555              #.simple-array-complex-single-float-widetag
556              #.simple-array-complex-double-float-widetag)
557             (incf non-descriptor-headers)
558             (incf non-descriptor-bytes (- size n-word-bytes)))
559            ((#.list-pointer-lowtag
560              #.instance-pointer-lowtag
561              #.ratio-widetag
562              #.complex-widetag
563              #.simple-array-widetag
564              #.simple-vector-widetag
565              #.complex-base-string-widetag
566              #.complex-vector-nil-widetag
567              #.complex-bit-vector-widetag
568              #.complex-vector-widetag
569              #.complex-array-widetag
570              #.closure-header-widetag
571              #.funcallable-instance-header-widetag
572              #.value-cell-header-widetag
573              #.symbol-header-widetag
574              #.sap-widetag
575              #.weak-pointer-widetag
576              #.instance-header-widetag)
577             (incf descriptor-words (truncate (the fixnum size) n-word-bytes)))
578            (t
579             (error "bogus widetag: ~W" type))))
580        space))
581     (format t "~:D words allocated for descriptor objects.~%"
582             descriptor-words)
583     (format t "~:D bytes data/~:D words header for non-descriptor objects.~%"
584             non-descriptor-bytes non-descriptor-headers)
585     (values)))
586 \f
587 ;;; Print a breakdown by instance type of all the instances allocated
588 ;;; in SPACE. If TOP-N is true, print only information for the
589 ;;; TOP-N types with largest usage.
590 (defun instance-usage (space &key (top-n 15))
591   (declare (type spaces space) (type (or fixnum null) top-n))
592   (format t "~2&~@[Top ~W ~]~(~A~) instance types:~%" top-n space)
593   (let ((totals (make-hash-table :test 'eq))
594         (total-objects 0)
595         (total-bytes 0))
596     (declare (unsigned-byte total-objects total-bytes))
597     (map-allocated-objects
598      (lambda (obj type size)
599        (declare (optimize (speed 3)))
600        (when (eql type instance-header-widetag)
601          (incf total-objects)
602          (let* ((classoid (layout-classoid (%instance-ref obj 0)))
603                 (found (gethash classoid totals))
604                 (size size))
605            (declare (fixnum size))
606            (incf total-bytes size)
607            (cond (found
608                   (incf (the fixnum (car found)))
609                   (incf (the fixnum (cdr found)) size))
610                  (t
611                   (setf (gethash classoid totals) (cons 1 size)))))))
612      space)
613
614     (collect ((totals-list))
615       (maphash (lambda (classoid what)
616                  (totals-list (cons (prin1-to-string
617                                      (classoid-proper-name classoid))
618                                     what)))
619                totals)
620       (let ((sorted (sort (totals-list) #'> :key #'cddr))
621             (printed-bytes 0)
622             (printed-objects 0))
623         (declare (unsigned-byte printed-bytes printed-objects))
624         (dolist (what (if top-n
625                           (subseq sorted 0 (min (length sorted) top-n))
626                           sorted))
627           (let ((bytes (cddr what))
628                 (objects (cadr what)))
629             (incf printed-bytes bytes)
630             (incf printed-objects objects)
631             (format t "  ~A: ~:D bytes, ~:D object~:P.~%" (car what)
632                     bytes objects)))
633
634         (let ((residual-objects (- total-objects printed-objects))
635               (residual-bytes (- total-bytes printed-bytes)))
636           (unless (zerop residual-objects)
637             (format t "  Other types: ~:D bytes, ~:D object~:P.~%"
638                     residual-bytes residual-objects))))
639
640       (format t "  ~:(~A~) instance total: ~:D bytes, ~:D object~:P.~%"
641               space total-bytes total-objects)))
642
643   (values))
644 \f
645 ;;;; PRINT-ALLOCATED-OBJECTS
646
647 (defun print-allocated-objects (space &key (percent 0) (pages 5)
648                                       type larger smaller count
649                                       (stream *standard-output*))
650   (declare (type (integer 0 99) percent) (type index pages)
651            (type stream stream) (type spaces space)
652            (type (or index null) type larger smaller count))
653   (multiple-value-bind (start-sap end-sap) (space-bounds space)
654     (let* ((space-start (sap-int start-sap))
655            (space-end (sap-int end-sap))
656            (space-size (- space-end space-start))
657            (pagesize (sb!sys:get-page-size))
658            (start (+ space-start (round (* space-size percent) 100)))
659            (printed-conses (make-hash-table :test 'eq))
660            (pages-so-far 0)
661            (count-so-far 0)
662            (last-page 0))
663       (declare (type (unsigned-byte 32) last-page start)
664                (fixnum pages-so-far count-so-far pagesize))
665       (labels ((note-conses (x)
666                  (unless (or (atom x) (gethash x printed-conses))
667                    (setf (gethash x printed-conses) t)
668                    (note-conses (car x))
669                    (note-conses (cdr x)))))
670         (map-allocated-objects
671          (lambda (obj obj-type size)
672            (let ((addr (get-lisp-obj-address obj)))
673              (when (>= addr start)
674                (when (if count
675                          (> count-so-far count)
676                          (> pages-so-far pages))
677                  (return-from print-allocated-objects (values)))
678
679                (unless count
680                  (let ((this-page (* (the (values (unsigned-byte 32) t)
681                                        (truncate addr pagesize))
682                                      pagesize)))
683                    (declare (type (unsigned-byte 32) this-page))
684                    (when (/= this-page last-page)
685                      (when (< pages-so-far pages)
686                        ;; FIXME: What is this? (ERROR "Argh..")? or
687                        ;; a warning? or code that can be removed
688                        ;; once the system is stable? or what?
689                        (format stream "~2&**** Page ~W, address ~X:~%"
690                                pages-so-far addr))
691                      (setq last-page this-page)
692                      (incf pages-so-far))))
693
694                (when (and (or (not type) (eql obj-type type))
695                           (or (not smaller) (<= size smaller))
696                           (or (not larger) (>= size larger)))
697                  (incf count-so-far)
698                  (case type
699                    (#.code-header-widetag
700                     (let ((dinfo (%code-debug-info obj)))
701                       (format stream "~&Code object: ~S~%"
702                               (if dinfo
703                                   (sb!c::compiled-debug-info-name dinfo)
704                                   "No debug info."))))
705                    (#.symbol-header-widetag
706                     (format stream "~&~S~%" obj))
707                    (#.list-pointer-lowtag
708                     (unless (gethash obj printed-conses)
709                       (note-conses obj)
710                       (let ((*print-circle* t)
711                             (*print-level* 5)
712                             (*print-length* 10))
713                         (format stream "~&~S~%" obj))))
714                    (t
715                     (fresh-line stream)
716                     (let ((str (write-to-string obj :level 5 :length 10
717                                                 :pretty nil)))
718                       (unless (eql type instance-header-widetag)
719                         (format stream "~S: " (type-of obj)))
720                       (format stream "~A~%"
721                               (subseq str 0 (min (length str) 60))))))))))
722          space))))
723   (values))
724 \f
725 ;;;; LIST-ALLOCATED-OBJECTS, LIST-REFERENCING-OBJECTS
726
727 (defvar *ignore-after* nil)
728
729 (defun valid-obj (space x)
730   (or (not (eq space :dynamic))
731       ;; this test looks bogus if the allocator doesn't work linearly,
732       ;; which I suspect is the case for GENCGC.  -- CSR, 2004-06-29
733       (< (get-lisp-obj-address x) (get-lisp-obj-address *ignore-after*))))
734
735 (defun maybe-cons (space x stuff)
736   (if (valid-obj space x)
737       (cons x stuff)
738       stuff))
739
740 (defun list-allocated-objects (space &key type larger smaller count
741                                      test)
742   (declare (type spaces space)
743            (type (or index null) larger smaller type count)
744            (type (or function null) test)
745            (inline map-allocated-objects))
746   (unless *ignore-after*
747     (setq *ignore-after* (cons 1 2)))
748   (collect ((counted 0 1+))
749     (let ((res ()))
750       (map-allocated-objects
751        (lambda (obj obj-type size)
752          (when (and (or (not type) (eql obj-type type))
753                     (or (not smaller) (<= size smaller))
754                     (or (not larger) (>= size larger))
755                     (or (not test) (funcall test obj)))
756            (setq res (maybe-cons space obj res))
757            (when (and count (>= (counted) count))
758              (return-from list-allocated-objects res))))
759        space)
760       res)))
761
762 ;;; Calls FUNCTION with all object that have (possibly conservative)
763 ;;; references to them on current stack.
764 (defun map-stack-references (function)
765   (let ((end
766          (sb!di::descriptor-sap
767           #!+stack-grows-downward-not-upward *control-stack-end*
768           #!-stack-grows-downward-not-upward *control-stack-start*))
769         (sp (current-sp))
770         (seen nil))
771     (loop until #!+stack-grows-downward-not-upward (sap> sp end)
772                 #!-stack-grows-downward-not-upward (sap< sp end)
773           do (multiple-value-bind (obj ok) (make-lisp-obj (sap-ref-word sp 0) nil)
774                (when (and ok (typep obj '(not (or fixnum character))))
775                  (unless (member obj seen :test #'eq)
776                    (funcall function obj)
777                    (push obj seen))))
778              (setf sp
779                    #!+stack-grows-downward-not-upward (sap+ sp n-word-bytes)
780                    #!-stack-grows-downward-not-upward (sap+ sp (- n-word-bytes))))))
781
782 (defun map-referencing-objects (fun space object)
783   (declare (type spaces space) (inline map-allocated-objects))
784   (unless *ignore-after*
785     (setq *ignore-after* (cons 1 2)))
786   (flet ((maybe-call (fun obj)
787            (when (valid-obj space obj)
788              (funcall fun obj))))
789     (map-allocated-objects
790      (lambda (obj obj-type size)
791        (declare (ignore obj-type size))
792        (typecase obj
793          (cons
794           (when (or (eq (car obj) object)
795                     (eq (cdr obj) object))
796             (maybe-call fun obj)))
797          (instance
798           (dotimes (i (%instance-length obj))
799             (when (eq (%instance-ref obj i) object)
800               (maybe-call fun obj)
801               (return))))
802          (code-component
803           (let ((length (get-header-data obj)))
804             (do ((i code-constants-offset (1+ i)))
805                 ((= i length))
806               (when (eq (code-header-ref obj i) object)
807                 (maybe-call fun obj)
808                 (return)))))
809          (simple-vector
810           (dotimes (i (length obj))
811             (when (eq (svref obj i) object)
812               (maybe-call fun obj)
813               (return))))
814          (symbol
815           (when (or (eq (symbol-name obj) object)
816                     (eq (symbol-package obj) object)
817                     (eq (symbol-plist obj) object)
818                     (and (boundp obj)
819                          (eq (symbol-value obj) object)))
820             (maybe-call fun obj)))))
821      space)))
822
823 (defun list-referencing-objects (space object)
824   (collect ((res))
825     (map-referencing-objects
826      (lambda (obj) (res obj)) space object)
827     (res)))