Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
numba
GitHub Repository: numba/llvmlite
Path: blob/main/llvmlite/binding/analysis.py
1154 views
1
"""
2
A collection of analysis utilities
3
"""
4
5
from ctypes import POINTER, c_char_p, c_int
6
7
from llvmlite.binding import ffi
8
from llvmlite.binding.module import parse_assembly
9
10
11
def get_function_cfg(func, show_inst=True):
12
"""Return a string of the control-flow graph of the function in DOT
13
format. If the input `func` is not a materialized function, the module
14
containing the function is parsed to create an actual LLVM module.
15
The `show_inst` flag controls whether the instructions of each block
16
are printed.
17
"""
18
assert func is not None
19
from llvmlite import ir
20
if isinstance(func, ir.Function):
21
mod = parse_assembly(str(func.module))
22
func = mod.get_function(func.name)
23
24
# Assume func is a materialized function
25
with ffi.OutputString() as dotstr:
26
ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst)
27
return str(dotstr)
28
29
30
def view_dot_graph(graph, filename=None, view=False):
31
"""
32
View the given DOT source. If view is True, the image is rendered
33
and viewed by the default application in the system. The file path of
34
the output is returned. If view is False, a graphviz.Source object is
35
returned. If view is False and the environment is in a IPython session,
36
an IPython image object is returned and can be displayed inline in the
37
notebook.
38
39
This function requires the graphviz package.
40
41
Args
42
----
43
- graph [str]: a DOT source code
44
- filename [str]: optional. if given and view is True, this specifies
45
the file path for the rendered output to write to.
46
- view [bool]: if True, opens the rendered output file.
47
48
"""
49
# Optionally depends on graphviz package
50
import graphviz as gv
51
52
src = gv.Source(graph)
53
if view:
54
# Returns the output file path
55
return src.render(filename, view=view)
56
else:
57
# Attempts to show the graph in IPython notebook
58
try:
59
__IPYTHON__
60
except NameError:
61
return src
62
else:
63
import IPython.display as display
64
format = 'svg'
65
return display.SVG(data=src.pipe(format))
66
67
68
# Ctypes binding
69
ffi.lib.LLVMPY_WriteCFG.argtypes = [ffi.LLVMValueRef, POINTER(c_char_p), c_int]
70
71