1 ! Copyright (C) 2008, 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel assocs arrays namespaces accessors sequences deques fry
4 search-deques dlists combinators.short-circuit make sets compiler.tree ;
5 IN: compiler.tree.recursive
7 TUPLE: call-site tail? node label ;
9 : recursive-phi-in ( #enter-recursive -- seq )
10 [ label>> calls>> [ node>> in-d>> ] map ] [ in-d>> ] bi suffix ;
14 TUPLE: call-graph-node tail? label children calls ;
16 : (tail-calls) ( tail? seq -- seq' )
17 reverse [ swap [ and ] keep ] map nip reverse ;
19 : tail-calls ( tail? node -- seq )
24 [ #return-recursive? ]
28 SYMBOLS: children calls ;
30 GENERIC: node-call-graph ( tail? node -- )
32 : (build-call-graph) ( tail? nodes -- )
34 [ node-call-graph ] 2each ;
36 : build-call-graph ( nodes -- labels calls )
38 V{ } clone children set
40 [ t ] dip (build-call-graph)
45 M: #return-recursive node-call-graph
46 nip dup label>> (>>return) ;
48 M: #call-recursive node-call-graph
49 [ dup label>> call-site boa ] keep
50 [ drop calls get push ]
51 [ label>> calls>> push ] 2bi ;
53 M: #recursive node-call-graph
54 [ label>> V{ } clone >>calls drop ]
56 [ label>> ] [ child>> build-call-graph ] bi
57 call-graph-node boa children get push
60 M: #branch node-call-graph
61 children>> [ (build-call-graph) ] with each ;
63 M: node node-call-graph 2drop ;
65 SYMBOLS: not-loops recursive-nesting ;
67 : not-a-loop ( label -- ) not-loops get conjoin ;
69 : not-a-loop? ( label -- ? ) not-loops get key? ;
71 : non-tail-calls ( call-graph-node -- seq )
72 calls>> [ tail?>> not ] filter ;
74 : visit-back-edges ( call-graph -- )
76 [ non-tail-calls [ label>> not-a-loop ] each ]
77 [ children>> visit-back-edges ]
83 : check-cross-frame-call ( call-site -- )
84 label>> dup not-a-loop? [ drop ] [
85 recursive-nesting get <reversed> [
86 2dup label>> eq? [ 2drop f ] [
87 [ label>> not-a-loop? ] [ tail?>> not ] bi or
88 [ not-a-loop changed? on ] [ drop ] if t
93 : detect-cross-frame-calls ( call-graph -- )
94 ! Suppose we have a nesting of recursives A --> B --> C
95 ! B tail-calls A, and C non-tail-calls B. Then A cannot be
96 ! a loop, it needs its own procedure, since the call from
97 ! C to A crosses a call-frame boundary.
99 [ recursive-nesting get push ]
100 [ calls>> [ check-cross-frame-call ] each ]
101 [ children>> detect-cross-frame-calls ] tri
102 recursive-nesting get pop*
105 : while-changing ( ... quot: ( ... -- ... ) -- ... )
107 [ call ] [ changed? get [ while-changing ] [ drop ] if ] bi ;
110 : detect-loops ( call-graph -- )
111 H{ } clone not-loops set
112 V{ } clone recursive-nesting set
114 [ '[ _ detect-cross-frame-calls ] while-changing ]
117 : mark-loops ( call-graph -- )
119 [ label>> dup not-a-loop? [ t >>loop? ] unless drop ]
120 [ children>> mark-loops ]
128 : analyze-recursive ( nodes -- nodes )
129 dup build-call-graph drop