1 ! Copyright (C) 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license
3 USING: accessors compiler.tree.builder compiler.cfg compiler.cfg.rpo
4 compiler.cfg.dominance compiler.cfg.dominance.private
5 compiler.cfg.predecessors compiler.cfg.debugger compiler.cfg.optimizer
6 compiler.cfg.utilities compiler.tree.recursive images.viewer
7 images.png io io.encodings.ascii io.files io.files.unique io.launcher
8 kernel math.parser sequences assocs arrays make math namespaces
9 quotations combinators locals words ;
12 : quotes ( str -- str' ) "\"" "\"" surround ;
14 : graph, ( quot title -- )
16 quotes "digraph " " {" surround ,
21 : render-graph ( quot -- )
23 "cfg" ".dot" make-unique-file
24 dup "Wrote " prepend print
25 [ [ concat ] dip ascii set-file-lines ]
26 [ { "dot" "-Tpng" "-O" } swap suffix try-process ]
27 [ ".png" append "open" swap 2array try-process ]
30 : attrs>string ( seq -- str )
31 [ "" ] [ "," join "[" "]" surround ] if-empty ;
33 : edge,* ( from to attrs -- )
35 [ quotes % " -> " % ] [ quotes % " " % ] [ attrs>string % ] tri*
39 : edge, ( from to -- )
42 : bb-edge, ( from to -- )
43 [ number>> number>string ] bi@ edge, ;
45 : node-style, ( str attrs -- )
46 [ [ quotes % " " % ] [ attrs>string % ";" % ] bi* ] "" make , ;
48 : cfg-title ( cfg/mr -- string )
51 [ word>> name>> % ", label: " % ]
56 : cfg-vertex, ( bb -- )
57 [ number>> number>string ]
58 [ kill-block? { "color=grey" "style=filled" } { } ? ]
64 [ [ cfg-vertex, ] each-basic-block ]
72 ] over cfg-title graph,
75 : optimized-cfg ( quot -- cfgs )
77 { [ dup cfg? ] [ 1array ] }
78 { [ dup quotation? ] [ test-cfg [ optimize-cfg ] map ] }
79 { [ dup word? ] [ test-cfg [ optimize-cfg ] map ] }
83 : render-cfg ( cfg -- )
84 optimized-cfg [ cfgs ] render-graph ;
86 : dom-trees ( cfgs -- )
95 ] over cfg-title graph,
98 : render-dom ( cfg -- )
99 optimized-cfg [ dom-trees ] render-graph ;
104 : vertex-name ( call-graph-node -- string )
105 label>> vertex-names get [
107 dup word-counts get [ 0 or 1 + dup ] change-at number>string " #" glue
110 : vertex-attrs ( obj -- string )
111 tail?>> { "style=bold,label=\"tail\"" } { } ? ;
113 : call-graph-edge, ( from to attrs -- )
114 [ [ vertex-name ] [ vertex-attrs ] bi ] dip append edge,* ;
116 : (call-graph-back-edges) ( string calls -- )
117 [ { "color=red" } call-graph-edge, ] with each ;
119 : (call-graph-edges) ( string children -- )
122 [ { } call-graph-edge, ]
123 [ [ vertex-name ] [ label>> loop?>> { "shape=box" } { } ? ] bi node-style, ]
124 [ [ vertex-name ] [ calls>> ] bi (call-graph-back-edges) ]
125 [ [ vertex-name ] [ children>> ] bi (call-graph-edges) ]
129 : call-graph-edges ( call-graph-node -- )
130 H{ } clone word-counts set
131 H{ } clone vertex-names set
132 [ "ROOT" ] dip (call-graph-edges) ;
134 : render-call-graph ( tree -- )
135 dup quotation? [ build-tree ] when
136 analyze-recursive drop
137 [ [ call-graph get call-graph-edges ] "Call graph" graph, ]