File size: 8,677 Bytes
a7e4fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""
Contains tests and a prototype implementation for the fanout algorithm in
the LLVM refprune pass.
"""

try:
    from graphviz import Digraph
except ImportError:
    pass
from collections import defaultdict

# The entry block. It's always the same.
ENTRY = "A"


# The following caseNN() functions returns a 3-tuple of
# (nodes, edges, expected).
# `nodes` maps BB nodes to incref/decref inside the block.
# `edges` maps BB nodes to their successor BB.
# `expected` maps BB-node with incref to a set of BB-nodes with the decrefs, or
#            the value can be None, indicating invalid prune.

def case1():
    edges = {
        "A": ["B"],
        "B": ["C", "D"],
        "C": [],
        "D": ["E", "F"],
        "E": ["G"],
        "F": [],
        "G": ["H", "I"],
        "I": ["G", "F"],
        "H": ["J", "K"],
        "J": ["L", "M"],
        "K": [],
        "L": ["Z"],
        "M": ["Z", "O", "P"],
        "O": ["Z"],
        "P": ["Z"],
        "Z": [],
    }
    nodes = defaultdict(list)
    nodes["D"] = ["incref"]
    nodes["H"] = ["decref"]
    nodes["F"] = ["decref", "decref"]
    expected = {"D": {"H", "F"}}
    return nodes, edges, expected


def case2():
    edges = {
        "A": ["B", "C"],
        "B": ["C"],
        "C": [],
    }
    nodes = defaultdict(list)
    nodes["A"] = ["incref"]
    nodes["B"] = ["decref"]
    nodes["C"] = ["decref"]
    expected = {"A": None}
    return nodes, edges, expected


def case3():
    nodes, edges, _ = case1()
    # adds an invalid edge
    edges["H"].append("F")
    expected = {"D": None}
    return nodes, edges, expected


def case4():
    nodes, edges, _ = case1()
    # adds an invalid edge
    edges["H"].append("E")
    expected = {"D": None}
    return nodes, edges, expected


def case5():
    nodes, edges, _ = case1()
    # adds backedge to go before incref
    edges["B"].append("I")
    expected = {"D": None}
    return nodes, edges, expected


def case6():
    nodes, edges, _ = case1()
    # adds backedge to go before incref
    edges["I"].append("B")
    expected = {"D": None}
    return nodes, edges, expected


def case7():
    nodes, edges, _ = case1()
    # adds forward jump outside
    edges["I"].append("M")
    expected = {"D": None}
    return nodes, edges, expected


def case8():
    edges = {
        "A": ["B", "C"],
        "B": ["C"],
        "C": [],
    }
    nodes = defaultdict(list)
    nodes["A"] = ["incref"]
    nodes["C"] = ["decref"]
    expected = {"A": {"C"}}
    return nodes, edges, expected


def case9():
    nodes, edges, _ = case8()
    # adds back edge
    edges["C"].append("B")
    expected = {"A": None}
    return nodes, edges, expected


def case10():
    nodes, edges, _ = case8()
    # adds back edge to A
    edges["C"].append("A")
    expected = {"A": {"C"}}
    return nodes, edges, expected


def case11():
    nodes, edges, _ = case8()
    edges["C"].append("D")
    edges["D"] = []
    expected = {"A": {"C"}}
    return nodes, edges, expected


def case12():
    nodes, edges, _ = case8()
    edges["C"].append("D")
    edges["D"] = ["A"]
    expected = {"A": {"C"}}
    return nodes, edges, expected


def case13():
    nodes, edges, _ = case8()
    edges["C"].append("D")
    edges["D"] = ["B"]
    expected = {"A": None}
    return nodes, edges, expected


def make_predecessor_map(edges):
    d = defaultdict(set)
    for src, outgoings in edges.items():
        for dst in outgoings:
            d[dst].add(src)
    return d


class FanoutAlgorithm:
    def __init__(self, nodes, edges, verbose=False):
        self.nodes = nodes
        self.edges = edges
        self.rev_edges = make_predecessor_map(edges)
        self.print = print if verbose else self._null_print

    def run(self):
        return self.find_fanout_in_function()

    def _null_print(self, *args, **kwargs):
        pass

    def find_fanout_in_function(self):
        got = {}
        for cur_node in self.edges:
            for incref in (x for x in self.nodes[cur_node] if x == "incref"):
                decref_blocks = self.find_fanout(cur_node)
                self.print(">>", cur_node, "===", decref_blocks)
                got[cur_node] = decref_blocks
        return got

    def find_fanout(self, head_node):
        decref_blocks = self.find_decref_candidates(head_node)
        self.print("candidates", decref_blocks)
        if not decref_blocks:
            return None
        if not self.verify_non_overlapping(
            head_node, decref_blocks, entry=ENTRY
        ):
            return None
        return set(decref_blocks)

    def verify_non_overlapping(self, head_node, decref_blocks, entry):
        self.print("verify_non_overlapping".center(80, "-"))
        # reverse walk for each decref_blocks
        # they should end at head_node
        todo = list(decref_blocks)
        while todo:
            cur_node = todo.pop()
            visited = set()

            workstack = [cur_node]
            del cur_node
            while workstack:
                cur_node = workstack.pop()
                self.print("cur_node", cur_node, "|", workstack)
                if cur_node in visited:
                    continue  # skip
                if cur_node == entry:
                    # Entry node
                    self.print(
                        "!! failed because we arrived at entry", cur_node
                    )
                    return False
                visited.add(cur_node)
                # check all predecessors
                self.print(
                    f"   {cur_node} preds {self.get_predecessors(cur_node)}"
                )
                for pred in self.get_predecessors(cur_node):
                    if pred in decref_blocks:
                        # reject because there's a predecessor in decref_blocks
                        self.print(
                            "!! reject because predecessor in decref_blocks"
                        )
                        return False
                    if pred != head_node:

                        workstack.append(pred)

        return True

    def get_successors(self, node):
        return tuple(self.edges[node])

    def get_predecessors(self, node):
        return tuple(self.rev_edges[node])

    def has_decref(self, node):
        return "decref" in self.nodes[node]

    def walk_child_for_decref(
        self, cur_node, path_stack, decref_blocks, depth=10
    ):
        indent = " " * len(path_stack)
        self.print(indent, "walk", path_stack, cur_node)
        if depth <= 0:
            return False  # missing
        if cur_node in path_stack:
            if cur_node == path_stack[0]:
                return False  # reject interior node backedge
            return True  # skip
        if self.has_decref(cur_node):
            decref_blocks.add(cur_node)
            self.print(indent, "found decref")
            return True

        depth -= 1
        path_stack += (cur_node,)
        found = False
        for child in self.get_successors(cur_node):
            if not self.walk_child_for_decref(
                child, path_stack, decref_blocks
            ):
                found = False
                break
            else:
                found = True

        self.print(indent, f"ret {found}")
        return found

    def find_decref_candidates(self, cur_node):
        # Forward pass
        self.print("find_decref_candidates".center(80, "-"))
        path_stack = (cur_node,)
        found = False
        decref_blocks = set()
        for child in self.get_successors(cur_node):
            if not self.walk_child_for_decref(
                child, path_stack, decref_blocks
            ):
                found = False
                break
            else:
                found = True
        if not found:
            return set()
        else:
            return decref_blocks


def check_once():
    nodes, edges, expected = case13()

    # Render graph
    G = Digraph()
    for node in edges:
        G.node(node, shape="rect", label=f"{node}\n" + r"\l".join(nodes[node]))
    for node, children in edges.items():
        for child in children:
            G.edge(node, child)

    G.view()

    algo = FanoutAlgorithm(nodes, edges, verbose=True)
    got = algo.run()
    assert expected == got


def check_all():
    for k, fn in list(globals().items()):
        if k.startswith("case"):
            print(f"{fn}".center(80, "-"))
            nodes, edges, expected = fn()
            algo = FanoutAlgorithm(nodes, edges)
            got = algo.run()
            assert expected == got
    print("ALL PASSED")


if __name__ == "__main__":
    # check_once()
    check_all()