xref: /aosp_15_r20/external/mesa3d/src/compiler/nir/nir_range_analysis.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright © 2018 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 #include "nir_range_analysis.h"
24 #include <float.h>
25 #include <math.h>
26 #include "util/hash_table.h"
27 #include "util/u_dynarray.h"
28 #include "util/u_math.h"
29 #include "c99_alloca.h"
30 #include "nir.h"
31 
32 /**
33  * Analyzes a sequence of operations to determine some aspects of the range of
34  * the result.
35  */
36 
37 struct analysis_query {
38    uint32_t pushed_queries;
39    uint32_t result_index;
40 };
41 
42 struct analysis_state {
43    nir_shader *shader;
44    const nir_unsigned_upper_bound_config *config;
45    struct hash_table *range_ht;
46 
47    struct util_dynarray query_stack;
48    struct util_dynarray result_stack;
49 
50    size_t query_size;
51    uintptr_t (*get_key)(struct analysis_query *q);
52    void (*process_query)(struct analysis_state *state, struct analysis_query *q,
53                          uint32_t *result, const uint32_t *src);
54 };
55 
56 static void *
push_analysis_query(struct analysis_state * state,size_t size)57 push_analysis_query(struct analysis_state *state, size_t size)
58 {
59    struct analysis_query *q = util_dynarray_grow_bytes(&state->query_stack, 1, size);
60    q->pushed_queries = 0;
61    q->result_index = util_dynarray_num_elements(&state->result_stack, uint32_t);
62 
63    util_dynarray_append(&state->result_stack, uint32_t, 0);
64 
65    return q;
66 }
67 
68 /* Helper for performing range analysis without recursion. */
69 static uint32_t
perform_analysis(struct analysis_state * state)70 perform_analysis(struct analysis_state *state)
71 {
72    while (state->query_stack.size) {
73       struct analysis_query *cur =
74          (struct analysis_query *)((char *)util_dynarray_end(&state->query_stack) - state->query_size);
75       uint32_t *result = util_dynarray_element(&state->result_stack, uint32_t, cur->result_index);
76 
77       uintptr_t key = state->get_key(cur);
78       struct hash_entry *he = NULL;
79       /* There might be a cycle-resolving entry for loop header phis. Ignore this when finishing
80        * them by testing pushed_queries.
81        */
82       if (cur->pushed_queries == 0 && key &&
83           (he = _mesa_hash_table_search(state->range_ht, (void *)key))) {
84          *result = (uintptr_t)he->data;
85          state->query_stack.size -= state->query_size;
86          continue;
87       }
88 
89       uint32_t *src = (uint32_t *)util_dynarray_end(&state->result_stack) - cur->pushed_queries;
90       state->result_stack.size -= sizeof(uint32_t) * cur->pushed_queries;
91 
92       uint32_t prev_num_queries = state->query_stack.size;
93       state->process_query(state, cur, result, src);
94 
95       uint32_t num_queries = state->query_stack.size;
96       if (num_queries > prev_num_queries) {
97          cur = (struct analysis_query *)util_dynarray_element(&state->query_stack, char,
98                                                               prev_num_queries - state->query_size);
99          cur->pushed_queries = (num_queries - prev_num_queries) / state->query_size;
100          continue;
101       }
102 
103       if (key)
104          _mesa_hash_table_insert(state->range_ht, (void *)key, (void *)(uintptr_t)*result);
105 
106       state->query_stack.size -= state->query_size;
107    }
108 
109    assert(state->result_stack.size == sizeof(uint32_t));
110 
111    uint32_t res = util_dynarray_top(&state->result_stack, uint32_t);
112    util_dynarray_fini(&state->query_stack);
113    util_dynarray_fini(&state->result_stack);
114 
115    return res;
116 }
117 
118 static bool
is_not_negative(enum ssa_ranges r)119 is_not_negative(enum ssa_ranges r)
120 {
121    return r == gt_zero || r == ge_zero || r == eq_zero;
122 }
123 
124 static bool
is_not_zero(enum ssa_ranges r)125 is_not_zero(enum ssa_ranges r)
126 {
127    return r == gt_zero || r == lt_zero || r == ne_zero;
128 }
129 
130 static uint32_t
pack_data(const struct ssa_result_range r)131 pack_data(const struct ssa_result_range r)
132 {
133    return r.range | r.is_integral << 8 | r.is_finite << 9 | r.is_a_number << 10;
134 }
135 
136 static struct ssa_result_range
unpack_data(uint32_t v)137 unpack_data(uint32_t v)
138 {
139    return (struct ssa_result_range){
140       .range = v & 0xff,
141       .is_integral = (v & 0x00100) != 0,
142       .is_finite = (v & 0x00200) != 0,
143       .is_a_number = (v & 0x00400) != 0
144    };
145 }
146 
147 static nir_alu_type
nir_alu_src_type(const nir_alu_instr * instr,unsigned src)148 nir_alu_src_type(const nir_alu_instr *instr, unsigned src)
149 {
150    return nir_alu_type_get_base_type(nir_op_infos[instr->op].input_types[src]) |
151           nir_src_bit_size(instr->src[src].src);
152 }
153 
154 static struct ssa_result_range
analyze_constant(const struct nir_alu_instr * instr,unsigned src,nir_alu_type use_type)155 analyze_constant(const struct nir_alu_instr *instr, unsigned src,
156                  nir_alu_type use_type)
157 {
158    uint8_t swizzle[NIR_MAX_VEC_COMPONENTS] = { 0, 1, 2, 3,
159                                                4, 5, 6, 7,
160                                                8, 9, 10, 11,
161                                                12, 13, 14, 15 };
162 
163    /* If the source is an explicitly sized source, then we need to reset
164     * both the number of components and the swizzle.
165     */
166    const unsigned num_components = nir_ssa_alu_instr_src_components(instr, src);
167 
168    for (unsigned i = 0; i < num_components; ++i)
169       swizzle[i] = instr->src[src].swizzle[i];
170 
171    const nir_load_const_instr *const load =
172       nir_instr_as_load_const(instr->src[src].src.ssa->parent_instr);
173 
174    struct ssa_result_range r = { unknown, false, false, false };
175 
176    switch (nir_alu_type_get_base_type(use_type)) {
177    case nir_type_float: {
178       double min_value = NAN;
179       double max_value = NAN;
180       bool any_zero = false;
181       bool all_zero = true;
182 
183       r.is_integral = true;
184       r.is_a_number = true;
185       r.is_finite = true;
186 
187       for (unsigned i = 0; i < num_components; ++i) {
188          const double v = nir_const_value_as_float(load->value[swizzle[i]],
189                                                    load->def.bit_size);
190 
191          if (floor(v) != v)
192             r.is_integral = false;
193 
194          if (isnan(v))
195             r.is_a_number = false;
196 
197          if (!isfinite(v))
198             r.is_finite = false;
199 
200          any_zero = any_zero || (v == 0.0);
201          all_zero = all_zero && (v == 0.0);
202          min_value = fmin(min_value, v);
203          max_value = fmax(max_value, v);
204       }
205 
206       assert(any_zero >= all_zero);
207       assert(isnan(max_value) || max_value >= min_value);
208 
209       if (all_zero)
210          r.range = eq_zero;
211       else if (min_value > 0.0)
212          r.range = gt_zero;
213       else if (min_value == 0.0)
214          r.range = ge_zero;
215       else if (max_value < 0.0)
216          r.range = lt_zero;
217       else if (max_value == 0.0)
218          r.range = le_zero;
219       else if (!any_zero)
220          r.range = ne_zero;
221       else
222          r.range = unknown;
223 
224       return r;
225    }
226 
227    case nir_type_int:
228    case nir_type_bool: {
229       int64_t min_value = INT_MAX;
230       int64_t max_value = INT_MIN;
231       bool any_zero = false;
232       bool all_zero = true;
233 
234       for (unsigned i = 0; i < num_components; ++i) {
235          const int64_t v = nir_const_value_as_int(load->value[swizzle[i]],
236                                                   load->def.bit_size);
237 
238          any_zero = any_zero || (v == 0);
239          all_zero = all_zero && (v == 0);
240          min_value = MIN2(min_value, v);
241          max_value = MAX2(max_value, v);
242       }
243 
244       assert(any_zero >= all_zero);
245       assert(max_value >= min_value);
246 
247       if (all_zero)
248          r.range = eq_zero;
249       else if (min_value > 0)
250          r.range = gt_zero;
251       else if (min_value == 0)
252          r.range = ge_zero;
253       else if (max_value < 0)
254          r.range = lt_zero;
255       else if (max_value == 0)
256          r.range = le_zero;
257       else if (!any_zero)
258          r.range = ne_zero;
259       else
260          r.range = unknown;
261 
262       return r;
263    }
264 
265    case nir_type_uint: {
266       bool any_zero = false;
267       bool all_zero = true;
268 
269       for (unsigned i = 0; i < num_components; ++i) {
270          const uint64_t v = nir_const_value_as_uint(load->value[swizzle[i]],
271                                                     load->def.bit_size);
272 
273          any_zero = any_zero || (v == 0);
274          all_zero = all_zero && (v == 0);
275       }
276 
277       assert(any_zero >= all_zero);
278 
279       if (all_zero)
280          r.range = eq_zero;
281       else if (any_zero)
282          r.range = ge_zero;
283       else
284          r.range = gt_zero;
285 
286       return r;
287    }
288 
289    default:
290       unreachable("Invalid alu source type");
291    }
292 }
293 
294 /**
295  * Short-hand name for use in the tables in process_fp_query.  If this name
296  * becomes a problem on some compiler, we can change it to _.
297  */
298 #define _______ unknown
299 
300 #if defined(__clang__)
301 /* clang wants _Pragma("unroll X") */
302 #define pragma_unroll_5 _Pragma("unroll 5")
303 #define pragma_unroll_7 _Pragma("unroll 7")
304 /* gcc wants _Pragma("GCC unroll X") */
305 #elif defined(__GNUC__)
306 #if __GNUC__ >= 8
307 #define pragma_unroll_5 _Pragma("GCC unroll 5")
308 #define pragma_unroll_7 _Pragma("GCC unroll 7")
309 #else
310 #pragma GCC optimize("unroll-loops")
311 #define pragma_unroll_5
312 #define pragma_unroll_7
313 #endif
314 #else
315 /* MSVC doesn't have C99's _Pragma() */
316 #define pragma_unroll_5
317 #define pragma_unroll_7
318 #endif
319 
320 #ifndef NDEBUG
321 #define ASSERT_TABLE_IS_COMMUTATIVE(t)                                      \
322    do {                                                                     \
323       static bool first = true;                                             \
324       if (first) {                                                          \
325          first = false;                                                     \
326          pragma_unroll_7 for (unsigned r = 0; r < ARRAY_SIZE(t); r++)       \
327          {                                                                  \
328             pragma_unroll_7 for (unsigned c = 0; c < ARRAY_SIZE(t[0]); c++) \
329                assert(t[r][c] == t[c][r]);                                  \
330          }                                                                  \
331       }                                                                     \
332    } while (false)
333 
334 #define ASSERT_TABLE_IS_DIAGONAL(t)                                   \
335    do {                                                               \
336       static bool first = true;                                       \
337       if (first) {                                                    \
338          first = false;                                               \
339          pragma_unroll_7 for (unsigned r = 0; r < ARRAY_SIZE(t); r++) \
340             assert(t[r][r] == r);                                     \
341       }                                                               \
342    } while (false)
343 
344 #else
345 #define ASSERT_TABLE_IS_COMMUTATIVE(t)
346 #define ASSERT_TABLE_IS_DIAGONAL(t)
347 #endif /* !defined(NDEBUG) */
348 
349 static enum ssa_ranges
union_ranges(enum ssa_ranges a,enum ssa_ranges b)350 union_ranges(enum ssa_ranges a, enum ssa_ranges b)
351 {
352    static const enum ssa_ranges union_table[last_range + 1][last_range + 1] = {
353       /* left\right   unknown  lt_zero  le_zero  gt_zero  ge_zero  ne_zero  eq_zero */
354       /* unknown */ { _______, _______, _______, _______, _______, _______, _______ },
355       /* lt_zero */ { _______, lt_zero, le_zero, ne_zero, _______, ne_zero, le_zero },
356       /* le_zero */ { _______, le_zero, le_zero, _______, _______, _______, le_zero },
357       /* gt_zero */ { _______, ne_zero, _______, gt_zero, ge_zero, ne_zero, ge_zero },
358       /* ge_zero */ { _______, _______, _______, ge_zero, ge_zero, _______, ge_zero },
359       /* ne_zero */ { _______, ne_zero, _______, ne_zero, _______, ne_zero, _______ },
360       /* eq_zero */ { _______, le_zero, le_zero, ge_zero, ge_zero, _______, eq_zero },
361    };
362 
363    ASSERT_TABLE_IS_COMMUTATIVE(union_table);
364    ASSERT_TABLE_IS_DIAGONAL(union_table);
365 
366    return union_table[a][b];
367 }
368 
369 #ifndef NDEBUG
370 /* Verify that the 'unknown' entry in each row (or column) of the table is the
371  * union of all the other values in the row (or column).
372  */
373 #define ASSERT_UNION_OF_OTHERS_MATCHES_UNKNOWN_2_SOURCE(t)                      \
374    do {                                                                         \
375       static bool first = true;                                                 \
376       if (first) {                                                              \
377          first = false;                                                         \
378          pragma_unroll_7 for (unsigned i = 0; i < last_range; i++)              \
379          {                                                                      \
380             enum ssa_ranges col_range = t[i][unknown + 1];                      \
381             enum ssa_ranges row_range = t[unknown + 1][i];                      \
382                                                                                 \
383             pragma_unroll_5 for (unsigned j = unknown + 2; j < last_range; j++) \
384             {                                                                   \
385                col_range = union_ranges(col_range, t[i][j]);                    \
386                row_range = union_ranges(row_range, t[j][i]);                    \
387             }                                                                   \
388                                                                                 \
389             assert(col_range == t[i][unknown]);                                 \
390             assert(row_range == t[unknown][i]);                                 \
391          }                                                                      \
392       }                                                                         \
393    } while (false)
394 
395 /* For most operations, the union of ranges for a strict inequality and
396  * equality should be the range of the non-strict inequality (e.g.,
397  * union_ranges(range(op(lt_zero), range(op(eq_zero))) == range(op(le_zero)).
398  *
399  * Does not apply to selection-like opcodes (bcsel, fmin, fmax, etc.).
400  */
401 #define ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_1_SOURCE(t) \
402    do {                                                                  \
403       assert(union_ranges(t[lt_zero], t[eq_zero]) == t[le_zero]);        \
404       assert(union_ranges(t[gt_zero], t[eq_zero]) == t[ge_zero]);        \
405    } while (false)
406 
407 #define ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_2_SOURCE(t)         \
408    do {                                                                          \
409       static bool first = true;                                                  \
410       if (first) {                                                               \
411          first = false;                                                          \
412          pragma_unroll_7 for (unsigned i = 0; i < last_range; i++)               \
413          {                                                                       \
414             assert(union_ranges(t[i][lt_zero], t[i][eq_zero]) == t[i][le_zero]); \
415             assert(union_ranges(t[i][gt_zero], t[i][eq_zero]) == t[i][ge_zero]); \
416             assert(union_ranges(t[lt_zero][i], t[eq_zero][i]) == t[le_zero][i]); \
417             assert(union_ranges(t[gt_zero][i], t[eq_zero][i]) == t[ge_zero][i]); \
418          }                                                                       \
419       }                                                                          \
420    } while (false)
421 
422 /* Several other unordered tuples span the range of "everything."  Each should
423  * have the same value as unknown: (lt_zero, ge_zero), (le_zero, gt_zero), and
424  * (eq_zero, ne_zero).  union_ranges is already commutative, so only one
425  * ordering needs to be checked.
426  *
427  * Does not apply to selection-like opcodes (bcsel, fmin, fmax, etc.).
428  *
429  * In cases where this can be used, it is unnecessary to also use
430  * ASSERT_UNION_OF_OTHERS_MATCHES_UNKNOWN_*_SOURCE.  For any range X,
431  * union_ranges(X, X) == X.  The disjoint ranges cover all of the non-unknown
432  * possibilities, so the union of all the unions of disjoint ranges is
433  * equivalent to the union of "others."
434  */
435 #define ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_1_SOURCE(t)      \
436    do {                                                           \
437       assert(union_ranges(t[lt_zero], t[ge_zero]) == t[unknown]); \
438       assert(union_ranges(t[le_zero], t[gt_zero]) == t[unknown]); \
439       assert(union_ranges(t[eq_zero], t[ne_zero]) == t[unknown]); \
440    } while (false)
441 
442 #define ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_2_SOURCE(t)       \
443    do {                                                            \
444       static bool first = true;                                    \
445       if (first) {                                                 \
446          first = false;                                            \
447          pragma_unroll_7 for (unsigned i = 0; i < last_range; i++) \
448          {                                                         \
449             assert(union_ranges(t[i][lt_zero], t[i][ge_zero]) ==   \
450                    t[i][unknown]);                                 \
451             assert(union_ranges(t[i][le_zero], t[i][gt_zero]) ==   \
452                    t[i][unknown]);                                 \
453             assert(union_ranges(t[i][eq_zero], t[i][ne_zero]) ==   \
454                    t[i][unknown]);                                 \
455                                                                    \
456             assert(union_ranges(t[lt_zero][i], t[ge_zero][i]) ==   \
457                    t[unknown][i]);                                 \
458             assert(union_ranges(t[le_zero][i], t[gt_zero][i]) ==   \
459                    t[unknown][i]);                                 \
460             assert(union_ranges(t[eq_zero][i], t[ne_zero][i]) ==   \
461                    t[unknown][i]);                                 \
462          }                                                         \
463       }                                                            \
464    } while (false)
465 
466 #else
467 #define ASSERT_UNION_OF_OTHERS_MATCHES_UNKNOWN_2_SOURCE(t)
468 #define ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_1_SOURCE(t)
469 #define ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_2_SOURCE(t)
470 #define ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_1_SOURCE(t)
471 #define ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_2_SOURCE(t)
472 #endif /* !defined(NDEBUG) */
473 
474 struct fp_query {
475    struct analysis_query head;
476    const nir_alu_instr *instr;
477    unsigned src;
478    nir_alu_type use_type;
479 };
480 
481 static void
push_fp_query(struct analysis_state * state,const nir_alu_instr * alu,unsigned src,nir_alu_type type)482 push_fp_query(struct analysis_state *state, const nir_alu_instr *alu, unsigned src, nir_alu_type type)
483 {
484    struct fp_query *pushed_q = push_analysis_query(state, sizeof(struct fp_query));
485    pushed_q->instr = alu;
486    pushed_q->src = src;
487    pushed_q->use_type = type == nir_type_invalid ? nir_alu_src_type(alu, src) : type;
488 }
489 
490 static uintptr_t
get_fp_key(struct analysis_query * q)491 get_fp_key(struct analysis_query *q)
492 {
493    struct fp_query *fp_q = (struct fp_query *)q;
494    const nir_src *src = &fp_q->instr->src[fp_q->src].src;
495 
496    if (src->ssa->parent_instr->type != nir_instr_type_alu)
497       return 0;
498 
499    uintptr_t type_encoding;
500    uintptr_t ptr = (uintptr_t)nir_instr_as_alu(src->ssa->parent_instr);
501 
502    /* The low 2 bits have to be zero or this whole scheme falls apart. */
503    assert((ptr & 0x3) == 0);
504 
505    /* NIR is typeless in the sense that sequences of bits have whatever
506     * meaning is attached to them by the instruction that consumes them.
507     * However, the number of bits must match between producer and consumer.
508     * As a result, the number of bits does not need to be encoded here.
509     */
510    switch (nir_alu_type_get_base_type(fp_q->use_type)) {
511    case nir_type_int:
512       type_encoding = 0;
513       break;
514    case nir_type_uint:
515       type_encoding = 1;
516       break;
517    case nir_type_bool:
518       type_encoding = 2;
519       break;
520    case nir_type_float:
521       type_encoding = 3;
522       break;
523    default:
524       unreachable("Invalid base type.");
525    }
526 
527    return ptr | type_encoding;
528 }
529 
530 /**
531  * Analyze an expression to determine the range of its result
532  *
533  * The end result of this analysis is a token that communicates something
534  * about the range of values.  There's an implicit grammar that produces
535  * tokens from sequences of literal values, other tokens, and operations.
536  * This function implements this grammar as a recursive-descent parser.  Some
537  * (but not all) of the grammar is listed in-line in the function.
538  */
539 static void
process_fp_query(struct analysis_state * state,struct analysis_query * aq,uint32_t * result,const uint32_t * src_res)540 process_fp_query(struct analysis_state *state, struct analysis_query *aq, uint32_t *result,
541                  const uint32_t *src_res)
542 {
543    /* Ensure that the _Pragma("GCC unroll 7") above are correct. */
544    STATIC_ASSERT(last_range + 1 == 7);
545 
546    struct fp_query q = *(struct fp_query *)aq;
547    const nir_alu_instr *instr = q.instr;
548    unsigned src = q.src;
549    nir_alu_type use_type = q.use_type;
550 
551    if (nir_src_is_const(instr->src[src].src)) {
552       *result = pack_data(analyze_constant(instr, src, use_type));
553       return;
554    }
555 
556    if (instr->src[src].src.ssa->parent_instr->type != nir_instr_type_alu) {
557       *result = pack_data((struct ssa_result_range){ unknown, false, false, false });
558       return;
559    }
560 
561    const struct nir_alu_instr *const alu =
562       nir_instr_as_alu(instr->src[src].src.ssa->parent_instr);
563 
564    /* Bail if the type of the instruction generating the value does not match
565     * the type the value will be interpreted as.  int/uint/bool can be
566     * reinterpreted trivially.  The most important cases are between float and
567     * non-float.
568     */
569    if (alu->op != nir_op_mov && alu->op != nir_op_bcsel) {
570       const nir_alu_type use_base_type =
571          nir_alu_type_get_base_type(use_type);
572       const nir_alu_type src_base_type =
573          nir_alu_type_get_base_type(nir_op_infos[alu->op].output_type);
574 
575       if (use_base_type != src_base_type &&
576           (use_base_type == nir_type_float ||
577            src_base_type == nir_type_float)) {
578          *result = pack_data((struct ssa_result_range){ unknown, false, false, false });
579          return;
580       }
581    }
582 
583    if (!aq->pushed_queries) {
584       switch (alu->op) {
585       case nir_op_bcsel:
586          push_fp_query(state, alu, 1, use_type);
587          push_fp_query(state, alu, 2, use_type);
588          return;
589       case nir_op_mov:
590          push_fp_query(state, alu, 0, use_type);
591          return;
592       case nir_op_i2f32:
593       case nir_op_u2f32:
594       case nir_op_fabs:
595       case nir_op_fexp2:
596       case nir_op_frcp:
597       case nir_op_fneg:
598       case nir_op_fsat:
599       case nir_op_fsign:
600       case nir_op_ffloor:
601       case nir_op_fceil:
602       case nir_op_ftrunc:
603       case nir_op_fdot2:
604       case nir_op_fdot3:
605       case nir_op_fdot4:
606       case nir_op_fdot8:
607       case nir_op_fdot16:
608       case nir_op_fdot2_replicated:
609       case nir_op_fdot3_replicated:
610       case nir_op_fdot4_replicated:
611       case nir_op_fdot8_replicated:
612       case nir_op_fdot16_replicated:
613          push_fp_query(state, alu, 0, nir_type_invalid);
614          return;
615       case nir_op_fadd:
616       case nir_op_fmax:
617       case nir_op_fmin:
618       case nir_op_fmul:
619       case nir_op_fmulz:
620       case nir_op_fpow:
621          push_fp_query(state, alu, 0, nir_type_invalid);
622          push_fp_query(state, alu, 1, nir_type_invalid);
623          return;
624       case nir_op_ffma:
625       case nir_op_flrp:
626          push_fp_query(state, alu, 0, nir_type_invalid);
627          push_fp_query(state, alu, 1, nir_type_invalid);
628          push_fp_query(state, alu, 2, nir_type_invalid);
629          return;
630       default:
631          break;
632       }
633    }
634 
635    struct ssa_result_range r = { unknown, false, false, false };
636 
637    /* ge_zero: ge_zero + ge_zero
638     *
639     * gt_zero: gt_zero + eq_zero
640     *        | gt_zero + ge_zero
641     *        | eq_zero + gt_zero   # Addition is commutative
642     *        | ge_zero + gt_zero   # Addition is commutative
643     *        | gt_zero + gt_zero
644     *        ;
645     *
646     * le_zero: le_zero + le_zero
647     *
648     * lt_zero: lt_zero + eq_zero
649     *        | lt_zero + le_zero
650     *        | eq_zero + lt_zero   # Addition is commutative
651     *        | le_zero + lt_zero   # Addition is commutative
652     *        | lt_zero + lt_zero
653     *        ;
654     *
655     * ne_zero: eq_zero + ne_zero
656     *        | ne_zero + eq_zero   # Addition is commutative
657     *        ;
658     *
659     * eq_zero: eq_zero + eq_zero
660     *        ;
661     *
662     * All other cases are 'unknown'.  The seeming odd entry is (ne_zero,
663     * ne_zero), but that could be (-5, +5) which is not ne_zero.
664     */
665    static const enum ssa_ranges fadd_table[last_range + 1][last_range + 1] = {
666       /* left\right   unknown  lt_zero  le_zero  gt_zero  ge_zero  ne_zero  eq_zero */
667       /* unknown */ { _______, _______, _______, _______, _______, _______, _______ },
668       /* lt_zero */ { _______, lt_zero, lt_zero, _______, _______, _______, lt_zero },
669       /* le_zero */ { _______, lt_zero, le_zero, _______, _______, _______, le_zero },
670       /* gt_zero */ { _______, _______, _______, gt_zero, gt_zero, _______, gt_zero },
671       /* ge_zero */ { _______, _______, _______, gt_zero, ge_zero, _______, ge_zero },
672       /* ne_zero */ { _______, _______, _______, _______, _______, _______, ne_zero },
673       /* eq_zero */ { _______, lt_zero, le_zero, gt_zero, ge_zero, ne_zero, eq_zero },
674    };
675 
676    ASSERT_TABLE_IS_COMMUTATIVE(fadd_table);
677    ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_2_SOURCE(fadd_table);
678    ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_2_SOURCE(fadd_table);
679 
680    /* Due to flush-to-zero semanatics of floating-point numbers with very
681     * small mangnitudes, we can never really be sure a result will be
682     * non-zero.
683     *
684     * ge_zero: ge_zero * ge_zero
685     *        | ge_zero * gt_zero
686     *        | ge_zero * eq_zero
687     *        | le_zero * lt_zero
688     *        | lt_zero * le_zero  # Multiplication is commutative
689     *        | le_zero * le_zero
690     *        | gt_zero * ge_zero  # Multiplication is commutative
691     *        | eq_zero * ge_zero  # Multiplication is commutative
692     *        | a * a              # Left source == right source
693     *        | gt_zero * gt_zero
694     *        | lt_zero * lt_zero
695     *        ;
696     *
697     * le_zero: ge_zero * le_zero
698     *        | ge_zero * lt_zero
699     *        | lt_zero * ge_zero  # Multiplication is commutative
700     *        | le_zero * ge_zero  # Multiplication is commutative
701     *        | le_zero * gt_zero
702     *        | lt_zero * gt_zero
703     *        | gt_zero * lt_zero  # Multiplication is commutative
704     *        ;
705     *
706     * eq_zero: eq_zero * <any>
707     *          <any> * eq_zero    # Multiplication is commutative
708     *
709     * All other cases are 'unknown'.
710     */
711    static const enum ssa_ranges fmul_table[last_range + 1][last_range + 1] = {
712       /* left\right   unknown  lt_zero  le_zero  gt_zero  ge_zero  ne_zero  eq_zero */
713       /* unknown */ { _______, _______, _______, _______, _______, _______, eq_zero },
714       /* lt_zero */ { _______, ge_zero, ge_zero, le_zero, le_zero, _______, eq_zero },
715       /* le_zero */ { _______, ge_zero, ge_zero, le_zero, le_zero, _______, eq_zero },
716       /* gt_zero */ { _______, le_zero, le_zero, ge_zero, ge_zero, _______, eq_zero },
717       /* ge_zero */ { _______, le_zero, le_zero, ge_zero, ge_zero, _______, eq_zero },
718       /* ne_zero */ { _______, _______, _______, _______, _______, _______, eq_zero },
719       /* eq_zero */ { eq_zero, eq_zero, eq_zero, eq_zero, eq_zero, eq_zero, eq_zero }
720    };
721 
722    ASSERT_TABLE_IS_COMMUTATIVE(fmul_table);
723    ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_2_SOURCE(fmul_table);
724    ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_2_SOURCE(fmul_table);
725 
726    static const enum ssa_ranges fneg_table[last_range + 1] = {
727       /* unknown  lt_zero  le_zero  gt_zero  ge_zero  ne_zero  eq_zero */
728       _______, gt_zero, ge_zero, lt_zero, le_zero, ne_zero, eq_zero
729    };
730 
731    ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_1_SOURCE(fneg_table);
732    ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_1_SOURCE(fneg_table);
733 
734    switch (alu->op) {
735    case nir_op_b2f32:
736    case nir_op_b2i32:
737       /* b2f32 will generate either 0.0 or 1.0.  This case is trivial.
738        *
739        * b2i32 will generate either 0x00000000 or 0x00000001.  When those bit
740        * patterns are interpreted as floating point, they are 0.0 and
741        * 1.401298464324817e-45.  The latter is subnormal, but it is finite and
742        * a number.
743        */
744       r = (struct ssa_result_range){ ge_zero, alu->op == nir_op_b2f32, true, true };
745       break;
746 
747    case nir_op_bcsel: {
748       const struct ssa_result_range left = unpack_data(src_res[0]);
749       const struct ssa_result_range right = unpack_data(src_res[1]);
750 
751       r.is_integral = left.is_integral && right.is_integral;
752 
753       /* This could be better, but it would require a lot of work.  For
754        * example, the result of the following is a number:
755        *
756        *    bcsel(a > 0.0, a, 38.6)
757        *
758        * If the result of 'a > 0.0' is true, then the use of 'a' in the true
759        * part of the bcsel must be a number.
760        *
761        * Other cases are even more challenging.
762        *
763        *    bcsel(a > 0.5, a - 0.5, 0.0)
764        */
765       r.is_a_number = left.is_a_number && right.is_a_number;
766       r.is_finite = left.is_finite && right.is_finite;
767 
768       r.range = union_ranges(left.range, right.range);
769       break;
770    }
771 
772    case nir_op_i2f32:
773    case nir_op_u2f32:
774       r = unpack_data(src_res[0]);
775 
776       r.is_integral = true;
777       r.is_a_number = true;
778       r.is_finite = true;
779 
780       if (r.range == unknown && alu->op == nir_op_u2f32)
781          r.range = ge_zero;
782 
783       break;
784 
785    case nir_op_fabs:
786       r = unpack_data(src_res[0]);
787 
788       switch (r.range) {
789       case unknown:
790       case le_zero:
791       case ge_zero:
792          r.range = ge_zero;
793          break;
794 
795       case lt_zero:
796       case gt_zero:
797       case ne_zero:
798          r.range = gt_zero;
799          break;
800 
801       case eq_zero:
802          break;
803       }
804 
805       break;
806 
807    case nir_op_fadd: {
808       const struct ssa_result_range left = unpack_data(src_res[0]);
809       const struct ssa_result_range right = unpack_data(src_res[1]);
810 
811       r.is_integral = left.is_integral && right.is_integral;
812       r.range = fadd_table[left.range][right.range];
813 
814       /* X + Y is NaN if either operand is NaN or if one operand is +Inf and
815        * the other is -Inf.  If neither operand is NaN and at least one of the
816        * operands is finite, then the result cannot be NaN.
817        */
818       r.is_a_number = left.is_a_number && right.is_a_number &&
819                       (left.is_finite || right.is_finite);
820       break;
821    }
822 
823    case nir_op_fexp2: {
824       /* If the parameter might be less than zero, the mathematically result
825        * will be on (0, 1).  For sufficiently large magnitude negative
826        * parameters, the result will flush to zero.
827        */
828       static const enum ssa_ranges table[last_range + 1] = {
829          /* unknown  lt_zero  le_zero  gt_zero  ge_zero  ne_zero  eq_zero */
830          ge_zero, ge_zero, ge_zero, gt_zero, gt_zero, ge_zero, gt_zero
831       };
832 
833       r = unpack_data(src_res[0]);
834 
835       ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_1_SOURCE(table);
836       ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_1_SOURCE(table);
837 
838       r.is_integral = r.is_integral && is_not_negative(r.range);
839       r.range = table[r.range];
840 
841       /* Various cases can result in NaN, so assume the worst. */
842       r.is_finite = false;
843       r.is_a_number = false;
844       break;
845    }
846 
847    case nir_op_fmax: {
848       const struct ssa_result_range left = unpack_data(src_res[0]);
849       const struct ssa_result_range right = unpack_data(src_res[1]);
850 
851       r.is_integral = left.is_integral && right.is_integral;
852 
853       /* This is conservative.  It may be possible to determine that the
854        * result must be finite in more cases, but it would take some effort to
855        * work out all the corners.  For example, fmax({lt_zero, finite},
856        * {lt_zero}) should result in {lt_zero, finite}.
857        */
858       r.is_finite = left.is_finite && right.is_finite;
859 
860       /* If one source is NaN, fmax always picks the other source. */
861       r.is_a_number = left.is_a_number || right.is_a_number;
862 
863       /* gt_zero: fmax(gt_zero, *)
864        *        | fmax(*, gt_zero)        # Treat fmax as commutative
865        *        ;
866        *
867        * ge_zero: fmax(ge_zero, ne_zero)
868        *        | fmax(ge_zero, lt_zero)
869        *        | fmax(ge_zero, le_zero)
870        *        | fmax(ge_zero, eq_zero)
871        *        | fmax(ne_zero, ge_zero)  # Treat fmax as commutative
872        *        | fmax(lt_zero, ge_zero)  # Treat fmax as commutative
873        *        | fmax(le_zero, ge_zero)  # Treat fmax as commutative
874        *        | fmax(eq_zero, ge_zero)  # Treat fmax as commutative
875        *        | fmax(ge_zero, ge_zero)
876        *        ;
877        *
878        * le_zero: fmax(le_zero, lt_zero)
879        *        | fmax(lt_zero, le_zero)  # Treat fmax as commutative
880        *        | fmax(le_zero, le_zero)
881        *        ;
882        *
883        * lt_zero: fmax(lt_zero, lt_zero)
884        *        ;
885        *
886        * ne_zero: fmax(ne_zero, lt_zero)
887        *        | fmax(lt_zero, ne_zero)  # Treat fmax as commutative
888        *        | fmax(ne_zero, ne_zero)
889        *        ;
890        *
891        * eq_zero: fmax(eq_zero, le_zero)
892        *        | fmax(eq_zero, lt_zero)
893        *        | fmax(le_zero, eq_zero)  # Treat fmax as commutative
894        *        | fmax(lt_zero, eq_zero)  # Treat fmax as commutative
895        *        | fmax(eq_zero, eq_zero)
896        *        ;
897        *
898        * All other cases are 'unknown'.
899        */
900       static const enum ssa_ranges table[last_range + 1][last_range + 1] = {
901          /* left\right   unknown  lt_zero  le_zero  gt_zero  ge_zero  ne_zero  eq_zero */
902          /* unknown */ { _______, _______, _______, gt_zero, ge_zero, _______, ge_zero },
903          /* lt_zero */ { _______, lt_zero, le_zero, gt_zero, ge_zero, ne_zero, eq_zero },
904          /* le_zero */ { _______, le_zero, le_zero, gt_zero, ge_zero, _______, eq_zero },
905          /* gt_zero */ { gt_zero, gt_zero, gt_zero, gt_zero, gt_zero, gt_zero, gt_zero },
906          /* ge_zero */ { ge_zero, ge_zero, ge_zero, gt_zero, ge_zero, ge_zero, ge_zero },
907          /* ne_zero */ { _______, ne_zero, _______, gt_zero, ge_zero, ne_zero, ge_zero },
908          /* eq_zero */ { ge_zero, eq_zero, eq_zero, gt_zero, ge_zero, ge_zero, eq_zero }
909       };
910 
911       /* Treat fmax as commutative. */
912       ASSERT_TABLE_IS_COMMUTATIVE(table);
913       ASSERT_TABLE_IS_DIAGONAL(table);
914       ASSERT_UNION_OF_OTHERS_MATCHES_UNKNOWN_2_SOURCE(table);
915 
916       r.range = table[left.range][right.range];
917 
918       /* Recall that when either value is NaN, fmax will pick the other value.
919        * This means the result range of the fmax will either be the "ideal"
920        * result range (calculated above) or the range of the non-NaN value.
921        */
922       if (!left.is_a_number)
923          r.range = union_ranges(r.range, right.range);
924 
925       if (!right.is_a_number)
926          r.range = union_ranges(r.range, left.range);
927 
928       break;
929    }
930 
931    case nir_op_fmin: {
932       const struct ssa_result_range left = unpack_data(src_res[0]);
933       const struct ssa_result_range right = unpack_data(src_res[1]);
934 
935       r.is_integral = left.is_integral && right.is_integral;
936 
937       /* This is conservative.  It may be possible to determine that the
938        * result must be finite in more cases, but it would take some effort to
939        * work out all the corners.  For example, fmin({gt_zero, finite},
940        * {gt_zero}) should result in {gt_zero, finite}.
941        */
942       r.is_finite = left.is_finite && right.is_finite;
943 
944       /* If one source is NaN, fmin always picks the other source. */
945       r.is_a_number = left.is_a_number || right.is_a_number;
946 
947       /* lt_zero: fmin(lt_zero, *)
948        *        | fmin(*, lt_zero)        # Treat fmin as commutative
949        *        ;
950        *
951        * le_zero: fmin(le_zero, ne_zero)
952        *        | fmin(le_zero, gt_zero)
953        *        | fmin(le_zero, ge_zero)
954        *        | fmin(le_zero, eq_zero)
955        *        | fmin(ne_zero, le_zero)  # Treat fmin as commutative
956        *        | fmin(gt_zero, le_zero)  # Treat fmin as commutative
957        *        | fmin(ge_zero, le_zero)  # Treat fmin as commutative
958        *        | fmin(eq_zero, le_zero)  # Treat fmin as commutative
959        *        | fmin(le_zero, le_zero)
960        *        ;
961        *
962        * ge_zero: fmin(ge_zero, gt_zero)
963        *        | fmin(gt_zero, ge_zero)  # Treat fmin as commutative
964        *        | fmin(ge_zero, ge_zero)
965        *        ;
966        *
967        * gt_zero: fmin(gt_zero, gt_zero)
968        *        ;
969        *
970        * ne_zero: fmin(ne_zero, gt_zero)
971        *        | fmin(gt_zero, ne_zero)  # Treat fmin as commutative
972        *        | fmin(ne_zero, ne_zero)
973        *        ;
974        *
975        * eq_zero: fmin(eq_zero, ge_zero)
976        *        | fmin(eq_zero, gt_zero)
977        *        | fmin(ge_zero, eq_zero)  # Treat fmin as commutative
978        *        | fmin(gt_zero, eq_zero)  # Treat fmin as commutative
979        *        | fmin(eq_zero, eq_zero)
980        *        ;
981        *
982        * All other cases are 'unknown'.
983        */
984       static const enum ssa_ranges table[last_range + 1][last_range + 1] = {
985          /* left\right   unknown  lt_zero  le_zero  gt_zero  ge_zero  ne_zero  eq_zero */
986          /* unknown */ { _______, lt_zero, le_zero, _______, _______, _______, le_zero },
987          /* lt_zero */ { lt_zero, lt_zero, lt_zero, lt_zero, lt_zero, lt_zero, lt_zero },
988          /* le_zero */ { le_zero, lt_zero, le_zero, le_zero, le_zero, le_zero, le_zero },
989          /* gt_zero */ { _______, lt_zero, le_zero, gt_zero, ge_zero, ne_zero, eq_zero },
990          /* ge_zero */ { _______, lt_zero, le_zero, ge_zero, ge_zero, _______, eq_zero },
991          /* ne_zero */ { _______, lt_zero, le_zero, ne_zero, _______, ne_zero, le_zero },
992          /* eq_zero */ { le_zero, lt_zero, le_zero, eq_zero, eq_zero, le_zero, eq_zero }
993       };
994 
995       /* Treat fmin as commutative. */
996       ASSERT_TABLE_IS_COMMUTATIVE(table);
997       ASSERT_TABLE_IS_DIAGONAL(table);
998       ASSERT_UNION_OF_OTHERS_MATCHES_UNKNOWN_2_SOURCE(table);
999 
1000       r.range = table[left.range][right.range];
1001 
1002       /* Recall that when either value is NaN, fmin will pick the other value.
1003        * This means the result range of the fmin will either be the "ideal"
1004        * result range (calculated above) or the range of the non-NaN value.
1005        */
1006       if (!left.is_a_number)
1007          r.range = union_ranges(r.range, right.range);
1008 
1009       if (!right.is_a_number)
1010          r.range = union_ranges(r.range, left.range);
1011 
1012       break;
1013    }
1014 
1015    case nir_op_fmul:
1016    case nir_op_fmulz: {
1017       const struct ssa_result_range left = unpack_data(src_res[0]);
1018       const struct ssa_result_range right = unpack_data(src_res[1]);
1019 
1020       r.is_integral = left.is_integral && right.is_integral;
1021 
1022       /* x * x => ge_zero */
1023       if (left.range != eq_zero && nir_alu_srcs_equal(alu, alu, 0, 1)) {
1024          /* Even if x > 0, the result of x*x can be zero when x is, for
1025           * example, a subnormal number.
1026           */
1027          r.range = ge_zero;
1028       } else if (left.range != eq_zero && nir_alu_srcs_negative_equal(alu, alu, 0, 1)) {
1029          /* -x * x => le_zero. */
1030          r.range = le_zero;
1031       } else
1032          r.range = fmul_table[left.range][right.range];
1033 
1034       if (alu->op == nir_op_fmul) {
1035          /* Mulitpliation produces NaN for X * NaN and for 0 * ±Inf.  If both
1036           * operands are numbers and either both are finite or one is finite and
1037           * the other cannot be zero, then the result must be a number.
1038           */
1039          r.is_a_number = (left.is_a_number && right.is_a_number) &&
1040                          ((left.is_finite && right.is_finite) ||
1041                           (!is_not_zero(left.range) && right.is_finite) ||
1042                           (left.is_finite && !is_not_zero(right.range)));
1043       } else {
1044          /* nir_op_fmulz: unlike nir_op_fmul, 0 * ±Inf is a number. */
1045          r.is_a_number = left.is_a_number && right.is_a_number;
1046       }
1047 
1048       break;
1049    }
1050 
1051    case nir_op_frcp:
1052       r = (struct ssa_result_range){
1053          unpack_data(src_res[0]).range,
1054          false,
1055          false, /* Various cases can result in NaN, so assume the worst. */
1056          false  /*    "      "    "     "    "  "    "    "    "    "    */
1057       };
1058       break;
1059 
1060    case nir_op_mov:
1061       r = unpack_data(src_res[0]);
1062       break;
1063 
1064    case nir_op_fneg:
1065       r = unpack_data(src_res[0]);
1066       r.range = fneg_table[r.range];
1067       break;
1068 
1069    case nir_op_fsat: {
1070       const struct ssa_result_range left = unpack_data(src_res[0]);
1071 
1072       /* fsat(NaN) = 0. */
1073       r.is_a_number = true;
1074       r.is_finite = true;
1075 
1076       switch (left.range) {
1077       case le_zero:
1078       case lt_zero:
1079       case eq_zero:
1080          r.range = eq_zero;
1081          r.is_integral = true;
1082          break;
1083 
1084       case gt_zero:
1085          /* fsat is equivalent to fmin(fmax(X, 0.0), 1.0), so if X is not a
1086           * number, the result will be 0.
1087           */
1088          r.range = left.is_a_number ? gt_zero : ge_zero;
1089          r.is_integral = left.is_integral;
1090          break;
1091 
1092       case ge_zero:
1093       case ne_zero:
1094       case unknown:
1095          /* Since the result must be in [0, 1], the value must be >= 0. */
1096          r.range = ge_zero;
1097          r.is_integral = left.is_integral;
1098          break;
1099       }
1100       break;
1101    }
1102 
1103    case nir_op_fsign:
1104       r = (struct ssa_result_range){
1105          unpack_data(src_res[0]).range,
1106          true,
1107          true, /* fsign is -1, 0, or 1, even for NaN, so it must be a number. */
1108          true  /* fsign is -1, 0, or 1, even for NaN, so it must be finite. */
1109       };
1110       break;
1111 
1112    case nir_op_fsqrt:
1113    case nir_op_frsq:
1114       r = (struct ssa_result_range){ ge_zero, false, false, false };
1115       break;
1116 
1117    case nir_op_ffloor: {
1118       const struct ssa_result_range left = unpack_data(src_res[0]);
1119 
1120       r.is_integral = true;
1121 
1122       /* In IEEE 754, floor(NaN) is NaN, and floor(±Inf) is ±Inf. See
1123        * https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/functions/floor.html
1124        */
1125       r.is_a_number = left.is_a_number;
1126       r.is_finite = left.is_finite;
1127 
1128       if (left.is_integral || left.range == le_zero || left.range == lt_zero)
1129          r.range = left.range;
1130       else if (left.range == ge_zero || left.range == gt_zero)
1131          r.range = ge_zero;
1132       else if (left.range == ne_zero)
1133          r.range = unknown;
1134 
1135       break;
1136    }
1137 
1138    case nir_op_fceil: {
1139       const struct ssa_result_range left = unpack_data(src_res[0]);
1140 
1141       r.is_integral = true;
1142 
1143       /* In IEEE 754, ceil(NaN) is NaN, and ceil(±Inf) is ±Inf. See
1144        * https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/functions/ceil.html
1145        */
1146       r.is_a_number = left.is_a_number;
1147       r.is_finite = left.is_finite;
1148 
1149       if (left.is_integral || left.range == ge_zero || left.range == gt_zero)
1150          r.range = left.range;
1151       else if (left.range == le_zero || left.range == lt_zero)
1152          r.range = le_zero;
1153       else if (left.range == ne_zero)
1154          r.range = unknown;
1155 
1156       break;
1157    }
1158 
1159    case nir_op_ftrunc: {
1160       const struct ssa_result_range left = unpack_data(src_res[0]);
1161 
1162       r.is_integral = true;
1163 
1164       /* In IEEE 754, trunc(NaN) is NaN, and trunc(±Inf) is ±Inf.  See
1165        * https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/functions/trunc.html
1166        */
1167       r.is_a_number = left.is_a_number;
1168       r.is_finite = left.is_finite;
1169 
1170       if (left.is_integral)
1171          r.range = left.range;
1172       else if (left.range == ge_zero || left.range == gt_zero)
1173          r.range = ge_zero;
1174       else if (left.range == le_zero || left.range == lt_zero)
1175          r.range = le_zero;
1176       else if (left.range == ne_zero)
1177          r.range = unknown;
1178 
1179       break;
1180    }
1181 
1182    case nir_op_flt:
1183    case nir_op_fge:
1184    case nir_op_feq:
1185    case nir_op_fneu:
1186    case nir_op_ilt:
1187    case nir_op_ige:
1188    case nir_op_ieq:
1189    case nir_op_ine:
1190    case nir_op_ult:
1191    case nir_op_uge:
1192       /* Boolean results are 0 or -1. */
1193       r = (struct ssa_result_range){ le_zero, false, true, false };
1194       break;
1195 
1196    case nir_op_fdot2:
1197    case nir_op_fdot3:
1198    case nir_op_fdot4:
1199    case nir_op_fdot8:
1200    case nir_op_fdot16:
1201    case nir_op_fdot2_replicated:
1202    case nir_op_fdot3_replicated:
1203    case nir_op_fdot4_replicated:
1204    case nir_op_fdot8_replicated:
1205    case nir_op_fdot16_replicated: {
1206       const struct ssa_result_range left = unpack_data(src_res[0]);
1207 
1208       /* If the two sources are the same SSA value, then the result is either
1209        * NaN or some number >= 0.  If one source is the negation of the other,
1210        * the result is either NaN or some number <= 0.
1211        *
1212        * In either of these two cases, if one source is a number, then the
1213        * other must also be a number.  Since it should not be possible to get
1214        * Inf-Inf in the dot-product, the result must also be a number.
1215        */
1216       if (nir_alu_srcs_equal(alu, alu, 0, 1)) {
1217          r = (struct ssa_result_range){ ge_zero, false, left.is_a_number, false };
1218       } else if (nir_alu_srcs_negative_equal(alu, alu, 0, 1)) {
1219          r = (struct ssa_result_range){ le_zero, false, left.is_a_number, false };
1220       } else {
1221          r = (struct ssa_result_range){ unknown, false, false, false };
1222       }
1223       break;
1224    }
1225 
1226    case nir_op_fpow: {
1227       /* Due to flush-to-zero semanatics of floating-point numbers with very
1228        * small mangnitudes, we can never really be sure a result will be
1229        * non-zero.
1230        *
1231        * NIR uses pow() and powf() to constant evaluate nir_op_fpow.  The man
1232        * page for that function says:
1233        *
1234        *    If y is 0, the result is 1.0 (even if x is a NaN).
1235        *
1236        * gt_zero: pow(*, eq_zero)
1237        *        | pow(eq_zero, lt_zero)   # 0^-y = +inf
1238        *        | pow(eq_zero, le_zero)   # 0^-y = +inf or 0^0 = 1.0
1239        *        ;
1240        *
1241        * eq_zero: pow(eq_zero, gt_zero)
1242        *        ;
1243        *
1244        * ge_zero: pow(gt_zero, gt_zero)
1245        *        | pow(gt_zero, ge_zero)
1246        *        | pow(gt_zero, lt_zero)
1247        *        | pow(gt_zero, le_zero)
1248        *        | pow(gt_zero, ne_zero)
1249        *        | pow(gt_zero, unknown)
1250        *        | pow(ge_zero, gt_zero)
1251        *        | pow(ge_zero, ge_zero)
1252        *        | pow(ge_zero, lt_zero)
1253        *        | pow(ge_zero, le_zero)
1254        *        | pow(ge_zero, ne_zero)
1255        *        | pow(ge_zero, unknown)
1256        *        | pow(eq_zero, ge_zero)  # 0^0 = 1.0 or 0^+y = 0.0
1257        *        | pow(eq_zero, ne_zero)  # 0^-y = +inf or 0^+y = 0.0
1258        *        | pow(eq_zero, unknown)  # union of all other y cases
1259        *        ;
1260        *
1261        * All other cases are unknown.
1262        *
1263        * We could do better if the right operand is a constant, integral
1264        * value.
1265        */
1266       static const enum ssa_ranges table[last_range + 1][last_range + 1] = {
1267          /* left\right   unknown  lt_zero  le_zero  gt_zero  ge_zero  ne_zero  eq_zero */
1268          /* unknown */ { _______, _______, _______, _______, _______, _______, gt_zero },
1269          /* lt_zero */ { _______, _______, _______, _______, _______, _______, gt_zero },
1270          /* le_zero */ { _______, _______, _______, _______, _______, _______, gt_zero },
1271          /* gt_zero */ { ge_zero, ge_zero, ge_zero, ge_zero, ge_zero, ge_zero, gt_zero },
1272          /* ge_zero */ { ge_zero, ge_zero, ge_zero, ge_zero, ge_zero, ge_zero, gt_zero },
1273          /* ne_zero */ { _______, _______, _______, _______, _______, _______, gt_zero },
1274          /* eq_zero */ { ge_zero, gt_zero, gt_zero, eq_zero, ge_zero, ge_zero, gt_zero },
1275       };
1276 
1277       const struct ssa_result_range left = unpack_data(src_res[0]);
1278       const struct ssa_result_range right = unpack_data(src_res[1]);
1279 
1280       ASSERT_UNION_OF_DISJOINT_MATCHES_UNKNOWN_2_SOURCE(table);
1281       ASSERT_UNION_OF_EQ_AND_STRICT_INEQ_MATCHES_NONSTRICT_2_SOURCE(table);
1282 
1283       r.is_integral = left.is_integral && right.is_integral &&
1284                       is_not_negative(right.range);
1285       r.range = table[left.range][right.range];
1286 
1287       /* Various cases can result in NaN, so assume the worst. */
1288       r.is_a_number = false;
1289 
1290       break;
1291    }
1292 
1293    case nir_op_ffma: {
1294       const struct ssa_result_range first = unpack_data(src_res[0]);
1295       const struct ssa_result_range second = unpack_data(src_res[1]);
1296       const struct ssa_result_range third = unpack_data(src_res[2]);
1297 
1298       r.is_integral = first.is_integral && second.is_integral &&
1299                       third.is_integral;
1300 
1301       /* Various cases can result in NaN, so assume the worst. */
1302       r.is_a_number = false;
1303 
1304       enum ssa_ranges fmul_range;
1305 
1306       if (first.range != eq_zero && nir_alu_srcs_equal(alu, alu, 0, 1)) {
1307          /* See handling of nir_op_fmul for explanation of why ge_zero is the
1308           * range.
1309           */
1310          fmul_range = ge_zero;
1311       } else if (first.range != eq_zero && nir_alu_srcs_negative_equal(alu, alu, 0, 1)) {
1312          /* -x * x => le_zero */
1313          fmul_range = le_zero;
1314       } else
1315          fmul_range = fmul_table[first.range][second.range];
1316 
1317       r.range = fadd_table[fmul_range][third.range];
1318       break;
1319    }
1320 
1321    case nir_op_flrp: {
1322       const struct ssa_result_range first = unpack_data(src_res[0]);
1323       const struct ssa_result_range second = unpack_data(src_res[1]);
1324       const struct ssa_result_range third = unpack_data(src_res[2]);
1325 
1326       r.is_integral = first.is_integral && second.is_integral &&
1327                       third.is_integral;
1328 
1329       /* Various cases can result in NaN, so assume the worst. */
1330       r.is_a_number = false;
1331 
1332       /* Decompose the flrp to first + third * (second + -first) */
1333       const enum ssa_ranges inner_fadd_range =
1334          fadd_table[second.range][fneg_table[first.range]];
1335 
1336       const enum ssa_ranges fmul_range =
1337          fmul_table[third.range][inner_fadd_range];
1338 
1339       r.range = fadd_table[first.range][fmul_range];
1340       break;
1341    }
1342 
1343    default:
1344       r = (struct ssa_result_range){ unknown, false, false, false };
1345       break;
1346    }
1347 
1348    if (r.range == eq_zero)
1349       r.is_integral = true;
1350 
1351    /* Just like isfinite(), the is_finite flag implies the value is a number. */
1352    assert((int)r.is_finite <= (int)r.is_a_number);
1353 
1354    *result = pack_data(r);
1355 }
1356 
1357 #undef _______
1358 
1359 struct ssa_result_range
nir_analyze_range(struct hash_table * range_ht,const nir_alu_instr * alu,unsigned src)1360 nir_analyze_range(struct hash_table *range_ht,
1361                   const nir_alu_instr *alu, unsigned src)
1362 {
1363    struct fp_query query_alloc[64];
1364    uint32_t result_alloc[64];
1365 
1366    struct analysis_state state;
1367    state.range_ht = range_ht;
1368    util_dynarray_init_from_stack(&state.query_stack, query_alloc, sizeof(query_alloc));
1369    util_dynarray_init_from_stack(&state.result_stack, result_alloc, sizeof(result_alloc));
1370    state.query_size = sizeof(struct fp_query);
1371    state.get_key = &get_fp_key;
1372    state.process_query = &process_fp_query;
1373 
1374    push_fp_query(&state, alu, src, nir_type_invalid);
1375 
1376    return unpack_data(perform_analysis(&state));
1377 }
1378 
1379 static uint32_t
bitmask(uint32_t size)1380 bitmask(uint32_t size)
1381 {
1382    return size >= 32 ? 0xffffffffu : ((uint32_t)1 << size) - 1u;
1383 }
1384 
1385 static uint64_t
mul_clamp(uint32_t a,uint32_t b)1386 mul_clamp(uint32_t a, uint32_t b)
1387 {
1388    if (a != 0 && (a * b) / a != b)
1389       return (uint64_t)UINT32_MAX + 1;
1390    else
1391       return a * b;
1392 }
1393 
1394 /* recursively gather at most "buf_size" phi/bcsel sources */
1395 static unsigned
search_phi_bcsel(nir_scalar scalar,nir_scalar * buf,unsigned buf_size,struct set * visited)1396 search_phi_bcsel(nir_scalar scalar, nir_scalar *buf, unsigned buf_size, struct set *visited)
1397 {
1398    if (_mesa_set_search(visited, scalar.def))
1399       return 0;
1400    _mesa_set_add(visited, scalar.def);
1401 
1402    if (scalar.def->parent_instr->type == nir_instr_type_phi) {
1403       nir_phi_instr *phi = nir_instr_as_phi(scalar.def->parent_instr);
1404       unsigned num_sources_left = exec_list_length(&phi->srcs);
1405       if (buf_size >= num_sources_left) {
1406          unsigned total_added = 0;
1407          nir_foreach_phi_src(src, phi) {
1408             num_sources_left--;
1409             unsigned added = search_phi_bcsel(nir_get_scalar(src->src.ssa, scalar.comp),
1410                                               buf + total_added, buf_size - num_sources_left, visited);
1411             assert(added <= buf_size);
1412             buf_size -= added;
1413             total_added += added;
1414          }
1415          return total_added;
1416       }
1417    }
1418 
1419    if (nir_scalar_is_alu(scalar)) {
1420       nir_op op = nir_scalar_alu_op(scalar);
1421 
1422       if ((op == nir_op_bcsel || op == nir_op_b32csel) && buf_size >= 2) {
1423          nir_scalar src1 = nir_scalar_chase_alu_src(scalar, 1);
1424          nir_scalar src2 = nir_scalar_chase_alu_src(scalar, 2);
1425 
1426          unsigned added = search_phi_bcsel(src1, buf, buf_size - 1, visited);
1427          buf_size -= added;
1428          added += search_phi_bcsel(src2, buf + added, buf_size, visited);
1429          return added;
1430       }
1431    }
1432 
1433    buf[0] = scalar;
1434    return 1;
1435 }
1436 
1437 static nir_variable *
lookup_input(nir_shader * shader,unsigned driver_location)1438 lookup_input(nir_shader *shader, unsigned driver_location)
1439 {
1440    return nir_find_variable_with_driver_location(shader, nir_var_shader_in,
1441                                                  driver_location);
1442 }
1443 
1444 /* The config here should be generic enough to be correct on any HW. */
1445 static const nir_unsigned_upper_bound_config default_ub_config = {
1446    .min_subgroup_size = 1u,
1447    .max_subgroup_size = UINT16_MAX,
1448    .max_workgroup_invocations = UINT16_MAX,
1449 
1450    /* max_workgroup_count represents the maximum compute shader / kernel
1451     * dispatchable work size. On most hardware, this is essentially
1452     * unbounded. On some hardware max_workgroup_count[1] and
1453     * max_workgroup_count[2] may be smaller.
1454     */
1455    .max_workgroup_count = { UINT32_MAX, UINT32_MAX, UINT32_MAX },
1456 
1457    /* max_workgroup_size is the local invocation maximum. This is generally
1458     * small the OpenGL 4.2 minimum maximum is 1024.
1459     */
1460    .max_workgroup_size = { UINT16_MAX, UINT16_MAX, UINT16_MAX },
1461 
1462    .vertex_attrib_max = {
1463       UINT32_MAX,
1464       UINT32_MAX,
1465       UINT32_MAX,
1466       UINT32_MAX,
1467       UINT32_MAX,
1468       UINT32_MAX,
1469       UINT32_MAX,
1470       UINT32_MAX,
1471       UINT32_MAX,
1472       UINT32_MAX,
1473       UINT32_MAX,
1474       UINT32_MAX,
1475       UINT32_MAX,
1476       UINT32_MAX,
1477       UINT32_MAX,
1478       UINT32_MAX,
1479       UINT32_MAX,
1480       UINT32_MAX,
1481       UINT32_MAX,
1482       UINT32_MAX,
1483       UINT32_MAX,
1484       UINT32_MAX,
1485       UINT32_MAX,
1486       UINT32_MAX,
1487       UINT32_MAX,
1488       UINT32_MAX,
1489       UINT32_MAX,
1490       UINT32_MAX,
1491       UINT32_MAX,
1492       UINT32_MAX,
1493       UINT32_MAX,
1494       UINT32_MAX,
1495    },
1496 };
1497 
1498 struct uub_query {
1499    struct analysis_query head;
1500    nir_scalar scalar;
1501 };
1502 
1503 static void
push_uub_query(struct analysis_state * state,nir_scalar scalar)1504 push_uub_query(struct analysis_state *state, nir_scalar scalar)
1505 {
1506    struct uub_query *pushed_q = push_analysis_query(state, sizeof(struct uub_query));
1507    pushed_q->scalar = scalar;
1508 }
1509 
1510 static uintptr_t
get_uub_key(struct analysis_query * q)1511 get_uub_key(struct analysis_query *q)
1512 {
1513    nir_scalar scalar = ((struct uub_query *)q)->scalar;
1514    /* keys can't be 0, so we have to add 1 to the index */
1515    unsigned shift_amount = ffs(NIR_MAX_VEC_COMPONENTS) - 1;
1516    return nir_scalar_is_const(scalar)
1517              ? 0
1518              : ((uintptr_t)(scalar.def->index + 1) << shift_amount) | scalar.comp;
1519 }
1520 
1521 static void
get_intrinsic_uub(struct analysis_state * state,struct uub_query q,uint32_t * result,const uint32_t * src)1522 get_intrinsic_uub(struct analysis_state *state, struct uub_query q, uint32_t *result,
1523                   const uint32_t *src)
1524 {
1525    nir_shader *shader = state->shader;
1526    const nir_unsigned_upper_bound_config *config = state->config;
1527 
1528    nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(q.scalar.def->parent_instr);
1529    switch (intrin->intrinsic) {
1530    case nir_intrinsic_load_local_invocation_index:
1531       /* The local invocation index is used under the hood by RADV for
1532        * some non-compute-like shaders (eg. LS and NGG). These technically
1533        * run in workgroups on the HW, even though this fact is not exposed
1534        * by the API.
1535        * They can safely use the same code path here as variable sized
1536        * compute-like shader stages.
1537        */
1538       if (!gl_shader_stage_uses_workgroup(shader->info.stage) ||
1539           shader->info.workgroup_size_variable) {
1540          *result = config->max_workgroup_invocations - 1;
1541       } else {
1542          *result = (shader->info.workgroup_size[0] *
1543                     shader->info.workgroup_size[1] *
1544                     shader->info.workgroup_size[2]) -
1545                    1u;
1546       }
1547       break;
1548    case nir_intrinsic_load_local_invocation_id:
1549       if (shader->info.workgroup_size_variable)
1550          *result = config->max_workgroup_size[q.scalar.comp] - 1u;
1551       else
1552          *result = shader->info.workgroup_size[q.scalar.comp] - 1u;
1553       break;
1554    case nir_intrinsic_load_workgroup_id:
1555       *result = config->max_workgroup_count[q.scalar.comp] - 1u;
1556       break;
1557    case nir_intrinsic_load_num_workgroups:
1558       *result = config->max_workgroup_count[q.scalar.comp];
1559       break;
1560    case nir_intrinsic_load_global_invocation_id:
1561       if (shader->info.workgroup_size_variable) {
1562          *result = mul_clamp(config->max_workgroup_size[q.scalar.comp],
1563                              config->max_workgroup_count[q.scalar.comp]) -
1564                    1u;
1565       } else {
1566          *result = (shader->info.workgroup_size[q.scalar.comp] *
1567                     config->max_workgroup_count[q.scalar.comp]) -
1568                    1u;
1569       }
1570       break;
1571    case nir_intrinsic_load_invocation_id:
1572       if (shader->info.stage == MESA_SHADER_TESS_CTRL)
1573          *result = shader->info.tess.tcs_vertices_out
1574                       ? (shader->info.tess.tcs_vertices_out - 1)
1575                       : 511; /* Generous maximum output patch size of 512 */
1576       break;
1577    case nir_intrinsic_load_subgroup_invocation:
1578    case nir_intrinsic_first_invocation:
1579       *result = config->max_subgroup_size - 1;
1580       break;
1581    case nir_intrinsic_mbcnt_amd: {
1582       if (!q.head.pushed_queries) {
1583          push_uub_query(state, nir_get_scalar(intrin->src[1].ssa, 0));
1584          return;
1585       } else {
1586          uint32_t src0 = config->max_subgroup_size - 1;
1587          uint32_t src1 = src[0];
1588          if (src0 + src1 >= src0) /* check overflow */
1589             *result = src0 + src1;
1590       }
1591       break;
1592    }
1593    case nir_intrinsic_load_subgroup_size:
1594       *result = config->max_subgroup_size;
1595       break;
1596    case nir_intrinsic_load_subgroup_id:
1597    case nir_intrinsic_load_num_subgroups: {
1598       uint32_t workgroup_size = config->max_workgroup_invocations;
1599       if (gl_shader_stage_uses_workgroup(shader->info.stage) &&
1600           !shader->info.workgroup_size_variable) {
1601          workgroup_size = shader->info.workgroup_size[0] *
1602                           shader->info.workgroup_size[1] *
1603                           shader->info.workgroup_size[2];
1604       }
1605       *result = DIV_ROUND_UP(workgroup_size, config->min_subgroup_size);
1606       if (intrin->intrinsic == nir_intrinsic_load_subgroup_id)
1607          (*result)--;
1608       break;
1609    }
1610    case nir_intrinsic_load_input: {
1611       if (shader->info.stage == MESA_SHADER_VERTEX && nir_src_is_const(intrin->src[0])) {
1612          nir_variable *var = lookup_input(shader, nir_intrinsic_base(intrin));
1613          if (var) {
1614             int loc = var->data.location - VERT_ATTRIB_GENERIC0;
1615             if (loc >= 0)
1616                *result = config->vertex_attrib_max[loc];
1617          }
1618       }
1619       break;
1620    }
1621    case nir_intrinsic_reduce:
1622    case nir_intrinsic_inclusive_scan:
1623    case nir_intrinsic_exclusive_scan: {
1624       nir_op op = nir_intrinsic_reduction_op(intrin);
1625       if (op == nir_op_umin || op == nir_op_umax || op == nir_op_imin || op == nir_op_imax) {
1626          if (!q.head.pushed_queries) {
1627             push_uub_query(state, nir_get_scalar(intrin->src[0].ssa, q.scalar.comp));
1628             return;
1629          } else {
1630             *result = src[0];
1631          }
1632       }
1633       break;
1634    }
1635    case nir_intrinsic_read_first_invocation:
1636    case nir_intrinsic_read_invocation:
1637    case nir_intrinsic_shuffle:
1638    case nir_intrinsic_shuffle_xor:
1639    case nir_intrinsic_shuffle_up:
1640    case nir_intrinsic_shuffle_down:
1641    case nir_intrinsic_quad_broadcast:
1642    case nir_intrinsic_quad_swap_horizontal:
1643    case nir_intrinsic_quad_swap_vertical:
1644    case nir_intrinsic_quad_swap_diagonal:
1645    case nir_intrinsic_quad_swizzle_amd:
1646    case nir_intrinsic_masked_swizzle_amd:
1647       if (!q.head.pushed_queries) {
1648          push_uub_query(state, nir_get_scalar(intrin->src[0].ssa, q.scalar.comp));
1649          return;
1650       } else {
1651          *result = src[0];
1652       }
1653       break;
1654    case nir_intrinsic_write_invocation_amd:
1655       if (!q.head.pushed_queries) {
1656          push_uub_query(state, nir_get_scalar(intrin->src[0].ssa, q.scalar.comp));
1657          push_uub_query(state, nir_get_scalar(intrin->src[1].ssa, q.scalar.comp));
1658          return;
1659       } else {
1660          *result = MAX2(src[0], src[1]);
1661       }
1662       break;
1663    case nir_intrinsic_load_tess_rel_patch_id_amd:
1664    case nir_intrinsic_load_tcs_num_patches_amd:
1665       /* Very generous maximum: TCS/TES executed by largest possible workgroup */
1666       *result = config->max_workgroup_invocations / MAX2(shader->info.tess.tcs_vertices_out, 1u);
1667       break;
1668    case nir_intrinsic_load_typed_buffer_amd: {
1669       const enum pipe_format format = nir_intrinsic_format(intrin);
1670       if (format == PIPE_FORMAT_NONE)
1671          break;
1672 
1673       const struct util_format_description *desc = util_format_description(format);
1674       if (desc->channel[q.scalar.comp].type != UTIL_FORMAT_TYPE_UNSIGNED)
1675          break;
1676 
1677       if (desc->channel[q.scalar.comp].normalized) {
1678          *result = fui(1.0);
1679          break;
1680       }
1681 
1682       const uint32_t chan_max = u_uintN_max(desc->channel[q.scalar.comp].size);
1683       *result = desc->channel[q.scalar.comp].pure_integer ? chan_max : fui(chan_max);
1684       break;
1685    }
1686    case nir_intrinsic_load_scalar_arg_amd:
1687    case nir_intrinsic_load_vector_arg_amd: {
1688       uint32_t upper_bound = nir_intrinsic_arg_upper_bound_u32_amd(intrin);
1689       if (upper_bound)
1690          *result = upper_bound;
1691       break;
1692    }
1693    default:
1694       break;
1695    }
1696 }
1697 
1698 static void
get_alu_uub(struct analysis_state * state,struct uub_query q,uint32_t * result,const uint32_t * src)1699 get_alu_uub(struct analysis_state *state, struct uub_query q, uint32_t *result, const uint32_t *src)
1700 {
1701    nir_op op = nir_scalar_alu_op(q.scalar);
1702 
1703    /* Early exit for unsupported ALU opcodes. */
1704    switch (op) {
1705    case nir_op_umin:
1706    case nir_op_imin:
1707    case nir_op_imax:
1708    case nir_op_umax:
1709    case nir_op_iand:
1710    case nir_op_ior:
1711    case nir_op_ixor:
1712    case nir_op_ishl:
1713    case nir_op_imul:
1714    case nir_op_ushr:
1715    case nir_op_ishr:
1716    case nir_op_iadd:
1717    case nir_op_umod:
1718    case nir_op_udiv:
1719    case nir_op_bcsel:
1720    case nir_op_b32csel:
1721    case nir_op_ubfe:
1722    case nir_op_bfm:
1723    case nir_op_fmul:
1724    case nir_op_fmulz:
1725    case nir_op_extract_u8:
1726    case nir_op_extract_i8:
1727    case nir_op_extract_u16:
1728    case nir_op_extract_i16:
1729    case nir_op_b2i8:
1730    case nir_op_b2i16:
1731    case nir_op_b2i32:
1732       break;
1733    case nir_op_u2u1:
1734    case nir_op_u2u8:
1735    case nir_op_u2u16:
1736    case nir_op_u2u32:
1737    case nir_op_f2u32:
1738       if (nir_scalar_chase_alu_src(q.scalar, 0).def->bit_size > 32) {
1739          /* If src is >32 bits, return max */
1740          return;
1741       }
1742       break;
1743    default:
1744       return;
1745    }
1746 
1747    if (!q.head.pushed_queries) {
1748       for (unsigned i = 0; i < nir_op_infos[op].num_inputs; i++)
1749          push_uub_query(state, nir_scalar_chase_alu_src(q.scalar, i));
1750       return;
1751    }
1752 
1753    uint32_t max = bitmask(q.scalar.def->bit_size);
1754    switch (op) {
1755    case nir_op_umin:
1756       *result = src[0] < src[1] ? src[0] : src[1];
1757       break;
1758    case nir_op_imin:
1759    case nir_op_imax:
1760    case nir_op_umax:
1761       *result = src[0] > src[1] ? src[0] : src[1];
1762       break;
1763    case nir_op_iand:
1764       *result = bitmask(util_last_bit64(src[0])) & bitmask(util_last_bit64(src[1]));
1765       break;
1766    case nir_op_ior:
1767    case nir_op_ixor:
1768       *result = bitmask(util_last_bit64(src[0])) | bitmask(util_last_bit64(src[1]));
1769       break;
1770    case nir_op_ishl: {
1771       uint32_t src1 = MIN2(src[1], q.scalar.def->bit_size - 1u);
1772       if (util_last_bit64(src[0]) + src1 <= q.scalar.def->bit_size) /* check overflow */
1773          *result = src[0] << src1;
1774       break;
1775    }
1776    case nir_op_imul:
1777       if (src[0] == 0 || (src[0] * src[1]) / src[0] == src[1]) /* check overflow */
1778          *result = src[0] * src[1];
1779       break;
1780    case nir_op_ushr: {
1781       nir_scalar src1_scalar = nir_scalar_chase_alu_src(q.scalar, 1);
1782       uint32_t mask = q.scalar.def->bit_size - 1u;
1783       if (nir_scalar_is_const(src1_scalar))
1784          *result = src[0] >> (nir_scalar_as_uint(src1_scalar) & mask);
1785       else
1786          *result = src[0];
1787       break;
1788    }
1789    case nir_op_ishr: {
1790       nir_scalar src1_scalar = nir_scalar_chase_alu_src(q.scalar, 1);
1791       uint32_t mask = q.scalar.def->bit_size - 1u;
1792       if (src[0] <= 2147483647 && nir_scalar_is_const(src1_scalar))
1793          *result = src[0] >> (nir_scalar_as_uint(src1_scalar) & mask);
1794       else
1795          *result = src[0];
1796       break;
1797    }
1798    case nir_op_iadd:
1799       if (src[0] + src[1] >= src[0]) /* check overflow */
1800          *result = src[0] + src[1];
1801       break;
1802    case nir_op_umod:
1803       *result = src[1] ? src[1] - 1 : 0;
1804       break;
1805    case nir_op_udiv: {
1806       nir_scalar src1_scalar = nir_scalar_chase_alu_src(q.scalar, 1);
1807       if (nir_scalar_is_const(src1_scalar))
1808          *result = nir_scalar_as_uint(src1_scalar)
1809                       ? src[0] / nir_scalar_as_uint(src1_scalar)
1810                       : 0;
1811       else
1812          *result = src[0];
1813       break;
1814    }
1815    case nir_op_bcsel:
1816    case nir_op_b32csel:
1817       *result = src[1] > src[2] ? src[1] : src[2];
1818       break;
1819    case nir_op_ubfe:
1820       *result = bitmask(MIN2(src[2], q.scalar.def->bit_size));
1821       break;
1822    case nir_op_bfm: {
1823       nir_scalar src1_scalar = nir_scalar_chase_alu_src(q.scalar, 1);
1824       if (nir_scalar_is_const(src1_scalar)) {
1825          uint32_t src0 = MIN2(src[0], 31);
1826          uint32_t src1 = nir_scalar_as_uint(src1_scalar) & 0x1fu;
1827          *result = bitmask(src0) << src1;
1828       } else {
1829          uint32_t src0 = MIN2(src[0], 31);
1830          uint32_t src1 = MIN2(src[1], 31);
1831          *result = bitmask(MIN2(src0 + src1, 32));
1832       }
1833       break;
1834    }
1835    /* limited floating-point support for f2u32(fmul(load_input(), <constant>)) */
1836    case nir_op_f2u32:
1837       /* infinity/NaN starts at 0x7f800000u, negative numbers at 0x80000000 */
1838       if (src[0] < 0x7f800000u) {
1839          float val;
1840          memcpy(&val, &src[0], 4);
1841          *result = (uint32_t)val;
1842       }
1843       break;
1844    case nir_op_fmul:
1845    case nir_op_fmulz:
1846       /* infinity/NaN starts at 0x7f800000u, negative numbers at 0x80000000 */
1847       if (src[0] < 0x7f800000u && src[1] < 0x7f800000u) {
1848          float src0_f, src1_f;
1849          memcpy(&src0_f, &src[0], 4);
1850          memcpy(&src1_f, &src[1], 4);
1851          /* not a proper rounding-up multiplication, but should be good enough */
1852          float max_f = ceilf(src0_f) * ceilf(src1_f);
1853          memcpy(result, &max_f, 4);
1854       }
1855       break;
1856    case nir_op_u2u1:
1857    case nir_op_u2u8:
1858    case nir_op_u2u16:
1859    case nir_op_u2u32:
1860       *result = MIN2(src[0], max);
1861       break;
1862    case nir_op_b2i8:
1863    case nir_op_b2i16:
1864    case nir_op_b2i32:
1865       *result = 1;
1866       break;
1867    case nir_op_msad_4x8:
1868       *result = MIN2((uint64_t)src[2] + 4 * 255, UINT32_MAX);
1869       break;
1870    case nir_op_extract_u8:
1871       *result = MIN2(src[0], UINT8_MAX);
1872       break;
1873    case nir_op_extract_i8:
1874       *result = (src[0] >= 0x80) ? max : MIN2(src[0], INT8_MAX);
1875       break;
1876    case nir_op_extract_u16:
1877       *result = MIN2(src[0], UINT16_MAX);
1878       break;
1879    case nir_op_extract_i16:
1880       *result = (src[0] >= 0x8000) ? max : MIN2(src[0], INT16_MAX);
1881       break;
1882    default:
1883       break;
1884    }
1885 }
1886 
1887 static void
get_phi_uub(struct analysis_state * state,struct uub_query q,uint32_t * result,const uint32_t * src)1888 get_phi_uub(struct analysis_state *state, struct uub_query q, uint32_t *result, const uint32_t *src)
1889 {
1890    nir_phi_instr *phi = nir_instr_as_phi(q.scalar.def->parent_instr);
1891 
1892    if (exec_list_is_empty(&phi->srcs))
1893       return;
1894 
1895    if (q.head.pushed_queries) {
1896       *result = src[0];
1897       for (unsigned i = 1; i < q.head.pushed_queries; i++)
1898          *result = MAX2(*result, src[i]);
1899       return;
1900    }
1901 
1902    nir_cf_node *prev = nir_cf_node_prev(&phi->instr.block->cf_node);
1903    if (!prev || prev->type == nir_cf_node_block) {
1904       /* Resolve cycles by inserting max into range_ht. */
1905       uint32_t max = bitmask(q.scalar.def->bit_size);
1906       _mesa_hash_table_insert(state->range_ht, (void *)get_uub_key(&q.head), (void *)(uintptr_t)max);
1907 
1908       struct set *visited = _mesa_pointer_set_create(NULL);
1909       nir_scalar *defs = alloca(sizeof(nir_scalar) * 64);
1910       unsigned def_count = search_phi_bcsel(q.scalar, defs, 64, visited);
1911       _mesa_set_destroy(visited, NULL);
1912 
1913       for (unsigned i = 0; i < def_count; i++)
1914          push_uub_query(state, defs[i]);
1915    } else {
1916       nir_foreach_phi_src(src, phi)
1917          push_uub_query(state, nir_get_scalar(src->src.ssa, q.scalar.comp));
1918    }
1919 }
1920 
1921 static void
process_uub_query(struct analysis_state * state,struct analysis_query * aq,uint32_t * result,const uint32_t * src)1922 process_uub_query(struct analysis_state *state, struct analysis_query *aq, uint32_t *result,
1923                   const uint32_t *src)
1924 {
1925    struct uub_query q = *(struct uub_query *)aq;
1926 
1927    *result = bitmask(q.scalar.def->bit_size);
1928    if (nir_scalar_is_const(q.scalar))
1929       *result = nir_scalar_as_uint(q.scalar);
1930    else if (nir_scalar_is_intrinsic(q.scalar))
1931       get_intrinsic_uub(state, q, result, src);
1932    else if (nir_scalar_is_alu(q.scalar))
1933       get_alu_uub(state, q, result, src);
1934    else if (q.scalar.def->parent_instr->type == nir_instr_type_phi)
1935       get_phi_uub(state, q, result, src);
1936 }
1937 
1938 uint32_t
nir_unsigned_upper_bound(nir_shader * shader,struct hash_table * range_ht,nir_scalar scalar,const nir_unsigned_upper_bound_config * config)1939 nir_unsigned_upper_bound(nir_shader *shader, struct hash_table *range_ht,
1940                          nir_scalar scalar,
1941                          const nir_unsigned_upper_bound_config *config)
1942 {
1943    if (!config)
1944       config = &default_ub_config;
1945 
1946    struct uub_query query_alloc[16];
1947    uint32_t result_alloc[16];
1948 
1949    struct analysis_state state;
1950    state.shader = shader;
1951    state.config = config;
1952    state.range_ht = range_ht;
1953    util_dynarray_init_from_stack(&state.query_stack, query_alloc, sizeof(query_alloc));
1954    util_dynarray_init_from_stack(&state.result_stack, result_alloc, sizeof(result_alloc));
1955    state.query_size = sizeof(struct uub_query);
1956    state.get_key = &get_uub_key;
1957    state.process_query = &process_uub_query;
1958 
1959    push_uub_query(&state, scalar);
1960 
1961    return perform_analysis(&state);
1962 }
1963 
1964 bool
nir_addition_might_overflow(nir_shader * shader,struct hash_table * range_ht,nir_scalar ssa,unsigned const_val,const nir_unsigned_upper_bound_config * config)1965 nir_addition_might_overflow(nir_shader *shader, struct hash_table *range_ht,
1966                             nir_scalar ssa, unsigned const_val,
1967                             const nir_unsigned_upper_bound_config *config)
1968 {
1969    if (nir_scalar_is_alu(ssa)) {
1970       nir_op alu_op = nir_scalar_alu_op(ssa);
1971 
1972       /* iadd(imul(a, #b), #c) */
1973       if (alu_op == nir_op_imul || alu_op == nir_op_ishl) {
1974          nir_scalar mul_src0 = nir_scalar_chase_alu_src(ssa, 0);
1975          nir_scalar mul_src1 = nir_scalar_chase_alu_src(ssa, 1);
1976          uint32_t stride = 1;
1977          if (nir_scalar_is_const(mul_src0))
1978             stride = nir_scalar_as_uint(mul_src0);
1979          else if (nir_scalar_is_const(mul_src1))
1980             stride = nir_scalar_as_uint(mul_src1);
1981 
1982          if (alu_op == nir_op_ishl)
1983             stride = 1u << (stride % 32u);
1984 
1985          if (!stride || const_val <= UINT32_MAX - (UINT32_MAX / stride * stride))
1986             return false;
1987       }
1988 
1989       /* iadd(iand(a, #b), #c) */
1990       if (alu_op == nir_op_iand) {
1991          nir_scalar and_src0 = nir_scalar_chase_alu_src(ssa, 0);
1992          nir_scalar and_src1 = nir_scalar_chase_alu_src(ssa, 1);
1993          uint32_t mask = 0xffffffff;
1994          if (nir_scalar_is_const(and_src0))
1995             mask = nir_scalar_as_uint(and_src0);
1996          else if (nir_scalar_is_const(and_src1))
1997             mask = nir_scalar_as_uint(and_src1);
1998          if (mask == 0 || const_val < (1u << (ffs(mask) - 1)))
1999             return false;
2000       }
2001    }
2002 
2003    uint32_t ub = nir_unsigned_upper_bound(shader, range_ht, ssa, config);
2004    return const_val + ub < const_val;
2005 }
2006 
2007 static uint64_t
ssa_def_bits_used(const nir_def * def,int recur)2008 ssa_def_bits_used(const nir_def *def, int recur)
2009 {
2010    uint64_t bits_used = 0;
2011    uint64_t all_bits = BITFIELD64_MASK(def->bit_size);
2012 
2013    /* Querying the bits used from a vector is too hard of a question to
2014     * answer.  Return the conservative answer that all bits are used.  To
2015     * handle this, the function would need to be extended to be a query of a
2016     * single component of the vector.  That would also necessary to fully
2017     * handle the 'num_components > 1' inside the loop below.
2018     *
2019     * FINISHME: This restriction will eventually need to be restricted to be
2020     * useful for hardware that uses u16vec2 as the native 16-bit integer type.
2021     */
2022    if (def->num_components > 1)
2023       return all_bits;
2024 
2025    /* Limit recursion */
2026    if (recur-- <= 0)
2027       return all_bits;
2028 
2029    nir_foreach_use(src, def) {
2030       switch (nir_src_parent_instr(src)->type) {
2031       case nir_instr_type_alu: {
2032          nir_alu_instr *use_alu = nir_instr_as_alu(nir_src_parent_instr(src));
2033          unsigned src_idx = container_of(src, nir_alu_src, src) - use_alu->src;
2034 
2035          /* If a user of the value produces a vector result, return the
2036           * conservative answer that all bits are used.  It is possible to
2037           * answer this query by looping over the components used.  For example,
2038           *
2039           * vec4 32 ssa_5 = load_const(0x0000f000, 0x00000f00, 0x000000f0, 0x0000000f)
2040           * ...
2041           * vec4 32 ssa_8 = iand ssa_7.xxxx, ssa_5
2042           *
2043           * could conceivably return 0x0000ffff when queyring the bits used of
2044           * ssa_7.  This is unlikely to be worth the effort because the
2045           * question can eventually answered after the shader has been
2046           * scalarized.
2047           */
2048          if (use_alu->def.num_components > 1)
2049             return all_bits;
2050 
2051          switch (use_alu->op) {
2052          case nir_op_u2u8:
2053          case nir_op_i2i8:
2054             bits_used |= 0xff;
2055             break;
2056 
2057          case nir_op_u2u16:
2058          case nir_op_i2i16:
2059             bits_used |= all_bits & 0xffff;
2060             break;
2061 
2062          case nir_op_u2u32:
2063          case nir_op_i2i32:
2064             bits_used |= all_bits & 0xffffffff;
2065             break;
2066 
2067          case nir_op_extract_u8:
2068          case nir_op_extract_i8:
2069             if (src_idx == 0 && nir_src_is_const(use_alu->src[1].src)) {
2070                unsigned chunk = nir_src_comp_as_uint(use_alu->src[1].src,
2071                                                      use_alu->src[1].swizzle[0]);
2072                bits_used |= 0xffull << (chunk * 8);
2073                break;
2074             } else {
2075                return all_bits;
2076             }
2077 
2078          case nir_op_extract_u16:
2079          case nir_op_extract_i16:
2080             if (src_idx == 0 && nir_src_is_const(use_alu->src[1].src)) {
2081                unsigned chunk = nir_src_comp_as_uint(use_alu->src[1].src,
2082                                                      use_alu->src[1].swizzle[0]);
2083                bits_used |= 0xffffull << (chunk * 16);
2084                break;
2085             } else {
2086                return all_bits;
2087             }
2088 
2089          case nir_op_ishl:
2090          case nir_op_ishr:
2091          case nir_op_ushr:
2092             if (src_idx == 1) {
2093                bits_used |= (nir_src_bit_size(use_alu->src[0].src) - 1);
2094                break;
2095             } else {
2096                return all_bits;
2097             }
2098 
2099          case nir_op_iand:
2100             assert(src_idx < 2);
2101             if (nir_src_is_const(use_alu->src[1 - src_idx].src)) {
2102                uint64_t u64 = nir_src_comp_as_uint(use_alu->src[1 - src_idx].src,
2103                                                    use_alu->src[1 - src_idx].swizzle[0]);
2104                bits_used |= u64;
2105                break;
2106             } else {
2107                return all_bits;
2108             }
2109 
2110          case nir_op_ior:
2111             assert(src_idx < 2);
2112             if (nir_src_is_const(use_alu->src[1 - src_idx].src)) {
2113                uint64_t u64 = nir_src_comp_as_uint(use_alu->src[1 - src_idx].src,
2114                                                    use_alu->src[1 - src_idx].swizzle[0]);
2115                bits_used |= all_bits & ~u64;
2116                break;
2117             } else {
2118                return all_bits;
2119             }
2120 
2121          default:
2122             /* We don't know what this op does */
2123             return all_bits;
2124          }
2125          break;
2126       }
2127 
2128       case nir_instr_type_intrinsic: {
2129          nir_intrinsic_instr *use_intrin =
2130             nir_instr_as_intrinsic(nir_src_parent_instr(src));
2131          unsigned src_idx = src - use_intrin->src;
2132 
2133          switch (use_intrin->intrinsic) {
2134          case nir_intrinsic_read_invocation:
2135          case nir_intrinsic_shuffle:
2136          case nir_intrinsic_shuffle_up:
2137          case nir_intrinsic_shuffle_down:
2138          case nir_intrinsic_shuffle_xor:
2139          case nir_intrinsic_quad_broadcast:
2140          case nir_intrinsic_quad_swap_horizontal:
2141          case nir_intrinsic_quad_swap_vertical:
2142          case nir_intrinsic_quad_swap_diagonal:
2143             if (src_idx == 0) {
2144                bits_used |= ssa_def_bits_used(&use_intrin->def, recur);
2145             } else {
2146                if (use_intrin->intrinsic == nir_intrinsic_quad_broadcast) {
2147                   bits_used |= 3;
2148                } else {
2149                   /* Subgroups larger than 128 are not a thing */
2150                   bits_used |= 127;
2151                }
2152             }
2153             break;
2154 
2155          case nir_intrinsic_reduce:
2156          case nir_intrinsic_inclusive_scan:
2157          case nir_intrinsic_exclusive_scan:
2158             assert(src_idx == 0);
2159             switch (nir_intrinsic_reduction_op(use_intrin)) {
2160             case nir_op_iadd:
2161             case nir_op_imul:
2162             case nir_op_ior:
2163             case nir_op_iand:
2164             case nir_op_ixor:
2165                bits_used |= ssa_def_bits_used(&use_intrin->def, recur);
2166                break;
2167 
2168             default:
2169                return all_bits;
2170             }
2171             break;
2172 
2173          default:
2174             /* We don't know what this op does */
2175             return all_bits;
2176          }
2177          break;
2178       }
2179 
2180       case nir_instr_type_phi: {
2181          nir_phi_instr *use_phi = nir_instr_as_phi(nir_src_parent_instr(src));
2182          bits_used |= ssa_def_bits_used(&use_phi->def, recur);
2183          break;
2184       }
2185 
2186       default:
2187          return all_bits;
2188       }
2189 
2190       /* If we've somehow shown that all our bits are used, we're done */
2191       assert((bits_used & ~all_bits) == 0);
2192       if (bits_used == all_bits)
2193          return all_bits;
2194    }
2195 
2196    return bits_used;
2197 }
2198 
2199 uint64_t
nir_def_bits_used(const nir_def * def)2200 nir_def_bits_used(const nir_def *def)
2201 {
2202    return ssa_def_bits_used(def, 2);
2203 }
2204