1.0.17.13: grab-bag of SB-SPROF enhancements
[sbcl.git] / contrib / sb-sprof / sb-sprof.lisp
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.
29
30 ;;; Statistical profiler.
31
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.
44
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?
99
100 (defpackage #:sb-sprof
101   (:use #:cl #:sb-ext #:sb-unix #:sb-alien #:sb-sys)
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))
108
109 (in-package #:sb-sprof)
110
111 \f
112 ;;;; Graph Utilities
113
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))
121
122 (defstruct edge
123   (vertex (sb-impl::missing-arg) :type vertex))
124
125 (defstruct graph
126   (vertices () :type list))
127
128 (declaim (inline scc-p))
129 (defun scc-p (vertex)
130   (not (null (vertex-scc-vertices vertex))))
131
132 (defmacro do-vertices ((vertex graph) &body body)
133   `(dolist (,vertex (graph-vertices ,graph))
134      ,@body))
135
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)))
140
141 (defun self-cycle-p (vertex)
142   (do-edges (e to vertex)
143     (when (eq to vertex)
144       (return t))))
145
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))))
152
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))
169                      rx
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)))
198
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))))
213
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))))))
234 \f
235 ;;;; The Profiler
236
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))
241
242 (defconstant +unknown-address+ 0
243   "Constant representing an address that cannot be determined.")
244
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))
262
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)))
291
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)))
295
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))
302
303 (defvar *sample-interval* 0.01
304   "Default number of seconds between samples.")
305 (declaim (type number *sample-interval*))
306
307 (defvar *alloc-interval* 4
308   "Default number of allocation region openings between samples.")
309 (declaim (type number *alloc-interval*))
310
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*))
316
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.
326                          10
327                          ;; Each sample takes two cells in the vector
328                          2))
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))
338
339 (defmethod print-object ((call-graph call-graph) stream)
340   (print-unreadable-object (call-graph stream :type t :identity t)
341     (format stream "~d samples" (call-graph-nsamples call-graph))))
342
343 (defmethod print-object ((node node) stream)
344   (print-unreadable-object (node stream :type t :identity t)
345     (format stream "~s [~d]" (node-name node) (node-index node))))
346
347 (defmethod print-object ((call call) stream)
348   (print-unreadable-object (call stream :type t :identity t)
349     (format stream "~s [~d]" (node-name (call-vertex call))
350             (node-index (call-vertex call)))))
351
352 (deftype report-type ()
353   '(member nil :flat :graph))
354
355 (defvar *sampling-mode* :cpu
356   "Default sampling mode. :CPU for cpu profiling, :ALLOC for allocation
357 profiling")
358 (declaim (type (member :cpu :alloc :time) *sampling-mode*))
359
360 (defvar *alloc-region-size*
361   #-gencgc
362   (get-page-size)
363   ;; This hardcoded 2 matches the one in gc_find_freeish_pages. It's not
364   ;; really worth genesifying.
365   #+gencgc
366   (* 2 sb-vm:gencgc-page-size))
367 (declaim (type number *alloc-region-size*))
368
369 (defvar *samples* nil)
370 (declaim (type (or null samples) *samples*))
371
372 (defvar *profiling* nil)
373 (declaim (type (member nil :alloc :cpu :time) *profiling*))
374 (defvar *sampling* nil)
375 (declaim (type boolean *sampling*))
376
377 (defvar *show-progress* nil)
378
379 (defvar *old-sampling* nil)
380
381 ;; Call count encapsulation information
382 (defvar *encapsulations* (make-hash-table :test 'equal))
383
384 (defun turn-off-sampling ()
385   (setq *old-sampling* *sampling*)
386   (setq *sampling* nil))
387
388 (defun turn-on-sampling ()
389   (setq *sampling* *old-sampling*))
390
391 (defun show-progress (format-string &rest args)
392   (when *show-progress*
393     (apply #'format t format-string args)
394     (finish-output)))
395
396 (defun start-sampling ()
397   "Switch on statistical sampling."
398   (setq *sampling* t))
399
400 (defun stop-sampling ()
401   "Switch off statistical sampling."
402   (setq *sampling* nil))
403
404 (defmacro with-sampling ((&optional (on t)) &body body)
405   "Evaluate body with statistical sampling turned on or off."
406   `(let ((*sampling* ,on)
407          (sb-vm:*alloc-signal* sb-vm:*alloc-signal*))
408      ,@body))
409
410 ;;; Return something serving as debug info for address PC.
411 (declaim (inline debug-info))
412 (defun debug-info (pc)
413   (declare (type system-area-pointer pc)
414            (muffle-conditions compiler-note))
415   (let ((ptr (sb-di::component-ptr-from-pc pc)))
416     (cond ((sap= ptr (int-sap 0))
417            (let ((name (sap-foreign-symbol pc)))
418              (if name
419                  (values (format nil "foreign function ~a" name)
420                          (sap-int pc))
421                  (values nil (sap-int pc)))))
422           (t
423            (let* ((code (sb-di::component-from-component-ptr ptr))
424                   (code-header-len (* (sb-kernel:get-header-data code)
425                                       sb-vm:n-word-bytes))
426                   (pc-offset (- (sap-int pc)
427                                 (- (sb-kernel:get-lisp-obj-address code)
428                                    sb-vm:other-pointer-lowtag)
429                                 code-header-len))
430                   (df (sb-di::debug-fun-from-pc code pc-offset)))
431              (cond ((typep df 'sb-di::bogus-debug-fun)
432                     (values code (sap-int pc)))
433                    (df
434                     ;; The code component might be moved by the GC. Store
435                     ;; a PC offset, and reconstruct the data in
436                     ;; SAMPLE-PC-FROM-PC-OR-OFFSET.
437                     (values df pc-offset))
438                    (t
439                     (values nil 0))))))))
440
441 (defun ensure-samples-vector (samples)
442   (let ((vector (samples-vector samples))
443         (index (samples-index samples)))
444     ;; Allocate a new sample vector if the old one is full
445     (if (= (length vector) index)
446         (let ((new-vector (make-array (* 2 index))))
447           (format *trace-output* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
448                   (samples-trace-count samples)
449                   (truncate index 2))
450           (replace new-vector vector)
451           (setf (samples-vector samples) new-vector))
452         vector)))
453
454 (declaim (inline record))
455 (defun record (samples pc)
456   (declare (type system-area-pointer pc)
457            (muffle-conditions compiler-note))
458   (multiple-value-bind (info pc-or-offset)
459       (debug-info pc)
460     (let ((vector (ensure-samples-vector samples))
461           (index (samples-index samples)))
462       (declare (type simple-vector vector))
463       ;; Allocate a new sample vector if the old one is full
464       (when (= (length vector) index)
465         (let ((new-vector (make-array (* 2 index))))
466           (format *trace-output* "Profiler sample vector full (~a traces / ~a samples), doubling the size~%"
467                   (samples-trace-count samples)
468                   (truncate index 2))
469           (replace new-vector vector)
470           (setf vector new-vector
471                 (samples-vector samples) new-vector)))
472       ;; For each sample, store the debug-info and the PC/offset into
473       ;; adjacent cells.
474       (setf (aref vector index) info
475             (aref vector (1+ index)) pc-or-offset)))
476   (incf (samples-index samples) 2))
477
478 (defun record-trace-start (samples)
479   ;; Mark the start of the trace.
480   (let ((vector (ensure-samples-vector samples)))
481     (declare (type simple-vector vector))
482     (setf (aref vector (samples-index samples))
483           'trace-start))
484   (incf (samples-index samples) 2))
485
486 ;;; List of thread currently profiled, or T for all threads.
487 (defvar *profiled-threads* nil)
488 (declaim (type (or list (member :all)) *profiled-threads*))
489
490 ;;; Thread which runs the wallclock timers, if any.
491 (defvar *timer-thread* nil)
492
493 (defun profiled-threads ()
494   (let ((profiled-threads *profiled-threads*))
495     (if (eq :all profiled-threads)
496         (remove *timer-thread* (sb-thread:list-all-threads))
497         profiled-threads)))
498
499 (defun profiled-thread-p (thread)
500   (let ((profiled-threads *profiled-threads*))
501     (or (and (eq :all profiled-threads)
502              (not (eq *timer-thread* thread)))
503         (member thread profiled-threads :test #'eq))))
504
505 #+(or x86 x86-64)
506 (progn
507   ;; Ensure that only one thread at a time will be doing profiling stuff.
508   (defvar *profiler-lock* (sb-thread:make-mutex :name "Statistical Profiler"))
509   (defvar *distribution-lock* (sb-thread:make-mutex :name "Wallclock profiling lock"))
510
511   (define-alien-routine pthread-kill int (signal int) (os-thread unsigned-long))
512
513   ;;; A random thread will call this in response to either a timer firing,
514   ;;; This in turn will distribute the notice to those threads we are
515   ;;; interested using SIGPROF.
516   (defun thread-distribution-handler ()
517     (declare (optimize sb-c::merge-tail-calls))
518     (when *sampling*
519       #+sb-thread
520       (let ((lock *distribution-lock*))
521         ;; Don't flood the system with more interrupts if the last
522         ;; set is still being delivered.
523         (unless (sb-thread:mutex-value lock)
524           (sb-thread::with-system-mutex (lock)
525             (dolist (thread (profiled-threads))
526               ;; This may occasionally fail to deliver the signal, but that
527               ;; seems better then using kill_thread_safely with it's 1
528               ;; second backoff.
529               (let ((os-thread (sb-thread::thread-os-thread thread)))
530                 (when os-thread
531                   (pthread-kill os-thread sb-unix:sigprof)))))))
532       #-sb-thread
533       (unix-kill 0 sb-unix:sigprof)))
534
535   (defun sigprof-handler (signal code scp)
536     (declare (ignore signal code) (optimize speed (space 0))
537              (disable-package-locks sb-di::x86-call-context)
538              (muffle-conditions compiler-note)
539              (type system-area-pointer scp))
540     (let ((self sb-thread:*current-thread*)
541           (profiling *profiling*))
542       ;; Turn off allocation counter when it is not needed. Doing this in the
543       ;; signal handler means we don't have to worry about racing with the runtime
544       (unless (eq :alloc profiling)
545         (setf sb-vm::*alloc-signal* nil))
546       (when (and *sampling*
547                  ;; Normal SIGPROF gets practically speaking delivered to threads
548                  ;; depending on the run time they use, so we need to filter
549                  ;; out those we don't care about. For :ALLOC and :TIME profiling
550                  ;; only the interesting threads get SIGPROF in the first place.
551                  ;;
552                  ;; ...except that Darwin at least doesn't seem to work like we
553                  ;; would want it to, which makes multithreaded :CPU profiling pretty
554                  ;; pointless there -- though it may be that our mach magic is
555                  ;; partially to blame?
556                  (or (not (eq :cpu profiling)) (profiled-thread-p self)))
557         (sb-thread::with-system-mutex (*profiler-lock* :without-gcing t)
558           (let ((samples *samples*))
559             (when (and samples
560                        (< (samples-trace-count samples)
561                           (samples-max-samples samples)))
562               (with-alien ((scp (* os-context-t) :local scp))
563                 (let* ((pc-ptr (sb-vm:context-pc scp))
564                        (fp (sb-vm::context-register scp #.sb-vm::ebp-offset)))
565                   ;; For some reason completely bogus small values for the
566                   ;; frame pointer are returned every now and then, leading
567                   ;; to segfaults. Try to avoid these cases.
568                   ;;
569                   ;; FIXME: Do a more thorough sanity check on ebp, or figure
570                   ;; out why this is happening.
571                   ;; -- JES, 2005-01-11
572                   (when (< fp 4096)
573                     (return-from sigprof-handler nil))
574                   (incf (samples-trace-count samples))
575                   (pushnew self (samples-sampled-threads samples))
576                   (let ((fp (int-sap fp))
577                         (ok t))
578                     (declare (type system-area-pointer fp pc-ptr))
579                     ;; FIXME: How annoying. The XC doesn't store enough
580                     ;; type information about SB-DI::X86-CALL-CONTEXT,
581                     ;; even if we declaim the ftype explicitly in
582                     ;; src/code/debug-int. And for some reason that type
583                     ;; information is needed for the inlined version to
584                     ;; be compiled without boxing the returned saps. So
585                     ;; we declare the correct ftype here manually, even
586                     ;; if the compiler should be able to deduce this
587                     ;; exact same information.
588                     (declare (ftype (function (system-area-pointer)
589                                               (values (member nil t)
590                                                       system-area-pointer
591                                                       system-area-pointer))
592                                     sb-di::x86-call-context))
593                     (record-trace-start samples)
594                     (dotimes (i (samples-max-depth samples))
595                       (record samples pc-ptr)
596                       (setf (values ok pc-ptr fp)
597                             (sb-di::x86-call-context fp))
598                       (unless ok
599                         (return))))))
600               ;; Reset thread-local allocation counter before interrupts
601               ;; are enabled.
602               (when (eq t sb-vm::*alloc-signal*)
603                 (setf sb-vm:*alloc-signal* (1- (samples-alloc-interval samples)))))))))
604     nil))
605
606 ;; FIXME: On non-x86 platforms we don't yet walk the call stack deeper
607 ;; than one level.
608 #-(or x86 x86-64)
609 (defun sigprof-handler (signal code scp)
610   (declare (ignore signal code))
611   (sb-sys:without-interrupts
612     (let ((samples *samples*))
613       (when (and *sampling*
614                  samples
615                  (< (samples-trace-count samples)
616                     (samples-max-samples samples)))
617         (sb-sys:without-gcing
618           (with-alien ((scp (* os-context-t) :local scp))
619             (locally (declare (optimize (inhibit-warnings 2)))
620               (incf (samples-trace-count samples))
621               (record-trace-start samples)
622               (let* ((pc-ptr (sb-vm:context-pc scp))
623                      (fp (sb-vm::context-register scp #.sb-vm::cfp-offset))
624                      (ra (sap-ref-word
625                           (int-sap fp)
626                           (* sb-vm::lra-save-offset sb-vm::n-word-bytes))))
627                 (record samples pc-ptr)
628                 (record samples (int-sap ra))))))))))
629
630 ;;; Return the start address of CODE.
631 (defun code-start (code)
632   (declare (type sb-kernel:code-component code))
633   (sap-int (sb-kernel:code-instructions code)))
634
635 ;;; Return start and end address of CODE as multiple values.
636 (defun code-bounds (code)
637   (declare (type sb-kernel:code-component code))
638   (let* ((start (code-start code))
639          (end (+ start (sb-kernel:%code-code-size code))))
640     (values start end)))
641
642 (defmacro with-profiling ((&key (sample-interval '*sample-interval*)
643                                 (alloc-interval '*alloc-interval*)
644                                 (max-samples '*max-samples*)
645                                 (reset nil)
646                                 (mode '*sampling-mode*)
647                                 (loop t)
648                                 (max-depth most-positive-fixnum)
649                                 show-progress
650                                 (threads '(list sb-thread:*current-thread*))
651                                 (report nil report-p))
652                           &body body)
653   "Repeatedly evaluate BODY with statistical profiling turned on.
654    In multi-threaded operation, only the thread in which WITH-PROFILING
655    was evaluated will be profiled by default. If you want to profile
656    multiple threads, invoke the profiler with START-PROFILING.
657
658    The following keyword args are recognized:
659
660    :SAMPLE-INTERVAL <n>
661      Take a sample every <n> seconds. Default is *SAMPLE-INTERVAL*.
662
663    :ALLOC-INTERVAL <n>
664      Take a sample every time <n> allocation regions (approximately
665      8kB) have been allocated since the last sample. Default is
666      *ALLOC-INTERVAL*.
667
668    :MODE <mode>
669      If :CPU, run the profiler in CPU profiling mode. If :ALLOC, run the
670      profiler in allocation profiling mode. If :TIME, run the profiler
671      in wallclock profiling mode.
672
673    :MAX-SAMPLES <max>
674      Repeat evaluating body until <max> samples are taken.
675      Default is *MAX-SAMPLES*.
676
677    :MAX-DEPTH <max>
678      Maximum call stack depth that the profiler should consider. Only
679      has an effect on x86 and x86-64.
680
681    :REPORT <type>
682      If specified, call REPORT with :TYPE <type> at the end.
683
684    :RESET <bool>
685      It true, call RESET at the beginning.
686
687    :THREADS <list-form>
688      Form that evaluates to the list threads to profile, or :ALL to indicate
689      that all threads should be profiled. Defaults to the current
690      thread. (Note: START-PROFILING defaults to all threads.)
691
692      :THREADS has no effect on call-counting at the moment.
693
694      On some platforms (eg. Darwin) the signals used by the profiler are
695      not properly delivered to threads in proportion to their CPU usage
696      when doing :CPU profiling. If you see empty call graphs, or are obviously
697      missing several samples from certain threads, you may be falling afoul
698      of this.
699
700    :LOOP <bool>
701      If true (the default) repeatedly evaluate BODY. If false, evaluate
702      if only once."
703   (declare (type report-type report))
704   `(let* ((*sample-interval* ,sample-interval)
705           (*alloc-interval* ,alloc-interval)
706           (*sampling* nil)
707           (*sampling-mode* ,mode)
708           (*max-samples* ,max-samples))
709      ,@(when reset '((reset)))
710      (unwind-protect
711           (progn
712             (start-profiling :max-depth ,max-depth :threads ,threads)
713             (loop
714                (when (>= (samples-trace-count *samples*)
715                          (samples-max-samples *samples*))
716                  (return))
717                ,@(when show-progress
718                        `((format t "~&===> ~d of ~d samples taken.~%"
719                                  (samples-trace-count *samples*)
720                                  (samples-max-samples *samples*))))
721                (let ((.last-index. (samples-index *samples*)))
722                  ,@body
723                  (when (= .last-index. (samples-index *samples*))
724                    (warn "No sampling progress; possibly a profiler bug.")
725                    (return)))
726                (unless ,loop
727                  (return))))
728        (stop-profiling))
729      ,@(when report-p `((report :type ,report)))))
730
731 (defvar *timer* nil)
732
733 (defvar *old-alloc-interval* nil)
734 (defvar *old-sample-interval* nil)
735
736 (defun start-profiling (&key (max-samples *max-samples*)
737                         (mode *sampling-mode*)
738                         (sample-interval *sample-interval*)
739                         (alloc-interval *alloc-interval*)
740                         (max-depth most-positive-fixnum)
741                         (threads :all)
742                         (sampling t))
743   "Start profiling statistically in the current thread if not already profiling.
744 The following keyword args are recognized:
745
746    :SAMPLE-INTERVAL <n>
747      Take a sample every <n> seconds.  Default is *SAMPLE-INTERVAL*.
748
749    :ALLOC-INTERVAL <n>
750      Take a sample every time <n> allocation regions (approximately
751      8kB) have been allocated since the last sample. Default is
752      *ALLOC-INTERVAL*.
753
754    :MODE <mode>
755      If :CPU, run the profiler in CPU profiling mode. If :ALLOC, run
756      the profiler in allocation profiling mode. If :TIME, run the profiler
757      in wallclock profiling mode.
758
759    :MAX-SAMPLES <max>
760      Maximum number of samples.  Default is *MAX-SAMPLES*.
761
762    :MAX-DEPTH <max>
763      Maximum call stack depth that the profiler should consider. Only
764      has an effect on x86 and x86-64.
765
766    :THREADS <list>
767      List threads to profile, or :ALL to indicate that all threads should be
768      profiled. Defaults to :ALL. (Note: WITH-PROFILING defaults to the current
769      thread.)
770
771      :THREADS has no effect on call-counting at the moment.
772
773      On some platforms (eg. Darwin) the signals used by the profiler are
774      not properly delivered to threads in proportion to their CPU usage
775      when doing :CPU profiling. If you see empty call graphs, or are obviously
776      missing several samples from certain threads, you may be falling afoul
777      of this.
778
779    :SAMPLING <bool>
780      If true, the default, start sampling right away.
781      If false, START-SAMPLING can be used to turn sampling on."
782   #-gencgc
783   (when (eq mode :alloc)
784     (error "Allocation profiling is only supported for builds using the generational garbage collector."))
785   (unless *profiling*
786     (multiple-value-bind (secs usecs)
787         (multiple-value-bind (secs rest)
788             (truncate sample-interval)
789           (values secs (truncate (* rest 1000000))))
790       (setf *sampling* sampling
791             *samples* (make-samples :max-depth max-depth
792                                     :max-samples max-samples
793                                     :sample-interval sample-interval
794                                     :alloc-interval alloc-interval
795                                     :mode mode))
796       (enable-call-counting)
797       (setf *profiled-threads* threads)
798       (sb-sys:enable-interrupt sb-unix:sigprof #'sigprof-handler)
799       (ecase mode
800         (:alloc
801          (let ((alloc-signal (1- alloc-interval)))
802            #+sb-thread
803            (progn
804              (when (eq t threads)
805                ;; Set the value new threads inherit.
806                (sb-thread::with-all-threads-lock
807                  (setf sb-thread::*default-alloc-signal* alloc-signal)))
808              ;; Turn on allocation profiling in existing threads.
809              (dolist (thread (profiled-threads))
810                (sb-thread::%set-symbol-value-in-thread 'sb-vm::*alloc-signal* thread alloc-signal)))
811            #-sb-thread
812            (setf sb-vm:*alloc-signal* alloc-signal)))
813         (:cpu
814          (unix-setitimer :profile secs usecs secs usecs))
815         (:time
816          #+sb-thread
817          (let ((setup (sb-thread:make-semaphore :name "Timer thread setup semaphore")))
818            (setf *timer-thread*
819                  (sb-thread:make-thread (lambda ()
820                                           (sb-thread:wait-on-semaphore setup)
821                                           (loop while (eq sb-thread:*current-thread* *timer-thread*)
822                                                 do (sleep 1.0)))
823                                         :name "SB-SPROF wallclock timer thread"))
824            (sb-thread:signal-semaphore setup))
825          #-sb-thread
826          (setf *timer-thread* nil)
827          (setf *timer* (make-timer #'thread-distribution-handler :name "SB-PROF wallclock timer"
828                                    :thread *timer-thread*))
829          (schedule-timer *timer* sample-interval :repeat-interval sample-interval)))
830       (setq *profiling* mode)))
831   (values))
832
833 (defun stop-profiling ()
834   "Stop profiling if profiling."
835   (let ((profiling *profiling*))
836     (when profiling
837       ;; Even with the timers shut down we cannot be sure that there is no
838       ;; undelivered sigprof. The handler is also responsible for turning the
839       ;; *ALLOC-SIGNAL* off in individual threads.
840       (ecase profiling
841         (:alloc
842          #+sb-thread
843          (setf sb-thread::*default-alloc-signal* nil)
844          #-sb-thread
845          (setf sb-vm:*alloc-signal* nil))
846         (:cpu
847          (unix-setitimer :profile 0 0 0 0))
848         (:time
849          (unschedule-timer *timer*)
850          (setf *timer* nil
851                *timer-thread* nil)))
852      (disable-call-counting)
853      (setf *profiling* nil
854            *sampling* nil
855            *profiled-threads* nil)))
856   (values))
857
858 (defun reset ()
859   "Reset the profiler."
860   (stop-profiling)
861   (setq *sampling* nil)
862   (setq *samples* nil)
863   (values))
864
865 ;;; Make a NODE for debug-info INFO.
866 (defun make-node (info)
867   (flet ((clean-name (name)
868            (if (and (consp name)
869                     (member (first name)
870                             '(sb-c::xep sb-c::tl-xep sb-c::&more-processor
871                               sb-c::varargs-entry
872                               sb-c::top-level-form
873                               sb-c::hairy-arg-processor
874                               sb-c::&optional-processor)))
875                (second name)
876                name)))
877     (typecase info
878       (sb-kernel::code-component
879        (multiple-value-bind (start end)
880            (code-bounds info)
881          (values
882           (%make-node :name (or (sb-disassem::find-assembler-routine start)
883                                 (format nil "~a" info))
884                       :debug-info info
885                       :start-pc-or-offset start
886                       :end-pc-or-offset end)
887           info)))
888       (sb-di::compiled-debug-fun
889        (let* ((name (sb-di::debug-fun-name info))
890               (cdf (sb-di::compiled-debug-fun-compiler-debug-fun info))
891               (start-offset (sb-c::compiled-debug-fun-start-pc cdf))
892               (end-offset (sb-c::compiled-debug-fun-elsewhere-pc cdf))
893               (component (sb-di::compiled-debug-fun-component info))
894               (start-pc (code-start component)))
895          ;; Call graphs are mostly useless unless we somehow
896          ;; distinguish a gazillion different (LAMBDA ())'s.
897          (when (equal name '(lambda ()))
898            (setf name (format nil "Unknown component: #x~x" start-pc)))
899          (values (%make-node :name (clean-name name)
900                              :debug-info info
901                              :start-pc-or-offset start-offset
902                              :end-pc-or-offset end-offset)
903                  component)))
904       (sb-di::debug-fun
905        (%make-node :name (clean-name (sb-di::debug-fun-name info))
906                    :debug-info info))
907       (t
908        (%make-node :name (coerce info 'string)
909                    :debug-info info)))))
910
911 ;;; One function can have more than one COMPILED-DEBUG-FUNCTION with
912 ;;; the same name.  Reduce the number of calls to Debug-Info by first
913 ;;; looking for a given PC in a red-black tree.  If not found in the
914 ;;; tree, get debug info, and look for a node in a hash-table by
915 ;;; function name.  If not found in the hash-table, make a new node.
916
917 (defvar *name->node*)
918
919 (defmacro with-lookup-tables (() &body body)
920   `(let ((*name->node* (make-hash-table :test 'equal)))
921      ,@body))
922
923 ;;; Find or make a new node for INFO.  Value is the NODE found or
924 ;;; made; NIL if not enough information exists to make a NODE for INFO.
925 (defun lookup-node (info)
926   (when info
927     (multiple-value-bind (new key)
928         (make-node info)
929       (when (eql (node-name new) 'call-counter)
930         (return-from lookup-node (values nil nil)))
931       (let* ((key (cons (node-name new) key))
932              (found (gethash key *name->node*)))
933         (cond (found
934                (setf (node-start-pc-or-offset found)
935                      (min (node-start-pc-or-offset found)
936                           (node-start-pc-or-offset new)))
937                (setf (node-end-pc-or-offset found)
938                      (max (node-end-pc-or-offset found)
939                           (node-end-pc-or-offset new)))
940                found)
941               (t
942                (let ((call-count-info (gethash (node-name new)
943                                                *encapsulations*)))
944                  (when call-count-info
945                    (setf (node-call-count new)
946                          (car call-count-info))))
947                (setf (gethash key *name->node*) new)
948                new))))))
949
950 ;;; Return a list of all nodes created by LOOKUP-NODE.
951 (defun collect-nodes ()
952   (loop for node being the hash-values of *name->node*
953         collect node))
954
955 ;;; Value is a CALL-GRAPH for the current contents of *SAMPLES*.
956 (defun make-call-graph-1 (max-depth)
957   (let ((elsewhere-count 0)
958         visited-nodes)
959     (with-lookup-tables ()
960       (loop for i below (- (samples-index *samples*) 2) by 2
961             with depth = 0
962             for debug-info = (aref (samples-vector *samples*) i)
963             for next-info = (aref (samples-vector *samples*)
964                                   (+ i 2))
965             do (if (eq debug-info 'trace-start)
966                    (setf depth 0)
967                    (let ((callee (lookup-node debug-info))
968                          (caller (unless (eq next-info 'trace-start)
969                                    (lookup-node next-info))))
970                      (when (< depth max-depth)
971                        (when (zerop depth)
972                          (setf visited-nodes nil)
973                          (cond (callee
974                                 (incf (node-accrued-count callee))
975                                 (incf (node-count callee)))
976                                (t
977                                 (incf elsewhere-count))))
978                        (incf depth)
979                        (when callee
980                          (push callee visited-nodes))
981                        (when caller
982                          (unless (member caller visited-nodes)
983                            (incf (node-accrued-count caller)))
984                          (when callee
985                            (let ((call (find callee (node-edges caller)
986                                              :key #'call-vertex)))
987                              (pushnew caller (node-callers callee))
988                              (if call
989                                  (unless (member caller visited-nodes)
990                                    (incf (call-count call)))
991                                  (push (make-call callee)
992                                        (node-edges caller))))))))))
993       (let ((sorted-nodes (sort (collect-nodes) #'> :key #'node-count)))
994         (loop for node in sorted-nodes and i from 1 do
995               (setf (node-index node) i))
996         (%make-call-graph :nsamples (samples-trace-count *samples*)
997                           :sample-interval (if (eq (samples-mode *samples*)
998                                                    :alloc)
999                                                (samples-alloc-interval *samples*)
1000                                                (samples-sample-interval *samples*))
1001                           :sampling-mode (samples-mode *samples*)
1002                           :sampled-threads (samples-sampled-threads *samples*)
1003                           :elsewhere-count elsewhere-count
1004                           :vertices sorted-nodes)))))
1005
1006 ;;; Reduce CALL-GRAPH to a dag, creating CYCLE structures for call
1007 ;;; cycles.
1008 (defun reduce-call-graph (call-graph)
1009   (let ((cycle-no 0))
1010     (flet ((make-one-cycle (vertices edges)
1011              (let* ((name (format nil "<Cycle ~d>" (incf cycle-no)))
1012                     (count (loop for v in vertices sum (node-count v))))
1013                (make-cycle :name name
1014                            :index cycle-no
1015                            :count count
1016                            :scc-vertices vertices
1017                            :edges edges))))
1018       (reduce-graph call-graph #'make-one-cycle))))
1019
1020 ;;; For all nodes in CALL-GRAPH, compute times including the time
1021 ;;; spent in functions called from them.  Note that the call-graph
1022 ;;; vertices are in reverse topological order, children first, so we
1023 ;;; will have computed accrued counts of called functions before they
1024 ;;; are used to compute accrued counts for callers.
1025 (defun compute-accrued-counts (call-graph)
1026   (do-vertices (from call-graph)
1027     (setf (node-accrued-count from) (node-count from))
1028     (do-edges (call to from)
1029       (incf (node-accrued-count from)
1030             (round (* (/ (call-count call) (node-count to))
1031                       (node-accrued-count to)))))))
1032
1033 ;;; Return a CALL-GRAPH structure for the current contents of
1034 ;;; *SAMPLES*.  The result contain a list of nodes sorted by self-time
1035 ;;; in the FLAT-NODES slot, and a dag in VERTICES, with call cycles
1036 ;;; reduced to CYCLE structures.
1037 (defun make-call-graph (max-depth)
1038   (stop-profiling)
1039   (show-progress "~&Computing call graph ")
1040   (let ((call-graph (without-gcing (make-call-graph-1 max-depth))))
1041     (setf (call-graph-flat-nodes call-graph)
1042           (copy-list (graph-vertices call-graph)))
1043     (show-progress "~&Finding cycles")
1044     #+nil
1045     (reduce-call-graph call-graph)
1046     (show-progress "~&Propagating counts")
1047     #+nil
1048     (compute-accrued-counts call-graph)
1049     call-graph))
1050
1051 \f
1052 ;;;; Reporting
1053
1054 (defun print-separator (&key (length 72) (char #\-))
1055   (format t "~&~V,,,V<~>~%" length char))
1056
1057 (defun samples-percent (call-graph count)
1058   (if (> count 0)
1059       (* 100.0 (/ count (call-graph-nsamples call-graph)))
1060       0))
1061
1062 (defun print-call-graph-header (call-graph)
1063   (let ((nsamples (call-graph-nsamples call-graph))
1064         (interval (call-graph-sample-interval call-graph))
1065         (ncycles (loop for v in (graph-vertices call-graph)
1066                        count (scc-p v))))
1067     (if (eq (call-graph-sampling-mode call-graph) :alloc)
1068         (format t "~2&Number of samples:     ~d~%~
1069                       Alloc interval:        ~a regions (approximately ~a kB)~%~
1070                       Total sampling amount: ~a regions (approximately ~a kB)~%~
1071                       Number of cycles:      ~d~%~
1072                       Sampled threads:~{~%   ~S~}~2%"
1073                 nsamples
1074                 interval
1075                 (truncate (* interval *alloc-region-size*) 1024)
1076                 (* nsamples interval)
1077                 (truncate (* nsamples interval *alloc-region-size*) 1024)
1078                 ncycles
1079                 (call-graph-sampled-threads call-graph))
1080         (format t "~2&Number of samples:   ~d~%~
1081                       Sample interval:     ~f seconds~%~
1082                       Total sampling time: ~f seconds~%~
1083                       Number of cycles:    ~d~%~
1084                       Sampled threads:~{~% ~S~}~2%"
1085                 nsamples
1086                 interval
1087                 (* nsamples interval)
1088                 ncycles
1089                 (call-graph-sampled-threads call-graph)))))
1090
1091 (declaim (type (member :samples :cumulative-samples) *report-sort-by*))
1092 (defvar *report-sort-by* :samples
1093   "Method for sorting the flat report: either by :SAMPLES or by :CUMULATIVE-SAMPLES.")
1094
1095 (declaim (type (member :descending :ascending) *report-sort-order*))
1096 (defvar *report-sort-order* :descending
1097   "Order for sorting the flat report: either :DESCENDING or :ASCENDING.")
1098
1099 (defun print-flat (call-graph &key (stream *standard-output*) max
1100                    min-percent (print-header t)
1101                    (sort-by *report-sort-by*)
1102                    (sort-order *report-sort-order*))
1103   (declare (type (member :descending :ascending) sort-order)
1104            (type (member :samples :cumulative-samples) sort-by))
1105   (let ((*standard-output* stream)
1106         (*print-pretty* nil)
1107         (total-count 0)
1108         (total-percent 0)
1109         (min-count (if min-percent
1110                        (round (* (/ min-percent 100.0)
1111                                  (call-graph-nsamples call-graph)))
1112                        0)))
1113     (when print-header
1114       (print-call-graph-header call-graph))
1115     (format t "~&           Self        Total        Cumul~%")
1116     (format t "~&  Nr  Count     %  Count     %  Count     %    Calls  Function~%")
1117     (print-separator)
1118     (let ((elsewhere-count (call-graph-elsewhere-count call-graph))
1119           (i 0)
1120           (nodes (stable-sort (copy-list (call-graph-flat-nodes call-graph))
1121                               (let ((cmp (if (eq :descending sort-order) #'> #'<)))
1122                                 (multiple-value-bind (primary secondary)
1123                                     (if (eq :samples sort-by)
1124                                         (values #'node-count #'node-accrued-count)
1125                                         (values #'node-accrued-count #'node-count))
1126                                   (lambda (x y)
1127                                     (let ((cx (funcall primary x))
1128                                           (cy (funcall primary y)))
1129                                       (if (= cx cy)
1130                                           (funcall cmp (funcall secondary x) (funcall secondary y))
1131                                           (funcall cmp cx cy)))))))))
1132       (dolist (node nodes)
1133         (when (or (and max (> (incf i) max))
1134                   (< (node-count node) min-count))
1135           (return))
1136         (let* ((count (node-count node))
1137                (percent (samples-percent call-graph count))
1138                (accrued-count (node-accrued-count node))
1139                (accrued-percent (samples-percent call-graph accrued-count)))
1140           (incf total-count count)
1141           (incf total-percent percent)
1142           (format t "~&~4d ~6d ~5,1f ~6d ~5,1f ~6d ~5,1f ~8@a  ~s~%"
1143                   (incf i)
1144                   count
1145                   percent
1146                   accrued-count
1147                   accrued-percent
1148                   total-count
1149                   total-percent
1150                   (or (node-call-count node) "-")
1151                   (node-name node))
1152           (finish-output)))
1153       (print-separator)
1154       (format t "~&     ~6d ~5,1f~36a elsewhere~%"
1155               elsewhere-count
1156               (samples-percent call-graph elsewhere-count)
1157               ""))))
1158
1159 (defun print-cycles (call-graph)
1160   (when (some #'cycle-p (graph-vertices call-graph))
1161     (format t "~&                            Cycle~%")
1162     (format t "~& Count     %                   Parts~%")
1163     (do-vertices (node call-graph)
1164       (when (cycle-p node)
1165         (flet ((print-info (indent index count percent name)
1166                  (format t "~&~6d ~5,1f ~11@t ~V@t  ~s [~d]~%"
1167                          count percent indent name index)))
1168           (print-separator)
1169           (format t "~&~6d ~5,1f                ~a...~%"
1170                   (node-count node)
1171                   (samples-percent call-graph (cycle-count node))
1172                   (node-name node))
1173           (dolist (v (vertex-scc-vertices node))
1174             (print-info 4 (node-index v) (node-count v)
1175                         (samples-percent call-graph (node-count v))
1176                         (node-name v))))))
1177     (print-separator)
1178     (format t "~2%")))
1179
1180 (defun print-graph (call-graph &key (stream *standard-output*)
1181                     max min-percent)
1182   (let ((*standard-output* stream)
1183         (*print-pretty* nil))
1184     (print-call-graph-header call-graph)
1185     (print-cycles call-graph)
1186     (flet ((find-call (from to)
1187              (find to (node-edges from) :key #'call-vertex))
1188            (print-info (indent index count percent name)
1189              (format t "~&~6d ~5,1f ~11@t ~V@t  ~s [~d]~%"
1190                      count percent indent name index)))
1191       (format t "~&                               Callers~%")
1192       (format t "~&                 Total.     Function~%")
1193       (format t "~& Count     %  Count     %      Callees~%")
1194       (do-vertices (node call-graph)
1195         (print-separator)
1196         ;;
1197         ;; Print caller information.
1198         (dolist (caller (node-callers node))
1199           (let ((call (find-call caller node)))
1200             (print-info 4 (node-index caller)
1201                         (call-count call)
1202                         (samples-percent call-graph (call-count call))
1203                         (node-name caller))))
1204         ;; Print the node itself.
1205         (format t "~&~6d ~5,1f ~6d ~5,1f   ~s [~d]~%"
1206                 (node-count node)
1207                 (samples-percent call-graph (node-count node))
1208                 (node-accrued-count node)
1209                 (samples-percent call-graph (node-accrued-count node))
1210                 (node-name node)
1211                 (node-index node))
1212         ;; Print callees.
1213         (do-edges (call called node)
1214           (print-info 4 (node-index called)
1215                       (call-count call)
1216                       (samples-percent call-graph (call-count call))
1217                       (node-name called))))
1218       (print-separator)
1219       (format t "~2%")
1220       (print-flat call-graph :stream stream :max max
1221                   :min-percent min-percent :print-header nil))))
1222
1223 (defun report (&key (type :graph) max min-percent call-graph
1224                ((:sort-by *report-sort-by*) *report-sort-by*)
1225                ((:sort-order *report-sort-order*) *report-sort-order*)
1226                (stream *standard-output*) ((:show-progress *show-progress*)))
1227   "Report statistical profiling results.  The following keyword
1228    args are recognized:
1229
1230    :TYPE <type>
1231       Specifies the type of report to generate.  If :FLAT, show
1232       flat report, if :GRAPH show a call graph and a flat report.
1233       If nil, don't print out a report.
1234
1235    :STREAM <stream>
1236       Specify a stream to print the report on.  Default is
1237       *STANDARD-OUTPUT*.
1238
1239    :MAX <max>
1240       Don't show more than <max> entries in the flat report.
1241
1242    :MIN-PERCENT <min-percent>
1243       Don't show functions taking less than <min-percent> of the
1244       total time in the flat report.
1245
1246    :SORT-BY <column>
1247       If :SAMPLES, sort flat report by number of samples taken.
1248       If :CUMULATIVE-SAMPLES, sort flat report by cumulative number of samples
1249       taken (shows how much time each function spent on stack.) Default
1250       is *REPORT-SORT-BY*.
1251
1252    :SORT-ORDER <order>
1253       If :DESCENDING, sort flat report in descending order. If :ASCENDING,
1254       sort flat report in ascending order. Default is *REPORT-SORT-ORDER*.
1255
1256    :SHOW-PROGRESS <bool>
1257      If true, print progress messages while generating the call graph.
1258
1259    :CALL-GRAPH <graph>
1260      Print a report from <graph> instead of the latest profiling
1261      results.
1262
1263 Value of this function is a CALL-GRAPH object representing the
1264 resulting call-graph, or NIL if there are no samples (eg. right after
1265 calling RESET.)"
1266   (cond (*samples*
1267          (let ((graph (or call-graph (make-call-graph most-positive-fixnum))))
1268            (ecase type
1269              (:flat
1270               (print-flat graph :stream stream :max max :min-percent min-percent))
1271              (:graph
1272               (print-graph graph :stream stream :max max :min-percent min-percent))
1273              ((nil)))
1274            graph))
1275         (t
1276          (format stream "~&; No samples to report.~%")
1277          nil)))
1278
1279 ;;; Interface to DISASSEMBLE
1280
1281 (defun sample-pc-from-pc-or-offset (sample pc-or-offset)
1282   (etypecase sample
1283     ;; Assembly routines or foreign functions don't move around, so we've
1284     ;; stored a raw PC
1285     ((or sb-kernel:code-component string)
1286      pc-or-offset)
1287     ;; Lisp functions might move, so we've stored a offset from the
1288     ;; start of the code component.
1289     (sb-di::compiled-debug-fun
1290      (let* ((component (sb-di::compiled-debug-fun-component sample))
1291             (start-pc (code-start component)))
1292        (+ start-pc pc-or-offset)))))
1293
1294 (defun add-disassembly-profile-note (chunk stream dstate)
1295   (declare (ignore chunk stream))
1296   (when *samples*
1297     (let* ((location (+ (sb-disassem::seg-virtual-location
1298                          (sb-disassem:dstate-segment dstate))
1299                         (sb-disassem::dstate-cur-offs dstate)))
1300            (samples (loop with index = (samples-index *samples*)
1301                           for x from 0 below (- index 2) by 2
1302                           for last-sample = nil then sample
1303                           for sample = (aref (samples-vector *samples*) x)
1304                           for pc-or-offset = (aref (samples-vector *samples*)
1305                                                    (1+ x))
1306                           when (and sample (eq last-sample 'trace-start))
1307                           count (= location
1308                                    (sample-pc-from-pc-or-offset sample
1309                                                                 pc-or-offset)))))
1310       (unless (zerop samples)
1311         (sb-disassem::note (format nil "~A/~A samples"
1312                                    samples (samples-trace-count *samples*))
1313                            dstate)))))
1314
1315 (pushnew 'add-disassembly-profile-note sb-disassem::*default-dstate-hooks*)
1316
1317 \f
1318 ;;;; Call counting
1319
1320 ;;; The following functions tell sb-sprof to do call count profiling
1321 ;;; for the named functions in addition to normal statistical
1322 ;;; profiling.  The benefit of this over using SB-PROFILE is that this
1323 ;;; encapsulation is a lot more lightweight, due to not needing to
1324 ;;; track cpu usage / consing. (For example, compiling asdf 20 times
1325 ;;; took 13s normally, 15s with call counting for all functions in
1326 ;;; SB-C, and 94s with SB-PROFILE profiling SB-C).
1327
1328 (defun profile-call-counts (&rest names)
1329   "Mark the functions named by NAMES as being subject to call counting
1330 during statistical profiling. If a string is used as a name, it will
1331 be interpreted as a package name. In this case call counting will be
1332 done for all functions with names like X or (SETF X), where X is a symbol
1333 with the package as its home package."
1334   (dolist (name names)
1335     (if (stringp name)
1336         (let ((package (find-package name)))
1337           (do-symbols (symbol package)
1338             (when (eql (symbol-package symbol) package)
1339               (dolist (function-name (list symbol (list 'setf symbol)))
1340                 (profile-call-counts-for-function function-name)))))
1341         (profile-call-counts-for-function name))))
1342
1343 (defun profile-call-counts-for-function (function-name)
1344   (unless (gethash function-name *encapsulations*)
1345     (setf (gethash function-name *encapsulations*) nil)))
1346
1347 (defun unprofile-call-counts ()
1348   "Clear all call counting information. Call counting will be done for no
1349 functions during statistical profiling."
1350   (clrhash *encapsulations*))
1351
1352 ;;; Called when profiling is started to enable the call counting
1353 ;;; encapsulation. Wrap all the call counted functions
1354 (defun enable-call-counting ()
1355   (maphash (lambda (k v)
1356              (declare (ignore v))
1357              (enable-call-counting-for-function k))
1358            *encapsulations*))
1359
1360 ;;; Called when profiling is stopped to disable the encapsulation. Restore
1361 ;;; the original functions.
1362 (defun disable-call-counting ()
1363   (maphash (lambda (k v)
1364              (when v
1365                (assert (cdr v))
1366                (without-package-locks
1367                  (setf (fdefinition k) (cdr v)))
1368                (setf (cdr v) nil)))
1369            *encapsulations*))
1370
1371 (defun enable-call-counting-for-function (function-name)
1372   (let ((info (gethash function-name *encapsulations*)))
1373     ;; We should never try to encapsulate an fdefn multiple times.
1374     (assert (or (null info)
1375                 (null (cdr info))))
1376     (when (and (fboundp function-name)
1377                (or (not (symbolp function-name))
1378                    (and (not (special-operator-p function-name))
1379                         (not (macro-function function-name)))))
1380       (let* ((original-fun (fdefinition function-name))
1381              (info (cons 0 original-fun)))
1382         (setf (gethash function-name *encapsulations*) info)
1383         (without-package-locks
1384           (setf (fdefinition function-name)
1385                 (sb-int:named-lambda call-counter (sb-int:&more more-context more-count)
1386                   (declare (optimize speed (safety 0)))
1387                   ;; 2^59 calls should be enough for anybody, and it
1388                   ;; allows using fixnum arithmetic on x86-64. 2^32
1389                   ;; isn't enough, so we can't do that on 32 bit platforms.
1390                   (incf (the (unsigned-byte 59)
1391                           (car info)))
1392                   (multiple-value-call original-fun
1393                     (sb-c:%more-arg-values more-context
1394                                            0
1395                                            more-count)))))))))
1396
1397 \f
1398 ;;; silly examples
1399
1400 (defun test-0 (n &optional (depth 0))
1401   (declare (optimize (debug 3)))
1402   (when (< depth n)
1403     (dotimes (i n)
1404       (test-0 n (1+ depth))
1405       (test-0 n (1+ depth)))))
1406
1407 (defun test ()
1408   (with-profiling (:reset t :max-samples 1000 :report :graph)
1409     (test-0 7)))
1410
1411
1412 ;;; provision
1413 (provide 'sb-sprof)
1414
1415 ;;; end of file