-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrendering.py
412 lines (343 loc) · 14 KB
/
rendering.py
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import ast
import logging
from abc import abstractmethod
from numba_rvsdg.core.datastructures.basic_block import (
BasicBlock,
RegionBlock,
PythonBytecodeBlock,
PythonASTBlock,
SyntheticAssignment,
SyntheticBranch,
SyntheticBlock,
)
from numba_rvsdg.core.datastructures.scfg import SCFG
from numba_rvsdg.core.datastructures.byte_flow import ByteFlow
import dis
from typing import Dict, Optional
from graphviz import Digraph
node_style_kwargs = {"shape": "rect", "style": "rounded"}
class BaseRenderer:
"""Base Renderer class.
This is the base class for all types of graph renderers. It defines two
methods `render_block` and `render_edges` that define how the blocks and
edges of the graph are rendered respectively.
"""
g: "Digraph"
@abstractmethod
def render_basic_block(
self, digraph: "Digraph", name: str, block: BasicBlock
) -> None:
""" """
@abstractmethod
def render_control_variable_block(
self, digraph: "Digraph", name: str, block: SyntheticAssignment
) -> None:
""" """
@abstractmethod
def render_branching_block(
self, digraph: "Digraph", name: str, block: SyntheticBranch
) -> None:
""" """
@abstractmethod
def render_region_block(
self, digraph: "Digraph", name: str, regionblock: RegionBlock
) -> None:
""" """
def render_block(
self, digraph: "Digraph", name: str, block: BasicBlock
) -> None:
"""Function that defines how the BasicBlocks in a graph should be
rendered.
Parameters
----------
digraph: Digraph
The graphviz Digraph object that represents the graph/subgraph upon
which the current blocks are to be rendered.
name: str
Name of the block to be rendered.
block: BasicBlock
The BasicBlock to be rendered.
"""
if type(block) == BasicBlock: # noqa: E721
self.render_basic_block(digraph, name, block)
elif type(block) == PythonBytecodeBlock: # noqa: E721
self.render_basic_block(digraph, name, block)
elif type(block) == PythonASTBlock: # noqa: E721
self.render_python_ast_block(digraph, name, block) # type: ignore
elif type(block) == SyntheticAssignment: # noqa: E721
self.render_control_variable_block(digraph, name, block)
elif isinstance(block, SyntheticBranch):
self.render_branching_block(digraph, name, block)
elif type(block) == RegionBlock: # noqa: E721
self.render_region_block(digraph, name, block)
elif isinstance(block, SyntheticBlock):
self.render_basic_block(digraph, name, block)
else:
raise Exception("unreachable")
def render_edges(self, scfg: SCFG) -> None:
"""Function that renders the edges in an SCFG.
Parameters
----------
scfg: SCFG
The graph whose edges are to be rendered.
"""
blocks = dict(scfg)
def find_base_header(block: BasicBlock) -> BasicBlock:
if isinstance(block, RegionBlock):
block = blocks[block.header] # type: ignore
block = find_base_header(block)
return block
for _, src_block in blocks.items():
if isinstance(src_block, RegionBlock):
continue
src_block = find_base_header(src_block)
for dst_name in src_block.jump_targets:
try:
dst_name = find_base_header(blocks[dst_name]).name
except KeyError:
continue
if dst_name in blocks.keys():
self.g.edge(str(src_block.name), str(dst_name))
else:
raise Exception("unreachable " + str(src_block))
for dst_name in src_block.backedges:
dst_name = find_base_header(blocks[dst_name]).name
if dst_name in blocks.keys():
self.g.edge(
str(src_block.name),
str(dst_name),
style="dashed",
color="grey",
constraint="0",
)
else:
raise Exception("unreachable " + str(src_block))
class ByteFlowRenderer(BaseRenderer):
"""The `ByteFlowRenderer` class is used to render the visual
representation of a `ByteFlow` object.
Attributes
----------
g: Digraph
The graphviz Digraph object that represents the entire graph upon
which the current ByteFlow is to be rendered.
bcmap: Dict[int, dis.Instruction]
Mapping of bytecode offset to instruction.
"""
def __init__(self) -> None:
from graphviz import Digraph
self.g = Digraph()
def render_region_block(
self, digraph: "Digraph", name: str, regionblock: RegionBlock
) -> None:
# render subgraph
with digraph.subgraph(name=f"cluster_{name}") as subg:
color = "blue"
if regionblock.kind == "branch":
color = "green"
if regionblock.kind == "tail":
color = "purple"
if regionblock.kind == "head":
color = "red"
subg.attr(color=color, label=regionblock.name)
assert regionblock.subregion is not None
for name, block in regionblock.subregion.graph.items():
self.render_block(subg, name, block)
def render_basic_block(
self, digraph: "Digraph", name: str, block: BasicBlock
) -> None:
if name.startswith("python_bytecode") and isinstance(
block, PythonBytecodeBlock
):
instlist = block.get_instructions(self.bcmap)
body = name + r"\l"
body += r"\l".join(
[f"{inst.offset:3}: {inst.opname}" for inst in instlist] + [""]
)
else:
body = name + r"\l"
digraph.node(str(name), shape="rect", label=body)
def render_control_variable_block(
self, digraph: "Digraph", name: str, block: SyntheticAssignment
) -> None:
if isinstance(name, str):
body = name + r"\l"
body += r"\l".join(
(f"{k} = {v}" for k, v in block.variable_assignment.items())
)
else:
raise Exception("Unknown name type: " + name)
digraph.node(str(name), shape="rect", label=body)
def render_branching_block(
self, digraph: "Digraph", name: str, block: SyntheticBranch
) -> None:
if isinstance(name, str):
body = name + r"\l"
body += rf"variable: {block.variable}\l"
body += r"\l".join(
(f"{k}=>{v}" for k, v in block.branch_value_table.items())
)
else:
raise Exception("Unknown name type: " + name)
digraph.node(str(name), shape="rect", label=body)
def render_byteflow(self, byteflow: ByteFlow) -> "Digraph":
"""Renders the provided `ByteFlow` object."""
self.bcmap_from_bytecode(byteflow.bc)
# render nodes
for name, block in byteflow.scfg.graph.items():
self.render_block(self.g, name, block)
self.render_edges(byteflow.scfg)
return self.g
def bcmap_from_bytecode(self, bc: dis.Bytecode) -> None:
self.bcmap: Dict[int, dis.Instruction] = SCFG.bcmap_from_bytecode(bc)
class SCFGRenderer(BaseRenderer):
"""The `SCFGRenderer` class is used to render the visual
representation of a `SCFG` object.
Attributes
----------
g: Digraph
The graphviz Digraph object that represents the entire graph upon
which the current SCFG is to be rendered.
"""
def __init__(self, scfg: SCFG):
from graphviz import Digraph
self.g = Digraph()
# render nodes
for name, block in scfg.graph.items():
self.render_block(self.g, name, block)
self.render_edges(scfg)
def render_region_block(
self, digraph: "Digraph", name: str, regionblock: RegionBlock
) -> None:
# render subgraph
with digraph.subgraph(name=f"cluster_{name}") as subg:
color = "blue"
if regionblock.kind == "branch":
color = "green"
if regionblock.kind == "tail":
color = "purple"
if regionblock.kind == "head":
color = "red"
label = [regionblock.name, r"\n"]
if regionblock.jump_targets:
label.append(
f"\njump targets: {str(regionblock.jump_targets)}"
)
if regionblock.backedges:
label.append(f"\nback edges: {str(regionblock.backedges)}")
subg.attr(color=color, label="".join(label), **node_style_kwargs)
assert regionblock.subregion is not None
for name, block in regionblock.subregion.graph.items():
self.render_block(subg, name, block)
def render_basic_block(
self, digraph: "Digraph", name: str, block: BasicBlock
) -> None:
label = [name, r"\n"]
if block.jump_targets:
label.append(f"\njump targets: {str(block.jump_targets)}")
if block.backedges:
label.append(f"\nback edges: {str(block.backedges)}")
digraph.node(str(name), label="".join(label), **node_style_kwargs)
def render_python_ast_block(
self, digraph: "Digraph", name: str, block: BasicBlock
) -> None:
code = r"\l".join(
ast.unparse(n) for n in block.get_tree() # type: ignore
)
label = [name, r"\n\l", code, r"\l"]
if block.jump_targets:
label.append(f"\njump targets: {str(block.jump_targets)}")
if block.backedges:
label.append(f"\nback edges: {str(block.backedges)}")
digraph.node(str(name), label="".join(label), **node_style_kwargs)
def render_control_variable_block(
self, digraph: "Digraph", name: str, block: SyntheticAssignment
) -> None:
if isinstance(name, str):
assignments = r"\l".join(
(
f"{k} = {v}"
for k, v in sorted(block.variable_assignment.items())
)
)
label = [name, r"\n\l", assignments, r"\l"]
if block.jump_targets:
label.append(f"\njump targets: {str(block.jump_targets)}")
if block.backedges:
label.append(f"\nback edges: {str(block.backedges)}")
else:
raise Exception("Unknown name type: " + name)
digraph.node(str(name), label="".join(label), **node_style_kwargs)
def render_branching_block(
self, digraph: "Digraph", name: str, block: SyntheticBranch
) -> None:
if isinstance(name, str):
branches = rf"variable: {block.variable}\l" + r"\l".join(
(f"{k} → {v}" for k, v in block.branch_value_table.items())
)
label = [name, r"\n\l", branches, r"\l"]
if block.jump_targets:
label.append(f"\njump targets: {str(block.jump_targets)}")
if block.backedges:
label.append(f"\nback edges: {str(block.backedges)}")
else:
raise Exception("Unknown name type: " + name)
digraph.node(str(name), label="".join(label), **node_style_kwargs)
def render_scfg(self) -> "Digraph":
"""Return the graphviz Digraph that contains the rendered SCFG."""
return self.g
def view(self, name: Optional[str] = None) -> None:
"""Method used to view the current SCFG as an external graphviz
generated PDF file.
Parameters
----------
name: str
Name to be given to the external graphviz generated PDF file.
"""
self.g.view(name)
# logging.basicConfig(level=logging.DEBUG)
def render_func(func) -> None: # type: ignore
"""The `render_func`` function takes a `func` parameter as the Python
function to be transformed and rendered and renders the byte flow
representation of the bytecode of the function.
Parameters
----------
func: Python function
The Python function for which bytecode is to be rendered.
"""
render_flow(ByteFlow.from_bytecode(func))
def render_flow(flow: ByteFlow) -> None:
"""Renders multiple ByteFlow representations across various SCFG
transformations.
The `render_flow`` function takes a `flow` parameter as the `ByteFlow`
to be transformed and rendered and performs the following operations:
- Renders the pure `ByteFlow` representation of the function using
`ByteFlowRenderer` and displays it as a document named "before".
- Joins the return blocks in the `ByteFlow` object graph and renders
the graph, displaying it as a document named "closed".
- Restructures the loops recursively in the `ByteFlow` object graph
and renders the graph, displaying it as named "loop restructured".
- Restructures the branch recursively in the `ByteFlow` object graph
and renders the graph, displaying it as named "branch restructured".
Parameters
----------
flow: ByteFlow
The ByteFlow object to be trnasformed and rendered.
"""
ByteFlowRenderer().render_byteflow(flow).view("before")
flow.scfg.join_returns()
ByteFlowRenderer().render_byteflow(flow).view("closed")
flow.scfg.restructure_loop()
ByteFlowRenderer().render_byteflow(flow).view("loop restructured")
flow.scfg.restructure_branch()
ByteFlowRenderer().render_byteflow(flow).view("branch restructured")
def render_scfg(scfg: SCFG) -> None:
"""The `render_scfg` function takes a `scfg` parameter as the SCFG
object to be transformed and rendered and renders the graphviz
representation of the SCFG.
Parameters
----------
scfg: SCFG
The structured control flow graph (SCFG) to be rendered.
"""
# is this function used??
SCFGRenderer(scfg).view("scfg")