Debian Codegraph @

src/asahi/compiler/agx_nir_algebraic.py

raw
1 # Copyright 2022 Alyssa Rosenzweig
2 # Copyright 2021 Collabora, Ltd.
3 # Copyright 2016 Intel Corporation
4 # SPDX-License-Identifier: MIT
5
6 import argparse
7 import sys
8 import math
9
10 a = 'a'
11 b = 'b'
12 c = 'c'
13 d = 'd'
14 e = 'e'
15
16 lower_sm5_shift = []
17
18 # Our shifts differ from SM5 for the upper bits. Mask to match the NIR
19 # behaviour. Because this happens as a late lowering, NIR won't optimize the
20 # masking back out (that happens in the main nir_opt_algebraic).
21 for s in [8, 16, 32, 64]:
22 for shift in ["ishl", "ishr", "ushr"]:
23 lower_sm5_shift += [((shift, f'a@{s}', b),
24 (shift, a, ('iand', b, s - 1)))]
25
26 lower_pack = [
27 (('pack_half_2x16_split', a, b),
28 ('pack_32_2x16_split', ('f2f16', a), ('f2f16', b))),
29
30 # We don't have 8-bit ALU, so we need to lower this. But if we lower it like
31 # this, we can at least coalesce the pack_32_2x16_split and only pay the
32 # cost of the iors and ishl. (u2u16 of 8-bit is assumed free.)
33 (('pack_32_4x8_split', a, b, c, d),
34 ('pack_32_2x16_split', ('ior', ('u2u16', a), ('ishl', ('u2u16', b), 8)),
35 ('ior', ('u2u16', c), ('ishl', ('u2u16', d), 8)))),
36
37 (('extract_u16', 'a@32', 0), ('u2u32', ('unpack_32_2x16_split_x', a))),
38 (('extract_u16', 'a@32', 1), ('u2u32', ('unpack_32_2x16_split_y', a))),
39 (('extract_i16', 'a@32', 0), ('i2i32', ('unpack_32_2x16_split_x', a))),
40 (('extract_i16', 'a@32', 1), ('i2i32', ('unpack_32_2x16_split_y', a))),
41
42 # For optimizing extract->convert sequences for unpack/pack norm
43 (('u2f32', ('u2u32', a)), ('u2f32', a)),
44 (('i2f32', ('i2i32', a)), ('i2f32', a)),
45
46 # Chew through some 8-bit before the backend has to deal with it
47 (('f2u8', a), ('u2u8', ('f2u16', a))),
48 (('f2i8', a), ('i2i8', ('f2i16', a))),
49
50 # Duplicated from nir_opt_algebraic since this pattern is generated by our
51 # bounds checking optimization which needs to run relatively late.
52 (('unpack_64_2x32_split_x', ('pack_64_2x32_split', a, b)), a),
53 (('unpack_64_2x32_split_y', ('pack_64_2x32_split', a, b)), b),
54
55 # Based on the VIR lowering
56 (('f2f16_rtz', 'a@32'),
57 ('bcsel', ('flt', ('fabs', a), ('fabs', ('f2f32', ('f2f16_rtne', a)))),
58 ('isub', ('f2f16_rtne', a), 1), ('f2f16_rtne', a))),
59
60 # These are based on the lowerings from nir_opt_algebraic, but conditioned
61 # on the number of bits not being constant. If the bit count is constant
62 # (the happy path) we can use our native instruction instead.
63 (('ibitfield_extract', 'value', 'offset', 'bits(is_not_const)'),
64 ('bcsel', ('ieq', 0, 'bits'),
65 0,
66 ('ishr',
67 ('ishl', 'value', ('isub', ('isub', 32, 'bits'), 'offset')),
68 ('isub', 32, 'bits')))),
69
70 (('ubitfield_extract', 'value', 'offset', 'bits(is_not_const)'),
71 ('iand',
72 ('ushr', 'value', 'offset'),
73 ('bcsel', ('ieq', 'bits', 32),
74 0xffffffff,
75 ('isub', ('ishl', 1, 'bits'), 1)))),
76
77 # Codegen depends on this trivial case being optimized out.
78 (('ubitfield_extract', 'value', 'offset', 0), 0),
79 (('ibitfield_extract', 'value', 'offset', 0), 0),
80
81 # At this point, bitfield extracts are constant. We can only do constant
82 # unsigned bitfield extract, so lower signed to unsigned + sign extend.
83 (('ibitfield_extract', a, b, '#bits'),
84 ('ishr', ('ishl', ('ubitfield_extract', a, b, 'bits'), ('isub', 32, 'bits')),
85 ('isub', 32, 'bits'))),
86 ]
87
88 lower_selects = []
89 for T, sizes, one in [('f', [16, 32], 1.0),
90 ('i', [8, 16, 32], 1),
91 ('b', [16, 32], -1)]:
92 for size in sizes:
93 lower_selects.extend([
94 ((f'b2{T}{size}', ('inot', 'a@1')), ('bcsel', a, 0, one)),
95 ((f'b2{T}{size}', 'a@1'), ('bcsel', a, one, 0)),
96 ])
97
98 # Rewriting bcsel(a || b, ...) in terms of bcsel(a, ...) and bcsel(b, ...) lets
99 # our rules to fuse compare-and-select do a better job, assuming that a and b
100 # are comparisons themselves.
101 #
102 # This needs to be a separate pass that runs after lower_selects, in order to
103 # pick up patterns like b2f32(iand(...))
104 opt_selects = [
105 (('bcsel', ('ior(is_used_once)', ('inot', a), b), c, d),
106 ('bcsel', a, ('bcsel', b, c, d), c)),
107
108 (('bcsel', ('ior(is_used_once)', a, b), c, d),
109 ('bcsel', a, c, ('bcsel', b, c, d))),
110
111 (('bcsel', ('iand(is_used_once)', ('inot', a), b), c, d),
112 ('bcsel', a, d, ('bcsel', b, c, d))),
113
114 (('bcsel', ('iand(is_used_once)', a, b), c, d),
115 ('bcsel', a, ('bcsel', b, c, d), d)),
116 ]
117
118 # When the ior/iand is used multiple times, we can instead fuse the other way.
119 opt_selects.extend([
120 (('iand', ('inot', 'a@1'), b), ('bcsel', a, False, b)),
121 (('iand', 'a@1', b), ('bcsel', a, b, False)),
122
123 (('ior', ('inot', 'a@1'), b), ('bcsel', a, b, True)),
124 (('ior', 'a@1', b), ('bcsel', a, True, b)),
125 ])
126
127 # Rewriting fneg to ixor costs a uniform but lets us CSE the bcsel if this is
128 # applied to a whole vector, hence the has_multiple_uses heuristic.
129 opt_selects.extend([
130 (('bcsel', 'a(has_multiple_uses)', ('fneg(is_used_once)', 'b@32'), b),
131 ('ixor', b, ('bcsel', a, 1 << 31, 0))),
132
133 (('bcsel', 'a(has_multiple_uses)', b, ('fneg(is_used_once)', 'b@32')),
134 ('ixor', b, ('bcsel', a, 0, 1 << 31))),
135 ])
136
137 fuse_extr = []
138 for start in range(32):
139 fuse_extr.extend([
140 (('ior', ('ushr', 'a@32', start), ('ishl', 'b@32', 32 - start)),
141 ('extr_agx', a, b, start, 0)),
142 ])
143
144 fuse_ubfe = []
145 for bits in range(1, 32):
146 fuse_ubfe.extend([
147 (('iand', ('ushr', 'a@32', b), (1 << bits) - 1),
148 ('ubitfield_extract', a, b, bits))
149 ])
150
151 # (x * y) + s = (x * y) + (s << 0)
152 def imad(x, y, z):
153 return ('imadshl_agx', x, y, z, 0)
154
155 # (x * y) - s = (x * y) - (s << 0)
156 def imsub(x, y, z):
157 return ('imsubshl_agx', x, y, z, 0)
158
159 # x + (y << s) = (x * 1) + (y << s)
160 def iaddshl(x, y, s):
161 return ('imadshl_agx', x, 1, y, s)
162
163 # x - (y << s) = (x * 1) - (y << s)
164 def isubshl(x, y, s):
165 return ('imsubshl_agx', x, 1, y, s)
166
167 fuse_imad = [
168 # Reassociate imul+iadd chain in order to fuse imads. This pattern comes up
169 # in compute shader lowering.
170 (('iadd', ('iadd(is_used_once)', ('imul(is_used_once)', a, b),
171 ('imul(is_used_once)', c, d)), e),
172 imad(a, b, imad(c, d, e))),
173
174 # Fuse regular imad
175 (('iadd', ('imul(is_used_once)', a, b), c), imad(a, b, c)),
176 (('isub', ('imul(is_used_once)', a, b), c), imsub(a, b, c)),
177 ]
178
179 for s in range(1, 5):
180 fuse_imad += [
181 # Definitions
182 (('iadd', a, ('ishl(is_used_once)', b, s)), iaddshl(a, b, s)),
183 (('isub', a, ('ishl(is_used_once)', b, s)), isubshl(a, b, s)),
184
185 # ineg(x) is 0 - x
186 (('ineg', ('ishl(is_used_once)', b, s)), isubshl(0, b, s)),
187
188 # Definitions
189 (imad(a, b, ('ishl(is_used_once)', c, s)), ('imadshl_agx', a, b, c, s)),
190 (imsub(a, b, ('ishl(is_used_once)', c, s)), ('imsubshl_agx', a, b, c, s)),
191
192 # The above but after the below shift lowering
193 (imad(a, b, ('imadshl_agx(is_used_once)', 0, 1, c, s)), ('imadshl_agx', a, b, c, s)),
194 (imsub(a, b, ('imadshl_agx(is_used_once)', 0, 1, c, s)), ('imsubshl_agx', a, b, c, s)),
195
196 # a + (a << s) = a + a * (1 << s) = a * (1 + (1 << s))
197 (('imul', a, 1 + (1 << s)), iaddshl(a, a, s)),
198
199 # a - (a << s) = a - a * (1 << s) = a * (1 - (1 << s))
200 (('imul', a, 1 - (1 << s)), isubshl(a, a, s)),
201
202 # a - (a << s) = a * (1 - (1 << s)) = -(a * (1 << s) - 1)
203 (('ineg', ('imul(is_used_once)', a, (1 << s) - 1)), isubshl(a, a, s)),
204
205 # iadd is SCIB, general shfit is IC (slower)
206 (('ishl', a, s), iaddshl(0, a, s)),
207 ]
208
209 # If the above rules failed, we have a large constant shift on the IC unit.
210 # Might as well fuse an add to form an imad, if we're on the IC anyway.
211 fuse_imad += [
212 (('iadd', a, ('ishl(is_used_once)', b, '#c')), imad(b, ('ishl', 1, c), a)),
213 ]
214
215 # Discard lowering generates this pattern, clean it up
216 ixor_bcsel = [
217 (('ixor', ('bcsel', a, '#b', '#c'), '#d'),
218 ('bcsel', a, ('ixor', b, d), ('ixor', c, d))),
219 ]
220
221 # The main NIR optimizer works on imul, not iadd. We need just enough patterns
222 # for amul to let us fuse lea.
223 cleanup_amul = [
224 # Neither operation overflows so we can keep the amul.
225 (('amul', ('amul', a, '#b'), '#c'), ('amul', a, ('imul', b, c))),
226
227 # Result of u2u64 has zero in upper half, so the shift doesn't overflow, so
228 # neither multiplication overflows.
229 (('amul', ('ishl', ('u2u64', 'a@32'), '#b(is_ult_32)'), '#c'),
230 ('amul', ('u2u64', a), ('ishl', c, b))),
231
232 # We depending on simplifying this.
233 (('iadd', a, 0), a),
234 ]
235
236 fuse_lea = []
237
238 # Handle 64-bit address arithmetic (OpenCL)
239 for s in range(1, 5):
240 pot = 1 << s
241
242 fuse_lea += [
243 # A + (#b + c) 2^s = (A + c 2^s) + #b 2^s
244 (('iadd', 'a@64', ('amul', pot, ('iadd', '#b(is_upper_half_zero)', ('u2u64', 'c@32')))),
245 ('ulea_agx', ('ulea_agx', a, c, s), ('u2u32', b), s)),
246
247 # A + (B + c) 2^s = (A + B 2^s) + c 2^s
248 (('iadd', 'a@64', ('amul', ('iadd', 'b@64', ('i2i64', 'c@32')), pot)),
249 ('ilea_agx', ('iadd', a, ('ishl', b, s)), c, s)),
250
251 # A + 2^s (B + (C + d)) = (A + (B + C)2^s) + d 2^s
252 (('iadd', 'a@64', ('amul', ('iadd', 'b@64',
253 ('iadd', 'c@64', ('u2u64', 'd@32'))), pot)),
254 ('ulea_agx', ('iadd', a, ('ishl', ('iadd', b, c), s)), d, s)),
255 ]
256
257 for sgn in ["u", "i"]:
258 upconv = f'{sgn}2{sgn}64'
259 lea = f'{sgn}lea_agx'
260
261 fuse_lea += [
262 # Basic pattern match
263 (('iadd', 'a@64', ('amul', (upconv, 'b@32'), pot)), (lea, a, b, s)),
264 (('iadd', 'a@64', ('ishl', (upconv, 'b@32'), s)), (lea, a, b, s)),
265 ]
266
267 # Handle relaxed 32-bit address arithmetic (OpenGL, Vulkan)
268 for s_ in range(1, 5):
269 # Iterate backwards
270 s = 5 - s_
271
272 v = 1 << s
273 is_mult = f'(is_unsigned_multiple_of_{v})'
274
275 fuse_lea += [
276 # A + b * s = A + B * s with relaxed multiply
277 (('iadd', 'a@64', ('u2u64', ('amul', 'b@32', v))),
278 ('ulea_agx', a, b, s)),
279
280 # A + (b * c 2^s) = A + (b * c) 2^s with relaxed multiply
281 (('iadd', 'a@64', ('u2u64', ('amul', 'b@32', f'#c{is_mult}'))),
282 ('ulea_agx', a, ('imul', b, ('ushr', c, s)), s)),
283
284 # A + (b 2^s + c d 2^s) = A + (b + cd) 2^s with relaxation.
285 #
286 # amul is bounded by the buffer size by definition, and both the GL & VK
287 # limit UBOs and SSBOs to INT32_MAX bytes. Therefore, amul has no signed
288 # wrap.
289 #
290 # Further, because we are zero-extending the 32-bit result, the 32-bit
291 # sum must be nonnegative -- if it were negative, it would represent an
292 # offset above INT32_MAX which would be invalid given the amul and
293 # max buffer size. Thus with signed math
294 #
295 # 0 <= b 2^s + cd 2^s < INT32_MAX
296 #
297 # ..and hence
298 #
299 # 0 <= b + cd < INT32_MAX
300 #
301 # Those bounds together with distributivity mean that
302 #
303 # (b 2^s + cd 2^s) mod 2^32 = 2^s ((b + cd) mod 2^32)
304 #
305 # ...which is exactly what we need to factor out the shift.
306 (('iadd', 'a@64', ('u2u64', ('iadd', f'#b{is_mult}',
307 ('amul', 'c@32', f'#d{is_mult}')))),
308 ('ulea_agx', a, ('iadd', ('ishr', b, s),
309 ('amul', 'c@32', ('ishr', d, s))), s)),
310 ]
311
312 # 8-bit rules are lowest precedence since we really like to fuse shifts
313 fuse_lea += [
314 (('iadd', a, ('u2u64', 'b@32')), ('ulea_agx', a, b, 0)),
315 (('iadd', a, ('i2i64', 'b@32')), ('ilea_agx', a, b, 0)),
316
317 (('iadd', a, ('iadd', ('u2u64', 'b@32'), c)),
318 ('ulea_agx', ('iadd', a, c), b, 0)),
319 (('iadd', a, ('iadd', ('i2i64', 'b@32'), c)),
320 ('ilea_agx', ('iadd', a, c), b, 0)),
321 ]
322
323 # After lowering address arithmetic, the various address arithmetic opcodes are
324 # no longer useful. Lower them to regular arithmetic to let nir_opt_algebraic
325 # take over.
326 lower_lea = [
327 (('amul', a, b), ('imul', a, b)),
328 (('ulea_agx', a, b, c), ('iadd', a, ('ishl', ('u2u64', b), c))),
329 (('ilea_agx', a, b, c), ('iadd', a, ('ishl', ('i2i64', b), c))),
330 ]
331
332 def main():
333 parser = argparse.ArgumentParser()
334 parser.add_argument('-p', '--import-path', required=True)
335 args = parser.parse_args()
336 sys.path.insert(0, args.import_path)
337 run()
338
339 def run():
340 import nir_algebraic # pylint: disable=import-error
341
342 print('#include "agx_nir.h"')
343
344 print(nir_algebraic.AlgebraicPass("agx_nir_cleanup_amul", cleanup_amul).render())
345 print(nir_algebraic.AlgebraicPass("agx_nir_fuse_lea", fuse_lea).render())
346 print(nir_algebraic.AlgebraicPass("agx_nir_lower_lea", lower_lea).render())
347
348 print(nir_algebraic.AlgebraicPass("agx_nir_lower_algebraic_late",
349 lower_sm5_shift + lower_pack +
350 lower_selects).render())
351 print(nir_algebraic.AlgebraicPass("agx_nir_fuse_selects",
352 opt_selects).render())
353 print(nir_algebraic.AlgebraicPass("agx_nir_fuse_algebraic_late",
354 fuse_extr + fuse_ubfe +
355 fuse_imad + ixor_bcsel).render())
356
357
358 if __name__ == '__main__':
359 main()