Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
numba
GitHub Repository: numba/llvmlite
Path: blob/main/examples/newpassmanagers.py
1154 views
1
"""
2
Demonstration of llvmlite's New Pass Manager API.
3
4
This example shows how to use the new pass manager to optimize LLVM IR.
5
Comments show the equivalent legacy pass manager approach for comparison.
6
"""
7
8
import llvmlite.binding as llvm
9
10
# Initialize LLVM
11
llvm.initialize_native_target()
12
llvm.initialize_native_asmprinter()
13
14
# Create a module with some sample IR
15
module = llvm.parse_assembly("""
16
define i32 @test_function(i32 %x, i32 %y) {
17
entry:
18
%z = add i32 %x, %y
19
%w = add i32 %z, 0 ; This can be optimized away
20
%t = mul i32 %w, 1 ; This can also be optimized away
21
ret i32 %t
22
}
23
24
define i32 @unused_function() {
25
entry:
26
ret i32 42
27
}
28
""")
29
30
print("Original IR:")
31
print(str(module))
32
33
# Create target machine
34
target = llvm.Target.from_default_triple()
35
target_machine = target.create_target_machine()
36
37
# NEW PASS MANAGER API:
38
# Create pipeline tuning options with optimization settings
39
pto = llvm.create_pipeline_tuning_options(speed_level=2, size_level=0)
40
# LEGACY EQUIVALENT:
41
# pmb = llvm.PassManagerBuilder()
42
# pmb.opt_level = 2
43
# pmb.size_level = 0
44
45
# Optionally customize the tuning options
46
pto.loop_vectorization = True
47
pto.slp_vectorization = True
48
pto.loop_unrolling = True
49
# LEGACY EQUIVALENT:
50
# pmb.loop_vectorize = True
51
# pmb.slp_vectorize = True
52
# pmb.disable_unroll_loops = False
53
54
# Create the pass builder
55
pass_builder = llvm.create_pass_builder(target_machine, pto)
56
# LEGACY EQUIVALENT: PassManagerBuilder handles this internally
57
58
# Get a populated module pass manager
59
mpm = pass_builder.getModulePassManager()
60
# LEGACY EQUIVALENT:
61
# mpm = llvm.ModulePassManager()
62
# pmb.populate(mpm)
63
64
# Run the optimization passes
65
mpm.run(module, pass_builder)
66
# LEGACY EQUIVALENT:
67
# changed = mpm.run(module)
68
69
print("\nOptimized IR:")
70
print(str(module))
71
72
# For function-level optimizations, you can also use:
73
fpm = pass_builder.getFunctionPassManager()
74
# LEGACY EQUIVALENT:
75
# fpm = llvm.FunctionPassManager(module)
76
# pmb.populate(fpm)
77
# fpm.initialize()
78
79
for function in module.functions:
80
fpm.run(function, pass_builder)
81
# LEGACY EQUIVALENT:
82
# for function in module.functions:
83
# fpm.run(function)
84
# fpm.finalize() # Call after all functions are processed
85
86