Debian Codegraph @

rpython/doc/jit/ruleopt.rst

raw
1 ===========================================
2 JIT Integer Optimization Peephole Rule DSL
3 ===========================================
4
5 For integer peephole optimizations in the JIT we use a domain specific language
6 based on pattern matching that specifies how (sequences of) integer operations
7 should be simplified. It is implemented in the directory
8 ``jit/metainterp/optimizeopt``. This directory contains the implementation of
9 the DSL for integer rewrites in optimizeopt. The rules are then compiled to
10 RPython code that executes the transformations in optimizeopt. The rewrite
11 rules are automatically proven correct with Z3 as part of the build process.
12 This page is an introduction to how that DSL works and how to use it.
13
14 Simple transformation rules
15 ============================
16
17 The rules in the DSL specify how integer operation can be transformed into
18 cheaper other integer operations. A rule always consists of a name, a pattern,
19 and a target. Here's a simple rule::
20
21 add_zero: int_add(x, 0)
22 => x
23
24 The name of the rule is ``add_zero``. It matches operations in the trace of the
25 form ``int_add(x, 0)``, where ``x`` will match anything and ``0`` will match only the
26 constant zero. After the ``=>`` arrow is the target of the rewrite, i.e. what the
27 operation is rewritten to, in this case ``x``.
28
29 The rule language knowns which of the operations are commutative, so ``add_zero``
30 will also optimize ``int_add(0, x)`` to ``x``.
31
32 Variables in the pattern can repeat::
33
34 sub_x_x: int_sub(x, x)
35 => 0
36
37 This rule matches against ``int_sub`` operations where the two arguments are the
38 same (either the same box, or the same constant).
39
40 Here's a rule with a more complicated pattern::
41
42 sub_add: int_sub(int_add(x, y), y)
43 => x
44
45 This pattern matches ``int_sub`` operations, where the first argument was
46 produced by an ``int_add`` operation. In addition, one of the arguments of the
47 addition has to be the same as the second argument of the subtraction.
48
49 The constants ``MININT``, ``MAXINT`` and ``LONG_BIT`` (which is either 32 or 64) can
50 be used in rules, they behave like writing numbers but allow
51 bit-width-independent formulations::
52
53 is_true_and_minint: int_is_true(int_and(x, MININT))
54 => int_lt(x, 0)
55
56 It is also possible to have a pattern where some arguments needs to be a
57 constant, without specifying which constant. Those patterns look like this::
58
59 sub_add_consts: int_sub(int_add(x, C1), C2) # incomplete
60 # more goes here
61 => int_sub(x, C)
62
63 Variables in the pattern that start with a ``C`` match against constants only.
64 However, in this current form the rule is incomplete, because the variable ``C``
65 that is being used in the target operation is not defined anywhere. We will see
66 how to compute it in the next section.
67
68 Computing constants and other intermediate results
69 ===================================================
70
71 Sometimes it is necessary to compute intermediate results that are used in the
72 target operation. To do that, there can be extra assignments between the rule head
73 and the rule target.::
74
75 sub_add_consts: int_sub(int_add(x, C1), C2) # incomplete
76 C = C1 + C1
77 => int_sub(x, C)
78
79 The right hand side of such an assignment is a subset of Python syntax,
80 supporting arithmetic using ``+``, ``-``, ``*``, and certain helper functions.
81 However, the syntax allows you to be explicit about unsignedness for some
82 operations. E.g. ``>>u`` exists for unsigned right shifts (and I plan to add
83 ``>u``, ``>=u``, ``<u``, ``<=u`` for comparisons).
84
85 Checks
86 ===================================================
87
88 Some rewrites are only true under certain conditions. For example,
89 ``int_eq(x, 1)`` can be rewritten to ``x``, if ``x`` is know to store a boolean value. This can
90 be expressed with *checks*::
91
92 eq_one: int_eq(x, 1)
93 check x.is_bool()
94 => x
95
96 A check is followed by a boolean expression. The variables from the pattern can
97 be used as ``IntBound`` instances in checks (and also in assignments) to find out
98 what the abstract interpretation knows about the value of a trace variable.
99
100 Here's another example::
101
102 mul_lshift: int_mul(x, int_lshift(1, y))
103 check y.known_ge_const(0) and y.known_le_const(LONG_BIT)
104 => int_lshift(x, y)
105
106 It expresses that ``x * (1 << y)`` can be rewritten to ``x << y`` but checks that
107 ``y`` is known to be between ``0`` and ``LONG_BIT``.
108
109 Checks and assignments can be repeated and combined with each other::
110
111 mul_pow2_const: int_mul(x, C)
112 check C > 0 and C & (C - 1) == 0
113 shift = highest_bit(C)
114 => int_lshift(x, shift)
115
116 In addition to calling methods on ``IntBound`` instances, it's also possible to
117 access their attributes, like in this rule::
118
119 and_x_c_in_range: int_and(x, C)
120 check x.lower >= 0 and x.upper <= C & ~(C + 1)
121 => x
122
123
124
125 Rule Ordering and Liveness
126 ===================================================
127
128 The generated optimizer code will give preference to applying rules that
129 produce a constant or a variable as a rewrite result. Only if none of those
130 match do rules that produce new result operations get applied. For example, the
131 rules ``sub_x_x`` and ``sub_add`` are tried before trying ``sub_add_consts``,
132 because the former two rules optimize to a constant and a variable
133 respectively, while the latter produces a new operation as the result.
134
135 The rule ``sub_add_consts`` has a possible problem, which is that if the
136 intermediate result of the ``int_add`` operation in the rule head is used by
137 some other operations, then the ``sub_add_consts`` rule does not actually
138 reduce the number of operations (and might actually make things slightly worse
139 due to increased register pressure). However, currently it would be extremely
140 hard to take that kind of information into account in the optimization pass of
141 the JIT, so we optimistically apply the rules anyway.
142
143 Checking rule coverage
144 ===================================================
145
146 Every rewrite rule should have at least one unit test where it triggers. To
147 ensure this, the tests in file ``test_optimizeintbound.py`` have an assert at the
148 end of a test run, that every rule fired at least once (this check can
149 somethings trigger as a false positive, for example when running individual
150 tests with ``-k``).
151
152 Printing rule statistics
153 ===================================================
154
155 The JIT can print statistics about which rule fired how often in the
156 ``jit-intbounds-stats`` :doc:`logging <../logging>` category. For example, to
157 print it to stdout at the end of program execution, run PyPy like this::
158
159 PYPYLOG=jit-intbounds-stats:- pypy ...
160
161 The output of that will look something like this::
162
163 int_add
164 add_reassoc_consts 2514
165 add_zero 107008
166 int_sub
167 sub_zero 31519
168 sub_from_zero 523
169 sub_x_x 3153
170 sub_add_consts 159
171 sub_add 55
172 sub_sub_x_c_c 1752
173 sub_sub_c_x_c 0
174 sub_xor_x_y_y 0
175 sub_or_x_y_y 0
176 int_mul
177 mul_zero 0
178 mul_one 110
179 mul_minus_one 0
180 mul_pow2_const 1456
181 mul_lshift 0
182 ...
183
184 Termination and Confluence
185 =========================================
186
187 Right now there are unfortunately no checks that the rules actually rewrite
188 operations towards "simpler" forms. There is no cost model, and also nothing
189 that prevents you from writing a rule like this::
190
191
192 neg_complication: int_neg(x) # leads to infinite rewrites
193 => int_mul(-1, x)
194
195 Doing this would lead to endless rewrites if there is also another rule that
196 turns multiplication with -1 into negation.
197
198 There is also no checking for confluence__ (yet?), i.e. the property that all
199 rewrites starting from the same input trace always lead to the same output
200 trace, no matter in which order the rules are applied.
201
202 .. __: https://en.wikipedia.org/wiki/Confluence_(abstract_rewriting)
203
204
205 Proofs
206 ===================================================
207
208 It is very easy to write a peephole rule that is not correct in all corner
209 cases. Therefore all the rules are proven correct with Z3 before compiled into
210 actual JIT code, by default. When the proof fails, a (hopefully minimal)
211 counterexample is printed. The counterexample consists of values for all the
212 inputs that fulfil the checks, values for the intermediate expressions, and
213 then two *different* values for the source and the target operations.
214
215 E.g. if we try to add the incorrect rule::
216
217 mul_is_add: int_mul(a, b)
218 => int_add(a, b)
219
220 We get the following counterexample as output::
221
222 Could not prove correctness of rule 'mul_is_add'
223 in line 1
224 counterexample given by Z3:
225 counterexample values:
226 a: 0
227 b: 1
228 operation int_mul(a, b) with Z3 formula a*b
229 has counterexample result vale: 0
230 BUT
231 target expression: int_add(a, b) with Z3 formula a + b
232 has counterexample value: 1
233
234 If we add conditions, they are taken into account::
235
236 mul_is_add: int_mul(a, b)
237 check a.known_gt_const(1) and b.known_gt_const(2)
238 => int_add(a, b)
239
240 This leads to the following counterexample::
241
242 Could not prove correctness of rule 'mul_is_add'
243 in line 46
244 counterexample given by Z3:
245 counterexample values:
246 a: 2
247 b: 3
248 operation int_mul(a, b) with Z3 formula a*b
249 has counterexample result vale: 6
250 BUT
251 target expression: int_add(a, b) with Z3 formula a + b
252 has counterexample value: 5
253
254 Some ``IntBound`` methods cannot be used in Z3 proofs because they have `too
255 complex control flow`__ If that is the case, they can have Z3-equivalent
256 formulations defined, in the ``test_z3intbound.Z3IntBound`` class (in every
257 case this is done, it's a potential proof hole if the Z3 friendly reformulation
258 and the real implementation differ from each other, therefore extra care is
259 required to make very sure they are equivalent).
260
261 .. __: https://pypy.org/posts/2024/08/toy-knownbits.html#cases-where-this-style-of-z3-proof-doesnt-work).
262
263 If that is too hard as well, it's possible to skip the proof of individual
264 rules by adding ``SORRY_Z3`` to its body (but we should try not to do that too
265 often)::
266
267 eq_different_knownbits: int_eq(x, y)
268 SORRY_Z3
269 check x.known_ne(y)
270 => 0
271
272 Checking for satisfiability
273 ===================================================
274
275 In addition to checking whether the rule yields a correct optimization, we also
276 check whether the rule can ever apply. This ensures that there are *some*
277 runtime values that would fulfil all the checks in a rule. Here's an example of
278 a rule violating this::
279
280 never_applies: int_is_true(x)
281 check x.known_lt_const(0) and x.known_gt_const(0) # impossible condition, always False
282 => x
283
284 Right now the error messages are not completely easy to understand, I hope to
285 improve this later::
286
287 Rule 'never_applies' cannot ever apply
288 in line 1
289 Z3 did not manage to find values for variables x such that the following condition becomes True:
290 And(x <= x_upper,
291 x_lower <= x,
292 If(x_upper < 0, x_lower > 0, x_upper < 0))
293
294 Adding new rules
295 ===================================================
296
297 To add new rules (ideally motivated by `observed problems in real traces`__),
298 the following steps should be performed:
299
300 .. __: https://pypy.org/posts/2024/07/mining-jit-traces-missing-optimizations-z3.html
301
302 - Add a failing test to ``test_optimizeintbound.py``.
303 - Add the rule to ``real.rules``.
304 - Regenerate the Python code by running ``pypy ruleopt/generate.py`` (you need
305 the ``z3-solver`` and ``rply`` packages installed for that).
306 - Check that ``test_optimizeintbound.py`` passes, then run the other
307 ``optimizeopt/`` tests (in particular ``optimizeopt/test/test_z3checktests.py``
308 checks that the operations and expected outputs `are sensible`__).
309
310 .. __: https://pypy.org/posts/2022/12/jit-bug-finding-smt-fuzzing.html
311
312
313 DSL Implementation Notes
314 ================================
315
316 The implementation of the DSL is done in a relatively ad-hoc manner. It is
317 parsed using `rply`__, there's a small type checker that tries to find common
318 problems in how the rules are written. Z3 is used via the Python API. The
319 pattern matching RPython code is generated using an approach inspired by Luc
320 Maranget's paper `Compiling Pattern Matching to Good Decision Trees`__, see
321 `this blog post`__ for an approachable introduction.
322
323 .. __: https://rply.readthedocs.io/
324 .. __: http://moscova.inria.fr/~maranget/papers/ml05e-maranget.pdf
325 .. __: https://compiler.club/compiling-pattern-matching/
326
327
328
329