Fix sb-pcl::%update-slots.
[sbcl.git] / contrib / sb-sprof / sb-sprof.lisp
blob03a64832c856c7c57605cf4ae90371e93399cb56
1 ;;; Copyright (C) 2003 Gerd Moellmann <gerd.moellmann@t-online.de>
2 ;;; All rights reserved.
3 ;;;
4 ;;; Redistribution and use in source and binary forms, with or without
5 ;;; modification, are permitted provided that the following conditions
6 ;;; are met:
7 ;;;
8 ;;; 1. Redistributions of source code must retain the above copyright
9 ;;; notice, this list of conditions and the following disclaimer.
10 ;;; 2. Redistributions in binary form must reproduce the above copyright
11 ;;; notice, this list of conditions and the following disclaimer in the
12 ;;; documentation and/or other materials provided with the distribution.
13 ;;; 3. The name of the author may not be used to endorse or promote
14 ;;; products derived from this software without specific prior written
15 ;;; permission.
16 ;;;
17 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
18 ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE
21 ;;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
23 ;;; OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 ;;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 ;;; USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
28 ;;; DAMAGE.
30 ;;; Statistical profiler.
32 ;;; Overview:
33 ;;;
34 ;;; This profiler arranges for SIGPROF interrupts to interrupt a
35 ;;; running program at regular intervals. Each time a SIGPROF occurs,
36 ;;; the current program counter and return address is recorded in a
37 ;;; vector, until a configurable maximum number of samples have been
38 ;;; taken.
39 ;;;
40 ;;; A profiling report is generated from the samples array by
41 ;;; determining the Lisp functions corresponding to the recorded
42 ;;; addresses. Each program counter/return address pair forms one
43 ;;; edge in a call graph.
45 ;;; Problems:
46 ;;;
47 ;;; The code being generated on x86 makes determining callers reliably
48 ;;; something between extremely difficult and impossible. Example:
49 ;;;
50 ;;; 10979F00: .entry eval::eval-stack-args(arg-count)
51 ;;; 18: pop dword ptr [ebp-8]
52 ;;; 1B: lea esp, [ebp-32]
53 ;;; 1E: mov edi, edx
54 ;;;
55 ;;; 20: cmp ecx, 4
56 ;;; 23: jne L4
57 ;;; 29: mov [ebp-12], edi
58 ;;; 2C: mov dword ptr [ebp-16], #x28F0000B ; nil
59 ;;; ; No-arg-parsing entry point
60 ;;; 33: mov dword ptr [ebp-20], 0
61 ;;; 3A: jmp L3
62 ;;; 3C: L0: mov edx, esp
63 ;;; 3E: sub esp, 12
64 ;;; 41: mov eax, [#x10979EF8] ; #<FDEFINITION object for eval::eval-stack-pop>
65 ;;; 47: xor ecx, ecx
66 ;;; 49: mov [edx-4], ebp
67 ;;; 4C: mov ebp, edx
68 ;;; 4E: call dword ptr [eax+5]
69 ;;; 51: mov esp, ebx
70 ;;;
71 ;;; Suppose this function is interrupted by SIGPROF at 4E. At that
72 ;;; point, the frame pointer EBP has been modified so that the
73 ;;; original return address of the caller of eval-stack-args is no
74 ;;; longer where it can be found by x86-call-context, and the new
75 ;;; return address, for the call to eval-stack-pop, is not yet on the
76 ;;; stack. The effect is that x86-call-context returns something
77 ;;; bogus, which leads to wrong edges in the call graph.
78 ;;;
79 ;;; One thing that one might try is filtering cases where the program
80 ;;; is interrupted at a call instruction. But since the above example
81 ;;; of an interrupt at a call instruction isn't the only case where
82 ;;; the stack is something x86-call-context can't really cope with,
83 ;;; this is not a general solution.
84 ;;;
85 ;;; Random ideas for implementation:
86 ;;;
87 ;;; * Space profiler. Sample when new pages are allocated instead of
88 ;;; at SIGPROF.
89 ;;;
90 ;;; * Record a configurable number of callers up the stack. That
91 ;;; could give a more complete graph when there are many small
92 ;;; functions.
93 ;;;
94 ;;; * Print help strings for reports, include hints to the problem
95 ;;; explained above.
96 ;;;
97 ;;; * Make flat report the default since call-graph isn't that
98 ;;; reliable?
100 (defpackage #:sb-sprof
101 (:use #:cl #:sb-ext #:sb-unix #:sb-alien #:sb-sys :sb-int)
102 (:export #:*sample-interval* #:*max-samples* #:*alloc-interval*
103 #:*report-sort-by* #:*report-sort-order*
104 #:start-sampling #:stop-sampling #:with-sampling
105 #:with-profiling #:start-profiling #:stop-profiling
106 #:profile-call-counts #:unprofile-call-counts
107 #:reset #:report))
109 (in-package #:sb-sprof)
112 ;;;; Graph Utilities
114 (defstruct (vertex (:constructor make-vertex)
115 (:constructor make-scc (scc-vertices edges)))
116 (visited nil :type boolean)
117 (root nil :type (or null vertex))
118 (dfn 0 :type fixnum)
119 (edges () :type list)
120 (scc-vertices () :type list))
122 (defstruct edge
123 (vertex (sb-impl::missing-arg) :type vertex))
125 (defstruct graph
126 (vertices () :type list))
128 (declaim (inline scc-p))
129 (defun scc-p (vertex)
130 (not (null (vertex-scc-vertices vertex))))
132 (defmacro do-vertices ((vertex graph) &body body)
133 `(dolist (,vertex (graph-vertices ,graph))
134 ,@body))
136 (defmacro do-edges ((edge edge-to vertex) &body body)
137 `(dolist (,edge (vertex-edges ,vertex))
138 (let ((,edge-to (edge-vertex ,edge)))
139 ,@body)))
141 (defun self-cycle-p (vertex)
142 (do-edges (e to vertex)
143 (when (eq to vertex)
144 (return t))))
146 (defun map-vertices (fn vertices)
147 (dolist (v vertices)
148 (setf (vertex-visited v) nil))
149 (dolist (v vertices)
150 (unless (vertex-visited v)
151 (funcall fn v))))
153 ;;; Eeko Nuutila, Eljas Soisalon-Soininen, around 1992. Improves on
154 ;;; Tarjan's original algorithm by not using the stack when processing
155 ;;; trivial components. Trivial components should appear frequently
156 ;;; in a call-graph such as ours, I think. Same complexity O(V+E) as
157 ;;; Tarjan.
158 (defun strong-components (vertices)
159 (let ((in-component (make-array (length vertices)
160 :element-type 'boolean
161 :initial-element nil))
162 (stack ())
163 (components ())
164 (dfn -1))
165 (labels ((min-root (x y)
166 (let ((rx (vertex-root x))
167 (ry (vertex-root y)))
168 (if (< (vertex-dfn rx) (vertex-dfn ry))
170 ry)))
171 (in-component (v)
172 (aref in-component (vertex-dfn v)))
173 ((setf in-component) (in v)
174 (setf (aref in-component (vertex-dfn v)) in))
175 (vertex-> (x y)
176 (> (vertex-dfn x) (vertex-dfn y)))
177 (visit (v)
178 (setf (vertex-dfn v) (incf dfn)
179 (in-component v) nil
180 (vertex-root v) v
181 (vertex-visited v) t)
182 (do-edges (e w v)
183 (unless (vertex-visited w)
184 (visit w))
185 (unless (in-component w)
186 (setf (vertex-root v) (min-root v w))))
187 (if (eq v (vertex-root v))
188 (loop while (and stack (vertex-> (car stack) v))
189 as w = (pop stack)
190 collect w into this-component
191 do (setf (in-component w) t)
192 finally
193 (setf (in-component v) t)
194 (push (cons v this-component) components))
195 (push v stack))))
196 (map-vertices #'visit vertices)
197 components)))
199 ;;; Given a dag as a list of vertices, return the list sorted
200 ;;; topologically, children first.
201 (defun topological-sort (dag)
202 (let ((sorted ())
203 (dfn -1))
204 (labels ((rec-sort (v)
205 (setf (vertex-visited v) t)
206 (setf (vertex-dfn v) (incf dfn))
207 (dolist (e (vertex-edges v))
208 (unless (vertex-visited (edge-vertex e))
209 (rec-sort (edge-vertex e))))
210 (push v sorted)))
211 (map-vertices #'rec-sort dag)
212 (nreverse sorted))))
214 ;;; Reduce graph G to a dag by coalescing strongly connected components
215 ;;; into vertices. Sort the result topologically.
216 (defun reduce-graph (graph &optional (scc-constructor #'make-scc))
217 (sb-int:collect ((sccs) (trivial))
218 (dolist (c (strong-components (graph-vertices graph)))
219 (if (or (cdr c) (self-cycle-p (car c)))
220 (sb-int:collect ((outgoing))
221 (dolist (v c)
222 (do-edges (e w v)
223 (unless (member w c)
224 (outgoing e))))
225 (sccs (funcall scc-constructor c (outgoing))))
226 (trivial (car c))))
227 (dolist (scc (sccs))
228 (dolist (v (trivial))
229 (do-edges (e w v)
230 (when (member w (vertex-scc-vertices scc))
231 (setf (edge-vertex e) scc)))))
232 (setf (graph-vertices graph)
233 (topological-sort (nconc (sccs) (trivial))))))
235 ;;;; The Profiler
237 (deftype address ()
238 "Type used for addresses, for instance, program counters,
239 code start/end locations etc."
240 '(unsigned-byte #.sb-vm::n-machine-word-bits))
242 (defconstant +unknown-address+ 0
243 "Constant representing an address that cannot be determined.")
245 ;;; A call graph. Vertices are NODE structures, edges are CALL
246 ;;; structures.
247 (defstruct (call-graph (:include graph)
248 (:constructor %make-call-graph))
249 ;; the value of *SAMPLE-INTERVAL* or *ALLOC-INTERVAL* at the time
250 ;; the graph was created (depending on the current allocation mode)
251 (sample-interval (sb-impl::missing-arg) :type number)
252 ;; the sampling-mode that was used for the profiling run
253 (sampling-mode (sb-impl::missing-arg) :type (member :cpu :alloc :time))
254 ;; number of samples taken
255 (nsamples (sb-impl::missing-arg) :type sb-int:index)
256 ;; threads that have been sampled
257 (sampled-threads nil :type list)
258 ;; sample count for samples not in any function
259 (elsewhere-count (sb-impl::missing-arg) :type sb-int:index)
260 ;; a flat list of NODEs, sorted by sample count
261 (flat-nodes () :type list))
263 ;;; A node in a call graph, representing a function that has been
264 ;;; sampled. The edges of a node are CALL structures that represent
265 ;;; functions called from a given node.
266 (defstruct (node (:include vertex)
267 (:constructor %make-node))
268 ;; A numeric label for the node. The most frequently called function
269 ;; gets label 1. This is just for identification purposes in the
270 ;; profiling report.
271 (index 0 :type fixnum)
272 ;; Start and end address of the function's code. Depending on the
273 ;; debug-info, this might be either as absolute addresses for things
274 ;; that won't move around in memory, or as relative offsets from
275 ;; some point for things that might move.
276 (start-pc-or-offset 0 :type address)
277 (end-pc-or-offset 0 :type address)
278 ;; the name of the function
279 (name nil :type t)
280 ;; sample count for this function
281 (count 0 :type fixnum)
282 ;; count including time spent in functions called from this one
283 (accrued-count 0 :type fixnum)
284 ;; the debug-info that this node was created from
285 (debug-info nil :type t)
286 ;; list of NODEs for functions calling this one
287 (callers () :type list)
288 ;; the call count for the function that corresponds to this node (or NIL
289 ;; if call counting wasn't enabled for this function)
290 (call-count nil :type (or null integer)))
292 ;;; A cycle in a call graph. The functions forming the cycle are
293 ;;; found in the SCC-VERTICES slot of the VERTEX structure.
294 (defstruct (cycle (:include node)))
296 ;;; An edge in a call graph. EDGE-VERTEX is the function being
297 ;;; called.
298 (defstruct (call (:include edge)
299 (:constructor make-call (vertex)))
300 ;; number of times the call was sampled
301 (count 1 :type sb-int:index))
303 (defvar *sample-interval* 0.01
304 "Default number of seconds between samples.")
305 (declaim (type number *sample-interval*))
307 (defvar *alloc-interval* 4
308 "Default number of allocation region openings between samples.")
309 (declaim (type number *alloc-interval*))
311 (defvar *max-samples* 50000
312 "Default number of traces taken. This variable is somewhat misnamed:
313 each trace may actually consist of an arbitrary number of samples, depending
314 on the depth of the call stack.")
315 (declaim (type sb-int:index *max-samples*))
317 ;;; Encapsulate all the information about a sampling run
318 (defstruct (samples)
319 ;; When this vector fills up, we allocate a new one and copy over
320 ;; the old contents.
321 (vector (make-array (* *max-samples*
322 ;; Arbitrary guess at how many samples we'll be
323 ;; taking for each trace. The exact amount doesn't
324 ;; matter, this is just to decrease the amount of
325 ;; re-allocation that will need to be done.
327 ;; Each sample takes two cells in the vector
329 :type simple-vector)
330 (trace-count 0 :type sb-int:index)
331 (index 0 :type sb-int:index)
332 (mode nil :type (member :cpu :alloc :time))
333 (sample-interval (sb-int:missing-arg) :type number)
334 (alloc-interval (sb-int:missing-arg) :type number)
335 (max-depth most-positive-fixnum :type number)
336 (max-samples (sb-int:missing-arg) :type sb-int:index)
337 (sampled-threads nil :type list))
339 (defmethod print-object ((samples samples) stream)
340 (print-unreadable-object (samples stream :type t :identity t)
341 (let ((*print-array* nil))
342 (call-next-method))))
344 (defmethod print-object ((call-graph call-graph) stream)
345 (print-unreadable-object (call-graph stream :type t :identity t)
346 (format stream "~d samples" (call-graph-nsamples call-graph))))
348 (defmethod print-object ((node node) stream)
349 (print-unreadable-object (node stream :type t :identity t)
350 (format stream "~s [~d]" (node-name node) (node-index node))))
352 (defmethod print-object ((call call) stream)
353 (print-unreadable-object (call stream :type t :identity t)
354 (format stream "~s [~d]" (node-name (call-vertex call))
355 (node-index (call-vertex call)))))
357 (deftype report-type ()
358 '(member nil :flat :graph))
360 (defvar *sampling-mode* :cpu
361 "Default sampling mode. :CPU for cpu profiling, :ALLOC for allocation
362 profiling, and :TIME for wallclock profiling.")
363 (declaim (type (member :cpu :alloc :time) *sampling-mode*))
365 (defvar *alloc-region-size*
366 #-gencgc
367 (get-page-size)
368 #+gencgc
369 (max sb-vm:gencgc-alloc-granularity sb-vm:gencgc-card-bytes))
370 (declaim (type number *alloc-region-size*))
372 (defvar *samples* nil)
373 (declaim (type (or null samples) *samples*))
375 (defvar *profiling* nil)
376 (declaim (type (member nil :alloc :cpu :time) *profiling*))
377 (defvar *sampling* nil)
378 (declaim (type boolean *sampling*))
380 (defvar *show-progress* nil)
382 (defvar *old-sampling* nil)
384 ;; Call count encapsulation information
385 (defvar *encapsulations* (make-hash-table :test 'equal))
387 (defun turn-off-sampling ()
388 (setq *old-sampling* *sampling*)
389 (setq *sampling* nil))
391 (defun turn-on-sampling ()
392 (setq *sampling* *old-sampling*))
394 (defun show-progress (format-string &rest args)
395 (when *show-progress*
396 (apply #'format t format-string args)
397 (finish-output)))
399 (defun start-sampling ()
400 "Switch on statistical sampling."
401 (setq *sampling* t))
403 (defun stop-sampling ()
404 "Switch off statistical sampling."
405 (setq *sampling* nil))
407 (defmacro with-sampling ((&optional (on t)) &body body)
408 "Evaluate body with statistical sampling turned on or off."
409 `(let ((*sampling* ,on)
410 (sb-vm:*alloc-signal* sb-vm:*alloc-signal*))
411 ,@body))
413 ;;; Return something serving as debug info for address PC.
414 (declaim (inline debug-info))
415 (defun debug-info (pc)
416 (declare (type system-area-pointer pc)
417 (muffle-conditions compiler-note))
418 (let ((ptr (sb-di::component-ptr-from-pc pc)))
419 (cond ((sap= ptr (int-sap 0))
420 (let ((name (sap-foreign-symbol pc)))
421 (if name
422 (values (format nil "foreign function ~a" name)
423 (sap-int pc))
424 (values nil (sap-int pc)))))
426 (let* ((code (sb-di::component-from-component-ptr ptr))
427 (code-header-len (* (sb-kernel:get-header-data code)
428 sb-vm:n-word-bytes))
429 (pc-offset (- (sap-int pc)
430 (- (sb-kernel:get-lisp-obj-address code)
431 sb-vm:other-pointer-lowtag)
432 code-header-len))
433 (df (sb-di::debug-fun-from-pc code pc-offset)))
434 (cond ((typep df 'sb-di::bogus-debug-fun)
435 (values code (sap-int pc)))
437 ;; The code component might be moved by the GC. Store
438 ;; a PC offset, and reconstruct the data in
439 ;; SAMPLE-PC-FROM-PC-OR-OFFSET.
440 (values df pc-offset))
442 (values nil 0))))))))
444 (defun ensure-samples-vector (samples)
445 (let ((vector (samples-vector samples))
446 (index (samples-index samples)))
447 ;; Allocate a new sample vector if the old one is full
448 (if (= (length vector) index)
449 (let ((new-vector (make-array (* 2 index))))
450 (format *trace-output* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
451 (samples-trace-count samples)
452 (truncate index 2))
453 (replace new-vector vector)
454 (setf (samples-vector samples) new-vector))
455 vector)))
457 (declaim (inline record))
458 (defun record (samples pc)
459 (declare (type system-area-pointer pc)
460 (muffle-conditions compiler-note))
461 (multiple-value-bind (info pc-or-offset)
462 (debug-info pc)
463 (let ((vector (ensure-samples-vector samples))
464 (index (samples-index samples)))
465 (declare (type simple-vector vector))
466 ;; Allocate a new sample vector if the old one is full
467 (when (= (length vector) index)
468 (let ((new-vector (make-array (* 2 index))))
469 (format *trace-output* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
470 (samples-trace-count samples)
471 (truncate index 2))
472 (replace new-vector vector)
473 (setf vector new-vector
474 (samples-vector samples) new-vector)))
475 ;; For each sample, store the debug-info and the PC/offset into
476 ;; adjacent cells.
477 (setf (aref vector index) info
478 (aref vector (1+ index)) pc-or-offset)))
479 (incf (samples-index samples) 2))
481 (defun record-trace-start (samples)
482 ;; Mark the start of the trace.
483 (let ((vector (ensure-samples-vector samples)))
484 (declare (type simple-vector vector))
485 (setf (aref vector (samples-index samples))
486 'trace-start))
487 (incf (samples-index samples) 2))
489 ;;; List of thread currently profiled, or :ALL for all threads.
490 (defvar *profiled-threads* nil)
491 (declaim (type (or list (member :all)) *profiled-threads*))
493 ;;; Thread which runs the wallclock timers, if any.
494 (defvar *timer-thread* nil)
496 (defun profiled-threads ()
497 (let ((profiled-threads *profiled-threads*))
498 (remove *timer-thread*
499 (if (eq :all profiled-threads)
500 (sb-thread:list-all-threads)
501 profiled-threads))))
503 (defun profiled-thread-p (thread)
504 (let ((profiled-threads *profiled-threads*))
505 (or (and (eq :all profiled-threads)
506 (not (eq *timer-thread* thread)))
507 (member thread profiled-threads :test #'eq))))
509 #+(and (or x86 x86-64) (not win32))
510 (progn
511 ;; Ensure that only one thread at a time will be doing profiling stuff.
512 (defvar *profiler-lock* (sb-thread:make-mutex :name "Statistical Profiler"))
513 (defvar *distribution-lock* (sb-thread:make-mutex :name "Wallclock profiling lock"))
515 #+sb-thread
516 (declaim (inline pthread-kill))
517 #+sb-thread
518 (define-alien-routine pthread-kill int (os-thread unsigned-long) (signal int))
520 ;;; A random thread will call this in response to either a timer firing,
521 ;;; This in turn will distribute the notice to those threads we are
522 ;;; interested using SIGPROF.
523 (defun thread-distribution-handler ()
524 (declare (optimize speed (space 0)))
525 #+sb-thread
526 (let ((lock *distribution-lock*))
527 ;; Don't flood the system with more interrupts if the last
528 ;; set is still being delivered.
529 (unless (sb-thread:mutex-value lock)
530 (sb-thread::with-system-mutex (lock)
531 (dolist (thread (profiled-threads))
532 ;; This may occasionally fail to deliver the signal, but that
533 ;; seems better then using kill_thread_safely with it's 1
534 ;; second backoff.
535 (let ((os-thread (sb-thread::thread-os-thread thread)))
536 (when os-thread
537 (pthread-kill os-thread sb-unix:sigprof)))))))
538 #-sb-thread
539 (unix-kill 0 sb-unix:sigprof))
541 (defun sigprof-handler (signal code scp)
542 (declare (ignore signal code) (optimize speed (space 0))
543 (disable-package-locks sb-di::x86-call-context)
544 (muffle-conditions compiler-note)
545 (type system-area-pointer scp))
546 (let ((self sb-thread:*current-thread*)
547 (profiling *profiling*))
548 ;; Turn off allocation counter when it is not needed. Doing this in the
549 ;; signal handler means we don't have to worry about racing with the runtime
550 (unless (eq :alloc profiling)
551 (setf sb-vm::*alloc-signal* nil))
552 (when (and *sampling*
553 ;; Normal SIGPROF gets practically speaking delivered to threads
554 ;; depending on the run time they use, so we need to filter
555 ;; out those we don't care about. For :ALLOC and :TIME profiling
556 ;; only the interesting threads get SIGPROF in the first place.
558 ;; ...except that Darwin at least doesn't seem to work like we
559 ;; would want it to, which makes multithreaded :CPU profiling pretty
560 ;; pointless there -- though it may be that our mach magic is
561 ;; partially to blame?
562 (or (not (eq :cpu profiling)) (profiled-thread-p self)))
563 (sb-thread::with-system-mutex (*profiler-lock* :without-gcing t)
564 (let ((samples *samples*))
565 (when (and samples
566 (< (samples-trace-count samples)
567 (samples-max-samples samples)))
568 (with-alien ((scp (* os-context-t) :local scp))
569 (let* ((pc-ptr (sb-vm:context-pc scp))
570 (fp (sb-vm::context-register scp #.sb-vm::ebp-offset)))
571 ;; foreign code might not have a useful frame
572 ;; pointer in ebp/rbp, so make sure it looks
573 ;; reasonable before walking the stack
574 (unless (sb-di::control-stack-pointer-valid-p (sb-sys:int-sap fp))
575 (record samples pc-ptr)
576 (return-from sigprof-handler nil))
577 (incf (samples-trace-count samples))
578 (pushnew self (samples-sampled-threads samples))
579 (let ((fp (int-sap fp))
580 (ok t))
581 (declare (type system-area-pointer fp pc-ptr))
582 ;; FIXME: How annoying. The XC doesn't store enough
583 ;; type information about SB-DI::X86-CALL-CONTEXT,
584 ;; even if we declaim the ftype explicitly in
585 ;; src/code/debug-int. And for some reason that type
586 ;; information is needed for the inlined version to
587 ;; be compiled without boxing the returned saps. So
588 ;; we declare the correct ftype here manually, even
589 ;; if the compiler should be able to deduce this
590 ;; exact same information.
591 (declare (ftype (function (system-area-pointer)
592 (values (member nil t)
593 system-area-pointer
594 system-area-pointer))
595 sb-di::x86-call-context))
596 (record-trace-start samples)
597 (dotimes (i (samples-max-depth samples))
598 (record samples pc-ptr)
599 (setf (values ok pc-ptr fp)
600 (sb-di::x86-call-context fp))
601 (unless ok
602 (return))))))
603 ;; Reset thread-local allocation counter before interrupts
604 ;; are enabled.
605 (when (eq t sb-vm::*alloc-signal*)
606 (setf sb-vm:*alloc-signal* (1- (samples-alloc-interval samples)))))))))
607 nil))
609 ;; FIXME: On non-x86 platforms we don't yet walk the call stack deeper
610 ;; than one level.
611 #-(or x86 x86-64)
612 (defun sigprof-handler (signal code scp)
613 (declare (ignore signal code))
614 (sb-sys:without-interrupts
615 (let ((samples *samples*))
616 (when (and *sampling*
617 samples
618 (< (samples-trace-count samples)
619 (samples-max-samples samples)))
620 (sb-sys:without-gcing
621 (with-alien ((scp (* os-context-t) :local scp))
622 (locally (declare (optimize (inhibit-warnings 2)))
623 (incf (samples-trace-count samples))
624 (record-trace-start samples)
625 (let* ((pc-ptr (sb-vm:context-pc scp))
626 (fp (sb-vm::context-register scp #.sb-vm::cfp-offset))
627 (ra (sap-ref-word
628 (int-sap fp)
629 (* sb-vm::lra-save-offset sb-vm::n-word-bytes))))
630 (record samples pc-ptr)
631 (record samples (int-sap ra))))))))))
633 ;;; Return the start address of CODE.
634 (defun code-start (code)
635 (declare (type sb-kernel:code-component code))
636 (sap-int (sb-kernel:code-instructions code)))
638 ;;; Return start and end address of CODE as multiple values.
639 (defun code-bounds (code)
640 (declare (type sb-kernel:code-component code))
641 (let* ((start (code-start code))
642 (end (+ start (sb-kernel:%code-code-size code))))
643 (values start end)))
645 (defmacro with-profiling ((&key (sample-interval '*sample-interval*)
646 (alloc-interval '*alloc-interval*)
647 (max-samples '*max-samples*)
648 (reset nil)
649 (mode '*sampling-mode*)
650 (loop nil)
651 (max-depth most-positive-fixnum)
652 show-progress
653 (threads '(list sb-thread:*current-thread*))
654 (report nil report-p))
655 &body body)
656 "Evaluate BODY with statistical profiling turned on. If LOOP is true,
657 loop around the BODY until a sufficient number of samples has been collected.
658 Returns the values from the last evaluation of BODY.
660 In multithreaded operation, only the thread in which WITH-PROFILING was
661 evaluated will be profiled by default. If you want to profile multiple
662 threads, invoke the profiler with START-PROFILING.
664 The following keyword args are recognized:
666 :SAMPLE-INTERVAL <n>
667 Take a sample every <n> seconds. Default is *SAMPLE-INTERVAL*.
669 :ALLOC-INTERVAL <n>
670 Take a sample every time <n> allocation regions (approximately
671 8kB) have been allocated since the last sample. Default is
672 *ALLOC-INTERVAL*.
674 :MODE <mode>
675 If :CPU, run the profiler in CPU profiling mode. If :ALLOC, run the
676 profiler in allocation profiling mode. If :TIME, run the profiler
677 in wallclock profiling mode.
679 :MAX-SAMPLES <max>
680 Repeat evaluating body until <max> samples are taken.
681 Default is *MAX-SAMPLES*.
683 :MAX-DEPTH <max>
684 Maximum call stack depth that the profiler should consider. Only
685 has an effect on x86 and x86-64.
687 :REPORT <type>
688 If specified, call REPORT with :TYPE <type> at the end.
690 :RESET <bool>
691 It true, call RESET at the beginning.
693 :THREADS <list-form>
694 Form that evaluates to the list threads to profile, or :ALL to indicate
695 that all threads should be profiled. Defaults to the current
696 thread. (Note: START-PROFILING defaults to all threads.)
698 :THREADS has no effect on call-counting at the moment.
700 On some platforms (eg. Darwin) the signals used by the profiler are
701 not properly delivered to threads in proportion to their CPU usage
702 when doing :CPU profiling. If you see empty call graphs, or are obviously
703 missing several samples from certain threads, you may be falling afoul
704 of this. In this case using :MODE :TIME is likely to work better.
706 :LOOP <bool>
707 If false (the default), evaluate BODY only once. If true repeatedly
708 evaluate BODY."
709 (declare (type report-type report))
710 (check-type loop boolean)
711 (with-unique-names (values last-index oops)
712 `(let* ((*sample-interval* ,sample-interval)
713 (*alloc-interval* ,alloc-interval)
714 (*sampling* nil)
715 (*sampling-mode* ,mode)
716 (*max-samples* ,max-samples))
717 ,@(when reset '((reset)))
718 (flet ((,oops ()
719 (warn "~@<No sampling progress; run too short, sampling interval ~
720 too long, inappropriate set of sampled thread, or possibly ~
721 a profiler bug.~:@>")))
722 (unwind-protect
723 (progn
724 (start-profiling :max-depth ,max-depth :threads ,threads)
725 ,(if loop
726 `(let (,values)
727 (loop
728 (when (>= (samples-trace-count *samples*)
729 (samples-max-samples *samples*))
730 (return))
731 ,@(when show-progress
732 `((format t "~&===> ~d of ~d samples taken.~%"
733 (samples-trace-count *samples*)
734 (samples-max-samples *samples*))))
735 (let ((,last-index (samples-index *samples*)))
736 (setf ,values (multiple-value-list (progn ,@body)))
737 (when (= ,last-index (samples-index *samples*))
738 (,oops)
739 (return))))
740 (values-list ,values))
741 `(let ((,last-index (samples-index *samples*)))
742 (multiple-value-prog1 (progn ,@body)
743 (when (= ,last-index (samples-index *samples*))
744 (,oops))))))
745 (stop-profiling)))
746 ,@(when report-p `((report :type ,report))))))
748 (defvar *timer* nil)
750 (defvar *old-alloc-interval* nil)
751 (defvar *old-sample-interval* nil)
753 #-win32
754 (defun start-profiling (&key (max-samples *max-samples*)
755 (mode *sampling-mode*)
756 (sample-interval *sample-interval*)
757 (alloc-interval *alloc-interval*)
758 (max-depth most-positive-fixnum)
759 (threads :all)
760 (sampling t))
761 "Start profiling statistically in the current thread if not already profiling.
762 The following keyword args are recognized:
764 :SAMPLE-INTERVAL <n>
765 Take a sample every <n> seconds. Default is *SAMPLE-INTERVAL*.
767 :ALLOC-INTERVAL <n>
768 Take a sample every time <n> allocation regions (approximately
769 8kB) have been allocated since the last sample. Default is
770 *ALLOC-INTERVAL*.
772 :MODE <mode>
773 If :CPU, run the profiler in CPU profiling mode. If :ALLOC, run
774 the profiler in allocation profiling mode. If :TIME, run the profiler
775 in wallclock profiling mode.
777 :MAX-SAMPLES <max>
778 Maximum number of samples. Default is *MAX-SAMPLES*.
780 :MAX-DEPTH <max>
781 Maximum call stack depth that the profiler should consider. Only
782 has an effect on x86 and x86-64.
784 :THREADS <list>
785 List threads to profile, or :ALL to indicate that all threads should be
786 profiled. Defaults to :ALL. (Note: WITH-PROFILING defaults to the current
787 thread.)
789 :THREADS has no effect on call-counting at the moment.
791 On some platforms (eg. Darwin) the signals used by the profiler are
792 not properly delivered to threads in proportion to their CPU usage
793 when doing :CPU profiling. If you see empty call graphs, or are obviously
794 missing several samples from certain threads, you may be falling afoul
795 of this.
797 :SAMPLING <bool>
798 If true, the default, start sampling right away.
799 If false, START-SAMPLING can be used to turn sampling on."
800 #-gencgc
801 (when (eq mode :alloc)
802 (error "Allocation profiling is only supported for builds using the generational garbage collector."))
803 (unless *profiling*
804 (multiple-value-bind (secs usecs)
805 (multiple-value-bind (secs rest)
806 (truncate sample-interval)
807 (values secs (truncate (* rest 1000000))))
808 (setf *sampling* sampling
809 *samples* (make-samples :max-depth max-depth
810 :max-samples max-samples
811 :sample-interval sample-interval
812 :alloc-interval alloc-interval
813 :mode mode))
814 (enable-call-counting)
815 (setf *profiled-threads* threads)
816 (sb-sys:enable-interrupt sb-unix:sigprof
817 #'sigprof-handler
818 :synchronous t)
819 (ecase mode
820 (:alloc
821 (let ((alloc-signal (1- alloc-interval)))
822 #+sb-thread
823 (progn
824 (when (eq :all threads)
825 ;; Set the value new threads inherit.
826 (sb-thread::with-all-threads-lock
827 (setf sb-thread::*default-alloc-signal* alloc-signal)))
828 ;; Turn on allocation profiling in existing threads.
829 (dolist (thread (profiled-threads))
830 (sb-thread::%set-symbol-value-in-thread 'sb-vm::*alloc-signal* thread alloc-signal)))
831 #-sb-thread
832 (setf sb-vm:*alloc-signal* alloc-signal)))
833 (:cpu
834 (unix-setitimer :profile secs usecs secs usecs))
835 (:time
836 #+sb-thread
837 (let ((setup (sb-thread:make-semaphore :name "Timer thread setup semaphore")))
838 (setf *timer-thread*
839 (sb-thread:make-thread (lambda ()
840 (sb-thread:wait-on-semaphore setup)
841 (loop while (eq sb-thread:*current-thread* *timer-thread*)
842 do (sleep 1.0)))
843 :name "SB-SPROF wallclock timer thread"))
844 (sb-thread:signal-semaphore setup))
845 #-sb-thread
846 (setf *timer-thread* nil)
847 (setf *timer* (make-timer #'thread-distribution-handler :name "SB-PROF wallclock timer"
848 :thread *timer-thread*))
849 (schedule-timer *timer* sample-interval :repeat-interval sample-interval)))
850 (setq *profiling* mode)))
851 (values))
853 (defun stop-profiling ()
854 "Stop profiling if profiling."
855 (let ((profiling *profiling*))
856 (when profiling
857 ;; Even with the timers shut down we cannot be sure that there is no
858 ;; undelivered sigprof. The handler is also responsible for turning the
859 ;; *ALLOC-SIGNAL* off in individual threads.
860 (ecase profiling
861 (:alloc
862 #+sb-thread
863 (setf sb-thread::*default-alloc-signal* nil)
864 #-sb-thread
865 (setf sb-vm:*alloc-signal* nil))
866 (:cpu
867 (unix-setitimer :profile 0 0 0 0))
868 (:time
869 (unschedule-timer *timer*)
870 (setf *timer* nil
871 *timer-thread* nil)))
872 (disable-call-counting)
873 (setf *profiling* nil
874 *sampling* nil
875 *profiled-threads* nil)))
876 (values))
878 (defun reset ()
879 "Reset the profiler."
880 (stop-profiling)
881 (setq *sampling* nil)
882 (setq *samples* nil)
883 (values))
885 ;;; Make a NODE for debug-info INFO.
886 (defun make-node (info)
887 (flet ((clean-name (name)
888 (if (and (consp name)
889 (member (first name)
890 '(sb-c::xep sb-c::tl-xep sb-c::&more-processor
891 sb-c::top-level-form
892 sb-c::&optional-processor)))
893 (second name)
894 name)))
895 (typecase info
896 (sb-kernel::code-component
897 (multiple-value-bind (start end)
898 (code-bounds info)
899 (values
900 (%make-node :name (or (sb-disassem::find-assembler-routine start)
901 (format nil "~a" info))
902 :debug-info info
903 :start-pc-or-offset start
904 :end-pc-or-offset end)
905 info)))
906 (sb-di::compiled-debug-fun
907 (let* ((name (sb-di::debug-fun-name info))
908 (cdf (sb-di::compiled-debug-fun-compiler-debug-fun info))
909 (start-offset (sb-c::compiled-debug-fun-start-pc cdf))
910 (end-offset (sb-c::compiled-debug-fun-elsewhere-pc cdf))
911 (component (sb-di::compiled-debug-fun-component info))
912 (start-pc (code-start component)))
913 ;; Call graphs are mostly useless unless we somehow
914 ;; distinguish a gazillion different (LAMBDA ())'s.
915 (when (equal name '(lambda ()))
916 (setf name (format nil "Unknown component: #x~x" start-pc)))
917 (values (%make-node :name (clean-name name)
918 :debug-info info
919 :start-pc-or-offset start-offset
920 :end-pc-or-offset end-offset)
921 component)))
922 (sb-di::debug-fun
923 (%make-node :name (clean-name (sb-di::debug-fun-name info))
924 :debug-info info))
926 (%make-node :name (coerce info 'string)
927 :debug-info info)))))
929 ;;; One function can have more than one COMPILED-DEBUG-FUNCTION with
930 ;;; the same name. Reduce the number of calls to Debug-Info by first
931 ;;; looking for a given PC in a red-black tree. If not found in the
932 ;;; tree, get debug info, and look for a node in a hash-table by
933 ;;; function name. If not found in the hash-table, make a new node.
935 (defvar *name->node*)
937 (defmacro with-lookup-tables (() &body body)
938 `(let ((*name->node* (make-hash-table :test 'equal)))
939 ,@body))
941 ;;; Find or make a new node for INFO. Value is the NODE found or
942 ;;; made; NIL if not enough information exists to make a NODE for INFO.
943 (defun lookup-node (info)
944 (when info
945 (multiple-value-bind (new key)
946 (make-node info)
947 (when (eql (node-name new) 'call-counter)
948 (return-from lookup-node (values nil nil)))
949 (let* ((key (cons (node-name new) key))
950 (found (gethash key *name->node*)))
951 (cond (found
952 (setf (node-start-pc-or-offset found)
953 (min (node-start-pc-or-offset found)
954 (node-start-pc-or-offset new)))
955 (setf (node-end-pc-or-offset found)
956 (max (node-end-pc-or-offset found)
957 (node-end-pc-or-offset new)))
958 found)
960 (let ((call-count-info (gethash (node-name new)
961 *encapsulations*)))
962 (when call-count-info
963 (setf (node-call-count new)
964 (car call-count-info))))
965 (setf (gethash key *name->node*) new)
966 new))))))
968 ;;; Return a list of all nodes created by LOOKUP-NODE.
969 (defun collect-nodes ()
970 (loop for node being the hash-values of *name->node*
971 collect node))
973 ;;; Value is a CALL-GRAPH for the current contents of *SAMPLES*.
974 (defun make-call-graph-1 (max-depth)
975 (let ((elsewhere-count 0)
976 visited-nodes)
977 (with-lookup-tables ()
978 (loop for i below (- (samples-index *samples*) 2) by 2
979 with depth = 0
980 for debug-info = (aref (samples-vector *samples*) i)
981 for next-info = (aref (samples-vector *samples*)
982 (+ i 2))
983 do (if (eq debug-info 'trace-start)
984 (setf depth 0)
985 (let ((callee (lookup-node debug-info))
986 (caller (unless (eq next-info 'trace-start)
987 (lookup-node next-info))))
988 (when (< depth max-depth)
989 (when (zerop depth)
990 (setf visited-nodes nil)
991 (cond (callee
992 (incf (node-accrued-count callee))
993 (incf (node-count callee)))
995 (incf elsewhere-count))))
996 (incf depth)
997 (when callee
998 (push callee visited-nodes))
999 (when caller
1000 (unless (member caller visited-nodes)
1001 (incf (node-accrued-count caller)))
1002 (when callee
1003 (let ((call (find callee (node-edges caller)
1004 :key #'call-vertex)))
1005 (pushnew caller (node-callers callee))
1006 (if call
1007 (unless (member caller visited-nodes)
1008 (incf (call-count call)))
1009 (push (make-call callee)
1010 (node-edges caller))))))))))
1011 (let ((sorted-nodes (sort (collect-nodes) #'> :key #'node-count)))
1012 (loop for node in sorted-nodes and i from 1 do
1013 (setf (node-index node) i))
1014 (%make-call-graph :nsamples (samples-trace-count *samples*)
1015 :sample-interval (if (eq (samples-mode *samples*)
1016 :alloc)
1017 (samples-alloc-interval *samples*)
1018 (samples-sample-interval *samples*))
1019 :sampling-mode (samples-mode *samples*)
1020 :sampled-threads (samples-sampled-threads *samples*)
1021 :elsewhere-count elsewhere-count
1022 :vertices sorted-nodes)))))
1024 ;;; Reduce CALL-GRAPH to a dag, creating CYCLE structures for call
1025 ;;; cycles.
1026 (defun reduce-call-graph (call-graph)
1027 (let ((cycle-no 0))
1028 (flet ((make-one-cycle (vertices edges)
1029 (let* ((name (format nil "<Cycle ~d>" (incf cycle-no)))
1030 (count (loop for v in vertices sum (node-count v))))
1031 (make-cycle :name name
1032 :index cycle-no
1033 :count count
1034 :scc-vertices vertices
1035 :edges edges))))
1036 (reduce-graph call-graph #'make-one-cycle))))
1038 ;;; For all nodes in CALL-GRAPH, compute times including the time
1039 ;;; spent in functions called from them. Note that the call-graph
1040 ;;; vertices are in reverse topological order, children first, so we
1041 ;;; will have computed accrued counts of called functions before they
1042 ;;; are used to compute accrued counts for callers.
1043 (defun compute-accrued-counts (call-graph)
1044 (do-vertices (from call-graph)
1045 (setf (node-accrued-count from) (node-count from))
1046 (do-edges (call to from)
1047 (incf (node-accrued-count from)
1048 (round (* (/ (call-count call) (node-count to))
1049 (node-accrued-count to)))))))
1051 ;;; Return a CALL-GRAPH structure for the current contents of
1052 ;;; *SAMPLES*. The result contain a list of nodes sorted by self-time
1053 ;;; in the FLAT-NODES slot, and a dag in VERTICES, with call cycles
1054 ;;; reduced to CYCLE structures.
1055 (defun make-call-graph (max-depth)
1056 (stop-profiling)
1057 (show-progress "~&Computing call graph ")
1058 (let ((call-graph (without-gcing (make-call-graph-1 max-depth))))
1059 (setf (call-graph-flat-nodes call-graph)
1060 (copy-list (graph-vertices call-graph)))
1061 (show-progress "~&Finding cycles")
1062 #+nil
1063 (reduce-call-graph call-graph)
1064 (show-progress "~&Propagating counts")
1065 #+nil
1066 (compute-accrued-counts call-graph)
1067 call-graph))
1070 ;;;; Reporting
1072 (defun print-separator (&key (length 72) (char #\-))
1073 (format t "~&~V,,,V<~>~%" length char))
1075 (defun samples-percent (call-graph count)
1076 (if (> count 0)
1077 (* 100.0 (/ count (call-graph-nsamples call-graph)))
1080 (defun print-call-graph-header (call-graph)
1081 (let ((nsamples (call-graph-nsamples call-graph))
1082 (interval (call-graph-sample-interval call-graph))
1083 (ncycles (loop for v in (graph-vertices call-graph)
1084 count (scc-p v))))
1085 (if (eq (call-graph-sampling-mode call-graph) :alloc)
1086 (format t "~2&Number of samples: ~d~%~
1087 Alloc interval: ~a regions (approximately ~a kB)~%~
1088 Total sampling amount: ~a regions (approximately ~a kB)~%~
1089 Number of cycles: ~d~%~
1090 Sampled threads:~{~% ~S~}~2%"
1091 nsamples
1092 interval
1093 (truncate (* interval *alloc-region-size*) 1024)
1094 (* nsamples interval)
1095 (truncate (* nsamples interval *alloc-region-size*) 1024)
1096 ncycles
1097 (call-graph-sampled-threads call-graph))
1098 (format t "~2&Number of samples: ~d~%~
1099 Sample interval: ~f seconds~%~
1100 Total sampling time: ~f seconds~%~
1101 Number of cycles: ~d~%~
1102 Sampled threads:~{~% ~S~}~2%"
1103 nsamples
1104 interval
1105 (* nsamples interval)
1106 ncycles
1107 (call-graph-sampled-threads call-graph)))))
1109 (declaim (type (member :samples :cumulative-samples) *report-sort-by*))
1110 (defvar *report-sort-by* :samples
1111 "Method for sorting the flat report: either by :SAMPLES or by :CUMULATIVE-SAMPLES.")
1113 (declaim (type (member :descending :ascending) *report-sort-order*))
1114 (defvar *report-sort-order* :descending
1115 "Order for sorting the flat report: either :DESCENDING or :ASCENDING.")
1117 (defun print-flat (call-graph &key (stream *standard-output*) max
1118 min-percent (print-header t)
1119 (sort-by *report-sort-by*)
1120 (sort-order *report-sort-order*))
1121 (declare (type (member :descending :ascending) sort-order)
1122 (type (member :samples :cumulative-samples) sort-by))
1123 (let ((*standard-output* stream)
1124 (*print-pretty* nil)
1125 (total-count 0)
1126 (total-percent 0)
1127 (min-count (if min-percent
1128 (round (* (/ min-percent 100.0)
1129 (call-graph-nsamples call-graph)))
1130 0)))
1131 (when print-header
1132 (print-call-graph-header call-graph))
1133 (format t "~& Self Total Cumul~%")
1134 (format t "~& Nr Count % Count % Count % Calls Function~%")
1135 (print-separator)
1136 (let ((elsewhere-count (call-graph-elsewhere-count call-graph))
1137 (i 0)
1138 (nodes (stable-sort (copy-list (call-graph-flat-nodes call-graph))
1139 (let ((cmp (if (eq :descending sort-order) #'> #'<)))
1140 (multiple-value-bind (primary secondary)
1141 (if (eq :samples sort-by)
1142 (values #'node-count #'node-accrued-count)
1143 (values #'node-accrued-count #'node-count))
1144 (lambda (x y)
1145 (let ((cx (funcall primary x))
1146 (cy (funcall primary y)))
1147 (if (= cx cy)
1148 (funcall cmp (funcall secondary x) (funcall secondary y))
1149 (funcall cmp cx cy)))))))))
1150 (dolist (node nodes)
1151 (when (or (and max (> (incf i) max))
1152 (< (node-count node) min-count))
1153 (return))
1154 (let* ((count (node-count node))
1155 (percent (samples-percent call-graph count))
1156 (accrued-count (node-accrued-count node))
1157 (accrued-percent (samples-percent call-graph accrued-count)))
1158 (incf total-count count)
1159 (incf total-percent percent)
1160 (format t "~&~4d ~6d ~5,1f ~6d ~5,1f ~6d ~5,1f ~8@a ~s~%"
1161 (incf i)
1162 count
1163 percent
1164 accrued-count
1165 accrued-percent
1166 total-count
1167 total-percent
1168 (or (node-call-count node) "-")
1169 (node-name node))
1170 (finish-output)))
1171 (print-separator)
1172 (format t "~& ~6d ~5,1f~36a elsewhere~%"
1173 elsewhere-count
1174 (samples-percent call-graph elsewhere-count)
1175 ""))))
1177 (defun print-cycles (call-graph)
1178 (when (some #'cycle-p (graph-vertices call-graph))
1179 (format t "~& Cycle~%")
1180 (format t "~& Count % Parts~%")
1181 (do-vertices (node call-graph)
1182 (when (cycle-p node)
1183 (flet ((print-info (indent index count percent name)
1184 (format t "~&~6d ~5,1f ~11@t ~V@t ~s [~d]~%"
1185 count percent indent name index)))
1186 (print-separator)
1187 (format t "~&~6d ~5,1f ~a...~%"
1188 (node-count node)
1189 (samples-percent call-graph (cycle-count node))
1190 (node-name node))
1191 (dolist (v (vertex-scc-vertices node))
1192 (print-info 4 (node-index v) (node-count v)
1193 (samples-percent call-graph (node-count v))
1194 (node-name v))))))
1195 (print-separator)
1196 (format t "~2%")))
1198 (defun print-graph (call-graph &key (stream *standard-output*)
1199 max min-percent)
1200 (let ((*standard-output* stream)
1201 (*print-pretty* nil))
1202 (print-call-graph-header call-graph)
1203 (print-cycles call-graph)
1204 (flet ((find-call (from to)
1205 (find to (node-edges from) :key #'call-vertex))
1206 (print-info (indent index count percent name)
1207 (format t "~&~6d ~5,1f ~11@t ~V@t ~s [~d]~%"
1208 count percent indent name index)))
1209 (format t "~& Callers~%")
1210 (format t "~& Total. Function~%")
1211 (format t "~& Count % Count % Callees~%")
1212 (do-vertices (node call-graph)
1213 (print-separator)
1215 ;; Print caller information.
1216 (dolist (caller (node-callers node))
1217 (let ((call (find-call caller node)))
1218 (print-info 4 (node-index caller)
1219 (call-count call)
1220 (samples-percent call-graph (call-count call))
1221 (node-name caller))))
1222 ;; Print the node itself.
1223 (format t "~&~6d ~5,1f ~6d ~5,1f ~s [~d]~%"
1224 (node-count node)
1225 (samples-percent call-graph (node-count node))
1226 (node-accrued-count node)
1227 (samples-percent call-graph (node-accrued-count node))
1228 (node-name node)
1229 (node-index node))
1230 ;; Print callees.
1231 (do-edges (call called node)
1232 (print-info 4 (node-index called)
1233 (call-count call)
1234 (samples-percent call-graph (call-count call))
1235 (node-name called))))
1236 (print-separator)
1237 (format t "~2%")
1238 (print-flat call-graph :stream stream :max max
1239 :min-percent min-percent :print-header nil))))
1241 (defun report (&key (type :graph) max min-percent call-graph
1242 ((:sort-by *report-sort-by*) *report-sort-by*)
1243 ((:sort-order *report-sort-order*) *report-sort-order*)
1244 (stream *standard-output*) ((:show-progress *show-progress*)))
1245 "Report statistical profiling results. The following keyword
1246 args are recognized:
1248 :TYPE <type>
1249 Specifies the type of report to generate. If :FLAT, show
1250 flat report, if :GRAPH show a call graph and a flat report.
1251 If nil, don't print out a report.
1253 :STREAM <stream>
1254 Specify a stream to print the report on. Default is
1255 *STANDARD-OUTPUT*.
1257 :MAX <max>
1258 Don't show more than <max> entries in the flat report.
1260 :MIN-PERCENT <min-percent>
1261 Don't show functions taking less than <min-percent> of the
1262 total time in the flat report.
1264 :SORT-BY <column>
1265 If :SAMPLES, sort flat report by number of samples taken.
1266 If :CUMULATIVE-SAMPLES, sort flat report by cumulative number of samples
1267 taken (shows how much time each function spent on stack.) Default
1268 is *REPORT-SORT-BY*.
1270 :SORT-ORDER <order>
1271 If :DESCENDING, sort flat report in descending order. If :ASCENDING,
1272 sort flat report in ascending order. Default is *REPORT-SORT-ORDER*.
1274 :SHOW-PROGRESS <bool>
1275 If true, print progress messages while generating the call graph.
1277 :CALL-GRAPH <graph>
1278 Print a report from <graph> instead of the latest profiling
1279 results.
1281 Value of this function is a CALL-GRAPH object representing the
1282 resulting call-graph, or NIL if there are no samples (eg. right after
1283 calling RESET.)
1285 Profiling is stopped before the call graph is generated."
1286 (cond (*samples*
1287 (let ((graph (or call-graph (make-call-graph most-positive-fixnum))))
1288 (ecase type
1289 (:flat
1290 (print-flat graph :stream stream :max max :min-percent min-percent))
1291 (:graph
1292 (print-graph graph :stream stream :max max :min-percent min-percent))
1293 ((nil)))
1294 graph))
1296 (format stream "~&; No samples to report.~%")
1297 nil)))
1299 ;;; Interface to DISASSEMBLE
1301 (defun sample-pc-from-pc-or-offset (sample pc-or-offset)
1302 (etypecase sample
1303 ;; Assembly routines or foreign functions don't move around, so we've
1304 ;; stored a raw PC
1305 ((or sb-kernel:code-component string)
1306 pc-or-offset)
1307 ;; Lisp functions might move, so we've stored a offset from the
1308 ;; start of the code component.
1309 (sb-di::compiled-debug-fun
1310 (let* ((component (sb-di::compiled-debug-fun-component sample))
1311 (start-pc (code-start component)))
1312 (+ start-pc pc-or-offset)))))
1314 (defun add-disassembly-profile-note (chunk stream dstate)
1315 (declare (ignore chunk stream))
1316 (when *samples*
1317 (let* ((location (+ (sb-disassem::seg-virtual-location
1318 (sb-disassem:dstate-segment dstate))
1319 (sb-disassem::dstate-cur-offs dstate)))
1320 (samples (loop with index = (samples-index *samples*)
1321 for x from 0 below (- index 2) by 2
1322 for last-sample = nil then sample
1323 for sample = (aref (samples-vector *samples*) x)
1324 for pc-or-offset = (aref (samples-vector *samples*)
1325 (1+ x))
1326 when (and sample (eq last-sample 'trace-start))
1327 count (= location
1328 (sample-pc-from-pc-or-offset sample
1329 pc-or-offset)))))
1330 (unless (zerop samples)
1331 (sb-disassem::note (format nil "~A/~A samples"
1332 samples (samples-trace-count *samples*))
1333 dstate)))))
1335 (pushnew 'add-disassembly-profile-note sb-disassem::*default-dstate-hooks*)
1338 ;;;; Call counting
1340 ;;; The following functions tell sb-sprof to do call count profiling
1341 ;;; for the named functions in addition to normal statistical
1342 ;;; profiling. The benefit of this over using SB-PROFILE is that this
1343 ;;; encapsulation is a lot more lightweight, due to not needing to
1344 ;;; track cpu usage / consing. (For example, compiling asdf 20 times
1345 ;;; took 13s normally, 15s with call counting for all functions in
1346 ;;; SB-C, and 94s with SB-PROFILE profiling SB-C).
1348 (defun profile-call-counts (&rest names)
1349 "Mark the functions named by NAMES as being subject to call counting
1350 during statistical profiling. If a string is used as a name, it will
1351 be interpreted as a package name. In this case call counting will be
1352 done for all functions with names like X or (SETF X), where X is a symbol
1353 with the package as its home package."
1354 (dolist (name names)
1355 (if (stringp name)
1356 (let ((package (find-package name)))
1357 (do-symbols (symbol package)
1358 (when (eql (symbol-package symbol) package)
1359 (dolist (function-name (list symbol (list 'setf symbol)))
1360 (profile-call-counts-for-function function-name)))))
1361 (profile-call-counts-for-function name))))
1363 (defun profile-call-counts-for-function (function-name)
1364 (unless (gethash function-name *encapsulations*)
1365 (setf (gethash function-name *encapsulations*) nil)))
1367 (defun unprofile-call-counts ()
1368 "Clear all call counting information. Call counting will be done for no
1369 functions during statistical profiling."
1370 (clrhash *encapsulations*))
1372 ;;; Called when profiling is started to enable the call counting
1373 ;;; encapsulation. Wrap all the call counted functions
1374 (defun enable-call-counting ()
1375 (maphash (lambda (k v)
1376 (declare (ignore v))
1377 (enable-call-counting-for-function k))
1378 *encapsulations*))
1380 ;;; Called when profiling is stopped to disable the encapsulation. Restore
1381 ;;; the original functions.
1382 (defun disable-call-counting ()
1383 (maphash (lambda (k v)
1384 (when v
1385 (assert (cdr v))
1386 (without-package-locks
1387 (setf (fdefinition k) (cdr v)))
1388 (setf (cdr v) nil)))
1389 *encapsulations*))
1391 (defun enable-call-counting-for-function (function-name)
1392 (let ((info (gethash function-name *encapsulations*)))
1393 ;; We should never try to encapsulate an fdefn multiple times.
1394 (assert (or (null info)
1395 (null (cdr info))))
1396 (when (and (fboundp function-name)
1397 (or (not (symbolp function-name))
1398 (and (not (special-operator-p function-name))
1399 (not (macro-function function-name)))))
1400 (let* ((original-fun (fdefinition function-name))
1401 (info (cons 0 original-fun)))
1402 (setf (gethash function-name *encapsulations*) info)
1403 (without-package-locks
1404 (setf (fdefinition function-name)
1405 (sb-int:named-lambda call-counter (sb-int:&more more-context more-count)
1406 (declare (optimize speed (safety 0)))
1407 ;; 2^59 calls should be enough for anybody, and it
1408 ;; allows using fixnum arithmetic on x86-64. 2^32
1409 ;; isn't enough, so we can't do that on 32 bit platforms.
1410 (incf (the (unsigned-byte 59)
1411 (car info)))
1412 (multiple-value-call original-fun
1413 (sb-c:%more-arg-values more-context
1415 more-count)))))))))
1417 (provide 'sb-sprof)