• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2014 Connor Abbott
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  * Authors:
24  *    Connor Abbott (cwabbott0@gmail.com)
25  *
26  */
27 
28 #ifndef NIR_H
29 #define NIR_H
30 
31 #include <stdint.h>
32 #include "compiler/glsl_types.h"
33 #include "compiler/glsl/list.h"
34 #include "compiler/shader_enums.h"
35 #include "compiler/shader_info.h"
36 #include "util/bitscan.h"
37 #include "util/bitset.h"
38 #include "util/compiler.h"
39 #include "util/enum_operators.h"
40 #include "util/format/u_format.h"
41 #include "util/hash_table.h"
42 #include "util/list.h"
43 #include "util/log.h"
44 #include "util/macros.h"
45 #include "util/ralloc.h"
46 #include "util/set.h"
47 #include "util/u_math.h"
48 #include "util/u_printf.h"
49 #include "nir_defines.h"
50 #define XXH_INLINE_ALL
51 #include <stdio.h>
52 #include "util/xxhash.h"
53 
54 #ifndef NDEBUG
55 #include "util/u_debug.h"
56 #endif /* NDEBUG */
57 
58 #include "nir_opcodes.h"
59 
60 #ifdef __cplusplus
61 extern "C" {
62 #endif
63 
64 extern uint32_t nir_debug;
65 extern bool nir_debug_print_shader[MESA_SHADER_KERNEL + 1];
66 
67 #ifndef NDEBUG
68 #define NIR_DEBUG(flag) unlikely(nir_debug &(NIR_DEBUG_##flag))
69 #else
70 #define NIR_DEBUG(flag) false
71 #endif
72 
73 #define NIR_DEBUG_CLONE                  (1u << 0)
74 #define NIR_DEBUG_SERIALIZE              (1u << 1)
75 #define NIR_DEBUG_NOVALIDATE             (1u << 2)
76 #define NIR_DEBUG_VALIDATE_SSA_DOMINANCE (1u << 3)
77 #define NIR_DEBUG_TGSI                   (1u << 4)
78 #define NIR_DEBUG_PRINT_VS               (1u << 5)
79 #define NIR_DEBUG_PRINT_TCS              (1u << 6)
80 #define NIR_DEBUG_PRINT_TES              (1u << 7)
81 #define NIR_DEBUG_PRINT_GS               (1u << 8)
82 #define NIR_DEBUG_PRINT_FS               (1u << 9)
83 #define NIR_DEBUG_PRINT_CS               (1u << 10)
84 #define NIR_DEBUG_PRINT_TS               (1u << 11)
85 #define NIR_DEBUG_PRINT_MS               (1u << 12)
86 #define NIR_DEBUG_PRINT_RGS              (1u << 13)
87 #define NIR_DEBUG_PRINT_AHS              (1u << 14)
88 #define NIR_DEBUG_PRINT_CHS              (1u << 15)
89 #define NIR_DEBUG_PRINT_MHS              (1u << 16)
90 #define NIR_DEBUG_PRINT_IS               (1u << 17)
91 #define NIR_DEBUG_PRINT_CBS              (1u << 18)
92 #define NIR_DEBUG_PRINT_KS               (1u << 19)
93 #define NIR_DEBUG_PRINT_NO_INLINE_CONSTS (1u << 20)
94 #define NIR_DEBUG_PRINT_INTERNAL         (1u << 21)
95 #define NIR_DEBUG_PRINT_PASS_FLAGS       (1u << 22)
96 
97 #define NIR_DEBUG_PRINT (NIR_DEBUG_PRINT_VS |  \
98                          NIR_DEBUG_PRINT_TCS | \
99                          NIR_DEBUG_PRINT_TES | \
100                          NIR_DEBUG_PRINT_GS |  \
101                          NIR_DEBUG_PRINT_FS |  \
102                          NIR_DEBUG_PRINT_CS |  \
103                          NIR_DEBUG_PRINT_TS |  \
104                          NIR_DEBUG_PRINT_MS |  \
105                          NIR_DEBUG_PRINT_RGS | \
106                          NIR_DEBUG_PRINT_AHS | \
107                          NIR_DEBUG_PRINT_CHS | \
108                          NIR_DEBUG_PRINT_MHS | \
109                          NIR_DEBUG_PRINT_IS |  \
110                          NIR_DEBUG_PRINT_CBS | \
111                          NIR_DEBUG_PRINT_KS)
112 
113 #define NIR_FALSE              0u
114 #define NIR_TRUE               (~0u)
115 #define NIR_MAX_VEC_COMPONENTS 16
116 #define NIR_MAX_MATRIX_COLUMNS 4
117 #define NIR_STREAM_PACKED      (1 << 8)
118 typedef uint16_t nir_component_mask_t;
119 
120 static inline bool
nir_num_components_valid(unsigned num_components)121 nir_num_components_valid(unsigned num_components)
122 {
123    return (num_components >= 1 &&
124            num_components <= 5) ||
125           num_components == 8 ||
126           num_components == 16;
127 }
128 
129 /*
130  * Round up a vector size to a vector size that's valid in NIR. At present, NIR
131  * supports only vec2-5, vec8, and vec16. Attempting to generate other sizes
132  * will fail validation.
133  */
134 static inline unsigned
nir_round_up_components(unsigned n)135 nir_round_up_components(unsigned n)
136 {
137    return (n > 5) ? util_next_power_of_two(n) : n;
138 }
139 
140 static inline nir_component_mask_t
nir_component_mask(unsigned num_components)141 nir_component_mask(unsigned num_components)
142 {
143    assert(nir_num_components_valid(num_components));
144    return (1u << num_components) - 1;
145 }
146 
147 void
148 nir_process_debug_variable(void);
149 
150 bool nir_component_mask_can_reinterpret(nir_component_mask_t mask,
151                                         unsigned old_bit_size,
152                                         unsigned new_bit_size);
153 nir_component_mask_t
154 nir_component_mask_reinterpret(nir_component_mask_t mask,
155                                unsigned old_bit_size,
156                                unsigned new_bit_size);
157 
158 /** Defines a cast function
159  *
160  * This macro defines a cast function from in_type to out_type where
161  * out_type is some structure type that contains a field of type out_type.
162  *
163  * Note that you have to be a bit careful as the generated cast function
164  * destroys constness.
165  */
166 #define NIR_DEFINE_CAST(name, in_type, out_type, field,   \
167                         type_field, type_value)           \
168    static inline out_type *                               \
169    name(const in_type *parent)                            \
170    {                                                      \
171       assert(parent && parent->type_field == type_value); \
172       return exec_node_data(out_type, parent, field);     \
173    }
174 
175 struct nir_function;
176 struct nir_shader;
177 struct nir_instr;
178 struct nir_builder;
179 struct nir_xfb_info;
180 
181 /**
182  * Description of built-in state associated with a uniform
183  *
184  * :c:member:`nir_variable.state_slots`
185  */
186 typedef struct {
187    gl_state_index16 tokens[STATE_LENGTH];
188 } nir_state_slot;
189 
190 /* clang-format off */
191 typedef enum {
192    nir_var_system_value          = (1 << 0),
193    nir_var_uniform               = (1 << 1),
194    nir_var_shader_in             = (1 << 2),
195    nir_var_shader_out            = (1 << 3),
196    nir_var_image                 = (1 << 4),
197    /** Incoming call or ray payload data for ray-tracing shaders */
198    nir_var_shader_call_data      = (1 << 5),
199    /** Ray hit attributes */
200    nir_var_ray_hit_attrib        = (1 << 6),
201 
202    /* Modes named nir_var_mem_* have explicit data layout */
203    nir_var_mem_ubo               = (1 << 7),
204    nir_var_mem_push_const        = (1 << 8),
205    nir_var_mem_ssbo              = (1 << 9),
206    nir_var_mem_constant          = (1 << 10),
207    nir_var_mem_task_payload      = (1 << 11),
208    nir_var_mem_node_payload      = (1 << 12),
209    nir_var_mem_node_payload_in   = (1 << 13),
210 
211    nir_var_function_in           = (1 << 14),
212    nir_var_function_out          = (1 << 15),
213    nir_var_function_inout        = (1 << 16),
214 
215    /* Generic modes intentionally come last. See encode_dref_modes() in
216     * nir_serialize.c for more details.
217     */
218    nir_var_shader_temp           = (1 << 17),
219    nir_var_function_temp         = (1 << 18),
220    nir_var_mem_shared            = (1 << 19),
221    nir_var_mem_global            = (1 << 20),
222 
223    nir_var_mem_generic           = (nir_var_shader_temp |
224                                     nir_var_function_temp |
225                                     nir_var_mem_shared |
226                                     nir_var_mem_global),
227 
228    nir_var_read_only_modes       = nir_var_shader_in | nir_var_uniform |
229                                    nir_var_system_value | nir_var_mem_constant |
230                                    nir_var_mem_ubo,
231    /* Modes where vector derefs can be indexed as arrays. nir_var_shader_out
232     * is only for mesh stages. nir_var_system_value is only for kernel stages.
233     */
234    nir_var_vec_indexable_modes   = nir_var_shader_temp | nir_var_function_temp |
235                                  nir_var_mem_ubo | nir_var_mem_ssbo |
236                                  nir_var_mem_shared | nir_var_mem_global |
237                                  nir_var_mem_push_const | nir_var_mem_task_payload |
238                                  nir_var_shader_out | nir_var_system_value,
239    nir_num_variable_modes        = 21,
240    nir_var_all                   = (1 << nir_num_variable_modes) - 1,
241 } nir_variable_mode;
242 MESA_DEFINE_CPP_ENUM_BITFIELD_OPERATORS(nir_variable_mode)
243 /* clang-format on */
244 
245 /**
246  * Rounding modes.
247  */
248 typedef enum {
249    nir_rounding_mode_undef = 0,
250    nir_rounding_mode_rtne = 1, /* round to nearest even */
251    nir_rounding_mode_ru = 2,   /* round up */
252    nir_rounding_mode_rd = 3,   /* round down */
253    nir_rounding_mode_rtz = 4,  /* round towards zero */
254 } nir_rounding_mode;
255 
256 /**
257  * Ray query values that can read from a RayQueryKHR object.
258  */
259 typedef enum {
260    nir_ray_query_value_intersection_type,
261    nir_ray_query_value_intersection_t,
262    nir_ray_query_value_intersection_instance_custom_index,
263    nir_ray_query_value_intersection_instance_id,
264    nir_ray_query_value_intersection_instance_sbt_index,
265    nir_ray_query_value_intersection_geometry_index,
266    nir_ray_query_value_intersection_primitive_index,
267    nir_ray_query_value_intersection_barycentrics,
268    nir_ray_query_value_intersection_front_face,
269    nir_ray_query_value_intersection_object_ray_direction,
270    nir_ray_query_value_intersection_object_ray_origin,
271    nir_ray_query_value_intersection_object_to_world,
272    nir_ray_query_value_intersection_world_to_object,
273    nir_ray_query_value_intersection_candidate_aabb_opaque,
274    nir_ray_query_value_tmin,
275    nir_ray_query_value_flags,
276    nir_ray_query_value_world_ray_direction,
277    nir_ray_query_value_world_ray_origin,
278    nir_ray_query_value_intersection_triangle_vertex_positions
279 } nir_ray_query_value;
280 
281 /**
282  * Intel resource flags
283  */
284 typedef enum {
285    nir_resource_intel_bindless = 1u << 0,
286    nir_resource_intel_pushable = 1u << 1,
287    nir_resource_intel_sampler = 1u << 2,
288    nir_resource_intel_non_uniform = 1u << 3,
289    nir_resource_intel_sampler_embedded = 1u << 4,
290 } nir_resource_data_intel;
291 
292 /**
293  * Which components to interpret as signed in cmat_muladd.
294  * See 'Cooperative Matrix Operands' in SPV_KHR_cooperative_matrix.
295  */
296 typedef enum {
297    NIR_CMAT_A_SIGNED = 1u << 0,
298    NIR_CMAT_B_SIGNED = 1u << 1,
299    NIR_CMAT_C_SIGNED = 1u << 2,
300    NIR_CMAT_RESULT_SIGNED = 1u << 3,
301 } nir_cmat_signed;
302 
303 typedef union {
304    bool b;
305    float f32;
306    double f64;
307    int8_t i8;
308    uint8_t u8;
309    int16_t i16;
310    uint16_t u16;
311    int32_t i32;
312    uint32_t u32;
313    int64_t i64;
314    uint64_t u64;
315 } nir_const_value;
316 
317 #define nir_const_value_to_array(arr, c, components, m) \
318    do {                                                 \
319       for (unsigned i = 0; i < components; ++i)         \
320          arr[i] = c[i].m;                               \
321    } while (false)
322 
323 static inline nir_const_value
nir_const_value_for_raw_uint(uint64_t x,unsigned bit_size)324 nir_const_value_for_raw_uint(uint64_t x, unsigned bit_size)
325 {
326    nir_const_value v;
327    memset(&v, 0, sizeof(v));
328 
329    /* clang-format off */
330    switch (bit_size) {
331    case 1:  v.b   = x;  break;
332    case 8:  v.u8  = (uint8_t)x;  break;
333    case 16: v.u16 = (uint16_t)x;  break;
334    case 32: v.u32 = (uint32_t)x;  break;
335    case 64: v.u64 = x;  break;
336    default:
337       unreachable("Invalid bit size");
338    }
339    /* clang-format on */
340 
341    return v;
342 }
343 
344 static inline nir_const_value
nir_const_value_for_int(int64_t i,unsigned bit_size)345 nir_const_value_for_int(int64_t i, unsigned bit_size)
346 {
347    assert(bit_size <= 64);
348    if (bit_size < 64) {
349       assert(i >= (-(1ll << (bit_size - 1))));
350       assert(i < (1ll << (bit_size - 1)));
351    }
352 
353    return nir_const_value_for_raw_uint(i, bit_size);
354 }
355 
356 static inline nir_const_value
nir_const_value_for_uint(uint64_t u,unsigned bit_size)357 nir_const_value_for_uint(uint64_t u, unsigned bit_size)
358 {
359    assert(bit_size <= 64);
360    if (bit_size < 64)
361       assert(u < (1ull << bit_size));
362 
363    return nir_const_value_for_raw_uint(u, bit_size);
364 }
365 
366 static inline nir_const_value
nir_const_value_for_bool(bool b,unsigned bit_size)367 nir_const_value_for_bool(bool b, unsigned bit_size)
368 {
369    /* Booleans use a 0/-1 convention */
370    return nir_const_value_for_int(-(int)b, bit_size);
371 }
372 
373 /* This one isn't inline because it requires half-float conversion */
374 nir_const_value nir_const_value_for_float(double b, unsigned bit_size);
375 
376 static inline int64_t
nir_const_value_as_int(nir_const_value value,unsigned bit_size)377 nir_const_value_as_int(nir_const_value value, unsigned bit_size)
378 {
379    /* clang-format off */
380    switch (bit_size) {
381    /* int1_t uses 0/-1 convention */
382    case 1:  return -(int)value.b;
383    case 8:  return value.i8;
384    case 16: return value.i16;
385    case 32: return value.i32;
386    case 64: return value.i64;
387    default:
388       unreachable("Invalid bit size");
389    }
390    /* clang-format on */
391 }
392 
393 static inline uint64_t
nir_const_value_as_uint(nir_const_value value,unsigned bit_size)394 nir_const_value_as_uint(nir_const_value value, unsigned bit_size)
395 {
396    /* clang-format off */
397    switch (bit_size) {
398    case 1:  return value.b;
399    case 8:  return value.u8;
400    case 16: return value.u16;
401    case 32: return value.u32;
402    case 64: return value.u64;
403    default:
404       unreachable("Invalid bit size");
405    }
406    /* clang-format on */
407 }
408 
409 static inline bool
nir_const_value_as_bool(nir_const_value value,unsigned bit_size)410 nir_const_value_as_bool(nir_const_value value, unsigned bit_size)
411 {
412    int64_t i = nir_const_value_as_int(value, bit_size);
413 
414    /* Booleans of any size use 0/-1 convention */
415    assert(i == 0 || i == -1);
416 
417    return i;
418 }
419 
420 /* This one isn't inline because it requires half-float conversion */
421 double nir_const_value_as_float(nir_const_value value, unsigned bit_size);
422 
423 typedef struct nir_constant {
424    /**
425     * Value of the constant.
426     *
427     * The field used to back the values supplied by the constant is determined
428     * by the type associated with the ``nir_variable``.  Constants may be
429     * scalars, vectors, or matrices.
430     */
431    nir_const_value values[NIR_MAX_VEC_COMPONENTS];
432 
433    /* Indicates all the values are 0s which can enable some optimizations */
434    bool is_null_constant;
435 
436    /* we could get this from the var->type but makes clone *much* easier to
437     * not have to care about the type.
438     */
439    unsigned num_elements;
440 
441    /* Array elements / Structure Fields */
442    struct nir_constant **elements;
443 } nir_constant;
444 
445 /**
446  * Layout qualifiers for gl_FragDepth.
447  *
448  * The AMD/ARB_conservative_depth extensions allow gl_FragDepth to be redeclared
449  * with a layout qualifier.
450  */
451 typedef enum {
452    /** No depth layout is specified. */
453    nir_depth_layout_none,
454    nir_depth_layout_any,
455    nir_depth_layout_greater,
456    nir_depth_layout_less,
457    nir_depth_layout_unchanged
458 } nir_depth_layout;
459 
460 /**
461  * Enum keeping track of how a variable was declared.
462  */
463 typedef enum {
464    /**
465     * Normal declaration.
466     */
467    nir_var_declared_normally = 0,
468 
469    /**
470     * Variable is an implicitly declared built-in that has not been explicitly
471     * re-declared by the shader.
472     */
473    nir_var_declared_implicitly,
474 
475    /**
476     * Variable is implicitly generated by the compiler and should not be
477     * visible via the API.
478     */
479    nir_var_hidden,
480 } nir_var_declaration_type;
481 
482 /**
483  * Either a uniform, global variable, shader input, or shader output. Based on
484  * ir_variable - it should be easy to translate between the two.
485  */
486 
487 typedef struct nir_variable {
488    struct exec_node node;
489 
490    /**
491     * Declared type of the variable
492     */
493    const struct glsl_type *type;
494 
495    /**
496     * Declared name of the variable
497     */
498    char *name;
499 
500    struct nir_variable_data {
501       /**
502        * Storage class of the variable.
503        *
504        * :c:struct:`nir_variable_mode`
505        */
506       unsigned mode : 21;
507 
508       /**
509        * Is the variable read-only?
510        *
511        * This is set for variables declared as ``const``, shader inputs,
512        * and uniforms.
513        */
514       unsigned read_only : 1;
515       unsigned centroid : 1;
516       unsigned sample : 1;
517       unsigned patch : 1;
518       unsigned invariant : 1;
519 
520       /**
521        * Was an 'invariant' qualifier explicitly set in the shader?
522        *
523        * This is used to cross validate glsl qualifiers.
524        */
525       unsigned explicit_invariant:1;
526 
527       /**
528        * Is the variable a ray query?
529        */
530       unsigned ray_query : 1;
531 
532       /**
533        * Precision qualifier.
534        *
535        * In desktop GLSL we do not care about precision qualifiers at all, in
536        * fact, the spec says that precision qualifiers are ignored.
537        *
538        * To make things easy, we make it so that this field is always
539        * GLSL_PRECISION_NONE on desktop shaders. This way all the variables
540        * have the same precision value and the checks we add in the compiler
541        * for this field will never break a desktop shader compile.
542        */
543       unsigned precision : 2;
544 
545       /**
546        * Has this variable been statically assigned?
547        *
548        * This answers whether the variable was assigned in any path of
549        * the shader during ast_to_hir.  This doesn't answer whether it is
550        * still written after dead code removal, nor is it maintained in
551        * non-ast_to_hir.cpp (GLSL parsing) paths.
552        */
553       unsigned assigned : 1;
554 
555       /**
556        * Can this variable be coalesced with another?
557        *
558        * This is set by nir_lower_io_to_temporaries to say that any
559        * copies involving this variable should stay put. Propagating it can
560        * duplicate the resulting load/store, which is not wanted, and may
561        * result in a load/store of the variable with an indirect offset which
562        * the backend may not be able to handle.
563        */
564       unsigned cannot_coalesce : 1;
565 
566       /**
567        * When separate shader programs are enabled, only input/outputs between
568        * the stages of a multi-stage separate program can be safely removed
569        * from the shader interface. Other input/outputs must remains active.
570        *
571        * This is also used to make sure xfb varyings that are unused by the
572        * fragment shader are not removed.
573        */
574       unsigned always_active_io : 1;
575 
576       /**
577        * Interpolation mode for shader inputs / outputs
578        *
579        * :c:enum:`glsl_interp_mode`
580        */
581       unsigned interpolation : 3;
582 
583       /**
584        * If non-zero, then this variable may be packed along with other variables
585        * into a single varying slot, so this offset should be applied when
586        * accessing components.  For example, an offset of 1 means that the x
587        * component of this variable is actually stored in component y of the
588        * location specified by ``location``.
589        */
590       unsigned location_frac : 2;
591 
592       /**
593        * If true, this variable represents an array of scalars that should
594        * be tightly packed.  In other words, consecutive array elements
595        * should be stored one component apart, rather than one slot apart.
596        */
597       unsigned compact : 1;
598 
599       /**
600        * Whether this is a fragment shader output implicitly initialized with
601        * the previous contents of the specified render target at the
602        * framebuffer location corresponding to this shader invocation.
603        */
604       unsigned fb_fetch_output : 1;
605 
606       /**
607        * Non-zero if this variable is considered bindless as defined by
608        * ARB_bindless_texture.
609        */
610       unsigned bindless : 1;
611 
612       /**
613        * Was an explicit binding set in the shader?
614        */
615       unsigned explicit_binding : 1;
616 
617       /**
618        * Was the location explicitly set in the shader?
619        *
620        * If the location is explicitly set in the shader, it **cannot** be changed
621        * by the linker or by the API (e.g., calls to ``glBindAttribLocation`` have
622        * no effect).
623        */
624       unsigned explicit_location : 1;
625 
626       /* Was the array implicitly sized during linking */
627       unsigned implicit_sized_array : 1;
628 
629       /**
630        * Highest element accessed with a constant array index
631        *
632        * Not used for non-array variables. -1 is never accessed.
633        */
634       int max_array_access;
635 
636       /**
637        * Does this variable have an initializer?
638        *
639        * This is used by the linker to cross-validiate initializers of global
640        * variables.
641        */
642       unsigned has_initializer:1;
643 
644       /**
645        * Is the initializer created by the compiler (glsl_zero_init)
646        */
647       unsigned is_implicit_initializer:1;
648 
649       /**
650        * Is this varying used by transform feedback?
651        *
652        * This is used by the linker to decide if it's safe to pack the varying.
653        */
654       unsigned is_xfb : 1;
655 
656       /**
657        * Is this varying used only by transform feedback?
658        *
659        * This is used by the linker to decide if its safe to pack the varying.
660        */
661       unsigned is_xfb_only : 1;
662 
663       /**
664        * Was a transfer feedback buffer set in the shader?
665        */
666       unsigned explicit_xfb_buffer : 1;
667 
668       /**
669        * Was a transfer feedback stride set in the shader?
670        */
671       unsigned explicit_xfb_stride : 1;
672 
673       /**
674        * Was an explicit offset set in the shader?
675        */
676       unsigned explicit_offset : 1;
677 
678       /**
679        * Layout of the matrix.  Uses glsl_matrix_layout values.
680        */
681       unsigned matrix_layout : 2;
682 
683       /**
684        * Non-zero if this variable was created by lowering a named interface
685        * block.
686        */
687       unsigned from_named_ifc_block : 1;
688 
689       /**
690        * Unsized array buffer variable.
691        */
692       unsigned from_ssbo_unsized_array : 1;
693 
694       /**
695        * Non-zero if the variable must be a shader input. This is useful for
696        * constraints on function parameters.
697        */
698       unsigned must_be_shader_input : 1;
699 
700       /**
701        * Has this variable been used for reading or writing?
702        *
703        * Several GLSL semantic checks require knowledge of whether or not a
704        * variable has been used.  For example, it is an error to redeclare a
705        * variable as invariant after it has been used.
706        */
707       unsigned used:1;
708 
709       /**
710        * How the variable was declared.  See nir_var_declaration_type.
711        *
712        * This is used to detect variables generated by the compiler, so should
713        * not be visible via the API.
714        */
715       unsigned how_declared : 2;
716 
717       /**
718        * Is this variable per-view?  If so, we know it must be an array with
719        * size corresponding to the number of views.
720        */
721       unsigned per_view : 1;
722 
723       /**
724        * Whether the variable is per-primitive.
725        * Can be use by Mesh Shader outputs and corresponding Fragment Shader inputs.
726        */
727       unsigned per_primitive : 1;
728 
729       /**
730        * Whether the variable is declared to indicate that a fragment shader
731        * input will not have interpolated values.
732        */
733       unsigned per_vertex : 1;
734 
735       /**
736        * Layout qualifier for gl_FragDepth. See nir_depth_layout.
737        *
738        * This is not equal to ``ir_depth_layout_none`` if and only if this
739        * variable is ``gl_FragDepth`` and a layout qualifier is specified.
740        */
741       unsigned depth_layout : 3;
742 
743       /**
744        * Vertex stream output identifier.
745        *
746        * For packed outputs, NIR_STREAM_PACKED is set and bits [2*i+1,2*i]
747        * indicate the stream of the i-th component.
748        */
749       unsigned stream : 9;
750 
751       /**
752        * See gl_access_qualifier.
753        *
754        * Access flags for memory variables (SSBO/global), image uniforms, and
755        * bindless images in uniforms/inputs/outputs.
756        */
757       unsigned access : 9;
758 
759       /**
760        * Descriptor set binding for sampler or UBO.
761        */
762       unsigned descriptor_set : 5;
763 
764 #define NIR_VARIABLE_NO_INDEX ~0
765 
766       /**
767        * Output index for dual source blending or input attachment index. If
768        * it is not declared it is NIR_VARIABLE_NO_INDEX.
769        */
770       unsigned index;
771 
772       /**
773        * Initial binding point for a sampler or UBO.
774        *
775        * For array types, this represents the binding point for the first element.
776        */
777       unsigned binding;
778 
779       /**
780        * Storage location of the base of this variable
781        *
782        * The precise meaning of this field depends on the nature of the variable.
783        *
784        *   - Vertex shader input: one of the values from ``gl_vert_attrib``.
785        *   - Vertex shader output: one of the values from ``gl_varying_slot``.
786        *   - Geometry shader input: one of the values from ``gl_varying_slot``.
787        *   - Geometry shader output: one of the values from ``gl_varying_slot``.
788        *   - Fragment shader input: one of the values from ``gl_varying_slot``.
789        *   - Fragment shader output: one of the values from ``gl_frag_result``.
790        *   - Task shader output: one of the values from ``gl_varying_slot``.
791        *   - Mesh shader input: one of the values from ``gl_varying_slot``.
792        *   - Mesh shader output: one of the values from ``gl_varying_slot``.
793        *   - Uniforms: Per-stage uniform slot number for default uniform block.
794        *   - Uniforms: Index within the uniform block definition for UBO members.
795        *   - Non-UBO Uniforms: uniform slot number.
796        *   - Other: This field is not currently used.
797        *
798        * If the variable is a uniform, shader input, or shader output, and the
799        * slot has not been assigned, the value will be -1.
800        */
801       int location;
802 
803       /** Required alignment of this variable */
804       unsigned alignment;
805 
806       /**
807        * The actual location of the variable in the IR. Only valid for inputs,
808        * outputs, uniforms (including samplers and images), and for UBO and SSBO
809        * variables in GLSL.
810        */
811       unsigned driver_location;
812 
813       /**
814        * Location an atomic counter or transform feedback is stored at.
815        */
816       unsigned offset;
817 
818       union {
819          struct {
820             /** Image internal format if specified explicitly, otherwise PIPE_FORMAT_NONE. */
821             enum pipe_format format;
822          } image;
823 
824          struct {
825             /**
826              * For OpenCL inline samplers. See cl_sampler_addressing_mode and cl_sampler_filter_mode
827              */
828             unsigned is_inline_sampler : 1;
829             unsigned addressing_mode : 3;
830             unsigned normalized_coordinates : 1;
831             unsigned filter_mode : 1;
832          } sampler;
833 
834          struct {
835             /**
836              * Transform feedback buffer.
837              */
838             uint16_t buffer : 2;
839 
840             /**
841              * Transform feedback stride.
842              */
843             uint16_t stride;
844          } xfb;
845       };
846 
847       /** Name of the node this payload will be enqueued to. */
848       const char *node_name;
849    } data;
850 
851    /**
852     * Identifier for this variable generated by nir_index_vars() that is unique
853     * among other variables in the same exec_list.
854     */
855    unsigned index;
856 
857    /* Number of nir_variable_data members */
858    uint16_t num_members;
859 
860    /**
861     * For variables with non NULL interface_type, this points to an array of
862     * integers such that if the ith member of the interface block is an array,
863     * max_ifc_array_access[i] is the maximum array element of that member that
864     * has been accessed.  If the ith member of the interface block is not an
865     * array, max_ifc_array_access[i] is unused.
866     *
867     * For variables whose type is not an interface block, this pointer is
868     * NULL.
869     */
870    int *max_ifc_array_access;
871 
872    /**
873     * Built-in state that backs this uniform
874     *
875     * Once set at variable creation, ``state_slots`` must remain invariant.
876     * This is because, ideally, this array would be shared by all clones of
877     * this variable in the IR tree.  In other words, we'd really like for it
878     * to be a fly-weight.
879     *
880     * If the variable is not a uniform, ``num_state_slots`` will be zero and
881     * ``state_slots`` will be ``NULL``.
882     *
883     * Number of state slots used.
884     */
885    uint16_t num_state_slots;
886    /** State descriptors. */
887    nir_state_slot *state_slots;
888 
889    /**
890     * Constant expression assigned in the initializer of the variable
891     *
892     * This field should only be used temporarily by creators of NIR shaders
893     * and then nir_lower_variable_initializers can be used to get rid of them.
894     * Most of the rest of NIR ignores this field or asserts that it's NULL.
895     */
896    nir_constant *constant_initializer;
897 
898    /**
899     * Global variable assigned in the initializer of the variable
900     * This field should only be used temporarily by creators of NIR shaders
901     * and then nir_lower_variable_initializers can be used to get rid of them.
902     * Most of the rest of NIR ignores this field or asserts that it's NULL.
903     */
904    struct nir_variable *pointer_initializer;
905 
906    /**
907     * For variables that are in an interface block or are an instance of an
908     * interface block, this is the ``GLSL_TYPE_INTERFACE`` type for that block.
909     *
910     * ``ir_variable.location``
911     */
912    const struct glsl_type *interface_type;
913 
914    /**
915     * Description of per-member data for per-member struct variables
916     *
917     * This is used for variables which are actually an amalgamation of
918     * multiple entities such as a struct of built-in values or a struct of
919     * inputs each with their own layout specifier.  This is only allowed on
920     * variables with a struct or array of array of struct type.
921     */
922    struct nir_variable_data *members;
923 } nir_variable;
924 
925 static inline bool
_nir_shader_variable_has_mode(nir_variable * var,unsigned modes)926 _nir_shader_variable_has_mode(nir_variable *var, unsigned modes)
927 {
928    /* This isn't a shader variable */
929    assert(!(modes & nir_var_function_temp));
930    return var->data.mode & modes;
931 }
932 
933 #define nir_foreach_variable_in_list(var, var_list) \
934    foreach_list_typed(nir_variable, var, node, var_list)
935 
936 #define nir_foreach_variable_in_list_safe(var, var_list) \
937    foreach_list_typed_safe(nir_variable, var, node, var_list)
938 
939 #define nir_foreach_variable_in_shader(var, shader) \
940    nir_foreach_variable_in_list(var, &(shader)->variables)
941 
942 #define nir_foreach_variable_in_shader_safe(var, shader) \
943    nir_foreach_variable_in_list_safe(var, &(shader)->variables)
944 
945 #define nir_foreach_variable_with_modes(var, shader, modes) \
946    nir_foreach_variable_in_shader(var, shader)              \
947       if (_nir_shader_variable_has_mode(var, modes))
948 
949 #define nir_foreach_variable_with_modes_safe(var, shader, modes) \
950    nir_foreach_variable_in_shader_safe(var, shader)              \
951       if (_nir_shader_variable_has_mode(var, modes))
952 
953 #define nir_foreach_shader_in_variable(var, shader) \
954    nir_foreach_variable_with_modes(var, shader, nir_var_shader_in)
955 
956 #define nir_foreach_shader_in_variable_safe(var, shader) \
957    nir_foreach_variable_with_modes_safe(var, shader, nir_var_shader_in)
958 
959 #define nir_foreach_shader_out_variable(var, shader) \
960    nir_foreach_variable_with_modes(var, shader, nir_var_shader_out)
961 
962 #define nir_foreach_shader_out_variable_safe(var, shader) \
963    nir_foreach_variable_with_modes_safe(var, shader, nir_var_shader_out)
964 
965 #define nir_foreach_uniform_variable(var, shader) \
966    nir_foreach_variable_with_modes(var, shader, nir_var_uniform)
967 
968 #define nir_foreach_uniform_variable_safe(var, shader) \
969    nir_foreach_variable_with_modes_safe(var, shader, nir_var_uniform)
970 
971 #define nir_foreach_image_variable(var, shader) \
972    nir_foreach_variable_with_modes(var, shader, nir_var_image)
973 
974 #define nir_foreach_image_variable_safe(var, shader) \
975    nir_foreach_variable_with_modes_safe(var, shader, nir_var_image)
976 
977 static inline bool
nir_variable_is_global(const nir_variable * var)978 nir_variable_is_global(const nir_variable *var)
979 {
980    return var->data.mode != nir_var_function_temp;
981 }
982 
983 typedef enum ENUM_PACKED {
984    nir_instr_type_alu,
985    nir_instr_type_deref,
986    nir_instr_type_call,
987    nir_instr_type_tex,
988    nir_instr_type_intrinsic,
989    nir_instr_type_load_const,
990    nir_instr_type_jump,
991    nir_instr_type_undef,
992    nir_instr_type_phi,
993    nir_instr_type_parallel_copy,
994    nir_instr_type_debug_info,
995 } nir_instr_type;
996 
997 typedef struct nir_instr {
998    struct exec_node node;
999    struct nir_block *block;
1000    nir_instr_type type;
1001 
1002    /* A temporary for optimization and analysis passes to use for storing
1003     * flags.  For instance, DCE uses this to store the "dead/live" info.
1004     */
1005    uint8_t pass_flags;
1006 
1007    /** generic instruction index. */
1008    uint32_t index;
1009 } nir_instr;
1010 
1011 static inline nir_instr *
nir_instr_next(nir_instr * instr)1012 nir_instr_next(nir_instr *instr)
1013 {
1014    struct exec_node *next = exec_node_get_next(&instr->node);
1015    if (exec_node_is_tail_sentinel(next))
1016       return NULL;
1017    else
1018       return exec_node_data(nir_instr, next, node);
1019 }
1020 
1021 static inline nir_instr *
nir_instr_prev(nir_instr * instr)1022 nir_instr_prev(nir_instr *instr)
1023 {
1024    struct exec_node *prev = exec_node_get_prev(&instr->node);
1025    if (exec_node_is_head_sentinel(prev))
1026       return NULL;
1027    else
1028       return exec_node_data(nir_instr, prev, node);
1029 }
1030 
1031 static inline bool
nir_instr_is_first(const nir_instr * instr)1032 nir_instr_is_first(const nir_instr *instr)
1033 {
1034    return exec_node_is_head_sentinel(exec_node_get_prev_const(&instr->node));
1035 }
1036 
1037 static inline bool
nir_instr_is_last(const nir_instr * instr)1038 nir_instr_is_last(const nir_instr *instr)
1039 {
1040    return exec_node_is_tail_sentinel(exec_node_get_next_const(&instr->node));
1041 }
1042 
1043 typedef struct nir_def {
1044    /** Instruction which produces this SSA value. */
1045    nir_instr *parent_instr;
1046 
1047    /** set of nir_instrs where this register is used (read from) */
1048    struct list_head uses;
1049 
1050    /** generic SSA definition index. */
1051    unsigned index;
1052 
1053    uint8_t num_components;
1054 
1055    /* The bit-size of each channel; must be one of 1, 8, 16, 32, or 64 */
1056    uint8_t bit_size;
1057 
1058    /**
1059     * True if this SSA value may have different values in different SIMD
1060     * invocations of the shader.  This is set by nir_divergence_analysis.
1061     */
1062    bool divergent;
1063 
1064    /**
1065     * True if this SSA value is loop invariant w.r.t. the innermost parent
1066     * loop.  This is set by nir_divergence_analysis and used to determine
1067     * the divergence of a nir_src.
1068     */
1069    bool loop_invariant;
1070 } nir_def;
1071 
1072 struct nir_src;
1073 struct nir_if;
1074 
1075 typedef struct nir_src {
1076    /* Instruction or if-statement that consumes this value as a source. This
1077     * should only be accessed through nir_src_* helpers.
1078     *
1079     * Internally, it is a tagged pointer to a nir_instr or nir_if.
1080     */
1081    uintptr_t _parent;
1082 
1083    struct list_head use_link;
1084    nir_def *ssa;
1085 } nir_src;
1086 
1087 /* Layout of the _parent pointer. Bottom bit is set for nir_if parents (clear
1088  * for nir_instr parents). Remaining bits are the pointer.
1089  */
1090 #define NIR_SRC_PARENT_IS_IF (0x1)
1091 #define NIR_SRC_PARENT_MASK (~((uintptr_t) NIR_SRC_PARENT_IS_IF))
1092 
1093 static inline bool
nir_src_is_if(const nir_src * src)1094 nir_src_is_if(const nir_src *src)
1095 {
1096    return src->_parent & NIR_SRC_PARENT_IS_IF;
1097 }
1098 
1099 static inline nir_instr *
nir_src_parent_instr(const nir_src * src)1100 nir_src_parent_instr(const nir_src *src)
1101 {
1102    assert(!nir_src_is_if(src));
1103 
1104    /* Because it is not an if, the tag is 0, therefore we do not need to mask */
1105    return (nir_instr *)(src->_parent);
1106 }
1107 
1108 static inline struct nir_if *
nir_src_parent_if(const nir_src * src)1109 nir_src_parent_if(const nir_src *src)
1110 {
1111    assert(nir_src_is_if(src));
1112 
1113    /* Because it is an if, the tag is 1, so we need to mask */
1114    return (struct nir_if *)(src->_parent & NIR_SRC_PARENT_MASK);
1115 }
1116 
1117 static inline void
_nir_src_set_parent(nir_src * src,void * parent,bool is_if)1118 _nir_src_set_parent(nir_src *src, void *parent, bool is_if)
1119 {
1120     uintptr_t ptr = (uintptr_t) parent;
1121     assert((ptr & ~NIR_SRC_PARENT_MASK) == 0 && "pointer must be aligned");
1122 
1123     if (is_if)
1124        ptr |= NIR_SRC_PARENT_IS_IF;
1125 
1126     src->_parent = ptr;
1127 }
1128 
1129 static inline void
nir_src_set_parent_instr(nir_src * src,nir_instr * parent_instr)1130 nir_src_set_parent_instr(nir_src *src, nir_instr *parent_instr)
1131 {
1132    _nir_src_set_parent(src, parent_instr, false);
1133 }
1134 
1135 static inline void
nir_src_set_parent_if(nir_src * src,struct nir_if * parent_if)1136 nir_src_set_parent_if(nir_src *src, struct nir_if *parent_if)
1137 {
1138    _nir_src_set_parent(src, parent_if, true);
1139 }
1140 
1141 static inline nir_src
nir_src_init(void)1142 nir_src_init(void)
1143 {
1144    nir_src src = { 0 };
1145    return src;
1146 }
1147 
1148 #define NIR_SRC_INIT nir_src_init()
1149 
1150 #define nir_foreach_use_including_if(src, reg_or_ssa_def) \
1151    list_for_each_entry(nir_src, src, &(reg_or_ssa_def)->uses, use_link)
1152 
1153 #define nir_foreach_use_including_if_safe(src, reg_or_ssa_def) \
1154    list_for_each_entry_safe(nir_src, src, &(reg_or_ssa_def)->uses, use_link)
1155 
1156 #define nir_foreach_use(src, reg_or_ssa_def)         \
1157    nir_foreach_use_including_if(src, reg_or_ssa_def) \
1158       if (!nir_src_is_if(src))
1159 
1160 #define nir_foreach_use_safe(src, reg_or_ssa_def)         \
1161    nir_foreach_use_including_if_safe(src, reg_or_ssa_def) \
1162       if (!nir_src_is_if(src))
1163 
1164 #define nir_foreach_if_use(src, reg_or_ssa_def)      \
1165    nir_foreach_use_including_if(src, reg_or_ssa_def) \
1166       if (nir_src_is_if(src))
1167 
1168 #define nir_foreach_if_use_safe(src, reg_or_ssa_def)      \
1169    nir_foreach_use_including_if_safe(src, reg_or_ssa_def) \
1170       if (nir_src_is_if(src))
1171 
1172 static inline bool
nir_def_used_by_if(const nir_def * def)1173 nir_def_used_by_if(const nir_def *def)
1174 {
1175    nir_foreach_if_use(_, def)
1176       return true;
1177 
1178    return false;
1179 }
1180 
1181 static inline bool
nir_def_only_used_by_if(const nir_def * def)1182 nir_def_only_used_by_if(const nir_def *def)
1183 {
1184    nir_foreach_use(_, def)
1185       return false;
1186 
1187    return true;
1188 }
1189 
1190 static inline nir_src
nir_src_for_ssa(nir_def * def)1191 nir_src_for_ssa(nir_def *def)
1192 {
1193    nir_src src = NIR_SRC_INIT;
1194 
1195    src.ssa = def;
1196 
1197    return src;
1198 }
1199 
1200 static inline unsigned
nir_src_bit_size(nir_src src)1201 nir_src_bit_size(nir_src src)
1202 {
1203    return src.ssa->bit_size;
1204 }
1205 
1206 static inline unsigned
nir_src_num_components(nir_src src)1207 nir_src_num_components(nir_src src)
1208 {
1209    return src.ssa->num_components;
1210 }
1211 
1212 static inline bool
nir_src_is_const(nir_src src)1213 nir_src_is_const(nir_src src)
1214 {
1215    return src.ssa->parent_instr->type == nir_instr_type_load_const;
1216 }
1217 
1218 static inline bool
nir_src_is_undef(nir_src src)1219 nir_src_is_undef(nir_src src)
1220 {
1221    return src.ssa->parent_instr->type == nir_instr_type_undef;
1222 }
1223 
1224 bool nir_src_is_divergent(nir_src *src);
1225 
1226 /* Are all components the same, ie. .xxxx */
1227 static inline bool
nir_is_same_comp_swizzle(uint8_t * swiz,unsigned nr_comp)1228 nir_is_same_comp_swizzle(uint8_t *swiz, unsigned nr_comp)
1229 {
1230    for (unsigned i = 1; i < nr_comp; i++)
1231       if (swiz[i] != swiz[0])
1232          return false;
1233    return true;
1234 }
1235 
1236 /* Are all components sequential, ie. .yzw */
1237 static inline bool
nir_is_sequential_comp_swizzle(uint8_t * swiz,unsigned nr_comp)1238 nir_is_sequential_comp_swizzle(uint8_t *swiz, unsigned nr_comp)
1239 {
1240    for (unsigned i = 1; i < nr_comp; i++)
1241       if (swiz[i] != (swiz[0] + i))
1242          return false;
1243    return true;
1244 }
1245 
1246 /***/
1247 typedef struct nir_alu_src {
1248    /** Base source */
1249    nir_src src;
1250 
1251    /**
1252     * For each input component, says which component of the register it is
1253     * chosen from.
1254     *
1255     * Note that which elements of the swizzle are used and which are ignored
1256     * are based on the write mask for most opcodes - for example, a statement
1257     * like "foo.xzw = bar.zyx" would have a writemask of 1101b and a swizzle
1258     * of {2, 1, x, 0} where x means "don't care."
1259     */
1260    uint8_t swizzle[NIR_MAX_VEC_COMPONENTS];
1261 } nir_alu_src;
1262 
1263 nir_alu_type
1264 nir_get_nir_type_for_glsl_base_type(enum glsl_base_type base_type);
1265 
1266 static inline nir_alu_type
nir_get_nir_type_for_glsl_type(const struct glsl_type * type)1267 nir_get_nir_type_for_glsl_type(const struct glsl_type *type)
1268 {
1269    return nir_get_nir_type_for_glsl_base_type(glsl_get_base_type(type));
1270 }
1271 
1272 enum glsl_base_type
1273 nir_get_glsl_base_type_for_nir_type(nir_alu_type base_type);
1274 
1275 nir_op nir_type_conversion_op(nir_alu_type src, nir_alu_type dst,
1276                               nir_rounding_mode rnd);
1277 
1278 /**
1279  * Atomic intrinsics perform different operations depending on the value of
1280  * their atomic_op constant index. nir_atomic_op defines the operations.
1281  */
1282 typedef enum {
1283    nir_atomic_op_iadd,
1284    nir_atomic_op_imin,
1285    nir_atomic_op_umin,
1286    nir_atomic_op_imax,
1287    nir_atomic_op_umax,
1288    nir_atomic_op_iand,
1289    nir_atomic_op_ior,
1290    nir_atomic_op_ixor,
1291    nir_atomic_op_xchg,
1292    nir_atomic_op_fadd,
1293    nir_atomic_op_fmin,
1294    nir_atomic_op_fmax,
1295    nir_atomic_op_cmpxchg,
1296    nir_atomic_op_fcmpxchg,
1297    nir_atomic_op_inc_wrap,
1298    nir_atomic_op_dec_wrap,
1299    nir_atomic_op_ordered_add_gfx12_amd,
1300 } nir_atomic_op;
1301 
1302 static inline nir_alu_type
nir_atomic_op_type(nir_atomic_op op)1303 nir_atomic_op_type(nir_atomic_op op)
1304 {
1305    switch (op) {
1306    case nir_atomic_op_imin:
1307    case nir_atomic_op_imax:
1308       return nir_type_int;
1309 
1310    case nir_atomic_op_fadd:
1311    case nir_atomic_op_fmin:
1312    case nir_atomic_op_fmax:
1313    case nir_atomic_op_fcmpxchg:
1314       return nir_type_float;
1315 
1316    case nir_atomic_op_iadd:
1317    case nir_atomic_op_iand:
1318    case nir_atomic_op_ior:
1319    case nir_atomic_op_ixor:
1320    case nir_atomic_op_xchg:
1321    case nir_atomic_op_cmpxchg:
1322    case nir_atomic_op_umin:
1323    case nir_atomic_op_umax:
1324    case nir_atomic_op_inc_wrap:
1325    case nir_atomic_op_dec_wrap:
1326    case nir_atomic_op_ordered_add_gfx12_amd:
1327       return nir_type_uint;
1328    }
1329 
1330    unreachable("Invalid nir_atomic_op");
1331 }
1332 
1333 nir_op
1334 nir_atomic_op_to_alu(nir_atomic_op op);
1335 
1336 /** Returns nir_op_vec<num_components> or nir_op_mov if num_components == 1
1337  *
1338  * This is subtly different from nir_op_is_vec() which returns false for
1339  * nir_op_mov.  Returning nir_op_mov from nir_op_vec() when num_components == 1
1340  * makes sense under the assumption that the num_components of the resulting
1341  * nir_def will same as what is passed in here because a single-component mov
1342  * is effectively a vec1.  However, if alu->def.num_components > 1, nir_op_mov
1343  * has different semantics from nir_op_vec* so so code which detects "is this
1344  * a vec?" typically needs to handle nir_op_mov separate from nir_op_vecN.
1345  *
1346  * In the unlikely case where you can handle nir_op_vecN and nir_op_mov
1347  * together, use nir_op_is_vec_or_mov().
1348  */
1349 nir_op
1350 nir_op_vec(unsigned num_components);
1351 
1352 /** Returns true if this op is one of nir_op_vec*
1353  *
1354  * Returns false for nir_op_mov.  See nir_op_vec() for more details.
1355  */
1356 bool
1357 nir_op_is_vec(nir_op op);
1358 
1359 static inline bool
nir_op_is_vec_or_mov(nir_op op)1360 nir_op_is_vec_or_mov(nir_op op)
1361 {
1362    return op == nir_op_mov || nir_op_is_vec(op);
1363 }
1364 
1365 static inline bool
nir_is_float_control_signed_zero_preserve(unsigned execution_mode,unsigned bit_size)1366 nir_is_float_control_signed_zero_preserve(unsigned execution_mode, unsigned bit_size)
1367 {
1368    return (16 == bit_size && execution_mode & FLOAT_CONTROLS_SIGNED_ZERO_PRESERVE_FP16) ||
1369           (32 == bit_size && execution_mode & FLOAT_CONTROLS_SIGNED_ZERO_PRESERVE_FP32) ||
1370           (64 == bit_size && execution_mode & FLOAT_CONTROLS_SIGNED_ZERO_PRESERVE_FP64);
1371 }
1372 
1373 static inline bool
nir_is_float_control_inf_preserve(unsigned execution_mode,unsigned bit_size)1374 nir_is_float_control_inf_preserve(unsigned execution_mode, unsigned bit_size)
1375 {
1376    return (16 == bit_size && execution_mode & FLOAT_CONTROLS_INF_PRESERVE_FP16) ||
1377           (32 == bit_size && execution_mode & FLOAT_CONTROLS_INF_PRESERVE_FP32) ||
1378           (64 == bit_size && execution_mode & FLOAT_CONTROLS_INF_PRESERVE_FP64);
1379 }
1380 
1381 static inline bool
nir_is_float_control_nan_preserve(unsigned execution_mode,unsigned bit_size)1382 nir_is_float_control_nan_preserve(unsigned execution_mode, unsigned bit_size)
1383 {
1384    return (16 == bit_size && execution_mode & FLOAT_CONTROLS_NAN_PRESERVE_FP16) ||
1385           (32 == bit_size && execution_mode & FLOAT_CONTROLS_NAN_PRESERVE_FP32) ||
1386           (64 == bit_size && execution_mode & FLOAT_CONTROLS_NAN_PRESERVE_FP64);
1387 }
1388 
1389 static inline bool
nir_is_float_control_signed_zero_inf_nan_preserve(unsigned execution_mode,unsigned bit_size)1390 nir_is_float_control_signed_zero_inf_nan_preserve(unsigned execution_mode, unsigned bit_size)
1391 {
1392    return (16 == bit_size && execution_mode & FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP16) ||
1393           (32 == bit_size && execution_mode & FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP32) ||
1394           (64 == bit_size && execution_mode & FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP64);
1395 }
1396 
1397 static inline bool
nir_is_denorm_flush_to_zero(unsigned execution_mode,unsigned bit_size)1398 nir_is_denorm_flush_to_zero(unsigned execution_mode, unsigned bit_size)
1399 {
1400    return (16 == bit_size && execution_mode & FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP16) ||
1401           (32 == bit_size && execution_mode & FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP32) ||
1402           (64 == bit_size && execution_mode & FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP64);
1403 }
1404 
1405 static inline bool
nir_is_denorm_preserve(unsigned execution_mode,unsigned bit_size)1406 nir_is_denorm_preserve(unsigned execution_mode, unsigned bit_size)
1407 {
1408    return (16 == bit_size && execution_mode & FLOAT_CONTROLS_DENORM_PRESERVE_FP16) ||
1409           (32 == bit_size && execution_mode & FLOAT_CONTROLS_DENORM_PRESERVE_FP32) ||
1410           (64 == bit_size && execution_mode & FLOAT_CONTROLS_DENORM_PRESERVE_FP64);
1411 }
1412 
1413 static inline bool
nir_is_rounding_mode_rtne(unsigned execution_mode,unsigned bit_size)1414 nir_is_rounding_mode_rtne(unsigned execution_mode, unsigned bit_size)
1415 {
1416    return (16 == bit_size && execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP16) ||
1417           (32 == bit_size && execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP32) ||
1418           (64 == bit_size && execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP64);
1419 }
1420 
1421 static inline bool
nir_is_rounding_mode_rtz(unsigned execution_mode,unsigned bit_size)1422 nir_is_rounding_mode_rtz(unsigned execution_mode, unsigned bit_size)
1423 {
1424    return (16 == bit_size && execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16) ||
1425           (32 == bit_size && execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32) ||
1426           (64 == bit_size && execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64);
1427 }
1428 
1429 static inline bool
nir_has_any_rounding_mode_rtz(unsigned execution_mode)1430 nir_has_any_rounding_mode_rtz(unsigned execution_mode)
1431 {
1432    return (execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16) ||
1433           (execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32) ||
1434           (execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64);
1435 }
1436 
1437 static inline bool
nir_has_any_rounding_mode_rtne(unsigned execution_mode)1438 nir_has_any_rounding_mode_rtne(unsigned execution_mode)
1439 {
1440    return (execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP16) ||
1441           (execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP32) ||
1442           (execution_mode & FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP64);
1443 }
1444 
1445 static inline nir_rounding_mode
nir_get_rounding_mode_from_float_controls(unsigned execution_mode,nir_alu_type type)1446 nir_get_rounding_mode_from_float_controls(unsigned execution_mode,
1447                                           nir_alu_type type)
1448 {
1449    if (nir_alu_type_get_base_type(type) != nir_type_float)
1450       return nir_rounding_mode_undef;
1451 
1452    unsigned bit_size = nir_alu_type_get_type_size(type);
1453 
1454    if (nir_is_rounding_mode_rtz(execution_mode, bit_size))
1455       return nir_rounding_mode_rtz;
1456    if (nir_is_rounding_mode_rtne(execution_mode, bit_size))
1457       return nir_rounding_mode_rtne;
1458    return nir_rounding_mode_undef;
1459 }
1460 
1461 static inline bool
nir_has_any_rounding_mode_enabled(unsigned execution_mode)1462 nir_has_any_rounding_mode_enabled(unsigned execution_mode)
1463 {
1464    bool result =
1465       nir_has_any_rounding_mode_rtne(execution_mode) ||
1466       nir_has_any_rounding_mode_rtz(execution_mode);
1467    return result;
1468 }
1469 
1470 typedef enum {
1471    /**
1472     * Operation where the first two sources are commutative.
1473     *
1474     * For 2-source operations, this just mathematical commutativity.  Some
1475     * 3-source operations, like ffma, are only commutative in the first two
1476     * sources.
1477     */
1478    NIR_OP_IS_2SRC_COMMUTATIVE = (1 << 0),
1479 
1480    /**
1481     * Operation is associative
1482     */
1483    NIR_OP_IS_ASSOCIATIVE = (1 << 1),
1484 
1485    /**
1486     * Operation where src[0] is used to select src[1] on true or src[2] false.
1487     * src[0] may be Boolean, or it may be another type used in an implicit
1488     * comparison.
1489     */
1490    NIR_OP_IS_SELECTION = (1 << 2),
1491 } nir_op_algebraic_property;
1492 
1493 /* vec16 is the widest ALU op in NIR, making the max number of input of ALU
1494  * instructions to be the same as NIR_MAX_VEC_COMPONENTS.
1495  */
1496 #define NIR_ALU_MAX_INPUTS NIR_MAX_VEC_COMPONENTS
1497 
1498 /***/
1499 typedef struct nir_op_info {
1500    /** Name of the NIR ALU opcode */
1501    const char *name;
1502 
1503    /** Number of inputs (sources) */
1504    uint8_t num_inputs;
1505 
1506    /**
1507     * The number of components in the output
1508     *
1509     * If non-zero, this is the size of the output and input sizes are
1510     * explicitly given; swizzle and writemask are still in effect, but if
1511     * the output component is masked out, then the input component may
1512     * still be in use.
1513     *
1514     * If zero, the opcode acts in the standard, per-component manner; the
1515     * operation is performed on each component (except the ones that are
1516     * masked out) with the input being taken from the input swizzle for
1517     * that component.
1518     *
1519     * The size of some of the inputs may be given (i.e. non-zero) even
1520     * though output_size is zero; in that case, the inputs with a zero
1521     * size act per-component, while the inputs with non-zero size don't.
1522     */
1523    uint8_t output_size;
1524 
1525    /**
1526     * The type of vector that the instruction outputs.
1527     */
1528    nir_alu_type output_type;
1529 
1530    /**
1531     * The number of components in each input
1532     *
1533     * See nir_op_infos::output_size for more detail about the relationship
1534     * between input and output sizes.
1535     */
1536    uint8_t input_sizes[NIR_ALU_MAX_INPUTS];
1537 
1538    /**
1539     * The type of vector that each input takes.
1540     */
1541    nir_alu_type input_types[NIR_ALU_MAX_INPUTS];
1542 
1543    /** Algebraic properties of this opcode */
1544    nir_op_algebraic_property algebraic_properties;
1545 
1546    /** Whether this represents a numeric conversion opcode */
1547    bool is_conversion;
1548 } nir_op_info;
1549 
1550 /** Metadata for each nir_op, indexed by opcode */
1551 extern const nir_op_info nir_op_infos[nir_num_opcodes];
1552 
1553 static inline bool
nir_op_is_selection(nir_op op)1554 nir_op_is_selection(nir_op op)
1555 {
1556    return (nir_op_infos[op].algebraic_properties & NIR_OP_IS_SELECTION) != 0;
1557 }
1558 
1559 /***/
1560 typedef struct nir_alu_instr {
1561    /** Base instruction */
1562    nir_instr instr;
1563 
1564    /** Opcode */
1565    nir_op op;
1566 
1567    /** Indicates that this ALU instruction generates an exact value
1568     *
1569     * This is kind of a mixture of GLSL "precise" and "invariant" and not
1570     * really equivalent to either.  This indicates that the value generated by
1571     * this operation is high-precision and any code transformations that touch
1572     * it must ensure that the resulting value is bit-for-bit identical to the
1573     * original.
1574     */
1575    bool exact : 1;
1576 
1577    /**
1578     * Indicates that this instruction doese not cause signed integer wrapping
1579     * to occur, in the form of overflow or underflow.
1580     */
1581    bool no_signed_wrap : 1;
1582 
1583    /**
1584     * Indicates that this instruction does not cause unsigned integer wrapping
1585     * to occur, in the form of overflow or underflow.
1586     */
1587    bool no_unsigned_wrap : 1;
1588 
1589    /**
1590     * The float controls bit float_controls2 cares about. That is,
1591     * NAN/INF/SIGNED_ZERO_PRESERVE only. Allow{Contract,Reassoc,Transform} are
1592     * still handled through the exact bit, and the other float controls bits
1593     * (rounding mode and denorm handling) remain in the execution mode only.
1594     */
1595    uint32_t fp_fast_math : 9;
1596 
1597    /** Destination */
1598    nir_def def;
1599 
1600    /** Sources
1601     *
1602     * The size of the array is given by :c:member:`nir_op_info.num_inputs`.
1603     */
1604    nir_alu_src src[];
1605 } nir_alu_instr;
1606 
1607 static inline bool
nir_alu_instr_is_signed_zero_preserve(nir_alu_instr * alu)1608 nir_alu_instr_is_signed_zero_preserve(nir_alu_instr *alu)
1609 {
1610    return nir_is_float_control_signed_zero_preserve(alu->fp_fast_math, alu->def.bit_size);
1611 }
1612 
1613 static inline bool
nir_alu_instr_is_inf_preserve(nir_alu_instr * alu)1614 nir_alu_instr_is_inf_preserve(nir_alu_instr *alu)
1615 {
1616    return nir_is_float_control_inf_preserve(alu->fp_fast_math, alu->def.bit_size);
1617 }
1618 
1619 static inline bool
nir_alu_instr_is_nan_preserve(nir_alu_instr * alu)1620 nir_alu_instr_is_nan_preserve(nir_alu_instr *alu)
1621 {
1622    return nir_is_float_control_nan_preserve(alu->fp_fast_math, alu->def.bit_size);
1623 }
1624 
1625 static inline bool
nir_alu_instr_is_signed_zero_inf_nan_preserve(nir_alu_instr * alu)1626 nir_alu_instr_is_signed_zero_inf_nan_preserve(nir_alu_instr *alu)
1627 {
1628    return nir_is_float_control_signed_zero_inf_nan_preserve(alu->fp_fast_math, alu->def.bit_size);
1629 }
1630 
1631 void nir_alu_src_copy(nir_alu_src *dest, const nir_alu_src *src);
1632 
1633 nir_component_mask_t
1634 nir_alu_instr_src_read_mask(const nir_alu_instr *instr, unsigned src);
1635 /**
1636  * Get the number of channels used for a source
1637  */
1638 unsigned
1639 nir_ssa_alu_instr_src_components(const nir_alu_instr *instr, unsigned src);
1640 
1641 /* is this source channel used? */
1642 static inline bool
nir_alu_instr_channel_used(const nir_alu_instr * instr,unsigned src,unsigned channel)1643 nir_alu_instr_channel_used(const nir_alu_instr *instr, unsigned src,
1644                            unsigned channel)
1645 {
1646    return channel < nir_ssa_alu_instr_src_components(instr, src);
1647 }
1648 
1649 bool
1650 nir_alu_instr_is_comparison(const nir_alu_instr *instr);
1651 
1652 bool nir_const_value_negative_equal(nir_const_value c1, nir_const_value c2,
1653                                     nir_alu_type full_type);
1654 
1655 bool nir_alu_srcs_equal(const nir_alu_instr *alu1, const nir_alu_instr *alu2,
1656                         unsigned src1, unsigned src2);
1657 
1658 bool nir_alu_srcs_negative_equal_typed(const nir_alu_instr *alu1,
1659                                        const nir_alu_instr *alu2,
1660                                        unsigned src1, unsigned src2,
1661                                        nir_alu_type base_type);
1662 bool nir_alu_srcs_negative_equal(const nir_alu_instr *alu1,
1663                                  const nir_alu_instr *alu2,
1664                                  unsigned src1, unsigned src2);
1665 
1666 bool nir_alu_src_is_trivial_ssa(const nir_alu_instr *alu, unsigned srcn);
1667 
1668 typedef enum {
1669    nir_deref_type_var,
1670    nir_deref_type_array,
1671    nir_deref_type_array_wildcard,
1672    nir_deref_type_ptr_as_array,
1673    nir_deref_type_struct,
1674    nir_deref_type_cast,
1675 } nir_deref_type;
1676 
1677 typedef struct {
1678    nir_instr instr;
1679 
1680    /** The type of this deref instruction */
1681    nir_deref_type deref_type;
1682 
1683    /** Bitmask what modes the underlying variable might be
1684     *
1685     * For OpenCL-style generic pointers, we may not know exactly what mode it
1686     * is at any given point in time in the compile process.  This bitfield
1687     * contains the set of modes which it MAY be.
1688     *
1689     * Generally, this field should not be accessed directly.  Use one of the
1690     * nir_deref_mode_ helpers instead.
1691     */
1692    nir_variable_mode modes;
1693 
1694    /** The dereferenced type of the resulting pointer value */
1695    const struct glsl_type *type;
1696 
1697    union {
1698       /** Variable being dereferenced if deref_type is a deref_var */
1699       nir_variable *var;
1700 
1701       /** Parent deref if deref_type is not deref_var */
1702       nir_src parent;
1703    };
1704 
1705    /** Additional deref parameters */
1706    union {
1707       struct {
1708          nir_src index;
1709          bool in_bounds;
1710       } arr;
1711 
1712       struct {
1713          unsigned index;
1714       } strct;
1715 
1716       struct {
1717          unsigned ptr_stride;
1718          unsigned align_mul;
1719          unsigned align_offset;
1720       } cast;
1721    };
1722 
1723    /** Destination to store the resulting "pointer" */
1724    nir_def def;
1725 } nir_deref_instr;
1726 
1727 /**
1728  * Returns true if the cast is trivial, i.e. the source and destination type is
1729  * the same.
1730  */
1731 bool nir_deref_cast_is_trivial(nir_deref_instr *cast);
1732 
1733 /** Returns true if deref might have one of the given modes
1734  *
1735  * For multi-mode derefs, this returns true if any of the possible modes for
1736  * the deref to have any of the specified modes.  This function returning true
1737  * does NOT mean that the deref definitely has one of those modes.  It simply
1738  * means that, with the best information we have at the time, it might.
1739  */
1740 static inline bool
nir_deref_mode_may_be(const nir_deref_instr * deref,nir_variable_mode modes)1741 nir_deref_mode_may_be(const nir_deref_instr *deref, nir_variable_mode modes)
1742 {
1743    assert(!(modes & ~nir_var_all));
1744    assert(deref->modes != 0);
1745    return deref->modes & modes;
1746 }
1747 
1748 /** Returns true if deref must have one of the given modes
1749  *
1750  * For multi-mode derefs, this returns true if NIR can prove that the given
1751  * deref has one of the specified modes.  This function returning false does
1752  * NOT mean that deref doesn't have one of the given mode.  It very well may
1753  * have one of those modes, we just don't have enough information to prove
1754  * that it does for sure.
1755  */
1756 static inline bool
nir_deref_mode_must_be(const nir_deref_instr * deref,nir_variable_mode modes)1757 nir_deref_mode_must_be(const nir_deref_instr *deref, nir_variable_mode modes)
1758 {
1759    assert(!(modes & ~nir_var_all));
1760    assert(deref->modes != 0);
1761    return !(deref->modes & ~modes);
1762 }
1763 
1764 /** Returns true if deref has the given mode
1765  *
1766  * This returns true if the deref has exactly the mode specified.  If the
1767  * deref may have that mode but may also have a different mode (i.e. modes has
1768  * multiple bits set), this will assert-fail.
1769  *
1770  * If you're confused about which nir_deref_mode_ helper to use, use this one
1771  * or nir_deref_mode_is_one_of below.
1772  */
1773 static inline bool
nir_deref_mode_is(const nir_deref_instr * deref,nir_variable_mode mode)1774 nir_deref_mode_is(const nir_deref_instr *deref, nir_variable_mode mode)
1775 {
1776    assert(util_bitcount(mode) == 1 && (mode & nir_var_all));
1777    assert(deref->modes != 0);
1778 
1779    /* This is only for "simple" cases so, if modes might interact with this
1780     * deref then the deref has to have a single mode.
1781     */
1782    if (nir_deref_mode_may_be(deref, mode)) {
1783       assert(util_bitcount(deref->modes) == 1);
1784       assert(deref->modes == mode);
1785    }
1786 
1787    return deref->modes == mode;
1788 }
1789 
1790 /** Returns true if deref has one of the given modes
1791  *
1792  * This returns true if the deref has exactly one possible mode and that mode
1793  * is one of the modes specified.  If the deref may have one of those modes
1794  * but may also have a different mode (i.e. modes has multiple bits set), this
1795  * will assert-fail.
1796  */
1797 static inline bool
nir_deref_mode_is_one_of(const nir_deref_instr * deref,nir_variable_mode modes)1798 nir_deref_mode_is_one_of(const nir_deref_instr *deref, nir_variable_mode modes)
1799 {
1800    /* This is only for "simple" cases so, if modes might interact with this
1801     * deref then the deref has to have a single mode.
1802     */
1803    if (nir_deref_mode_may_be(deref, modes)) {
1804       assert(util_bitcount(deref->modes) == 1);
1805       assert(nir_deref_mode_must_be(deref, modes));
1806    }
1807 
1808    return nir_deref_mode_may_be(deref, modes);
1809 }
1810 
1811 /** Returns true if deref's possible modes lie in the given set of modes
1812  *
1813  * This returns true if the deref's modes lie in the given set of modes.  If
1814  * the deref's modes overlap with the specified modes but aren't entirely
1815  * contained in the specified set of modes, this will assert-fail.  In
1816  * particular, if this is used in a generic pointers scenario, the specified
1817  * modes has to contain all or none of the possible generic pointer modes.
1818  *
1819  * This is intended mostly for mass-lowering of derefs which might have
1820  * generic pointers.
1821  */
1822 static inline bool
nir_deref_mode_is_in_set(const nir_deref_instr * deref,nir_variable_mode modes)1823 nir_deref_mode_is_in_set(const nir_deref_instr *deref, nir_variable_mode modes)
1824 {
1825    if (nir_deref_mode_may_be(deref, modes))
1826       assert(nir_deref_mode_must_be(deref, modes));
1827 
1828    return nir_deref_mode_may_be(deref, modes);
1829 }
1830 
1831 static inline nir_deref_instr *nir_src_as_deref(nir_src src);
1832 
1833 static inline nir_deref_instr *
nir_deref_instr_parent(const nir_deref_instr * instr)1834 nir_deref_instr_parent(const nir_deref_instr *instr)
1835 {
1836    if (instr->deref_type == nir_deref_type_var)
1837       return NULL;
1838    else
1839       return nir_src_as_deref(instr->parent);
1840 }
1841 
1842 static inline nir_variable *
nir_deref_instr_get_variable(const nir_deref_instr * instr)1843 nir_deref_instr_get_variable(const nir_deref_instr *instr)
1844 {
1845    while (instr->deref_type != nir_deref_type_var) {
1846       if (instr->deref_type == nir_deref_type_cast)
1847          return NULL;
1848 
1849       instr = nir_deref_instr_parent(instr);
1850    }
1851 
1852    return instr->var;
1853 }
1854 
1855 bool nir_deref_instr_has_indirect(nir_deref_instr *instr);
1856 bool nir_deref_instr_is_known_out_of_bounds(nir_deref_instr *instr);
1857 
1858 typedef enum {
1859    nir_deref_instr_has_complex_use_allow_memcpy_src = (1 << 0),
1860    nir_deref_instr_has_complex_use_allow_memcpy_dst = (1 << 1),
1861    nir_deref_instr_has_complex_use_allow_atomics = (1 << 2),
1862 } nir_deref_instr_has_complex_use_options;
1863 
1864 bool nir_deref_instr_has_complex_use(nir_deref_instr *instr,
1865                                      nir_deref_instr_has_complex_use_options opts);
1866 
1867 bool nir_deref_instr_remove_if_unused(nir_deref_instr *instr);
1868 
1869 unsigned nir_deref_instr_array_stride(nir_deref_instr *instr);
1870 
1871 typedef struct {
1872    nir_instr instr;
1873 
1874    struct nir_function *callee;
1875 
1876    unsigned num_params;
1877    nir_src params[];
1878 } nir_call_instr;
1879 
1880 #include "nir_intrinsics.h"
1881 
1882 #define NIR_INTRINSIC_MAX_CONST_INDEX 8
1883 
1884 /** Represents an intrinsic
1885  *
1886  * An intrinsic is an instruction type for handling things that are
1887  * more-or-less regular operations but don't just consume and produce SSA
1888  * values like ALU operations do.  Intrinsics are not for things that have
1889  * special semantic meaning such as phi nodes and parallel copies.
1890  * Examples of intrinsics include variable load/store operations, system
1891  * value loads, and the like.  Even though texturing more-or-less falls
1892  * under this category, texturing is its own instruction type because
1893  * trying to represent texturing with intrinsics would lead to a
1894  * combinatorial explosion of intrinsic opcodes.
1895  *
1896  * By having a single instruction type for handling a lot of different
1897  * cases, optimization passes can look for intrinsics and, for the most
1898  * part, completely ignore them.  Each intrinsic type also has a few
1899  * possible flags that govern whether or not they can be reordered or
1900  * eliminated.  That way passes like dead code elimination can still work
1901  * on intrisics without understanding the meaning of each.
1902  *
1903  * Each intrinsic has some number of constant indices, some number of
1904  * variables, and some number of sources.  What these sources, variables,
1905  * and indices mean depends on the intrinsic and is documented with the
1906  * intrinsic declaration in nir_intrinsics.h.  Intrinsics and texture
1907  * instructions are the only types of instruction that can operate on
1908  * variables.
1909  */
1910 typedef struct {
1911    nir_instr instr;
1912 
1913    nir_intrinsic_op intrinsic;
1914 
1915    nir_def def;
1916 
1917    /** number of components if this is a vectorized intrinsic
1918     *
1919     * Similarly to ALU operations, some intrinsics are vectorized.
1920     * An intrinsic is vectorized if nir_intrinsic_infos.dest_components == 0.
1921     * For vectorized intrinsics, the num_components field specifies the
1922     * number of destination components and the number of source components
1923     * for all sources with nir_intrinsic_infos.src_components[i] == 0.
1924     */
1925    uint8_t num_components;
1926 
1927    int const_index[NIR_INTRINSIC_MAX_CONST_INDEX];
1928 
1929    /* a variable name associated with this instr; cannot be modified or freed */
1930    const char *name;
1931 
1932    nir_src src[];
1933 } nir_intrinsic_instr;
1934 
1935 static inline nir_variable *
nir_intrinsic_get_var(const nir_intrinsic_instr * intrin,unsigned i)1936 nir_intrinsic_get_var(const nir_intrinsic_instr *intrin, unsigned i)
1937 {
1938    return nir_deref_instr_get_variable(nir_src_as_deref(intrin->src[i]));
1939 }
1940 
1941 typedef enum {
1942    /* Memory ordering. */
1943    NIR_MEMORY_ACQUIRE = 1 << 0,
1944    NIR_MEMORY_RELEASE = 1 << 1,
1945    NIR_MEMORY_ACQ_REL = NIR_MEMORY_ACQUIRE | NIR_MEMORY_RELEASE,
1946 
1947    /* Memory visibility operations. */
1948    NIR_MEMORY_MAKE_AVAILABLE = 1 << 2,
1949    NIR_MEMORY_MAKE_VISIBLE = 1 << 3,
1950 } nir_memory_semantics;
1951 
1952 /**
1953  * NIR intrinsics semantic flags
1954  *
1955  * information about what the compiler can do with the intrinsics.
1956  *
1957  * :c:member:`nir_intrinsic_info.flags`
1958  */
1959 typedef enum {
1960    /**
1961     * whether the intrinsic can be safely eliminated if none of its output
1962     * value is not being used.
1963     */
1964    NIR_INTRINSIC_CAN_ELIMINATE = (1 << 0),
1965 
1966    /**
1967     * Whether the intrinsic can be reordered with respect to any other
1968     * intrinsic, i.e. whether the only reordering dependencies of the
1969     * intrinsic are due to the register reads/writes.
1970     */
1971    NIR_INTRINSIC_CAN_REORDER = (1 << 1),
1972 } nir_intrinsic_semantic_flag;
1973 
1974 /**
1975  * Maximum valid value for a nir align_mul value (in intrinsics or derefs).
1976  *
1977  * Offsets can be signed, so this is the largest power of two in int32_t.
1978  */
1979 #define NIR_ALIGN_MUL_MAX 0x40000000
1980 
1981 typedef struct nir_io_semantics {
1982    unsigned location : 7;  /* gl_vert_attrib, gl_varying_slot, or gl_frag_result */
1983    unsigned num_slots : 6; /* max 32, may be pessimistic with const indexing */
1984    unsigned dual_source_blend_index : 1;
1985    unsigned fb_fetch_output : 1;  /* for GL_KHR_blend_equation_advanced */
1986    unsigned fb_fetch_output_coherent : 1;
1987    unsigned gs_streams : 8;       /* xxyyzzww: 2-bit stream index for each component */
1988    unsigned medium_precision : 1; /* GLSL mediump qualifier */
1989    unsigned per_view : 1;
1990    unsigned high_16bits : 1; /* whether accessing low or high half of the slot */
1991    unsigned invariant : 1;   /* The variable has the invariant flag set */
1992    unsigned high_dvec2 : 1; /* whether accessing the high half of dvec3/dvec4 */
1993    /* CLIP_DISTn, LAYER, VIEWPORT, and TESS_LEVEL_* have up to 3 uses:
1994     * - an output consumed by the next stage
1995     * - a system value output affecting fixed-func hardware, e.g. the clipper
1996     * - a transform feedback output written to memory
1997     * The following fields disable the first two. Transform feedback is disabled
1998     * by transform feedback info.
1999     */
2000    unsigned no_varying : 1;       /* whether this output isn't consumed by the next stage */
2001    unsigned no_sysval_output : 1; /* whether this system value output has no
2002                                      effect due to current pipeline states */
2003    unsigned interp_explicit_strict : 1; /* preserve original vertex order */
2004 } nir_io_semantics;
2005 
2006 /* Transform feedback info for 2 outputs. nir_intrinsic_store_output contains
2007  * this structure twice to support up to 4 outputs. The structure is limited
2008  * to 32 bits because it's stored in nir_intrinsic_instr::const_index[].
2009  */
2010 typedef struct nir_io_xfb {
2011    struct {
2012       /* start_component is equal to the index of out[]; add 2 for io_xfb2 */
2013       /* start_component is not relative to nir_intrinsic_component */
2014       /* get the stream index from nir_io_semantics */
2015       uint8_t num_components : 4; /* max 4; if this is 0, xfb is disabled */
2016       uint8_t buffer : 4;         /* buffer index, max 3 */
2017       uint8_t offset;             /* transform feedback buffer offset in dwords,
2018                                      max (1K - 4) bytes */
2019    } out[2];
2020 } nir_io_xfb;
2021 
2022 unsigned
2023 nir_instr_xfb_write_mask(nir_intrinsic_instr *instr);
2024 
2025 #define NIR_INTRINSIC_MAX_INPUTS 11
2026 
2027 typedef struct {
2028    const char *name;
2029 
2030    /** number of register/SSA inputs */
2031    uint8_t num_srcs;
2032 
2033    /** number of components of each input register
2034     *
2035     * If this value is 0, the number of components is given by the
2036     * num_components field of nir_intrinsic_instr.  If this value is -1, the
2037     * intrinsic consumes however many components are provided and it is not
2038     * validated at all.
2039     */
2040    int8_t src_components[NIR_INTRINSIC_MAX_INPUTS];
2041 
2042    bool has_dest;
2043 
2044    /** number of components of the output register
2045     *
2046     * If this value is 0, the number of components is given by the
2047     * num_components field of nir_intrinsic_instr.
2048     */
2049    uint8_t dest_components;
2050 
2051    /** bitfield of legal bit sizes */
2052    uint8_t dest_bit_sizes;
2053 
2054    /** source which the destination bit size must match
2055     *
2056     * Some intrinsics, such as subgroup intrinsics, are data manipulation
2057     * intrinsics and they have similar bit-size rules to ALU ops. This enables
2058     * validation to validate a bit more and enables auto-generated builder code
2059     * to properly determine destination bit sizes automatically.
2060     */
2061    int8_t bit_size_src;
2062 
2063    /** the number of constant indices used by the intrinsic */
2064    uint8_t num_indices;
2065 
2066    /** list of indices */
2067    uint8_t indices[NIR_INTRINSIC_MAX_CONST_INDEX];
2068 
2069    /** indicates the usage of intr->const_index[n] */
2070    uint8_t index_map[NIR_INTRINSIC_NUM_INDEX_FLAGS];
2071 
2072    /** semantic flags for calls to this intrinsic */
2073    nir_intrinsic_semantic_flag flags;
2074 } nir_intrinsic_info;
2075 
2076 extern const nir_intrinsic_info nir_intrinsic_infos[nir_num_intrinsics];
2077 
2078 unsigned
2079 nir_intrinsic_src_components(const nir_intrinsic_instr *intr, unsigned srcn);
2080 
2081 unsigned
2082 nir_intrinsic_dest_components(nir_intrinsic_instr *intr);
2083 
2084 nir_alu_type
2085 nir_intrinsic_instr_src_type(const nir_intrinsic_instr *intrin, unsigned src);
2086 
2087 nir_alu_type
2088 nir_intrinsic_instr_dest_type(const nir_intrinsic_instr *intrin);
2089 
2090 /**
2091  * Helper to copy const_index[] from src to dst, without assuming they
2092  * match in order.
2093  */
2094 void nir_intrinsic_copy_const_indices(nir_intrinsic_instr *dst, nir_intrinsic_instr *src);
2095 
2096 #include "nir_intrinsics_indices.h"
2097 
2098 static inline void
nir_intrinsic_set_align(nir_intrinsic_instr * intrin,unsigned align_mul,unsigned align_offset)2099 nir_intrinsic_set_align(nir_intrinsic_instr *intrin,
2100                         unsigned align_mul, unsigned align_offset)
2101 {
2102    assert(util_is_power_of_two_nonzero(align_mul));
2103    assert(align_offset < align_mul);
2104    nir_intrinsic_set_align_mul(intrin, align_mul);
2105    nir_intrinsic_set_align_offset(intrin, align_offset);
2106 }
2107 
2108 /** Returns a simple alignment for an align_mul/offset pair
2109  *
2110  * This helper converts from the full mul+offset alignment scheme used by
2111  * most NIR intrinsics to a simple alignment.  The returned value is the
2112  * largest power of two which divides both align_mul and align_offset.
2113  * For any offset X which satisfies the complex alignment described by
2114  * align_mul/offset, X % align == 0.
2115  */
2116 static inline uint32_t
nir_combined_align(uint32_t align_mul,uint32_t align_offset)2117 nir_combined_align(uint32_t align_mul, uint32_t align_offset)
2118 {
2119    assert(util_is_power_of_two_nonzero(align_mul));
2120    assert(align_offset < align_mul);
2121    return align_offset ? 1 << (ffs(align_offset) - 1) : align_mul;
2122 }
2123 
2124 /** Returns a simple alignment for a load/store intrinsic offset
2125  *
2126  * Instead of the full mul+offset alignment scheme provided by the ALIGN_MUL
2127  * and ALIGN_OFFSET parameters, this helper takes both into account and
2128  * provides a single simple alignment parameter.  The offset X is guaranteed
2129  * to satisfy X % align == 0.
2130  */
2131 static inline unsigned
nir_intrinsic_align(const nir_intrinsic_instr * intrin)2132 nir_intrinsic_align(const nir_intrinsic_instr *intrin)
2133 {
2134    return nir_combined_align(nir_intrinsic_align_mul(intrin),
2135                              nir_intrinsic_align_offset(intrin));
2136 }
2137 
2138 static inline bool
nir_intrinsic_has_align(const nir_intrinsic_instr * intrin)2139 nir_intrinsic_has_align(const nir_intrinsic_instr *intrin)
2140 {
2141    return nir_intrinsic_has_align_mul(intrin) &&
2142           nir_intrinsic_has_align_offset(intrin);
2143 }
2144 
2145 unsigned
2146 nir_image_intrinsic_coord_components(const nir_intrinsic_instr *instr);
2147 
2148 /* Converts a image_deref_* intrinsic into a image_* one */
2149 void nir_rewrite_image_intrinsic(nir_intrinsic_instr *instr,
2150                                  nir_def *handle, bool bindless);
2151 
2152 /* Determine if an intrinsic can be arbitrarily reordered and eliminated. */
2153 bool nir_intrinsic_can_reorder(nir_intrinsic_instr *instr);
2154 
2155 bool nir_intrinsic_writes_external_memory(const nir_intrinsic_instr *instr);
2156 
2157 static inline bool
nir_intrinsic_is_ray_query(nir_intrinsic_op intrinsic)2158 nir_intrinsic_is_ray_query(nir_intrinsic_op intrinsic)
2159 {
2160    switch (intrinsic) {
2161    case nir_intrinsic_rq_confirm_intersection:
2162    case nir_intrinsic_rq_generate_intersection:
2163    case nir_intrinsic_rq_initialize:
2164    case nir_intrinsic_rq_load:
2165    case nir_intrinsic_rq_proceed:
2166    case nir_intrinsic_rq_terminate:
2167       return true;
2168    default:
2169       return false;
2170    }
2171 }
2172 
2173 /** Texture instruction source type */
2174 typedef enum nir_tex_src_type {
2175    /** Texture coordinate
2176     *
2177     * Must have :c:member:`nir_tex_instr.coord_components` components.
2178     */
2179    nir_tex_src_coord,
2180 
2181    /** Projector
2182     *
2183     * The texture coordinate (except for the array component, if any) is
2184     * divided by this value before LOD computation and sampling.
2185     *
2186     * Must be a float scalar.
2187     */
2188    nir_tex_src_projector,
2189 
2190    /** Shadow comparator
2191     *
2192     * For shadow sampling, the fetched texel values are compared against the
2193     * shadow comparator using the compare op specified by the sampler object
2194     * and converted to 1.0 if the comparison succeeds and 0.0 if it fails.
2195     * Interpolation happens after this conversion so the actual result may be
2196     * anywhere in the range [0.0, 1.0].
2197     *
2198     * Only valid if :c:member:`nir_tex_instr.is_shadow` and must be a float
2199     * scalar.
2200     */
2201    nir_tex_src_comparator,
2202 
2203    /** Coordinate offset
2204     *
2205     * An integer value that is added to the texel address before sampling.
2206     * This is only allowed with operations that take an explicit LOD as it is
2207     * applied in integer texel space after LOD selection and not normalized
2208     * coordinate space.
2209     */
2210    nir_tex_src_offset,
2211 
2212    /** LOD bias
2213     *
2214     * This value is added to the computed LOD before mip-mapping.
2215     */
2216    nir_tex_src_bias,
2217 
2218    /** Explicit LOD */
2219    nir_tex_src_lod,
2220 
2221    /** Min LOD
2222     *
2223     * The computed LOD is clamped to be at least as large as min_lod before
2224     * mip-mapping.
2225     */
2226    nir_tex_src_min_lod,
2227 
2228    /** MSAA sample index */
2229    nir_tex_src_ms_index,
2230 
2231    /** Intel-specific MSAA compression data */
2232    nir_tex_src_ms_mcs_intel,
2233 
2234    /** Explicit horizontal (X-major) coordinate derivative */
2235    nir_tex_src_ddx,
2236 
2237    /** Explicit vertical (Y-major) coordinate derivative */
2238    nir_tex_src_ddy,
2239 
2240    /** Texture variable dereference */
2241    nir_tex_src_texture_deref,
2242 
2243    /** Sampler variable dereference */
2244    nir_tex_src_sampler_deref,
2245 
2246    /** Texture index offset
2247     *
2248     * This is added to :c:member:`nir_tex_instr.texture_index`.  Unless
2249     * :c:member:`nir_tex_instr.texture_non_uniform` is set, this is guaranteed
2250     * to be dynamically uniform.
2251     */
2252    nir_tex_src_texture_offset,
2253 
2254    /** Dynamically uniform sampler index offset
2255     *
2256     * This is added to :c:member:`nir_tex_instr.sampler_index`.  Unless
2257     * :c:member:`nir_tex_instr.sampler_non_uniform` is set, this is guaranteed to be
2258     * dynamically uniform.  This should not be present until GLSL ES 3.20, GLSL
2259     * 4.00, or ARB_gpu_shader5, because in ES 3.10 and GL 3.30 samplers said
2260     * "When aggregated into arrays within a shader, samplers can only be indexed
2261     * with a constant integral expression."
2262     */
2263    nir_tex_src_sampler_offset,
2264 
2265    /** Bindless texture handle
2266     *
2267     * This is, unfortunately, a bit overloaded at the moment.  There are
2268     * generally two types of bindless handles:
2269     *
2270     *  1. For GL_ARB_bindless bindless handles. These are part of the
2271     *     GL/Gallium-level API and are always a 64-bit integer.
2272     *
2273     *  2. HW-specific handles.  GL_ARB_bindless handles may be lowered to
2274     *     these.  Also, these are used by many Vulkan drivers to implement
2275     *     descriptor sets, especially for UPDATE_AFTER_BIND descriptors.
2276     *     The details of hardware handles (bit size, format, etc.) is
2277     *     HW-specific.
2278     *
2279     * Because of this overloading and the resulting ambiguity, we currently
2280     * don't validate anything for these.
2281     */
2282    nir_tex_src_texture_handle,
2283 
2284    /** Bindless sampler handle
2285     *
2286     * See nir_tex_src_texture_handle,
2287     */
2288    nir_tex_src_sampler_handle,
2289 
2290    /** Tex src intrinsic
2291     *
2292     * This is an intrinsic used before function inlining i.e. before we know
2293     * if a bindless value has been given as function param for use as a tex
2294     * src.
2295     */
2296    nir_tex_src_sampler_deref_intrinsic,
2297    nir_tex_src_texture_deref_intrinsic,
2298 
2299    /** Plane index for multi-plane YCbCr textures */
2300    nir_tex_src_plane,
2301 
2302    /**
2303     * Backend-specific vec4 tex src argument.
2304     *
2305     * Can be used to have NIR optimization (copy propagation, lower_vec_to_regs)
2306     * apply to the packing of the tex srcs.  This lowering must only happen
2307     * after nir_lower_tex().
2308     *
2309     * The nir_tex_instr_src_type() of this argument is float, so no lowering
2310     * will happen if nir_lower_int_to_float is used.
2311     */
2312    nir_tex_src_backend1,
2313 
2314    /** Second backend-specific vec4 tex src argument, see nir_tex_src_backend1. */
2315    nir_tex_src_backend2,
2316 
2317    nir_num_tex_src_types
2318 } nir_tex_src_type;
2319 
2320 /** A texture instruction source */
2321 typedef struct nir_tex_src {
2322    /** Base source */
2323    nir_src src;
2324 
2325    /** Type of this source */
2326    nir_tex_src_type src_type;
2327 } nir_tex_src;
2328 
2329 /** Texture instruction opcode */
2330 typedef enum nir_texop {
2331    /** Regular texture look-up */
2332    nir_texop_tex,
2333    /** Texture look-up with LOD bias */
2334    nir_texop_txb,
2335    /** Texture look-up with explicit LOD */
2336    nir_texop_txl,
2337    /** Texture look-up with partial derivatives */
2338    nir_texop_txd,
2339    /** Texel fetch with explicit LOD */
2340    nir_texop_txf,
2341    /** Multisample texture fetch */
2342    nir_texop_txf_ms,
2343    /** Multisample texture fetch from framebuffer */
2344    nir_texop_txf_ms_fb,
2345    /** Multisample compression value fetch */
2346    nir_texop_txf_ms_mcs_intel,
2347    /** Texture size */
2348    nir_texop_txs,
2349    /** Texture lod query */
2350    nir_texop_lod,
2351    /** Texture gather */
2352    nir_texop_tg4,
2353    /** Texture levels query */
2354    nir_texop_query_levels,
2355    /** Texture samples query */
2356    nir_texop_texture_samples,
2357    /** Query whether all samples are definitely identical. */
2358    nir_texop_samples_identical,
2359    /** Regular texture look-up, eligible for pre-dispatch */
2360    nir_texop_tex_prefetch,
2361    /** Multisample fragment color texture fetch */
2362    nir_texop_fragment_fetch_amd,
2363    /** Multisample fragment mask texture fetch */
2364    nir_texop_fragment_mask_fetch_amd,
2365    /** Returns a buffer or image descriptor. */
2366    nir_texop_descriptor_amd,
2367    /** Returns a sampler descriptor. */
2368    nir_texop_sampler_descriptor_amd,
2369    /** Returns the sampler's LOD bias */
2370    nir_texop_lod_bias_agx,
2371    /** Returns a bool indicating that the sampler uses a custom border colour */
2372    nir_texop_has_custom_border_color_agx,
2373    /** Returns the sampler's custom border colour (if has_custom_border_agx) */
2374    nir_texop_custom_border_color_agx,
2375    /** Maps to TXQ.DIMENSION */
2376    nir_texop_hdr_dim_nv,
2377    /** Maps to TXQ.TEXTURE_TYPE */
2378    nir_texop_tex_type_nv,
2379 } nir_texop;
2380 
2381 /** Represents a texture instruction */
2382 typedef struct nir_tex_instr {
2383    /** Base instruction */
2384    nir_instr instr;
2385 
2386    /** Dimensionality of the texture operation
2387     *
2388     * This will typically match the dimensionality of the texture deref type
2389     * if a nir_tex_src_texture_deref is present.  However, it may not if
2390     * texture lowering has occurred.
2391     */
2392    enum glsl_sampler_dim sampler_dim;
2393 
2394    /** ALU type of the destination
2395     *
2396     * This is the canonical sampled type for this texture operation and may
2397     * not exactly match the sampled type of the deref type when a
2398     * nir_tex_src_texture_deref is present.  For OpenCL, the sampled type of
2399     * the texture deref will be GLSL_TYPE_VOID and this is allowed to be
2400     * anything.  With SPIR-V, the signedness of integer types is allowed to
2401     * differ.  For all APIs, the bit size may differ if the driver has done
2402     * any sort of mediump or similar lowering since texture types always have
2403     * 32-bit sampled types.
2404     */
2405    nir_alu_type dest_type;
2406 
2407    /** Texture opcode */
2408    nir_texop op;
2409 
2410    /** Destination */
2411    nir_def def;
2412 
2413    /** Array of sources
2414     *
2415     * This array has :c:member:`nir_tex_instr.num_srcs` elements
2416     */
2417    nir_tex_src *src;
2418 
2419    /** Number of sources */
2420    unsigned num_srcs;
2421 
2422    /** Number of components in the coordinate, if any */
2423    unsigned coord_components;
2424 
2425    /** True if the texture instruction acts on an array texture */
2426    bool is_array;
2427 
2428    /** True if the texture instruction performs a shadow comparison
2429     *
2430     * If this is true, the texture instruction must have a
2431     * nir_tex_src_comparator.
2432     */
2433    bool is_shadow;
2434 
2435    /**
2436     * If is_shadow is true, whether this is the old-style shadow that outputs
2437     * 4 components or the new-style shadow that outputs 1 component.
2438     */
2439    bool is_new_style_shadow;
2440 
2441    /**
2442     * True if this texture instruction should return a sparse residency code.
2443     * The code is in the last component of the result.
2444     */
2445    bool is_sparse;
2446 
2447    /** nir_texop_tg4 component selector
2448     *
2449     * This determines which RGBA component is gathered.
2450     */
2451    unsigned component : 2;
2452 
2453    /** Validation needs to know this for gradient component count */
2454    unsigned array_is_lowered_cube : 1;
2455 
2456    /** True if this tg4 instruction has an implicit LOD or LOD bias, instead of using level 0 */
2457    unsigned is_gather_implicit_lod : 1;
2458 
2459    /** Gather offsets */
2460    int8_t tg4_offsets[4][2];
2461 
2462    /** True if the texture index or handle is not dynamically uniform */
2463    bool texture_non_uniform;
2464 
2465    /** True if the sampler index or handle is not dynamically uniform.
2466     *
2467     * This may be set when VK_EXT_descriptor_indexing is supported and the
2468     * appropriate capability is enabled.
2469     *
2470     * This should always be false in GLSL (GLSL ES 3.20 says "When aggregated
2471     * into arrays within a shader, opaque types can only be indexed with a
2472     * dynamically uniform integral expression", and GLSL 4.60 says "When
2473     * aggregated into arrays within a shader, [texture, sampler, and
2474     * samplerShadow] types can only be indexed with a dynamically uniform
2475     * expression, or texture lookup will result in undefined values.").
2476     */
2477    bool sampler_non_uniform;
2478 
2479    /** The texture index
2480     *
2481     * If this texture instruction has a nir_tex_src_texture_offset source,
2482     * then the texture index is given by texture_index + texture_offset.
2483     */
2484    unsigned texture_index;
2485 
2486    /** The sampler index
2487     *
2488     * The following operations do not require a sampler and, as such, this
2489     * field should be ignored:
2490     *
2491     *    - nir_texop_txf
2492     *    - nir_texop_txf_ms
2493     *    - nir_texop_txs
2494     *    - nir_texop_query_levels
2495     *    - nir_texop_texture_samples
2496     *    - nir_texop_samples_identical
2497     *
2498     * If this texture instruction has a nir_tex_src_sampler_offset source,
2499     * then the sampler index is given by sampler_index + sampler_offset.
2500     */
2501    unsigned sampler_index;
2502 
2503    /* Back-end specific flags, intended to be used in combination with
2504     * nir_tex_src_backend1/2 to provide additional hw-specific information
2505     * to the back-end compiler.
2506     */
2507    uint32_t backend_flags;
2508 } nir_tex_instr;
2509 
2510 /**
2511  * Returns true if the texture operation requires a sampler as a general rule
2512  *
2513  * Note that the specific hw/driver backend could require to a sampler
2514  * object/configuration packet in any case, for some other reason.
2515  *
2516  * See also :c:member:`nir_tex_instr.sampler_index`.
2517  */
2518 bool nir_tex_instr_need_sampler(const nir_tex_instr *instr);
2519 
2520 /** Returns the number of components returned by this nir_tex_instr
2521  *
2522  * Useful for code building texture instructions when you don't want to think
2523  * about how many components a particular texture op returns.  This does not
2524  * include the sparse residency code.
2525  */
2526 unsigned
2527 nir_tex_instr_result_size(const nir_tex_instr *instr);
2528 
2529 /**
2530  * Returns the destination size of this nir_tex_instr including the sparse
2531  * residency code, if any.
2532  */
2533 static inline unsigned
nir_tex_instr_dest_size(const nir_tex_instr * instr)2534 nir_tex_instr_dest_size(const nir_tex_instr *instr)
2535 {
2536    /* One more component is needed for the residency code. */
2537    return nir_tex_instr_result_size(instr) + instr->is_sparse;
2538 }
2539 
2540 /**
2541  * Returns true if this texture operation queries something about the texture
2542  * rather than actually sampling it.
2543  */
2544 bool
2545 nir_tex_instr_is_query(const nir_tex_instr *instr);
2546 
2547 /** Returns true if this texture instruction does implicit derivatives
2548  *
2549  * This is important as there are extra control-flow rules around derivatives
2550  * and texture instructions which perform them implicitly.
2551  */
2552 bool
2553 nir_tex_instr_has_implicit_derivative(const nir_tex_instr *instr);
2554 
2555 /** Returns the ALU type of the given texture instruction source */
2556 nir_alu_type
2557 nir_tex_instr_src_type(const nir_tex_instr *instr, unsigned src);
2558 
2559 /**
2560  * Returns the number of components required by the given texture instruction
2561  * source
2562  */
2563 unsigned
2564 nir_tex_instr_src_size(const nir_tex_instr *instr, unsigned src);
2565 
2566 /**
2567  * Returns the index of the texture instruction source with the given
2568  * nir_tex_src_type or -1 if no such source exists.
2569  */
2570 static inline int
nir_tex_instr_src_index(const nir_tex_instr * instr,nir_tex_src_type type)2571 nir_tex_instr_src_index(const nir_tex_instr *instr, nir_tex_src_type type)
2572 {
2573    for (unsigned i = 0; i < instr->num_srcs; i++)
2574       if (instr->src[i].src_type == type)
2575          return (int)i;
2576 
2577    return -1;
2578 }
2579 
2580 /** Adds a source to a texture instruction */
2581 void nir_tex_instr_add_src(nir_tex_instr *tex,
2582                            nir_tex_src_type src_type,
2583                            nir_def *src);
2584 
2585 /** Removes a source from a texture instruction */
2586 void nir_tex_instr_remove_src(nir_tex_instr *tex, unsigned src_idx);
2587 
2588 bool nir_tex_instr_has_explicit_tg4_offsets(nir_tex_instr *tex);
2589 
2590 typedef struct {
2591    nir_instr instr;
2592 
2593    nir_def def;
2594 
2595    nir_const_value value[];
2596 } nir_load_const_instr;
2597 
2598 typedef enum {
2599    /** Return from a function
2600     *
2601     * This instruction is a classic function return.  It jumps to
2602     * nir_function_impl::end_block.  No return value is provided in this
2603     * instruction.  Instead, the function is expected to write any return
2604     * data to a deref passed in from the caller.
2605     */
2606    nir_jump_return,
2607 
2608    /** Immediately exit the current shader
2609     *
2610     * This instruction is roughly the equivalent of C's "exit()" in that it
2611     * immediately terminates the current shader invocation.  From a CFG
2612     * perspective, it looks like a jump to nir_function_impl::end_block but
2613     * it actually jumps to the end block of the shader entrypoint.  A halt
2614     * instruction in the shader entrypoint itself is semantically identical
2615     * to a return.
2616     *
2617     * For shaders with built-in I/O, any outputs written prior to a halt
2618     * instruction remain written and any outputs not written prior to the
2619     * halt have undefined values.  It does NOT cause an implicit discard of
2620     * written results.  If one wants discard results in a fragment shader,
2621     * for instance, a discard or demote intrinsic is required.
2622     */
2623    nir_jump_halt,
2624 
2625    /** Break out of the inner-most loop
2626     *
2627     * This has the same semantics as C's "break" statement.
2628     */
2629    nir_jump_break,
2630 
2631    /** Jump back to the top of the inner-most loop
2632     *
2633     * This has the same semantics as C's "continue" statement assuming that a
2634     * NIR loop is implemented as "while (1) { body }".
2635     */
2636    nir_jump_continue,
2637 
2638    /** Jumps for unstructured CFG.
2639     *
2640     * As within an unstructured CFG we can't rely on block ordering we need to
2641     * place explicit jumps at the end of every block.
2642     */
2643    nir_jump_goto,
2644    nir_jump_goto_if,
2645 } nir_jump_type;
2646 
2647 typedef struct {
2648    nir_instr instr;
2649    nir_jump_type type;
2650    nir_src condition;
2651    struct nir_block *target;
2652    struct nir_block *else_target;
2653 } nir_jump_instr;
2654 
2655 /* creates a new SSA variable in an undefined state */
2656 
2657 typedef struct {
2658    nir_instr instr;
2659    nir_def def;
2660 } nir_undef_instr;
2661 
2662 typedef struct {
2663    struct exec_node node;
2664 
2665    /* The predecessor block corresponding to this source */
2666    struct nir_block *pred;
2667 
2668    nir_src src;
2669 } nir_phi_src;
2670 
2671 #define nir_foreach_phi_src(phi_src, phi) \
2672    foreach_list_typed(nir_phi_src, phi_src, node, &(phi)->srcs)
2673 #define nir_foreach_phi_src_safe(phi_src, phi) \
2674    foreach_list_typed_safe(nir_phi_src, phi_src, node, &(phi)->srcs)
2675 
2676 typedef struct {
2677    nir_instr instr;
2678 
2679    /** list of nir_phi_src */
2680    struct exec_list srcs;
2681 
2682    nir_def def;
2683 } nir_phi_instr;
2684 
2685 static inline nir_phi_src *
nir_phi_get_src_from_block(nir_phi_instr * phi,struct nir_block * block)2686 nir_phi_get_src_from_block(nir_phi_instr *phi, struct nir_block *block)
2687 {
2688    nir_foreach_phi_src(src, phi) {
2689       if (src->pred == block)
2690          return src;
2691    }
2692 
2693    assert(!"Block is not a predecessor of phi.");
2694    return NULL;
2695 }
2696 
2697 typedef struct {
2698    struct exec_node node;
2699    bool src_is_reg;
2700    bool dest_is_reg;
2701    nir_src src;
2702    union {
2703       nir_def def;
2704       nir_src reg;
2705    } dest;
2706 } nir_parallel_copy_entry;
2707 
2708 #define nir_foreach_parallel_copy_entry(entry, pcopy) \
2709    foreach_list_typed(nir_parallel_copy_entry, entry, node, &(pcopy)->entries)
2710 
2711 typedef struct {
2712    nir_instr instr;
2713 
2714    /* A list of nir_parallel_copy_entrys.  The sources of all of the
2715     * entries are copied to the corresponding destinations "in parallel".
2716     * In other words, if we have two entries: a -> b and b -> a, the values
2717     * get swapped.
2718     */
2719    struct exec_list entries;
2720 } nir_parallel_copy_instr;
2721 
2722 typedef enum nir_debug_info_type {
2723    nir_debug_info_src_loc,
2724    nir_debug_info_string,
2725 } nir_debug_info_type;
2726 
2727 typedef enum nir_debug_info_source {
2728    nir_debug_info_spirv,
2729    nir_debug_info_nir,
2730 } nir_debug_info_source;
2731 
2732 typedef struct nir_debug_info_instr {
2733    nir_instr instr;
2734 
2735    nir_debug_info_type type;
2736 
2737    union {
2738       struct {
2739          nir_src filename;
2740          /* 0 if only the spirv_offset is available. */
2741          uint32_t line;
2742          uint32_t column;
2743 
2744          uint32_t spirv_offset;
2745 
2746          nir_debug_info_source source;
2747       } src_loc;
2748 
2749       uint16_t string_length;
2750    };
2751 
2752    nir_def def;
2753 
2754    char string[];
2755 } nir_debug_info_instr;
2756 
2757 NIR_DEFINE_CAST(nir_instr_as_alu, nir_instr, nir_alu_instr, instr,
2758                 type, nir_instr_type_alu)
2759 NIR_DEFINE_CAST(nir_instr_as_deref, nir_instr, nir_deref_instr, instr,
2760                 type, nir_instr_type_deref)
2761 NIR_DEFINE_CAST(nir_instr_as_call, nir_instr, nir_call_instr, instr,
2762                 type, nir_instr_type_call)
2763 NIR_DEFINE_CAST(nir_instr_as_jump, nir_instr, nir_jump_instr, instr,
2764                 type, nir_instr_type_jump)
2765 NIR_DEFINE_CAST(nir_instr_as_tex, nir_instr, nir_tex_instr, instr,
2766                 type, nir_instr_type_tex)
2767 NIR_DEFINE_CAST(nir_instr_as_intrinsic, nir_instr, nir_intrinsic_instr, instr,
2768                 type, nir_instr_type_intrinsic)
2769 NIR_DEFINE_CAST(nir_instr_as_load_const, nir_instr, nir_load_const_instr, instr,
2770                 type, nir_instr_type_load_const)
2771 NIR_DEFINE_CAST(nir_instr_as_undef, nir_instr, nir_undef_instr, instr,
2772                 type, nir_instr_type_undef)
2773 NIR_DEFINE_CAST(nir_instr_as_phi, nir_instr, nir_phi_instr, instr,
2774                 type, nir_instr_type_phi)
2775 NIR_DEFINE_CAST(nir_instr_as_parallel_copy, nir_instr,
2776                 nir_parallel_copy_instr, instr,
2777                 type, nir_instr_type_parallel_copy)
2778 NIR_DEFINE_CAST(nir_instr_as_debug_info, nir_instr,
2779                 nir_debug_info_instr, instr,
2780                 type, nir_instr_type_debug_info)
2781 
2782 #define NIR_DEFINE_SRC_AS_CONST(type, suffix)                 \
2783    static inline type                                         \
2784       nir_src_comp_as_##suffix(nir_src src, unsigned comp)    \
2785    {                                                          \
2786       assert(nir_src_is_const(src));                          \
2787       nir_load_const_instr *load =                            \
2788          nir_instr_as_load_const(src.ssa->parent_instr);      \
2789       assert(comp < load->def.num_components);                \
2790       return nir_const_value_as_##suffix(load->value[comp],   \
2791                                          load->def.bit_size); \
2792    }                                                          \
2793                                                               \
2794    static inline type                                         \
2795       nir_src_as_##suffix(nir_src src)                        \
2796    {                                                          \
2797       assert(nir_src_num_components(src) == 1);               \
2798       return nir_src_comp_as_##suffix(src, 0);                \
2799    }
2800 
2801 NIR_DEFINE_SRC_AS_CONST(int64_t, int)
2802 NIR_DEFINE_SRC_AS_CONST(uint64_t, uint)
2803 NIR_DEFINE_SRC_AS_CONST(bool, bool)
2804 NIR_DEFINE_SRC_AS_CONST(double, float)
2805 
2806 #undef NIR_DEFINE_SRC_AS_CONST
2807 
2808 typedef struct {
2809    nir_def *def;
2810    unsigned comp;
2811 } nir_scalar;
2812 
2813 static inline bool
nir_scalar_is_const(nir_scalar s)2814 nir_scalar_is_const(nir_scalar s)
2815 {
2816    return s.def->parent_instr->type == nir_instr_type_load_const;
2817 }
2818 
2819 static inline bool
nir_scalar_is_undef(nir_scalar s)2820 nir_scalar_is_undef(nir_scalar s)
2821 {
2822    return s.def->parent_instr->type == nir_instr_type_undef;
2823 }
2824 
2825 static inline nir_const_value
nir_scalar_as_const_value(nir_scalar s)2826 nir_scalar_as_const_value(nir_scalar s)
2827 {
2828    assert(s.comp < s.def->num_components);
2829    nir_load_const_instr *load = nir_instr_as_load_const(s.def->parent_instr);
2830    return load->value[s.comp];
2831 }
2832 
2833 #define NIR_DEFINE_SCALAR_AS_CONST(type, suffix)         \
2834    static inline type                                    \
2835       nir_scalar_as_##suffix(nir_scalar s)               \
2836    {                                                     \
2837       return nir_const_value_as_##suffix(                \
2838          nir_scalar_as_const_value(s), s.def->bit_size); \
2839    }
2840 
NIR_DEFINE_SCALAR_AS_CONST(int64_t,int)2841 NIR_DEFINE_SCALAR_AS_CONST(int64_t, int)
2842 NIR_DEFINE_SCALAR_AS_CONST(uint64_t, uint)
2843 NIR_DEFINE_SCALAR_AS_CONST(bool, bool)
2844 NIR_DEFINE_SCALAR_AS_CONST(double, float)
2845 
2846 #undef NIR_DEFINE_SCALAR_AS_CONST
2847 
2848 static inline bool
2849 nir_scalar_is_alu(nir_scalar s)
2850 {
2851    return s.def->parent_instr->type == nir_instr_type_alu;
2852 }
2853 
2854 static inline nir_op
nir_scalar_alu_op(nir_scalar s)2855 nir_scalar_alu_op(nir_scalar s)
2856 {
2857    return nir_instr_as_alu(s.def->parent_instr)->op;
2858 }
2859 
2860 static inline bool
nir_scalar_is_intrinsic(nir_scalar s)2861 nir_scalar_is_intrinsic(nir_scalar s)
2862 {
2863    return s.def->parent_instr->type == nir_instr_type_intrinsic;
2864 }
2865 
2866 static inline nir_intrinsic_op
nir_scalar_intrinsic_op(nir_scalar s)2867 nir_scalar_intrinsic_op(nir_scalar s)
2868 {
2869    return nir_instr_as_intrinsic(s.def->parent_instr)->intrinsic;
2870 }
2871 
2872 static inline nir_scalar
nir_scalar_chase_alu_src(nir_scalar s,unsigned alu_src_idx)2873 nir_scalar_chase_alu_src(nir_scalar s, unsigned alu_src_idx)
2874 {
2875    nir_scalar out = { NULL, 0 };
2876 
2877    nir_alu_instr *alu = nir_instr_as_alu(s.def->parent_instr);
2878    assert(alu_src_idx < nir_op_infos[alu->op].num_inputs);
2879 
2880    /* Our component must be written */
2881    assert(s.comp < s.def->num_components);
2882 
2883    out.def = alu->src[alu_src_idx].src.ssa;
2884 
2885    if (nir_op_infos[alu->op].input_sizes[alu_src_idx] == 0) {
2886       /* The ALU src is unsized so the source component follows the
2887        * destination component.
2888        */
2889       out.comp = alu->src[alu_src_idx].swizzle[s.comp];
2890    } else {
2891       /* This is a sized source so all source components work together to
2892        * produce all the destination components.  Since we need to return a
2893        * scalar, this only works if the source is a scalar.
2894        */
2895       assert(nir_op_infos[alu->op].input_sizes[alu_src_idx] == 1);
2896       out.comp = alu->src[alu_src_idx].swizzle[0];
2897    }
2898    assert(out.comp < out.def->num_components);
2899 
2900    return out;
2901 }
2902 
2903 nir_scalar nir_scalar_chase_movs(nir_scalar s);
2904 
2905 static inline nir_scalar
nir_get_scalar(nir_def * def,unsigned channel)2906 nir_get_scalar(nir_def *def, unsigned channel)
2907 {
2908    nir_scalar s = { def, channel };
2909    return s;
2910 }
2911 
2912 /** Returns a nir_scalar where we've followed the bit-exact mov/vec use chain to the original definition */
2913 static inline nir_scalar
nir_scalar_resolved(nir_def * def,unsigned channel)2914 nir_scalar_resolved(nir_def *def, unsigned channel)
2915 {
2916    return nir_scalar_chase_movs(nir_get_scalar(def, channel));
2917 }
2918 
2919 static inline bool
nir_scalar_equal(nir_scalar s1,nir_scalar s2)2920 nir_scalar_equal(nir_scalar s1, nir_scalar s2)
2921 {
2922    return s1.def == s2.def && s1.comp == s2.comp;
2923 }
2924 
2925 static inline uint64_t
nir_alu_src_as_uint(nir_alu_src src)2926 nir_alu_src_as_uint(nir_alu_src src)
2927 {
2928    nir_scalar scalar = nir_get_scalar(src.src.ssa, src.swizzle[0]);
2929    return nir_scalar_as_uint(scalar);
2930 }
2931 
2932 typedef struct {
2933    bool success;
2934 
2935    nir_variable *var;
2936    unsigned desc_set;
2937    unsigned binding;
2938    unsigned num_indices;
2939    nir_src indices[4];
2940    bool read_first_invocation;
2941 } nir_binding;
2942 
2943 nir_binding nir_chase_binding(nir_src rsrc);
2944 nir_variable *nir_get_binding_variable(struct nir_shader *shader, nir_binding binding);
2945 
2946 /*
2947  * Control flow
2948  *
2949  * Control flow consists of a tree of control flow nodes, which include
2950  * if-statements and loops. The leaves of the tree are basic blocks, lists of
2951  * instructions that always run start-to-finish. Each basic block also keeps
2952  * track of its successors (blocks which may run immediately after the current
2953  * block) and predecessors (blocks which could have run immediately before the
2954  * current block). Each function also has a start block and an end block which
2955  * all return statements point to (which is always empty). Together, all the
2956  * blocks with their predecessors and successors make up the control flow
2957  * graph (CFG) of the function. There are helpers that modify the tree of
2958  * control flow nodes while modifying the CFG appropriately; these should be
2959  * used instead of modifying the tree directly.
2960  */
2961 
2962 typedef enum {
2963    nir_cf_node_block,
2964    nir_cf_node_if,
2965    nir_cf_node_loop,
2966    nir_cf_node_function
2967 } nir_cf_node_type;
2968 
2969 typedef struct nir_cf_node {
2970    struct exec_node node;
2971    nir_cf_node_type type;
2972    struct nir_cf_node *parent;
2973 } nir_cf_node;
2974 
2975 typedef struct nir_block {
2976    nir_cf_node cf_node;
2977 
2978    /** list of nir_instr */
2979    struct exec_list instr_list;
2980 
2981    /** generic block index; generated by nir_index_blocks */
2982    unsigned index;
2983 
2984    /* This indicates whether the block or any parent block is executed
2985     * conditionally and whether the condition uses a divergent value.
2986     */
2987    bool divergent;
2988 
2989    /*
2990     * Each block can only have up to 2 successors, so we put them in a simple
2991     * array - no need for anything more complicated.
2992     */
2993    struct nir_block *successors[2];
2994 
2995    /* Set of nir_block predecessors in the CFG */
2996    struct set *predecessors;
2997 
2998    /*
2999     * this node's immediate dominator in the dominance tree - set to NULL for
3000     * the start block and any unreachable blocks.
3001     */
3002    struct nir_block *imm_dom;
3003 
3004    /* This node's children in the dominance tree */
3005    unsigned num_dom_children;
3006    struct nir_block **dom_children;
3007 
3008    /* Set of nir_blocks on the dominance frontier of this block */
3009    struct set *dom_frontier;
3010 
3011    /*
3012     * These two indices have the property that dom_{pre,post}_index for each
3013     * child of this block in the dominance tree will always be between
3014     * dom_pre_index and dom_post_index for this block, which makes testing if
3015     * a given block is dominated by another block an O(1) operation.
3016     */
3017    uint32_t dom_pre_index, dom_post_index;
3018 
3019    /**
3020     * Value just before the first nir_instr->index in the block, but after
3021     * end_ip that of any predecessor block.
3022     */
3023    uint32_t start_ip;
3024    /**
3025     * Value just after the last nir_instr->index in the block, but before the
3026     * start_ip of any successor block.
3027     */
3028    uint32_t end_ip;
3029 
3030    /* SSA def live in and out for this block; used for liveness analysis.
3031     * Indexed by ssa_def->index
3032     */
3033    BITSET_WORD *live_in;
3034    BITSET_WORD *live_out;
3035 } nir_block;
3036 
3037 static inline bool
nir_block_is_reachable(nir_block * b)3038 nir_block_is_reachable(nir_block *b)
3039 {
3040    /* See also nir_block_dominates */
3041    return b->dom_post_index != 0;
3042 }
3043 
3044 static inline nir_instr *
nir_block_first_instr(nir_block * block)3045 nir_block_first_instr(nir_block *block)
3046 {
3047    struct exec_node *head = exec_list_get_head(&block->instr_list);
3048    return exec_node_data(nir_instr, head, node);
3049 }
3050 
3051 static inline nir_instr *
nir_block_last_instr(nir_block * block)3052 nir_block_last_instr(nir_block *block)
3053 {
3054    struct exec_node *tail = exec_list_get_tail(&block->instr_list);
3055    return exec_node_data(nir_instr, tail, node);
3056 }
3057 
3058 static inline bool
nir_block_ends_in_jump(nir_block * block)3059 nir_block_ends_in_jump(nir_block *block)
3060 {
3061    return !exec_list_is_empty(&block->instr_list) &&
3062           nir_block_last_instr(block)->type == nir_instr_type_jump;
3063 }
3064 
3065 static inline bool
nir_block_ends_in_return_or_halt(nir_block * block)3066 nir_block_ends_in_return_or_halt(nir_block *block)
3067 {
3068    if (exec_list_is_empty(&block->instr_list))
3069       return false;
3070 
3071    nir_instr *instr = nir_block_last_instr(block);
3072    if (instr->type != nir_instr_type_jump)
3073       return false;
3074 
3075    nir_jump_instr *jump_instr = nir_instr_as_jump(instr);
3076    return jump_instr->type == nir_jump_return ||
3077           jump_instr->type == nir_jump_halt;
3078 }
3079 
3080 static inline bool
nir_block_ends_in_break(nir_block * block)3081 nir_block_ends_in_break(nir_block *block)
3082 {
3083    if (exec_list_is_empty(&block->instr_list))
3084       return false;
3085 
3086    nir_instr *instr = nir_block_last_instr(block);
3087    return instr->type == nir_instr_type_jump &&
3088           nir_instr_as_jump(instr)->type == nir_jump_break;
3089 }
3090 
3091 bool nir_block_contains_work(nir_block *block);
3092 
3093 #define nir_foreach_instr(instr, block) \
3094    foreach_list_typed(nir_instr, instr, node, &(block)->instr_list)
3095 #define nir_foreach_instr_reverse(instr, block) \
3096    foreach_list_typed_reverse(nir_instr, instr, node, &(block)->instr_list)
3097 #define nir_foreach_instr_safe(instr, block) \
3098    foreach_list_typed_safe(nir_instr, instr, node, &(block)->instr_list)
3099 #define nir_foreach_instr_reverse_safe(instr, block) \
3100    foreach_list_typed_reverse_safe(nir_instr, instr, node, &(block)->instr_list)
3101 
3102 /* Phis come first in the block */
3103 static inline nir_phi_instr *
nir_first_phi_in_block(nir_block * block)3104 nir_first_phi_in_block(nir_block *block)
3105 {
3106    nir_foreach_instr(instr, block) {
3107       if (instr->type == nir_instr_type_phi)
3108          return nir_instr_as_phi(instr);
3109       else
3110          return NULL;
3111    }
3112 
3113    return NULL;
3114 }
3115 
3116 static inline nir_phi_instr *
nir_next_phi(nir_phi_instr * phi)3117 nir_next_phi(nir_phi_instr *phi)
3118 {
3119    nir_instr *next = nir_instr_next(&phi->instr);
3120 
3121    if (next && next->type == nir_instr_type_phi)
3122       return nir_instr_as_phi(next);
3123    else
3124       return NULL;
3125 }
3126 
3127 #define nir_foreach_phi(instr, block)                                        \
3128    for (nir_phi_instr *instr = nir_first_phi_in_block(block); instr != NULL; \
3129         instr = nir_next_phi(instr))
3130 
3131 #define nir_foreach_phi_safe(instr, block)                          \
3132    for (nir_phi_instr *instr = nir_first_phi_in_block(block),       \
3133                       *__next = instr ? nir_next_phi(instr) : NULL; \
3134         instr != NULL;                                              \
3135         instr = __next, __next = instr ? nir_next_phi(instr) : NULL)
3136 
3137 static inline nir_phi_instr *
nir_block_last_phi_instr(nir_block * block)3138 nir_block_last_phi_instr(nir_block *block)
3139 {
3140    nir_phi_instr *last_phi = NULL;
3141    nir_foreach_phi(instr, block)
3142       last_phi = instr;
3143 
3144    return last_phi;
3145 }
3146 
3147 typedef enum {
3148    nir_selection_control_none = 0x0,
3149 
3150    /**
3151     * Defined by SPIR-V spec 3.22 "Selection Control".
3152     * The application prefers to remove control flow.
3153     */
3154    nir_selection_control_flatten = 0x1,
3155 
3156    /**
3157     * Defined by SPIR-V spec 3.22 "Selection Control".
3158     * The application prefers to keep control flow.
3159     */
3160    nir_selection_control_dont_flatten = 0x2,
3161 
3162    /**
3163     * May be applied by the compiler stack when it knows
3164     * that a branch is divergent, and:
3165     * - either both the if and else are always taken
3166     * - the if or else is empty and the other is always taken
3167     */
3168    nir_selection_control_divergent_always_taken = 0x3,
3169 } nir_selection_control;
3170 
3171 typedef struct nir_if {
3172    nir_cf_node cf_node;
3173    nir_src condition;
3174    nir_selection_control control;
3175 
3176    /** list of nir_cf_node */
3177    struct exec_list then_list;
3178 
3179    /** list of nir_cf_node */
3180    struct exec_list else_list;
3181 } nir_if;
3182 
3183 typedef struct {
3184    nir_if *nif;
3185 
3186    /** Condition instruction that contains the induction variable */
3187    nir_instr *conditional_instr;
3188 
3189    /** Block within ::nif that has the break instruction. */
3190    nir_block *break_block;
3191 
3192    /** Last block for the then- or else-path that does not contain the break. */
3193    nir_block *continue_from_block;
3194 
3195    /** True when ::break_block is in the else-path of ::nif. */
3196    bool continue_from_then;
3197    bool induction_rhs;
3198 
3199    /* This is true if the terminators exact trip count is unknown. For
3200     * example:
3201     *
3202     *    for (int i = 0; i < imin(x, 4); i++)
3203     *       ...
3204     *
3205     * Here loop analysis would have set a max_trip_count of 4 however we dont
3206     * know for sure that this is the exact trip count.
3207     */
3208    bool exact_trip_count_unknown;
3209 
3210    struct list_head loop_terminator_link;
3211 } nir_loop_terminator;
3212 
3213 typedef struct {
3214    /* Induction variable. */
3215    nir_def *def;
3216 
3217    /* Init statement with only uniform. */
3218    nir_src *init_src;
3219 
3220    /* Update statement with only uniform. */
3221    nir_alu_src *update_src;
3222 } nir_loop_induction_variable;
3223 
3224 typedef struct {
3225    /* Estimated cost (in number of instructions) of the loop */
3226    unsigned instr_cost;
3227 
3228    /* Contains fp64 ops that will be lowered */
3229    bool has_soft_fp64;
3230 
3231    /* Guessed trip count based on array indexing */
3232    unsigned guessed_trip_count;
3233 
3234    /* Maximum number of times the loop is run (if known) */
3235    unsigned max_trip_count;
3236 
3237    /* Do we know the exact number of times the loop will be run */
3238    bool exact_trip_count_known;
3239 
3240    /* Unroll the loop regardless of its size */
3241    bool force_unroll;
3242 
3243    /* Does the loop contain complex loop terminators, continues or other
3244     * complex behaviours? If this is true we can't rely on
3245     * loop_terminator_list to be complete or accurate.
3246     */
3247    bool complex_loop;
3248 
3249    nir_loop_terminator *limiting_terminator;
3250 
3251    /* A list of loop_terminators terminating this loop. */
3252    struct list_head loop_terminator_list;
3253 
3254    /* array of induction variables for this loop */
3255    nir_loop_induction_variable *induction_vars;
3256    unsigned num_induction_vars;
3257 } nir_loop_info;
3258 
3259 typedef enum {
3260    nir_loop_control_none = 0x0,
3261    nir_loop_control_unroll = 0x1,
3262    nir_loop_control_dont_unroll = 0x2,
3263 } nir_loop_control;
3264 
3265 typedef struct {
3266    nir_cf_node cf_node;
3267 
3268    /** list of nir_cf_node */
3269    struct exec_list body;
3270 
3271    /** (optional) list of nir_cf_node */
3272    struct exec_list continue_list;
3273 
3274    nir_loop_info *info;
3275    nir_loop_control control;
3276    bool partially_unrolled;
3277 
3278    /**
3279     * Whether some loop-active invocations might take a different control-flow path:
3280     * divergent_continue indicates that a continue statement might be taken by
3281     * only some of the loop-active invocations. A subsequent break is always
3282     * considered divergent.
3283     */
3284    bool divergent_continue;
3285    bool divergent_break;
3286 } nir_loop;
3287 
3288 static inline bool
nir_loop_is_divergent(nir_loop * loop)3289 nir_loop_is_divergent(nir_loop *loop)
3290 {
3291    return loop->divergent_continue || loop->divergent_break;
3292 }
3293 
3294 /**
3295  * Various bits of metadata that can may be created or required by
3296  * optimization and analysis passes
3297  */
3298 typedef enum {
3299    nir_metadata_none = 0x0,
3300 
3301    /** Indicates that nir_block::index values are valid.
3302     *
3303     * The start block has index 0 and they increase through a natural walk of
3304     * the CFG.  nir_function_impl::num_blocks is the number of blocks and
3305     * every block index is in the range [0, nir_function_impl::num_blocks].
3306     *
3307     * A pass can preserve this metadata type if it doesn't touch the CFG.
3308     */
3309    nir_metadata_block_index = 0x1,
3310 
3311    /** Indicates that block dominance information is valid
3312     *
3313     * This includes:
3314     *
3315     *   - nir_block::num_dom_children
3316     *   - nir_block::dom_children
3317     *   - nir_block::dom_frontier
3318     *   - nir_block::dom_pre_index
3319     *   - nir_block::dom_post_index
3320     *
3321     * A pass can preserve this metadata type if it doesn't touch the CFG.
3322     */
3323    nir_metadata_dominance = 0x2,
3324 
3325    /** Indicates that SSA def data-flow liveness information is valid
3326     *
3327     * This includes:
3328     *
3329     *   - nir_block::live_in
3330     *   - nir_block::live_out
3331     *
3332     * A pass can preserve this metadata type if it never adds or removes any
3333     * SSA defs or uses of SSA defs (most passes shouldn't preserve this
3334     * metadata type).
3335     */
3336    nir_metadata_live_defs = 0x4,
3337 
3338    /** A dummy metadata value to track when a pass forgot to call
3339     * nir_metadata_preserve.
3340     *
3341     * A pass should always clear this value even if it doesn't make any
3342     * progress to indicate that it thought about preserving metadata.
3343     */
3344    nir_metadata_not_properly_reset = 0x8,
3345 
3346    /** Indicates that loop analysis information is valid.
3347     *
3348     * This includes everything pointed to by nir_loop::info.
3349     *
3350     * A pass can preserve this metadata type if it is guaranteed to not affect
3351     * any loop metadata.  However, since loop metadata includes things like
3352     * loop counts which depend on arithmetic in the loop, this is very hard to
3353     * determine.  Most passes shouldn't preserve this metadata type.
3354     */
3355    nir_metadata_loop_analysis = 0x10,
3356 
3357    /** Indicates that nir_instr::index values are valid.
3358     *
3359     * The start instruction has index 0 and they increase through a natural
3360     * walk of instructions in blocks in the CFG.  The indices my have holes
3361     * after passes such as DCE.
3362     *
3363     * A pass can preserve this metadata type if it never adds or moves any
3364     * instructions (most passes shouldn't preserve this metadata type), but
3365     * can preserve it if it only removes instructions.
3366     */
3367    nir_metadata_instr_index = 0x20,
3368 
3369    /** All control flow metadata
3370     *
3371     * This includes all metadata preserved by a pass that preserves control flow
3372     * but modifies instructions. For example, a pass using
3373     * nir_shader_instructions_pass will typically preserve this if it does not
3374     * insert control flow.
3375     *
3376     * This is the most common metadata set to preserve, so it has its own alias.
3377     */
3378    nir_metadata_control_flow = nir_metadata_block_index |
3379                                nir_metadata_dominance,
3380 
3381    /** All metadata
3382     *
3383     * This includes all nir_metadata flags except not_properly_reset.  Passes
3384     * which do not change the shader in any way should call
3385     *
3386     *    nir_metadata_preserve(impl, nir_metadata_all);
3387     */
3388    nir_metadata_all = ~nir_metadata_not_properly_reset,
3389 } nir_metadata;
3390 MESA_DEFINE_CPP_ENUM_BITFIELD_OPERATORS(nir_metadata)
3391 
3392 typedef struct {
3393    nir_cf_node cf_node;
3394 
3395    /** pointer to the function of which this is an implementation */
3396    struct nir_function *function;
3397 
3398    /**
3399     * For entrypoints, a pointer to a nir_function_impl which runs before
3400     * it, once per draw or dispatch, communicating via store_preamble and
3401     * load_preamble intrinsics. If NULL then there is no preamble.
3402     */
3403    struct nir_function *preamble;
3404 
3405    /** list of nir_cf_node */
3406    struct exec_list body;
3407 
3408    nir_block *end_block;
3409 
3410    /** list for all local variables in the function */
3411    struct exec_list locals;
3412 
3413    /** next available SSA value index */
3414    unsigned ssa_alloc;
3415 
3416    /* total number of basic blocks, only valid when block_index_dirty = false */
3417    unsigned num_blocks;
3418 
3419    /** True if this nir_function_impl uses structured control-flow
3420     *
3421     * Structured nir_function_impls have different validation rules.
3422     */
3423    bool structured;
3424 
3425    nir_metadata valid_metadata;
3426 } nir_function_impl;
3427 
3428 #define nir_foreach_function_temp_variable(var, impl) \
3429    foreach_list_typed(nir_variable, var, node, &(impl)->locals)
3430 
3431 #define nir_foreach_function_temp_variable_safe(var, impl) \
3432    foreach_list_typed_safe(nir_variable, var, node, &(impl)->locals)
3433 
3434 ATTRIBUTE_RETURNS_NONNULL static inline nir_block *
nir_start_block(nir_function_impl * impl)3435 nir_start_block(nir_function_impl *impl)
3436 {
3437    return (nir_block *)impl->body.head_sentinel.next;
3438 }
3439 
3440 ATTRIBUTE_RETURNS_NONNULL static inline nir_block *
nir_impl_last_block(nir_function_impl * impl)3441 nir_impl_last_block(nir_function_impl *impl)
3442 {
3443    return (nir_block *)impl->body.tail_sentinel.prev;
3444 }
3445 
3446 static inline nir_cf_node *
nir_cf_node_next(nir_cf_node * node)3447 nir_cf_node_next(nir_cf_node *node)
3448 {
3449    struct exec_node *next = exec_node_get_next(&node->node);
3450    if (exec_node_is_tail_sentinel(next))
3451       return NULL;
3452    else
3453       return exec_node_data(nir_cf_node, next, node);
3454 }
3455 
3456 static inline nir_cf_node *
nir_cf_node_prev(nir_cf_node * node)3457 nir_cf_node_prev(nir_cf_node *node)
3458 {
3459    struct exec_node *prev = exec_node_get_prev(&node->node);
3460    if (exec_node_is_head_sentinel(prev))
3461       return NULL;
3462    else
3463       return exec_node_data(nir_cf_node, prev, node);
3464 }
3465 
3466 static inline bool
nir_cf_node_is_first(const nir_cf_node * node)3467 nir_cf_node_is_first(const nir_cf_node *node)
3468 {
3469    return exec_node_is_head_sentinel(node->node.prev);
3470 }
3471 
3472 static inline bool
nir_cf_node_is_last(const nir_cf_node * node)3473 nir_cf_node_is_last(const nir_cf_node *node)
3474 {
3475    return exec_node_is_tail_sentinel(node->node.next);
3476 }
3477 
NIR_DEFINE_CAST(nir_cf_node_as_block,nir_cf_node,nir_block,cf_node,type,nir_cf_node_block)3478 NIR_DEFINE_CAST(nir_cf_node_as_block, nir_cf_node, nir_block, cf_node,
3479                 type, nir_cf_node_block)
3480 NIR_DEFINE_CAST(nir_cf_node_as_if, nir_cf_node, nir_if, cf_node,
3481                 type, nir_cf_node_if)
3482 NIR_DEFINE_CAST(nir_cf_node_as_loop, nir_cf_node, nir_loop, cf_node,
3483                 type, nir_cf_node_loop)
3484 NIR_DEFINE_CAST(nir_cf_node_as_function, nir_cf_node,
3485                 nir_function_impl, cf_node, type, nir_cf_node_function)
3486 
3487 static inline nir_block *
3488 nir_if_first_then_block(nir_if *if_stmt)
3489 {
3490    struct exec_node *head = exec_list_get_head(&if_stmt->then_list);
3491    return nir_cf_node_as_block(exec_node_data(nir_cf_node, head, node));
3492 }
3493 
3494 static inline nir_block *
nir_if_last_then_block(nir_if * if_stmt)3495 nir_if_last_then_block(nir_if *if_stmt)
3496 {
3497    struct exec_node *tail = exec_list_get_tail(&if_stmt->then_list);
3498    return nir_cf_node_as_block(exec_node_data(nir_cf_node, tail, node));
3499 }
3500 
3501 static inline nir_block *
nir_if_first_else_block(nir_if * if_stmt)3502 nir_if_first_else_block(nir_if *if_stmt)
3503 {
3504    struct exec_node *head = exec_list_get_head(&if_stmt->else_list);
3505    return nir_cf_node_as_block(exec_node_data(nir_cf_node, head, node));
3506 }
3507 
3508 static inline nir_block *
nir_if_last_else_block(nir_if * if_stmt)3509 nir_if_last_else_block(nir_if *if_stmt)
3510 {
3511    struct exec_node *tail = exec_list_get_tail(&if_stmt->else_list);
3512    return nir_cf_node_as_block(exec_node_data(nir_cf_node, tail, node));
3513 }
3514 
3515 static inline nir_block *
nir_loop_first_block(nir_loop * loop)3516 nir_loop_first_block(nir_loop *loop)
3517 {
3518    struct exec_node *head = exec_list_get_head(&loop->body);
3519    return nir_cf_node_as_block(exec_node_data(nir_cf_node, head, node));
3520 }
3521 
3522 static inline nir_block *
nir_loop_last_block(nir_loop * loop)3523 nir_loop_last_block(nir_loop *loop)
3524 {
3525    struct exec_node *tail = exec_list_get_tail(&loop->body);
3526    return nir_cf_node_as_block(exec_node_data(nir_cf_node, tail, node));
3527 }
3528 
3529 static inline bool
nir_loop_has_continue_construct(const nir_loop * loop)3530 nir_loop_has_continue_construct(const nir_loop *loop)
3531 {
3532    return !exec_list_is_empty(&loop->continue_list);
3533 }
3534 
3535 static inline nir_block *
nir_loop_first_continue_block(nir_loop * loop)3536 nir_loop_first_continue_block(nir_loop *loop)
3537 {
3538    assert(nir_loop_has_continue_construct(loop));
3539    struct exec_node *head = exec_list_get_head(&loop->continue_list);
3540    return nir_cf_node_as_block(exec_node_data(nir_cf_node, head, node));
3541 }
3542 
3543 static inline nir_block *
nir_loop_last_continue_block(nir_loop * loop)3544 nir_loop_last_continue_block(nir_loop *loop)
3545 {
3546    assert(nir_loop_has_continue_construct(loop));
3547    struct exec_node *tail = exec_list_get_tail(&loop->continue_list);
3548    return nir_cf_node_as_block(exec_node_data(nir_cf_node, tail, node));
3549 }
3550 
3551 /**
3552  * Return the target block of a nir_jump_continue statement
3553  */
3554 static inline nir_block *
nir_loop_continue_target(nir_loop * loop)3555 nir_loop_continue_target(nir_loop *loop)
3556 {
3557    if (nir_loop_has_continue_construct(loop))
3558       return nir_loop_first_continue_block(loop);
3559    else
3560       return nir_loop_first_block(loop);
3561 }
3562 
3563 /**
3564  * Return true if this list of cf_nodes contains a single empty block.
3565  */
3566 static inline bool
nir_cf_list_is_empty_block(struct exec_list * cf_list)3567 nir_cf_list_is_empty_block(struct exec_list *cf_list)
3568 {
3569    if (exec_list_is_singular(cf_list)) {
3570       struct exec_node *head = exec_list_get_head(cf_list);
3571       nir_block *block =
3572          nir_cf_node_as_block(exec_node_data(nir_cf_node, head, node));
3573       return exec_list_is_empty(&block->instr_list);
3574    }
3575    return false;
3576 }
3577 
3578 typedef struct {
3579    uint8_t num_components;
3580    uint8_t bit_size;
3581 
3582    /* True if this paramater is actually the function return variable */
3583    bool is_return;
3584 
3585    bool implicit_conversion_prohibited;
3586 
3587    nir_variable_mode mode;
3588 
3589    /* The type of the function param */
3590    const struct glsl_type *type;
3591 
3592    /* Name if known, null if unknown */
3593    const char *name;
3594 } nir_parameter;
3595 
3596 typedef struct nir_function {
3597    struct exec_node node;
3598 
3599    const char *name;
3600    struct nir_shader *shader;
3601 
3602    unsigned num_params;
3603    nir_parameter *params;
3604 
3605    /** The implementation of this function.
3606     *
3607     * If the function is only declared and not implemented, this is NULL.
3608     *
3609     * Unless setting to NULL or NIR_SERIALIZE_FUNC_HAS_IMPL, set with
3610     * nir_function_set_impl to maintain IR invariants.
3611     */
3612    nir_function_impl *impl;
3613 
3614    bool is_entrypoint;
3615    /* from SPIR-V linkage, only for libraries */
3616    bool is_exported;
3617    bool is_preamble;
3618    /* from SPIR-V function control */
3619    bool should_inline;
3620    bool dont_inline; /* from SPIR-V */
3621 
3622    /* Static workgroup size, if this is a kernel function in a library of OpenCL
3623     * kernels. Normally, the size in the shader info is used instead.
3624     */
3625    unsigned workgroup_size[3];
3626 
3627    /**
3628     * Is this function a subroutine type declaration
3629     * e.g. subroutine void type1(float arg1);
3630     */
3631    bool is_subroutine;
3632 
3633    /* Temporary function created to wrap global instructions before they can
3634     * be inlined into the main function.
3635     */
3636    bool is_tmp_globals_wrapper;
3637 
3638    /**
3639     * Is this function associated to a subroutine type
3640     * e.g. subroutine (type1, type2) function_name { function_body };
3641     * would have num_subroutine_types 2,
3642     * and pointers to the type1 and type2 types.
3643     */
3644    int num_subroutine_types;
3645    const struct glsl_type **subroutine_types;
3646 
3647    int subroutine_index;
3648 
3649    /* A temporary for passes to use for storing flags. */
3650    uint32_t pass_flags;
3651 } nir_function;
3652 
3653 typedef enum {
3654    nir_lower_imul64 = (1 << 0),
3655    nir_lower_isign64 = (1 << 1),
3656    /** Lower all int64 modulus and division opcodes */
3657    nir_lower_divmod64 = (1 << 2),
3658    /** Lower all 64-bit umul_high and imul_high opcodes */
3659    nir_lower_imul_high64 = (1 << 3),
3660    nir_lower_bcsel64 = (1 << 4),
3661    nir_lower_icmp64 = (1 << 5),
3662    nir_lower_iadd64 = (1 << 6),
3663    nir_lower_iabs64 = (1 << 7),
3664    nir_lower_ineg64 = (1 << 8),
3665    nir_lower_logic64 = (1 << 9),
3666    nir_lower_minmax64 = (1 << 10),
3667    nir_lower_shift64 = (1 << 11),
3668    nir_lower_imul_2x32_64 = (1 << 12),
3669    nir_lower_extract64 = (1 << 13),
3670    nir_lower_ufind_msb64 = (1 << 14),
3671    nir_lower_bit_count64 = (1 << 15),
3672    nir_lower_subgroup_shuffle64 = (1 << 16),
3673    nir_lower_scan_reduce_bitwise64 = (1 << 17),
3674    nir_lower_scan_reduce_iadd64 = (1 << 18),
3675    nir_lower_vote_ieq64 = (1 << 19),
3676    nir_lower_usub_sat64 = (1 << 20),
3677    nir_lower_iadd_sat64 = (1 << 21),
3678    nir_lower_find_lsb64 = (1 << 22),
3679    nir_lower_conv64 = (1 << 23),
3680    nir_lower_uadd_sat64 = (1 << 24),
3681    nir_lower_iadd3_64 = (1 << 25),
3682 } nir_lower_int64_options;
3683 
3684 typedef enum {
3685    nir_lower_drcp = (1 << 0),
3686    nir_lower_dsqrt = (1 << 1),
3687    nir_lower_drsq = (1 << 2),
3688    nir_lower_dtrunc = (1 << 3),
3689    nir_lower_dfloor = (1 << 4),
3690    nir_lower_dceil = (1 << 5),
3691    nir_lower_dfract = (1 << 6),
3692    nir_lower_dround_even = (1 << 7),
3693    nir_lower_dmod = (1 << 8),
3694    nir_lower_dsub = (1 << 9),
3695    nir_lower_ddiv = (1 << 10),
3696    nir_lower_dsign = (1 << 11),
3697    nir_lower_dminmax = (1 << 12),
3698    nir_lower_dsat = (1 << 13),
3699    nir_lower_fp64_full_software = (1 << 14),
3700 } nir_lower_doubles_options;
3701 
3702 typedef enum {
3703    nir_divergence_single_prim_per_subgroup = (1 << 0),
3704    nir_divergence_single_patch_per_tcs_subgroup = (1 << 1),
3705    nir_divergence_single_patch_per_tes_subgroup = (1 << 2),
3706    nir_divergence_view_index_uniform = (1 << 3),
3707    nir_divergence_single_frag_shading_rate_per_subgroup = (1 << 4),
3708    nir_divergence_multiple_workgroup_per_compute_subgroup = (1 << 5),
3709    nir_divergence_shader_record_ptr_uniform = (1 << 6),
3710    nir_divergence_uniform_load_tears = (1 << 7),
3711    /* If used, this allows phis for divergent merges with undef and a uniform source to be considered uniform */
3712    nir_divergence_ignore_undef_if_phi_srcs = (1 << 8),
3713 } nir_divergence_options;
3714 
3715 typedef enum {
3716    /**
3717     * Whether a fragment shader can interpolate the same input multiple times
3718     * with different modes (smooth, noperspective) and locations (pixel,
3719     * centroid, sample, at_offset, at_sample), excluding the flat mode.
3720     *
3721     * This matches AMD GPU flexibility and limitations and is a superset of
3722     * the GL4 requirement that each input can be interpolated at its specified
3723     * location, and then also as centroid, at_offset, and at_sample.
3724     */
3725    nir_io_has_flexible_input_interpolation_except_flat = BITFIELD_BIT(0),
3726 
3727    /**
3728     * nir_opt_varyings compacts (relocates) components of varyings by
3729     * rewriting their locations completely, effectively moving components of
3730     * varyings between slots. This option forces nir_opt_varyings to make
3731     * VARYING_SLOT_POS unused by moving its contents to VARn if the consumer
3732     * is not FS. If this option is not set and POS is unused, it moves
3733     * components of VARn to POS until it's fully used.
3734     */
3735    nir_io_dont_use_pos_for_non_fs_varyings = BITFIELD_BIT(1),
3736 
3737    nir_io_16bit_input_output_support = BITFIELD_BIT(2),
3738 
3739    /**
3740     * Implement mediump inputs and outputs as normal 32-bit IO.
3741     * Causes the mediump flag to be not set for IO semantics, essentially
3742     * destroying any mediump-related IO information in the shader.
3743     */
3744    nir_io_mediump_is_32bit = BITFIELD_BIT(3),
3745 
3746    /**
3747     * Whether nir_opt_vectorize_io should ignore FS inputs.
3748     */
3749    nir_io_prefer_scalar_fs_inputs = BITFIELD_BIT(4),
3750 
3751    /**
3752     * Whether interpolated fragment shader vec4 slots can use load_input for
3753     * a subset of its components to skip interpolation for those components.
3754     * The result of such load_input is a value from a random (not necessarily
3755     * provoking) vertex. If a value from the provoking vertex is required,
3756     * the vec4 slot should have no load_interpolated_input instructions.
3757     *
3758     * This exposes the AMD capability that allows packing flat inputs with
3759     * interpolated inputs in a limited number of cases. Normally, flat
3760     * components must be in a separate vec4 slot to get the value from
3761     * the provoking vertex. If the compiler can prove that all per-vertex
3762     * values are equal (convergent, i.e. the provoking vertex doesn't matter),
3763     * it can put such flat components into any interpolated vec4 slot.
3764     *
3765     * It should also be set if the hw can mix flat and interpolated components
3766     * in the same vec4 slot.
3767     *
3768     * This causes nir_opt_varyings to skip interpolation for all varyings
3769     * that are convergent, and enables better compaction and inter-shader code
3770     * motion for convergent varyings.
3771     */
3772    nir_io_mix_convergent_flat_with_interpolated = BITFIELD_BIT(5),
3773 
3774    /**
3775     * Whether src_type and dest_type of IO intrinsics are irrelevant and
3776     * should be ignored by nir_opt_vectorize_io. All drivers that always treat
3777     * load_input and store_output as untyped and load_interpolated_input as
3778     * float##bit_size should set this.
3779     */
3780    nir_io_vectorizer_ignores_types = BITFIELD_BIT(6),
3781 
3782    /**
3783     * Whether nir_opt_varyings should never promote convergent FS inputs
3784     * to flat.
3785     */
3786    nir_io_always_interpolate_convergent_fs_inputs = BITFIELD_BIT(7),
3787 
3788    /**
3789     * Whether the first assigned color channel component should be equal to
3790     * the first unused VARn component.
3791     *
3792     * For example, if the first unused VARn channel is VAR0.z, color channels
3793     * are assigned in this order:
3794     *       COL0.z, COL0.w, COL0.x, COL0.y, COL1.z, COL1.w, COL1.x, COL1.y
3795     *
3796     * This allows certain drivers to merge outputs if each output sets
3797     * different components, for example 2 outputs writing VAR0.xy and COL0.z
3798     * will only use 1 HW output.
3799     */
3800    nir_io_compaction_rotates_color_channels = BITFIELD_BIT(8),
3801 
3802    /* Options affecting the GLSL compiler or Gallium are below. */
3803 
3804    /**
3805     * Lower load_deref/store_deref to load_input/store_output/etc. intrinsics.
3806     * This is only affects GLSL compilation and Gallium.
3807     */
3808    nir_io_has_intrinsics = BITFIELD_BIT(16),
3809 
3810    /**
3811     * Don't run nir_opt_varyings and nir_opt_vectorize_io.
3812     *
3813     * This option is deprecated and is a hack. DO NOT USE.
3814     * Use MESA_GLSL_DISABLE_IO_OPT=1 instead.
3815     */
3816    nir_io_dont_optimize = BITFIELD_BIT(17),
3817 
3818    /**
3819     * Whether clip and cull distance arrays should be separate. If this is not
3820     * set, cull distances will be moved into VARYING_SLOT_CLIP_DISTn after clip
3821     * distances, and shader_info::clip_distance_array_size will be the index
3822     * of the first cull distance. nir_lower_clip_cull_distance_arrays does
3823     * that.
3824     */
3825    nir_io_separate_clip_cull_distance_arrays = BITFIELD_BIT(18),
3826 } nir_io_options;
3827 
3828 typedef enum {
3829    nir_lower_packing_op_pack_64_2x32,
3830    nir_lower_packing_op_unpack_64_2x32,
3831    nir_lower_packing_op_pack_64_4x16,
3832    nir_lower_packing_op_unpack_64_4x16,
3833    nir_lower_packing_op_pack_32_2x16,
3834    nir_lower_packing_op_unpack_32_2x16,
3835    nir_lower_packing_op_pack_32_4x8,
3836    nir_lower_packing_op_unpack_32_4x8,
3837    nir_lower_packing_num_ops,
3838 } nir_lower_packing_op;
3839 
3840 /** An instruction filtering callback
3841  *
3842  * Returns true if the instruction should be processed and false otherwise.
3843  */
3844 typedef bool (*nir_instr_filter_cb)(const nir_instr *, const void *);
3845 
3846 /* Like nir_instr_filter_cb but specialized to intrinsics */
3847 typedef bool (*nir_intrin_filter_cb)(const nir_intrinsic_instr *, const void *);
3848 
3849 /** A vectorization width callback
3850  *
3851  * Returns the maximum vectorization width per instruction.
3852  * 0, if the instruction must not be modified.
3853  *
3854  * The vectorization width must be a power of 2.
3855  */
3856 typedef uint8_t (*nir_vectorize_cb)(const nir_instr *, const void *);
3857 
3858 typedef struct nir_shader_compiler_options {
3859    bool lower_fdiv;
3860    bool lower_ffma16;
3861    bool lower_ffma32;
3862    bool lower_ffma64;
3863    bool fuse_ffma16;
3864    bool fuse_ffma32;
3865    bool fuse_ffma64;
3866    bool lower_flrp16;
3867    bool lower_flrp32;
3868    /** Lowers flrp when it does not support doubles */
3869    bool lower_flrp64;
3870    bool lower_fpow;
3871    bool lower_fsat;
3872    bool lower_fsqrt;
3873    bool lower_sincos;
3874    bool lower_fmod;
3875    /** Lowers ibitfield_extract/ubitfield_extract. */
3876    bool lower_bitfield_extract;
3877    /** Lowers bitfield_insert. */
3878    bool lower_bitfield_insert;
3879    /** Lowers bitfield_reverse to shifts. */
3880    bool lower_bitfield_reverse;
3881    /** Lowers bit_count to shifts. */
3882    bool lower_bit_count;
3883    /** Lowers ifind_msb. */
3884    bool lower_ifind_msb;
3885    /** Lowers ufind_msb. */
3886    bool lower_ufind_msb;
3887    /** Lowers find_lsb to ufind_msb and logic ops */
3888    bool lower_find_lsb;
3889    bool lower_uadd_carry;
3890    bool lower_usub_borrow;
3891    /** Lowers imul_high/umul_high to 16-bit multiplies and carry operations. */
3892    bool lower_mul_high;
3893    /** lowers fneg to fmul(x, -1.0). Driver must call nir_opt_algebraic_late() */
3894    bool lower_fneg;
3895    /** lowers ineg to isub. Driver must call nir_opt_algebraic_late(). */
3896    bool lower_ineg;
3897    /** lowers fisnormal to alu ops. */
3898    bool lower_fisnormal;
3899 
3900    /* lower {slt,sge,seq,sne} to {flt,fge,feq,fneu} + b2f: */
3901    bool lower_scmp;
3902 
3903    /* lower b/fall_equalN/b/fany_nequalN (ex:fany_nequal4 to sne+fdot4+fsat) */
3904    bool lower_vector_cmp;
3905 
3906    /** enable rules to avoid bit ops */
3907    bool lower_bitops;
3908 
3909    /** enables rules to lower isign to imin+imax */
3910    bool lower_isign;
3911 
3912    /** enables rules to lower fsign to fsub and flt */
3913    bool lower_fsign;
3914 
3915    /** enables rules to lower iabs to ineg+imax */
3916    bool lower_iabs;
3917 
3918    /** enable rules that avoid generating umax from signed integer ops */
3919    bool lower_umax;
3920 
3921    /** enable rules that avoid generating umin from signed integer ops */
3922    bool lower_umin;
3923 
3924    /* lower fmin/fmax with signed zero preserve to fmin/fmax with
3925     * no_signed_zero, for backends whose fmin/fmax implementations do not
3926     * implement IEEE-754-2019 semantics for signed zero.
3927     */
3928    bool lower_fminmax_signed_zero;
3929 
3930    /* lower fdph to fdot4 */
3931    bool lower_fdph;
3932 
3933    /** lower fdot to fmul and fsum/fadd. */
3934    bool lower_fdot;
3935 
3936    /* Does the native fdot instruction replicate its result for four
3937     * components?  If so, then opt_algebraic_late will turn all fdotN
3938     * instructions into fdotN_replicated instructions.
3939     */
3940    bool fdot_replicates;
3941 
3942    /** lowers ffloor to fsub+ffract: */
3943    bool lower_ffloor;
3944 
3945    /** lowers ffract to fsub+ffloor: */
3946    bool lower_ffract;
3947 
3948    /** lowers fceil to fneg+ffloor+fneg: */
3949    bool lower_fceil;
3950 
3951    bool lower_ftrunc;
3952 
3953    /** Lowers fround_even to ffract+feq+csel.
3954     *
3955     * Not correct in that it doesn't correctly handle the "_even" part of the
3956     * rounding, but good enough for DX9 array indexing handling on DX9-class
3957     * hardware.
3958     */
3959    bool lower_fround_even;
3960 
3961    bool lower_ldexp;
3962 
3963    bool lower_pack_half_2x16;
3964    bool lower_pack_unorm_2x16;
3965    bool lower_pack_snorm_2x16;
3966    bool lower_pack_unorm_4x8;
3967    bool lower_pack_snorm_4x8;
3968    bool lower_pack_64_2x32;
3969    bool lower_pack_64_4x16;
3970    bool lower_pack_32_2x16;
3971    bool lower_pack_64_2x32_split;
3972    bool lower_pack_32_2x16_split;
3973    bool lower_unpack_half_2x16;
3974    bool lower_unpack_unorm_2x16;
3975    bool lower_unpack_snorm_2x16;
3976    bool lower_unpack_unorm_4x8;
3977    bool lower_unpack_snorm_4x8;
3978    bool lower_unpack_64_2x32_split;
3979    bool lower_unpack_32_2x16_split;
3980 
3981    bool lower_pack_split;
3982 
3983    bool lower_extract_byte;
3984    bool lower_extract_word;
3985    bool lower_insert_byte;
3986    bool lower_insert_word;
3987 
3988    bool lower_all_io_to_temps;
3989    bool lower_all_io_to_elements;
3990 
3991    /* Indicates that the driver only has zero-based vertex id */
3992    bool vertex_id_zero_based;
3993 
3994    /**
3995     * If enabled, gl_BaseVertex will be lowered as:
3996     * is_indexed_draw (~0/0) & firstvertex
3997     */
3998    bool lower_base_vertex;
3999 
4000    /**
4001     * If enabled, gl_HelperInvocation will be lowered as:
4002     *
4003     *   !((1 << sample_id) & sample_mask_in))
4004     *
4005     * This depends on some possibly hw implementation details, which may
4006     * not be true for all hw.  In particular that the FS is only executed
4007     * for covered samples or for helper invocations.  So, do not blindly
4008     * enable this option.
4009     *
4010     * Note: See also issue #22 in ARB_shader_image_load_store
4011     */
4012    bool lower_helper_invocation;
4013 
4014    /**
4015     * Convert gl_SampleMaskIn to gl_HelperInvocation as follows:
4016     *
4017     *   gl_SampleMaskIn == 0 ---> gl_HelperInvocation
4018     *   gl_SampleMaskIn != 0 ---> !gl_HelperInvocation
4019     */
4020    bool optimize_sample_mask_in;
4021 
4022    /**
4023     * Optimize load_front_face ? a : -a to load_front_face_fsign * a
4024     */
4025    bool optimize_load_front_face_fsign;
4026 
4027    /**
4028     * Optimize boolean reductions of quad broadcasts. This should only be enabled if
4029     * nir_intrinsic_reduce supports INCLUDE_HELPERS.
4030     */
4031    bool optimize_quad_vote_to_reduce;
4032 
4033    bool lower_cs_local_index_to_id;
4034    bool lower_cs_local_id_to_index;
4035 
4036    /* Prevents lowering global_invocation_id to be in terms of workgroup_id */
4037    bool has_cs_global_id;
4038 
4039    bool lower_device_index_to_zero;
4040 
4041    /* Set if nir_lower_pntc_ytransform() should invert gl_PointCoord.
4042     * Either when frame buffer is flipped or GL_POINT_SPRITE_COORD_ORIGIN
4043     * is GL_LOWER_LEFT.
4044     */
4045    bool lower_wpos_pntc;
4046 
4047    /**
4048     * Set if nir_op_[iu]hadd and nir_op_[iu]rhadd instructions should be
4049     * lowered to simple arithmetic.
4050     *
4051     * If this flag is set, the lowering will be applied to all bit-sizes of
4052     * these instructions.
4053     *
4054     * :c:member:`lower_hadd64`
4055     */
4056    bool lower_hadd;
4057 
4058    /**
4059     * Set if only 64-bit nir_op_[iu]hadd and nir_op_[iu]rhadd instructions
4060     * should be lowered to simple arithmetic.
4061     *
4062     * If this flag is set, the lowering will be applied to only 64-bit
4063     * versions of these instructions.
4064     *
4065     * :c:member:`lower_hadd`
4066     */
4067    bool lower_hadd64;
4068 
4069    /**
4070     * Set if nir_op_uadd_sat should be lowered to simple arithmetic.
4071     *
4072     * If this flag is set, the lowering will be applied to all bit-sizes of
4073     * these instructions.
4074     */
4075    bool lower_uadd_sat;
4076 
4077    /**
4078     * Set if nir_op_usub_sat should be lowered to simple arithmetic.
4079     *
4080     * If this flag is set, the lowering will be applied to all bit-sizes of
4081     * these instructions.
4082     */
4083    bool lower_usub_sat;
4084 
4085    /**
4086     * Set if nir_op_iadd_sat and nir_op_isub_sat should be lowered to simple
4087     * arithmetic.
4088     *
4089     * If this flag is set, the lowering will be applied to all bit-sizes of
4090     * these instructions.
4091     */
4092    bool lower_iadd_sat;
4093 
4094    /**
4095     * Set if imul_32x16 and umul_32x16 should be lowered to simple
4096     * arithmetic.
4097     */
4098    bool lower_mul_32x16;
4099 
4100    /**
4101     * Should IO be re-vectorized?  Some scalar ISAs still operate on vec4's
4102     * for IO purposes and would prefer loads/stores be vectorized.
4103     */
4104    bool vectorize_io;
4105    bool vectorize_tess_levels;
4106    bool lower_to_scalar;
4107    nir_instr_filter_cb lower_to_scalar_filter;
4108 
4109    /**
4110     * Disables potentially harmful algebraic transformations for architectures
4111     * with SIMD-within-a-register semantics.
4112     *
4113     * Note, to actually vectorize 16bit instructions, use nir_opt_vectorize()
4114     * with a suitable callback function.
4115     */
4116    bool vectorize_vec2_16bit;
4117 
4118    /**
4119     * Should the linker unify inputs_read/outputs_written between adjacent
4120     * shader stages which are linked into a single program?
4121     */
4122    bool unify_interfaces;
4123 
4124    /**
4125     * Whether nir_lower_io() will lower interpolateAt functions to
4126     * load_interpolated_input intrinsics.
4127     *
4128     * Unlike nir_lower_io_use_interpolated_input_intrinsics this will only
4129     * lower these functions and leave input load intrinsics untouched.
4130     */
4131    bool lower_interpolate_at;
4132 
4133    /* Lowers when 32x32->64 bit multiplication is not supported */
4134    bool lower_mul_2x32_64;
4135 
4136    /* Indicates that urol and uror are supported */
4137    bool has_rotate8;
4138    bool has_rotate16;
4139    bool has_rotate32;
4140 
4141    /** Backend supports shfr */
4142    bool has_shfr32;
4143 
4144    /** Backend supports ternary addition */
4145    bool has_iadd3;
4146 
4147    /**
4148     * Backend supports amul and would like them generated whenever
4149     * possible. This is stronger than has_imul24 for amul, but does not imply
4150     * support for imul24.
4151     */
4152    bool has_amul;
4153 
4154    /**
4155     * Backend supports imul24, and would like to use it (when possible)
4156     * for address/offset calculation.  If true, driver should call
4157     * nir_lower_amul().  (If not set, amul will automatically be lowered
4158     * to imul.)
4159     */
4160    bool has_imul24;
4161 
4162    /** Backend supports umul24, if not set  umul24 will automatically be lowered
4163     * to imul with masked inputs */
4164    bool has_umul24;
4165 
4166    /** Backend supports 32-bit imad */
4167    bool has_imad32;
4168 
4169    /** Backend supports umad24, if not set  umad24 will automatically be lowered
4170     * to imul with masked inputs and iadd */
4171    bool has_umad24;
4172 
4173    /* Backend supports fused compare against zero and csel */
4174    bool has_fused_comp_and_csel;
4175    /* Backend supports fused int eq/ne against zero and csel. */
4176    bool has_icsel_eqz64;
4177    bool has_icsel_eqz32;
4178    bool has_icsel_eqz16;
4179 
4180    /* Backend supports fneo, fequ, fltu, fgeu. */
4181    bool has_fneo_fcmpu;
4182 
4183    /* Backend supports ford and funord. */
4184    bool has_ford_funord;
4185 
4186    /** Backend supports fsub, if not set fsub will automatically be lowered to
4187     * fadd(x, fneg(y)). If true, driver should call nir_opt_algebraic_late(). */
4188    bool has_fsub;
4189 
4190    /** Backend supports isub, if not set isub will automatically be lowered to
4191     * iadd(x, ineg(y)). If true, driver should call nir_opt_algebraic_late(). */
4192    bool has_isub;
4193 
4194    /** Backend supports pack_32_4x8 or pack_32_4x8_split. */
4195    bool has_pack_32_4x8;
4196 
4197    /** Backend supports nir_load_texture_scale and prefers it over txs for nir
4198     * lowerings. */
4199    bool has_texture_scaling;
4200 
4201    /** Backend supports sdot_4x8_iadd. */
4202    bool has_sdot_4x8;
4203 
4204    /** Backend supports udot_4x8_uadd. */
4205    bool has_udot_4x8;
4206 
4207    /** Backend supports sudot_4x8_iadd. */
4208    bool has_sudot_4x8;
4209 
4210    /** Backend supports sdot_4x8_iadd_sat. */
4211    bool has_sdot_4x8_sat;
4212 
4213    /** Backend supports udot_4x8_uadd_sat. */
4214    bool has_udot_4x8_sat;
4215 
4216    /** Backend supports sudot_4x8_iadd_sat. */
4217    bool has_sudot_4x8_sat;
4218 
4219    /** Backend supports sdot_2x16 and udot_2x16 opcodes. */
4220    bool has_dot_2x16;
4221 
4222    /** Backend supports fmulz (and ffmaz if lower_ffma32=false) */
4223    bool has_fmulz;
4224 
4225    /**
4226     * Backend supports fmulz (and ffmaz if lower_ffma32=false) but only if
4227     * FLOAT_CONTROLS_DENORM_PRESERVE_FP32 is not set
4228     */
4229    bool has_fmulz_no_denorms;
4230 
4231    /** Backend supports 32bit ufind_msb_rev and ifind_msb_rev. */
4232    bool has_find_msb_rev;
4233 
4234    /** Backend supports pack_half_2x16_rtz_split. */
4235    bool has_pack_half_2x16_rtz;
4236 
4237    /** Backend supports bitz/bitnz. */
4238    bool has_bit_test;
4239 
4240    /** Backend supports ubfe/ibfe. */
4241    bool has_bfe;
4242 
4243    /** Backend supports bfm. */
4244    bool has_bfm;
4245 
4246    /** Backend supports bfi. */
4247    bool has_bfi;
4248 
4249    /** Backend supports bitfield_select. */
4250    bool has_bitfield_select;
4251 
4252    /** Backend supports uclz. */
4253    bool has_uclz;
4254 
4255    /** Backend support msad_u4x8. */
4256    bool has_msad;
4257 
4258    /**
4259     * Is this the Intel vec4 backend?
4260     *
4261     * Used to inhibit algebraic optimizations that are known to be harmful on
4262     * the Intel vec4 backend.  This is generally applicable to any
4263     * optimization that might cause more immediate values to be used in
4264     * 3-source (e.g., ffma and flrp) instructions.
4265     */
4266    bool intel_vec4;
4267 
4268    /**
4269     * For most Intel GPUs, all ternary operations such as FMA and BFE cannot
4270     * have immediates, so two to three instructions may eventually be needed.
4271     */
4272    bool avoid_ternary_with_two_constants;
4273 
4274    /** Whether 8-bit ALU is supported. */
4275    bool support_8bit_alu;
4276 
4277    /** Whether 16-bit ALU is supported. */
4278    bool support_16bit_alu;
4279 
4280    unsigned max_unroll_iterations;
4281    unsigned max_unroll_iterations_aggressive;
4282    unsigned max_unroll_iterations_fp64;
4283 
4284    bool lower_uniforms_to_ubo;
4285 
4286    /* Specifies if indirect sampler array access will trigger forced loop
4287     * unrolling.
4288     */
4289    bool force_indirect_unrolling_sampler;
4290 
4291    /* Some older drivers don't support GLSL versions with the concept of flat
4292     * varyings and also don't support integers. This setting helps us avoid
4293     * marking varyings as flat and potentially having them changed to ints via
4294     * varying packing.
4295     */
4296    bool no_integers;
4297 
4298    /**
4299     * Specifies which type of indirectly accessed variables should force
4300     * loop unrolling.
4301     */
4302    nir_variable_mode force_indirect_unrolling;
4303 
4304    bool driver_functions;
4305 
4306    /**
4307     * If true, the driver will call nir_lower_int64 itself and the frontend
4308     * should not do so. This may enable better optimization around address
4309     * modes.
4310     */
4311    bool late_lower_int64;
4312    nir_lower_int64_options lower_int64_options;
4313    nir_lower_doubles_options lower_doubles_options;
4314    nir_divergence_options divergence_analysis_options;
4315 
4316    /**
4317     * The masks of shader stages that support indirect indexing with
4318     * load_input and store_output intrinsics. It's used by
4319     * nir_lower_io_passes.
4320     */
4321    uint8_t support_indirect_inputs;
4322    uint8_t support_indirect_outputs;
4323 
4324    /** store the variable offset into the instrinsic range_base instead
4325     *  of adding it to the image index.
4326     */
4327    bool lower_image_offset_to_range_base;
4328 
4329    /** store the variable offset into the instrinsic range_base instead
4330     *  of adding it to the atomic source
4331     */
4332    bool lower_atomic_offset_to_range_base;
4333 
4334    /** Don't convert medium-precision casts (e.g. f2fmp) into concrete
4335     *  type casts (e.g. f2f16).
4336     */
4337    bool preserve_mediump;
4338 
4339    /** lowers fquantize2f16 to alu ops. */
4340    bool lower_fquantize2f16;
4341 
4342    /** Lower f2f16 to f2f16_rtz when execution mode is not rtne. */
4343    bool force_f2f16_rtz;
4344 
4345    /** Lower VARYING_SLOT_LAYER in FS to SYSTEM_VALUE_LAYER_ID. */
4346    bool lower_layer_fs_input_to_sysval;
4347 
4348    /** clip/cull distance and tess level arrays use compact semantics */
4349    bool compact_arrays;
4350 
4351    /**
4352     * Whether discard gets emitted as nir_intrinsic_demote.
4353     * Otherwise, nir_intrinsic_terminate is being used.
4354     */
4355    bool discard_is_demote;
4356 
4357    /**
4358     * Whether the new-style derivative intrinsics are supported. If false,
4359     * legacy ALU derivative ops will be emitted. This transitional option will
4360     * be removed once all drivers are converted to derivative intrinsics.
4361     */
4362    bool has_ddx_intrinsics;
4363 
4364    /** Whether derivative intrinsics must be scalarized. */
4365    bool scalarize_ddx;
4366 
4367    /**
4368     * Assign a range of driver locations to per-view outputs, with unique
4369     * slots for each view. If unset, per-view outputs will be treated
4370     * similarly to other arrayed IO, and only slots for one view will be
4371     * assigned. Regardless of this setting, per-view outputs are only assigned
4372     * slots for one value in var->data.location.
4373     */
4374    bool per_view_unique_driver_locations;
4375 
4376    /**
4377     * Emit nir_intrinsic_store_per_view_output with compacted view indices
4378     * rather than absolute view indices. When using compacted indices, the Nth
4379     * index refers to the Nth enabled view, not the Nth absolute view. For
4380     * example, with view mask 0b1010, compacted index 0 is absolute index 1,
4381     * and compacted index 1 is absolute index 3. Note that compacted view
4382     * indices do not correspond directly to gl_ViewIndex.
4383     *
4384     * If compact_view_index is unset, per-view indices must be constant before
4385     * nir_lower_io. This can be guaranteed by calling nir_lower_io_temporaries
4386     * first.
4387     */
4388    bool compact_view_index;
4389 
4390    /** Options determining lowering and behavior of inputs and outputs. */
4391    nir_io_options io_options;
4392 
4393    /**
4394     * Bit mask of nir_lower_packing_op to skip lowering some nir ops in
4395     * nir_lower_packing().
4396     */
4397    unsigned skip_lower_packing_ops;
4398 
4399    /** Driver callback where drivers can define how to lower mediump.
4400     *  Used by nir_lower_io_passes.
4401     */
4402    void (*lower_mediump_io)(struct nir_shader *nir);
4403 
4404    /**
4405     * Return the maximum cost of an expression that's written to a shader
4406     * output that can be moved into the next shader to remove that output.
4407     *
4408     * Currently only uniform expressions are moved. A uniform expression is
4409     * any ALU expression sourcing only constants, uniforms, and UBO loads.
4410     *
4411     * Set to NULL or return 0 if you only want to propagate constants from
4412     * outputs to inputs.
4413     *
4414     * Drivers can set the maximum cost based on the types of consecutive
4415     * shaders or shader SHA1s.
4416     *
4417     * Drivers should also set "varying_estimate_instr_cost".
4418     */
4419    unsigned (*varying_expression_max_cost)(struct nir_shader *consumer,
4420                                            struct nir_shader *producer);
4421 
4422    /**
4423     * Return the cost of an instruction that could be moved into the next
4424     * shader. If the cost of all instructions in an expression is <=
4425     * varying_expression_max_cost(), the instruction is moved.
4426     *
4427     * When this callback isn't set, nir_opt_varyings uses its own version.
4428     */
4429    unsigned (*varying_estimate_instr_cost)(struct nir_instr *instr);
4430 
4431    /**
4432     * When the varying_expression_max_cost callback isn't set, this specifies
4433     * the maximum cost of a uniform expression that is allowed to be moved
4434     * from output stores into the next shader stage to eliminate those output
4435     * stores and corresponding inputs.
4436     *
4437     * 0 only allows propagating constants written to output stores to
4438     * the next shader.
4439     *
4440     * At least 2 is required for moving a uniform stored in an output into
4441     * the next shader according to default_varying_estimate_instr_cost.
4442     */
4443    unsigned max_varying_expression_cost;
4444 } nir_shader_compiler_options;
4445 
4446 typedef struct nir_shader {
4447    gc_ctx *gctx;
4448 
4449    /** list of uniforms (nir_variable) */
4450    struct exec_list variables;
4451 
4452    /** Set of driver-specific options for the shader.
4453     *
4454     * The memory for the options is expected to be kept in a single static
4455     * copy by the driver.
4456     */
4457    const struct nir_shader_compiler_options *options;
4458 
4459    /** Various bits of compile-time information about a given shader */
4460    struct shader_info info;
4461 
4462    /** list of nir_function */
4463    struct exec_list functions;
4464 
4465    /**
4466     * The size of the variable space for load_input_*, load_uniform_*, etc.
4467     * intrinsics.  This is in back-end specific units which is likely one of
4468     * bytes, dwords, or vec4s depending on context and back-end.
4469     */
4470    unsigned num_inputs, num_uniforms, num_outputs;
4471 
4472    /** Size in bytes of required implicitly bound global memory */
4473    unsigned global_mem_size;
4474 
4475    /** Size in bytes of required scratch space */
4476    unsigned scratch_size;
4477 
4478    /** Constant data associated with this shader.
4479     *
4480     * Constant data is loaded through load_constant intrinsics (as compared to
4481     * the NIR load_const instructions which have the constant value inlined
4482     * into them).  This is usually generated by nir_opt_large_constants (so
4483     * shaders don't have to load_const into a temporary array when they want
4484     * to indirect on a const array).
4485     */
4486    void *constant_data;
4487    /** Size of the constant data associated with the shader, in bytes */
4488    unsigned constant_data_size;
4489 
4490    struct nir_xfb_info *xfb_info;
4491 
4492    unsigned printf_info_count;
4493    u_printf_info *printf_info;
4494 } nir_shader;
4495 
4496 #define nir_foreach_function(func, shader) \
4497    foreach_list_typed(nir_function, func, node, &(shader)->functions)
4498 
4499 #define nir_foreach_function_safe(func, shader) \
4500    foreach_list_typed_safe(nir_function, func, node, &(shader)->functions)
4501 
4502 #define nir_foreach_entrypoint(func, lib) \
4503    nir_foreach_function(func, lib)        \
4504       if (func->is_entrypoint)
4505 
4506 #define nir_foreach_entrypoint_safe(func, lib) \
4507    nir_foreach_function_safe(func, lib)        \
4508       if (func->is_entrypoint)
4509 
4510 static inline nir_function *
nir_foreach_function_with_impl_first(const nir_shader * shader)4511 nir_foreach_function_with_impl_first(const nir_shader *shader)
4512 {
4513    foreach_list_typed(nir_function, func, node, &shader->functions) {
4514       if (func->impl != NULL)
4515          return func;
4516    }
4517 
4518    return NULL;
4519 }
4520 
4521 static inline nir_function_impl *
nir_foreach_function_with_impl_next(nir_function ** it)4522 nir_foreach_function_with_impl_next(nir_function **it)
4523 {
4524    foreach_list_typed_from(nir_function, func, node, _, (*it)->node.next) {
4525       if (func->impl != NULL) {
4526          *it = func;
4527          return func->impl;
4528       }
4529    }
4530 
4531    return NULL;
4532 }
4533 
4534 #define nir_foreach_function_with_impl(it, impl_it, shader)              \
4535    for (nir_function *it = nir_foreach_function_with_impl_first(shader); \
4536         it != NULL;                                                      \
4537         it = NULL)                                                       \
4538                                                                          \
4539       for (nir_function_impl *impl_it = it->impl;                        \
4540            impl_it != NULL;                                              \
4541            impl_it = nir_foreach_function_with_impl_next(&it))
4542 
4543 /* Equivalent to
4544  *
4545  *    nir_foreach_function(func, shader) {
4546  *       if (func->impl != NULL) {
4547  *             ...
4548  *       }
4549  *    }
4550  *
4551  * Carefully written to ensure break/continue work in the user code.
4552  */
4553 
4554 #define nir_foreach_function_impl(it, shader) \
4555    nir_foreach_function_with_impl(_func_##it, it, shader)
4556 
4557 static inline nir_function_impl *
nir_shader_get_entrypoint(const nir_shader * shader)4558 nir_shader_get_entrypoint(const nir_shader *shader)
4559 {
4560    nir_function *func = NULL;
4561 
4562    nir_foreach_function(function, shader) {
4563       assert(func == NULL);
4564       if (function->is_entrypoint) {
4565          func = function;
4566 #ifndef NDEBUG
4567          break;
4568 #endif
4569       }
4570    }
4571 
4572    if (!func)
4573       return NULL;
4574 
4575    assert(func->num_params == 0);
4576    assert(func->impl);
4577    return func->impl;
4578 }
4579 
4580 static inline nir_function *
nir_shader_get_function_for_name(const nir_shader * shader,const char * name)4581 nir_shader_get_function_for_name(const nir_shader *shader, const char *name)
4582 {
4583    nir_foreach_function(func, shader) {
4584       if (func->name && strcmp(func->name, name) == 0)
4585          return func;
4586    }
4587 
4588    return NULL;
4589 }
4590 
4591 /*
4592  * After all functions are forcibly inlined, these passes remove redundant
4593  * functions from a shader and library respectively.
4594  */
4595 void nir_remove_non_entrypoints(nir_shader *shader);
4596 void nir_remove_non_exported(nir_shader *shader);
4597 void nir_remove_entrypoints(nir_shader *shader);
4598 void nir_fixup_is_exported(nir_shader *shader);
4599 
4600 nir_shader *nir_shader_create(void *mem_ctx,
4601                               gl_shader_stage stage,
4602                               const nir_shader_compiler_options *options,
4603                               shader_info *si);
4604 
4605 /** Adds a variable to the appropriate list in nir_shader */
4606 void nir_shader_add_variable(nir_shader *shader, nir_variable *var);
4607 
4608 static inline void
nir_function_impl_add_variable(nir_function_impl * impl,nir_variable * var)4609 nir_function_impl_add_variable(nir_function_impl *impl, nir_variable *var)
4610 {
4611    assert(var->data.mode == nir_var_function_temp);
4612    exec_list_push_tail(&impl->locals, &var->node);
4613 }
4614 
4615 /** creates a variable, sets a few defaults, and adds it to the list */
4616 nir_variable *nir_variable_create(nir_shader *shader,
4617                                   nir_variable_mode mode,
4618                                   const struct glsl_type *type,
4619                                   const char *name);
4620 /** creates a local variable and adds it to the list */
4621 nir_variable *nir_local_variable_create(nir_function_impl *impl,
4622                                         const struct glsl_type *type,
4623                                         const char *name);
4624 
4625 /** Creates a uniform builtin state variable. */
4626 nir_variable *
4627 nir_state_variable_create(nir_shader *shader,
4628                           const struct glsl_type *type,
4629                           const char *name,
4630                           const gl_state_index16 tokens[STATE_LENGTH]);
4631 
4632 /* Gets the variable for the given mode and location, creating it (with the given
4633  * type) if necessary.
4634  */
4635 nir_variable *
4636 nir_get_variable_with_location(nir_shader *shader, nir_variable_mode mode, int location,
4637                                const struct glsl_type *type);
4638 
4639 /* Creates a variable for the given mode and location.
4640  */
4641 nir_variable *
4642 nir_create_variable_with_location(nir_shader *shader, nir_variable_mode mode, int location,
4643                                   const struct glsl_type *type);
4644 
4645 nir_variable *nir_find_variable_with_location(nir_shader *shader,
4646                                               nir_variable_mode mode,
4647                                               unsigned location);
4648 
4649 nir_variable *nir_find_variable_with_driver_location(nir_shader *shader,
4650                                                      nir_variable_mode mode,
4651                                                      unsigned location);
4652 
4653 nir_variable *nir_find_state_variable(nir_shader *s,
4654                                       gl_state_index16 tokens[STATE_LENGTH]);
4655 
4656 nir_variable *nir_find_sampler_variable_with_tex_index(nir_shader *shader,
4657                                                        unsigned texture_index);
4658 
4659 void nir_sort_variables_with_modes(nir_shader *shader,
4660                                    int (*compar)(const nir_variable *,
4661                                                  const nir_variable *),
4662                                    nir_variable_mode modes);
4663 
4664 /** creates a function and adds it to the shader's list of functions */
4665 nir_function *nir_function_create(nir_shader *shader, const char *name);
4666 
4667 static inline void
nir_function_set_impl(nir_function * func,nir_function_impl * impl)4668 nir_function_set_impl(nir_function *func, nir_function_impl *impl)
4669 {
4670    func->impl = impl;
4671    impl->function = func;
4672 }
4673 
4674 nir_function_impl *nir_function_impl_create(nir_function *func);
4675 /** creates a function_impl that isn't tied to any particular function */
4676 nir_function_impl *nir_function_impl_create_bare(nir_shader *shader);
4677 
4678 nir_block *nir_block_create(nir_shader *shader);
4679 nir_if *nir_if_create(nir_shader *shader);
4680 nir_loop *nir_loop_create(nir_shader *shader);
4681 
4682 nir_function_impl *nir_cf_node_get_function(nir_cf_node *node);
4683 
4684 /** requests that the given pieces of metadata be generated */
4685 void nir_metadata_require(nir_function_impl *impl, nir_metadata required, ...);
4686 /** dirties all but the preserved metadata */
4687 void nir_metadata_preserve(nir_function_impl *impl, nir_metadata preserved);
4688 /** Preserves all metadata for the given shader */
4689 void nir_shader_preserve_all_metadata(nir_shader *shader);
4690 
4691 /** creates an instruction with default swizzle/writemask/etc. with NULL registers */
4692 nir_alu_instr *nir_alu_instr_create(nir_shader *shader, nir_op op);
4693 
4694 nir_deref_instr *nir_deref_instr_create(nir_shader *shader,
4695                                         nir_deref_type deref_type);
4696 
4697 nir_jump_instr *nir_jump_instr_create(nir_shader *shader, nir_jump_type type);
4698 
4699 nir_load_const_instr *nir_load_const_instr_create(nir_shader *shader,
4700                                                   unsigned num_components,
4701                                                   unsigned bit_size);
4702 
4703 nir_intrinsic_instr *nir_intrinsic_instr_create(nir_shader *shader,
4704                                                 nir_intrinsic_op op);
4705 
4706 nir_call_instr *nir_call_instr_create(nir_shader *shader,
4707                                       nir_function *callee);
4708 
4709 /** Creates a NIR texture instruction */
4710 nir_tex_instr *nir_tex_instr_create(nir_shader *shader, unsigned num_srcs);
4711 
4712 nir_phi_instr *nir_phi_instr_create(nir_shader *shader);
4713 nir_phi_src *nir_phi_instr_add_src(nir_phi_instr *instr,
4714                                    nir_block *pred, nir_def *src);
4715 
4716 nir_parallel_copy_instr *nir_parallel_copy_instr_create(nir_shader *shader);
4717 
4718 nir_debug_info_instr *nir_debug_info_instr_create(nir_shader *shader,
4719                                                   nir_debug_info_type type,
4720                                                   uint32_t string_length);
4721 
4722 nir_undef_instr *nir_undef_instr_create(nir_shader *shader,
4723                                         unsigned num_components,
4724                                         unsigned bit_size);
4725 
4726 nir_const_value nir_alu_binop_identity(nir_op binop, unsigned bit_size);
4727 
4728 /**
4729  * NIR Cursors and Instruction Insertion API
4730  * @{
4731  *
4732  * A tiny struct representing a point to insert/extract instructions or
4733  * control flow nodes.  Helps reduce the combinatorial explosion of possible
4734  * points to insert/extract.
4735  *
4736  * \sa nir_control_flow.h
4737  */
4738 typedef enum {
4739    nir_cursor_before_block,
4740    nir_cursor_after_block,
4741    nir_cursor_before_instr,
4742    nir_cursor_after_instr,
4743 } nir_cursor_option;
4744 
4745 typedef struct {
4746    nir_cursor_option option;
4747    union {
4748       nir_block *block;
4749       nir_instr *instr;
4750    };
4751 } nir_cursor;
4752 
4753 static inline nir_block *
nir_cursor_current_block(nir_cursor cursor)4754 nir_cursor_current_block(nir_cursor cursor)
4755 {
4756    if (cursor.option == nir_cursor_before_instr ||
4757        cursor.option == nir_cursor_after_instr) {
4758       return cursor.instr->block;
4759    } else {
4760       return cursor.block;
4761    }
4762 }
4763 
4764 bool nir_cursors_equal(nir_cursor a, nir_cursor b);
4765 
4766 static inline nir_cursor
nir_before_block(nir_block * block)4767 nir_before_block(nir_block *block)
4768 {
4769    nir_cursor cursor;
4770    cursor.option = nir_cursor_before_block;
4771    cursor.block = block;
4772    return cursor;
4773 }
4774 
4775 static inline nir_cursor
nir_after_block(nir_block * block)4776 nir_after_block(nir_block *block)
4777 {
4778    nir_cursor cursor;
4779    cursor.option = nir_cursor_after_block;
4780    cursor.block = block;
4781    return cursor;
4782 }
4783 
4784 static inline nir_cursor
nir_before_instr(nir_instr * instr)4785 nir_before_instr(nir_instr *instr)
4786 {
4787    nir_cursor cursor;
4788    cursor.option = nir_cursor_before_instr;
4789    cursor.instr = instr;
4790    return cursor;
4791 }
4792 
4793 static inline nir_cursor
nir_after_instr(nir_instr * instr)4794 nir_after_instr(nir_instr *instr)
4795 {
4796    nir_cursor cursor;
4797    cursor.option = nir_cursor_after_instr;
4798    cursor.instr = instr;
4799    return cursor;
4800 }
4801 
4802 static inline nir_cursor
nir_before_block_after_phis(nir_block * block)4803 nir_before_block_after_phis(nir_block *block)
4804 {
4805    nir_phi_instr *last_phi = nir_block_last_phi_instr(block);
4806    if (last_phi)
4807       return nir_after_instr(&last_phi->instr);
4808    else
4809       return nir_before_block(block);
4810 }
4811 
4812 static inline nir_cursor
nir_after_block_before_jump(nir_block * block)4813 nir_after_block_before_jump(nir_block *block)
4814 {
4815    nir_instr *last_instr = nir_block_last_instr(block);
4816    if (last_instr && last_instr->type == nir_instr_type_jump) {
4817       return nir_before_instr(last_instr);
4818    } else {
4819       return nir_after_block(block);
4820    }
4821 }
4822 
4823 static inline nir_cursor
nir_before_src(nir_src * src)4824 nir_before_src(nir_src *src)
4825 {
4826    if (nir_src_is_if(src)) {
4827       nir_block *prev_block =
4828          nir_cf_node_as_block(nir_cf_node_prev(&nir_src_parent_if(src)->cf_node));
4829       return nir_after_block(prev_block);
4830    } else if (nir_src_parent_instr(src)->type == nir_instr_type_phi) {
4831 #ifndef NDEBUG
4832       nir_phi_instr *cond_phi = nir_instr_as_phi(nir_src_parent_instr(src));
4833       bool found = false;
4834       nir_foreach_phi_src(phi_src, cond_phi) {
4835          if (phi_src->src.ssa == src->ssa) {
4836             found = true;
4837             break;
4838          }
4839       }
4840       assert(found);
4841 #endif
4842       /* The list_entry() macro is a generic container-of macro, it just happens
4843        * to have a more specific name.
4844        */
4845       nir_phi_src *phi_src = list_entry(src, nir_phi_src, src);
4846       return nir_after_block_before_jump(phi_src->pred);
4847    } else {
4848       return nir_before_instr(nir_src_parent_instr(src));
4849    }
4850 }
4851 
4852 static inline nir_cursor
nir_before_cf_node(nir_cf_node * node)4853 nir_before_cf_node(nir_cf_node *node)
4854 {
4855    if (node->type == nir_cf_node_block)
4856       return nir_before_block(nir_cf_node_as_block(node));
4857 
4858    return nir_after_block(nir_cf_node_as_block(nir_cf_node_prev(node)));
4859 }
4860 
4861 static inline nir_cursor
nir_after_cf_node(nir_cf_node * node)4862 nir_after_cf_node(nir_cf_node *node)
4863 {
4864    if (node->type == nir_cf_node_block)
4865       return nir_after_block(nir_cf_node_as_block(node));
4866 
4867    return nir_before_block(nir_cf_node_as_block(nir_cf_node_next(node)));
4868 }
4869 
4870 static inline nir_cursor
nir_after_phis(nir_block * block)4871 nir_after_phis(nir_block *block)
4872 {
4873    nir_foreach_instr(instr, block) {
4874       if (instr->type != nir_instr_type_phi)
4875          return nir_before_instr(instr);
4876    }
4877    return nir_after_block(block);
4878 }
4879 
4880 static inline nir_cursor
nir_after_instr_and_phis(nir_instr * instr)4881 nir_after_instr_and_phis(nir_instr *instr)
4882 {
4883    if (instr->type == nir_instr_type_phi)
4884       return nir_after_phis(instr->block);
4885    else
4886       return nir_after_instr(instr);
4887 }
4888 
4889 static inline nir_cursor
nir_after_cf_node_and_phis(nir_cf_node * node)4890 nir_after_cf_node_and_phis(nir_cf_node *node)
4891 {
4892    if (node->type == nir_cf_node_block)
4893       return nir_after_block(nir_cf_node_as_block(node));
4894 
4895    nir_block *block = nir_cf_node_as_block(nir_cf_node_next(node));
4896 
4897    return nir_after_phis(block);
4898 }
4899 
4900 static inline nir_cursor
nir_before_cf_list(struct exec_list * cf_list)4901 nir_before_cf_list(struct exec_list *cf_list)
4902 {
4903    nir_cf_node *first_node = exec_node_data(nir_cf_node,
4904                                             exec_list_get_head(cf_list), node);
4905    return nir_before_cf_node(first_node);
4906 }
4907 
4908 static inline nir_cursor
nir_after_cf_list(struct exec_list * cf_list)4909 nir_after_cf_list(struct exec_list *cf_list)
4910 {
4911    nir_cf_node *last_node = exec_node_data(nir_cf_node,
4912                                            exec_list_get_tail(cf_list), node);
4913    return nir_after_cf_node(last_node);
4914 }
4915 
4916 static inline nir_cursor
nir_before_impl(nir_function_impl * impl)4917 nir_before_impl(nir_function_impl *impl)
4918 {
4919    return nir_before_cf_list(&impl->body);
4920 }
4921 
4922 static inline nir_cursor
nir_after_impl(nir_function_impl * impl)4923 nir_after_impl(nir_function_impl *impl)
4924 {
4925    return nir_after_cf_list(&impl->body);
4926 }
4927 
4928 /**
4929  * Insert a NIR instruction at the given cursor.
4930  *
4931  * Note: This does not update the cursor.
4932  */
4933 void nir_instr_insert(nir_cursor cursor, nir_instr *instr);
4934 
4935 bool nir_instr_move(nir_cursor cursor, nir_instr *instr);
4936 
4937 static inline void
nir_instr_insert_before(nir_instr * instr,nir_instr * before)4938 nir_instr_insert_before(nir_instr *instr, nir_instr *before)
4939 {
4940    nir_instr_insert(nir_before_instr(instr), before);
4941 }
4942 
4943 static inline void
nir_instr_insert_after(nir_instr * instr,nir_instr * after)4944 nir_instr_insert_after(nir_instr *instr, nir_instr *after)
4945 {
4946    nir_instr_insert(nir_after_instr(instr), after);
4947 }
4948 
4949 static inline void
nir_instr_insert_before_block(nir_block * block,nir_instr * before)4950 nir_instr_insert_before_block(nir_block *block, nir_instr *before)
4951 {
4952    nir_instr_insert(nir_before_block(block), before);
4953 }
4954 
4955 static inline void
nir_instr_insert_after_block(nir_block * block,nir_instr * after)4956 nir_instr_insert_after_block(nir_block *block, nir_instr *after)
4957 {
4958    nir_instr_insert(nir_after_block(block), after);
4959 }
4960 
4961 static inline void
nir_instr_insert_before_cf(nir_cf_node * node,nir_instr * before)4962 nir_instr_insert_before_cf(nir_cf_node *node, nir_instr *before)
4963 {
4964    nir_instr_insert(nir_before_cf_node(node), before);
4965 }
4966 
4967 static inline void
nir_instr_insert_after_cf(nir_cf_node * node,nir_instr * after)4968 nir_instr_insert_after_cf(nir_cf_node *node, nir_instr *after)
4969 {
4970    nir_instr_insert(nir_after_cf_node(node), after);
4971 }
4972 
4973 static inline void
nir_instr_insert_before_cf_list(struct exec_list * list,nir_instr * before)4974 nir_instr_insert_before_cf_list(struct exec_list *list, nir_instr *before)
4975 {
4976    nir_instr_insert(nir_before_cf_list(list), before);
4977 }
4978 
4979 static inline void
nir_instr_insert_after_cf_list(struct exec_list * list,nir_instr * after)4980 nir_instr_insert_after_cf_list(struct exec_list *list, nir_instr *after)
4981 {
4982    nir_instr_insert(nir_after_cf_list(list), after);
4983 }
4984 
4985 void nir_instr_remove_v(nir_instr *instr);
4986 void nir_instr_free(nir_instr *instr);
4987 void nir_instr_free_list(struct exec_list *list);
4988 
4989 static inline nir_cursor
nir_instr_remove(nir_instr * instr)4990 nir_instr_remove(nir_instr *instr)
4991 {
4992    nir_cursor cursor;
4993    nir_instr *prev = nir_instr_prev(instr);
4994    if (prev) {
4995       cursor = nir_after_instr(prev);
4996    } else {
4997       cursor = nir_before_block(instr->block);
4998    }
4999    nir_instr_remove_v(instr);
5000    return cursor;
5001 }
5002 
5003 nir_cursor nir_instr_free_and_dce(nir_instr *instr);
5004 
5005 /** @} */
5006 
5007 nir_def *nir_instr_def(nir_instr *instr);
5008 
5009 typedef bool (*nir_foreach_def_cb)(nir_def *def, void *state);
5010 typedef bool (*nir_foreach_src_cb)(nir_src *src, void *state);
5011 static inline bool nir_foreach_src(nir_instr *instr, nir_foreach_src_cb cb, void *state);
5012 bool nir_foreach_phi_src_leaving_block(nir_block *instr,
5013                                        nir_foreach_src_cb cb,
5014                                        void *state);
5015 
5016 nir_const_value *nir_src_as_const_value(nir_src src);
5017 
5018 #define NIR_SRC_AS_(name, c_type, type_enum, cast_macro) \
5019    static inline c_type *                                \
5020       nir_src_as_##name(nir_src src)                     \
5021    {                                                     \
5022       return src.ssa->parent_instr->type == type_enum    \
5023                 ? cast_macro(src.ssa->parent_instr)      \
5024                 : NULL;                                  \
5025    }
5026 
5027 NIR_SRC_AS_(alu_instr, nir_alu_instr, nir_instr_type_alu, nir_instr_as_alu)
5028 NIR_SRC_AS_(intrinsic, nir_intrinsic_instr,
5029             nir_instr_type_intrinsic, nir_instr_as_intrinsic)
5030 NIR_SRC_AS_(deref, nir_deref_instr, nir_instr_type_deref, nir_instr_as_deref)
5031 NIR_SRC_AS_(debug_info, nir_debug_info_instr, nir_instr_type_debug_info, nir_instr_as_debug_info)
5032 
5033 const char *nir_src_as_string(nir_src src);
5034 
5035 bool nir_src_is_always_uniform(nir_src src);
5036 bool nir_srcs_equal(nir_src src1, nir_src src2);
5037 bool nir_instrs_equal(const nir_instr *instr1, const nir_instr *instr2);
5038 nir_block *nir_src_get_block(nir_src *src);
5039 
5040 static inline void
nir_src_rewrite(nir_src * src,nir_def * new_ssa)5041 nir_src_rewrite(nir_src *src, nir_def *new_ssa)
5042 {
5043    assert(src->ssa);
5044    assert(nir_src_is_if(src) ? (nir_src_parent_if(src) != NULL) : (nir_src_parent_instr(src) != NULL));
5045    list_del(&src->use_link);
5046    src->ssa = new_ssa;
5047    list_addtail(&src->use_link, &new_ssa->uses);
5048 }
5049 
5050 /** Initialize a nir_src
5051  *
5052  * This is almost never the helper you want to use.  This helper assumes that
5053  * the source is uninitialized garbage and blasts over it without doing any
5054  * tear-down the existing source, including removing it from uses lists.
5055  * Using this helper on a source that currently exists in any uses list will
5056  * result in linked list corruption.  It also assumes that the instruction is
5057  * currently live in the IR and adds the source to the uses list for the given
5058  * nir_def as part of setup.
5059  *
5060  * This is pretty much only useful for adding sources to extant instructions
5061  * or manipulating parallel copy instructions as part of out-of-SSA.
5062  *
5063  * When in doubt, use nir_src_rewrite() instead.
5064  */
5065 void nir_instr_init_src(nir_instr *instr, nir_src *src, nir_def *def);
5066 
5067 /** Clear a nir_src
5068  *
5069  * This helper clears a nir_src by removing it from any uses lists and
5070  * resetting its contents to NIR_SRC_INIT.  This is typically used as a
5071  * precursor to removing the source from the instruction by adjusting a
5072  * num_srcs parameter somewhere or overwriting it with nir_instr_move_src().
5073  */
5074 void nir_instr_clear_src(nir_instr *instr, nir_src *src);
5075 
5076 void nir_instr_move_src(nir_instr *dest_instr, nir_src *dest, nir_src *src);
5077 
5078 void nir_def_init(nir_instr *instr, nir_def *def,
5079                   unsigned num_components, unsigned bit_size);
5080 static inline void
nir_def_init_for_type(nir_instr * instr,nir_def * def,const struct glsl_type * type)5081 nir_def_init_for_type(nir_instr *instr, nir_def *def,
5082                       const struct glsl_type *type)
5083 {
5084    assert(glsl_type_is_vector_or_scalar(type));
5085    nir_def_init(instr, def, glsl_get_components(type),
5086                 glsl_get_bit_size(type));
5087 }
5088 void nir_def_rewrite_uses(nir_def *def, nir_def *new_ssa);
5089 void nir_def_rewrite_uses_src(nir_def *def, nir_src new_src);
5090 void nir_def_rewrite_uses_after(nir_def *def, nir_def *new_ssa,
5091                                 nir_instr *after_me);
5092 
5093 static inline void
nir_def_replace(nir_def * def,nir_def * new_ssa)5094 nir_def_replace(nir_def *def, nir_def *new_ssa)
5095 {
5096    nir_def_rewrite_uses(def, new_ssa);
5097    nir_instr_remove(def->parent_instr);
5098 }
5099 
5100 nir_component_mask_t nir_src_components_read(const nir_src *src);
5101 nir_component_mask_t nir_def_components_read(const nir_def *def);
5102 bool nir_def_all_uses_are_fsat(const nir_def *def);
5103 bool nir_def_all_uses_ignore_sign_bit(const nir_def *def);
5104 
5105 static inline int
nir_def_first_component_read(nir_def * def)5106 nir_def_first_component_read(nir_def *def)
5107 {
5108     return (int)ffs(nir_def_components_read(def)) - 1;
5109 }
5110 
5111 static inline int
nir_def_last_component_read(nir_def * def)5112 nir_def_last_component_read(nir_def *def)
5113 {
5114     return (int)util_last_bit(nir_def_components_read(def)) - 1;
5115 }
5116 
5117 static inline bool
nir_def_is_unused(nir_def * ssa)5118 nir_def_is_unused(nir_def *ssa)
5119 {
5120    return list_is_empty(&ssa->uses);
5121 }
5122 
5123 /** Sorts unstructured blocks
5124  *
5125  * NIR requires that unstructured blocks be sorted in reverse post
5126  * depth-first-search order.  This is the standard ordering used in the
5127  * compiler literature which guarantees dominance.  In particular, reverse
5128  * post-DFS order guarantees that dominators occur in the list before the
5129  * blocks they dominate.
5130  *
5131  * NOTE: This function also implicitly deletes any unreachable blocks.
5132  */
5133 void nir_sort_unstructured_blocks(nir_function_impl *impl);
5134 
5135 /** Returns the next block
5136  *
5137  * For structured control-flow, this follows the same order as
5138  * nir_block_cf_tree_next().  For unstructured control-flow the blocks are in
5139  * reverse post-DFS order.  (See nir_sort_unstructured_blocks() above.)
5140  */
5141 nir_block *nir_block_unstructured_next(nir_block *block);
5142 nir_block *nir_unstructured_start_block(nir_function_impl *impl);
5143 
5144 #define nir_foreach_block_unstructured(block, impl)                           \
5145    for (nir_block *block = nir_unstructured_start_block(impl); block != NULL; \
5146         block = nir_block_unstructured_next(block))
5147 
5148 #define nir_foreach_block_unstructured_safe(block, impl)       \
5149    for (nir_block *block = nir_unstructured_start_block(impl), \
5150                   *next = nir_block_unstructured_next(block);  \
5151         block != NULL;                                         \
5152         block = next, next = nir_block_unstructured_next(block))
5153 
5154 /*
5155  * finds the next basic block in source-code order, returns NULL if there is
5156  * none
5157  */
5158 
5159 nir_block *nir_block_cf_tree_next(nir_block *block);
5160 
5161 /* Performs the opposite of nir_block_cf_tree_next() */
5162 
5163 nir_block *nir_block_cf_tree_prev(nir_block *block);
5164 
5165 /* Gets the first block in a CF node in source-code order */
5166 
5167 nir_block *nir_cf_node_cf_tree_first(nir_cf_node *node);
5168 
5169 /* Gets the last block in a CF node in source-code order */
5170 
5171 nir_block *nir_cf_node_cf_tree_last(nir_cf_node *node);
5172 
5173 /* Gets the next block after a CF node in source-code order */
5174 
5175 nir_block *nir_cf_node_cf_tree_next(nir_cf_node *node);
5176 
5177 /* Gets the block before a CF node in source-code order */
5178 
5179 nir_block *nir_cf_node_cf_tree_prev(nir_cf_node *node);
5180 
5181 /* Macros for loops that visit blocks in source-code order */
5182 
5183 #define nir_foreach_block(block, impl)                           \
5184    for (nir_block *block = nir_start_block(impl); block != NULL; \
5185         block = nir_block_cf_tree_next(block))
5186 
5187 #define nir_foreach_block_safe(block, impl)              \
5188    for (nir_block *block = nir_start_block(impl),        \
5189                   *next = nir_block_cf_tree_next(block); \
5190         block != NULL;                                   \
5191         block = next, next = nir_block_cf_tree_next(block))
5192 
5193 #define nir_foreach_block_reverse(block, impl)                       \
5194    for (nir_block *block = nir_impl_last_block(impl); block != NULL; \
5195         block = nir_block_cf_tree_prev(block))
5196 
5197 #define nir_foreach_block_reverse_safe(block, impl)      \
5198    for (nir_block *block = nir_impl_last_block(impl),    \
5199                   *prev = nir_block_cf_tree_prev(block); \
5200         block != NULL;                                   \
5201         block = prev, prev = nir_block_cf_tree_prev(block))
5202 
5203 #define nir_foreach_block_in_cf_node(block, node)           \
5204    for (nir_block *block = nir_cf_node_cf_tree_first(node); \
5205         block != nir_cf_node_cf_tree_next(node);            \
5206         block = nir_block_cf_tree_next(block))
5207 
5208 #define nir_foreach_block_in_cf_node_safe(block, node)      \
5209    for (nir_block *block = nir_cf_node_cf_tree_first(node), \
5210                   *next = nir_block_cf_tree_next(block);    \
5211         block != nir_cf_node_cf_tree_next(node);            \
5212         block = next, next = nir_block_cf_tree_next(block))
5213 
5214 #define nir_foreach_block_in_cf_node_reverse(block, node)  \
5215    for (nir_block *block = nir_cf_node_cf_tree_last(node); \
5216         block != nir_cf_node_cf_tree_prev(node);           \
5217         block = nir_block_cf_tree_prev(block))
5218 
5219 #define nir_foreach_block_in_cf_node_reverse_safe(block, node) \
5220    for (nir_block *block = nir_cf_node_cf_tree_last(node),     \
5221                   *prev = nir_block_cf_tree_prev(block);       \
5222         block != nir_cf_node_cf_tree_prev(node);               \
5223         block = prev, prev = nir_block_cf_tree_prev(block))
5224 
5225 /* If the following CF node is an if, this function returns that if.
5226  * Otherwise, it returns NULL.
5227  */
5228 nir_if *nir_block_get_following_if(nir_block *block);
5229 
5230 nir_loop *nir_block_get_following_loop(nir_block *block);
5231 
5232 nir_block **nir_block_get_predecessors_sorted(const nir_block *block, void *mem_ctx);
5233 
5234 void nir_index_ssa_defs(nir_function_impl *impl);
5235 unsigned nir_index_instrs(nir_function_impl *impl);
5236 
5237 void nir_index_blocks(nir_function_impl *impl);
5238 
5239 void nir_shader_clear_pass_flags(nir_shader *shader);
5240 
5241 unsigned nir_shader_index_vars(nir_shader *shader, nir_variable_mode modes);
5242 unsigned nir_function_impl_index_vars(nir_function_impl *impl);
5243 
5244 void nir_print_shader(nir_shader *shader, FILE *fp);
5245 void nir_print_shader_annotated(nir_shader *shader, FILE *fp, struct hash_table *errors);
5246 void nir_print_instr(const nir_instr *instr, FILE *fp);
5247 void nir_print_deref(const nir_deref_instr *deref, FILE *fp);
5248 void nir_log_shader_annotated_tagged(enum mesa_log_level level, const char *tag, nir_shader *shader, struct hash_table *annotations);
5249 #define nir_log_shadere(s)                       nir_log_shader_annotated_tagged(MESA_LOG_ERROR, (MESA_LOG_TAG), (s), NULL)
5250 #define nir_log_shaderw(s)                       nir_log_shader_annotated_tagged(MESA_LOG_WARN, (MESA_LOG_TAG), (s), NULL)
5251 #define nir_log_shaderi(s)                       nir_log_shader_annotated_tagged(MESA_LOG_INFO, (MESA_LOG_TAG), (s), NULL)
5252 #define nir_log_shader_annotated(s, annotations) nir_log_shader_annotated_tagged(MESA_LOG_ERROR, (MESA_LOG_TAG), (s), annotations)
5253 
5254 char *nir_shader_as_str(nir_shader *nir, void *mem_ctx);
5255 char *nir_shader_as_str_annotated(nir_shader *nir, struct hash_table *annotations, void *mem_ctx);
5256 char *nir_instr_as_str(const nir_instr *instr, void *mem_ctx);
5257 
5258 /** Adds debug information to the shader. The line numbers point to
5259  * the corresponding lines in the printed NIR, starting first_line;
5260  */
5261 char *nir_shader_gather_debug_info(nir_shader *shader, const char *filename, uint32_t first_line);
5262 
5263 /** Shallow clone of a single instruction. */
5264 nir_instr *nir_instr_clone(nir_shader *s, const nir_instr *orig);
5265 
5266 /** Clone a single instruction, including a remap table to rewrite sources. */
5267 nir_instr *nir_instr_clone_deep(nir_shader *s, const nir_instr *orig,
5268                                 struct hash_table *remap_table);
5269 
5270 /** Shallow clone of a single ALU instruction. */
5271 nir_alu_instr *nir_alu_instr_clone(nir_shader *s, const nir_alu_instr *orig);
5272 
5273 nir_shader *nir_shader_clone(void *mem_ctx, const nir_shader *s);
5274 nir_function *nir_function_clone(nir_shader *ns, const nir_function *fxn);
5275 nir_function_impl *nir_function_impl_clone(nir_shader *shader,
5276                                            const nir_function_impl *fi);
5277 nir_function_impl *
5278 nir_function_impl_clone_remap_globals(nir_shader *shader,
5279                                       const nir_function_impl *fi,
5280                                       struct hash_table *remap_table);
5281 nir_constant *nir_constant_clone(const nir_constant *c, nir_variable *var);
5282 nir_variable *nir_variable_clone(const nir_variable *c, nir_shader *shader);
5283 
5284 void nir_shader_replace(nir_shader *dest, nir_shader *src);
5285 
5286 void nir_shader_serialize_deserialize(nir_shader *s);
5287 
5288 #ifndef NDEBUG
5289 void nir_validate_shader(nir_shader *shader, const char *when);
5290 void nir_validate_ssa_dominance(nir_shader *shader, const char *when);
5291 void nir_metadata_set_validation_flag(nir_shader *shader);
5292 void nir_metadata_check_validation_flag(nir_shader *shader);
5293 
5294 static inline bool
should_skip_nir(const char * name)5295 should_skip_nir(const char *name)
5296 {
5297    static const char *list = NULL;
5298    if (!list) {
5299       /* Comma separated list of names to skip. */
5300       list = getenv("NIR_SKIP");
5301       if (!list)
5302          list = "";
5303    }
5304 
5305    if (!list[0])
5306       return false;
5307 
5308    return comma_separated_list_contains(list, name);
5309 }
5310 
5311 static inline bool
should_print_nir(nir_shader * shader)5312 should_print_nir(nir_shader *shader)
5313 {
5314    if ((shader->info.internal && !NIR_DEBUG(PRINT_INTERNAL)) ||
5315        shader->info.stage < 0 ||
5316        shader->info.stage > MESA_SHADER_KERNEL)
5317       return false;
5318 
5319    return unlikely(nir_debug_print_shader[shader->info.stage]);
5320 }
5321 #else
5322 static inline void
nir_validate_shader(nir_shader * shader,const char * when)5323 nir_validate_shader(nir_shader *shader, const char *when)
5324 {
5325    (void)shader;
5326    (void)when;
5327 }
5328 static inline void
nir_validate_ssa_dominance(nir_shader * shader,const char * when)5329 nir_validate_ssa_dominance(nir_shader *shader, const char *when)
5330 {
5331    (void)shader;
5332    (void)when;
5333 }
5334 static inline void
nir_metadata_set_validation_flag(nir_shader * shader)5335 nir_metadata_set_validation_flag(nir_shader *shader)
5336 {
5337    (void)shader;
5338 }
5339 static inline void
nir_metadata_check_validation_flag(nir_shader * shader)5340 nir_metadata_check_validation_flag(nir_shader *shader)
5341 {
5342    (void)shader;
5343 }
5344 static inline bool
should_skip_nir(UNUSED const char * pass_name)5345 should_skip_nir(UNUSED const char *pass_name)
5346 {
5347    return false;
5348 }
5349 static inline bool
should_print_nir(UNUSED nir_shader * shader)5350 should_print_nir(UNUSED nir_shader *shader)
5351 {
5352    return false;
5353 }
5354 #endif /* NDEBUG */
5355 
5356 #define _PASS(pass, nir, do_pass)                                       \
5357    do {                                                                 \
5358       if (should_skip_nir(#pass)) {                                     \
5359          printf("skipping %s\n", #pass);                                \
5360          break;                                                         \
5361       }                                                                 \
5362       do_pass if (NIR_DEBUG(CLONE))                                     \
5363       {                                                                 \
5364          nir_shader *_clone = nir_shader_clone(ralloc_parent(nir), nir);\
5365          nir_shader_replace(nir, _clone);                               \
5366       }                                                                 \
5367       if (NIR_DEBUG(SERIALIZE)) {                                       \
5368          nir_shader_serialize_deserialize(nir);                         \
5369       }                                                                 \
5370    } while (0)
5371 
5372 #define NIR_PASS(progress, nir, pass, ...) _PASS(pass, nir, {   \
5373    nir_metadata_set_validation_flag(nir);                       \
5374    if (should_print_nir(nir))                                   \
5375       printf("%s\n", #pass);                                    \
5376    if (pass(nir, ##__VA_ARGS__)) {                              \
5377       nir_validate_shader(nir, "after " #pass " in " __FILE__); \
5378       UNUSED bool _;                                            \
5379       progress = true;                                          \
5380       if (should_print_nir(nir))                                \
5381          nir_print_shader(nir, stdout);                         \
5382       nir_metadata_check_validation_flag(nir);                  \
5383    }                                                            \
5384 })
5385 
5386 #define NIR_PASS_V(nir, pass, ...) _PASS(pass, nir, {        \
5387    if (should_print_nir(nir))                                \
5388       printf("%s\n", #pass);                                 \
5389    pass(nir, ##__VA_ARGS__);                                 \
5390    nir_validate_shader(nir, "after " #pass " in " __FILE__); \
5391    if (should_print_nir(nir))                                \
5392       nir_print_shader(nir, stdout);                         \
5393 })
5394 
5395 #define _NIR_LOOP_PASS(progress, idempotent, skip, nir, pass, ...)   \
5396 do {                                                                 \
5397    bool nir_loop_pass_progress = false;                              \
5398    if (!_mesa_set_search(skip, (void (*)())&pass))                   \
5399       NIR_PASS(nir_loop_pass_progress, nir, pass, ##__VA_ARGS__);    \
5400    if (nir_loop_pass_progress)                                       \
5401       _mesa_set_clear(skip, NULL);                                   \
5402    if (idempotent || !nir_loop_pass_progress)                        \
5403       _mesa_set_add(skip, (void (*)())&pass);                        \
5404    UNUSED bool _ = false;                                            \
5405    progress |= nir_loop_pass_progress;                               \
5406 } while (0)
5407 
5408 /* Helper to skip a pass if no different passes have made progress since it was
5409  * previously run. Note that two passes are considered the same if they have
5410  * the same function pointer, even if they used different options.
5411  *
5412  * The usage of this is mostly identical to NIR_PASS. "skip" is a "struct set *"
5413  * (created by _mesa_pointer_set_create) which the macro uses to keep track of
5414  * already run passes.
5415  *
5416  * Example:
5417  * bool progress = true;
5418  * struct set *skip = _mesa_pointer_set_create(NULL);
5419  * while (progress) {
5420  *    progress = false;
5421  *    NIR_LOOP_PASS(progress, skip, nir, pass1);
5422  *    NIR_LOOP_PASS_NOT_IDEMPOTENT(progress, skip, nir, nir_opt_algebraic);
5423  *    NIR_LOOP_PASS(progress, skip, nir, pass2);
5424  *    ...
5425  * }
5426  * _mesa_set_destroy(skip, NULL);
5427  *
5428  * You shouldn't mix usage of this with the NIR_PASS set of helpers, without
5429  * using a new "skip" in-between.
5430  */
5431 #define NIR_LOOP_PASS(progress, skip, nir, pass, ...) \
5432    _NIR_LOOP_PASS(progress, true, skip, nir, pass, ##__VA_ARGS__)
5433 
5434 /* Like NIR_LOOP_PASS, but use this for passes which may make further progress
5435  * when repeated.
5436  */
5437 #define NIR_LOOP_PASS_NOT_IDEMPOTENT(progress, skip, nir, pass, ...) \
5438    _NIR_LOOP_PASS(progress, false, skip, nir, pass, ##__VA_ARGS__)
5439 
5440 #define NIR_SKIP(name) should_skip_nir(#name)
5441 
5442 /** An instruction filtering callback with writemask
5443  *
5444  * Returns true if the instruction should be processed with the associated
5445  * writemask and false otherwise.
5446  */
5447 typedef bool (*nir_instr_writemask_filter_cb)(const nir_instr *,
5448                                               unsigned writemask, const void *);
5449 
5450 /** A simple instruction lowering callback
5451  *
5452  * Many instruction lowering passes can be written as a simple function which
5453  * takes an instruction as its input and returns a sequence of instructions
5454  * that implement the consumed instruction.  This function type represents
5455  * such a lowering function.  When called, a function with this prototype
5456  * should either return NULL indicating that no lowering needs to be done or
5457  * emit a sequence of instructions using the provided builder (whose cursor
5458  * will already be placed after the instruction to be lowered) and return the
5459  * resulting nir_def.
5460  */
5461 typedef nir_def *(*nir_lower_instr_cb)(struct nir_builder *,
5462                                        nir_instr *, void *);
5463 
5464 /**
5465  * Special return value for nir_lower_instr_cb when some progress occurred
5466  * (like changing an input to the instr) that didn't result in a replacement
5467  * SSA def being generated.
5468  */
5469 #define NIR_LOWER_INSTR_PROGRESS ((nir_def *)(uintptr_t)1)
5470 
5471 /**
5472  * Special return value for nir_lower_instr_cb when some progress occurred
5473  * that should remove the current instruction that doesn't create an output
5474  * (like a store)
5475  */
5476 
5477 #define NIR_LOWER_INSTR_PROGRESS_REPLACE ((nir_def *)(uintptr_t)2)
5478 
5479 /** Iterate over all the instructions in a nir_function_impl and lower them
5480  *  using the provided callbacks
5481  *
5482  * This function implements the guts of a standard lowering pass for you.  It
5483  * iterates over all of the instructions in a nir_function_impl and calls the
5484  * filter callback on each one.  If the filter callback returns true, it then
5485  * calls the lowering call back on the instruction.  (Splitting it this way
5486  * allows us to avoid some save/restore work for instructions we know won't be
5487  * lowered.)  If the instruction is dead after the lowering is complete, it
5488  * will be removed.  If new instructions are added, the lowering callback will
5489  * also be called on them in case multiple lowerings are required.
5490  *
5491  * If the callback indicates that the original instruction is replaced (either
5492  * through a new SSA def or NIR_LOWER_INSTR_PROGRESS_REPLACE), then the
5493  * instruction is removed along with any now-dead SSA defs it used.
5494  *
5495  * The metadata for the nir_function_impl will also be updated.  If any blocks
5496  * are added (they cannot be removed), dominance and block indices will be
5497  * invalidated.
5498  */
5499 bool nir_function_impl_lower_instructions(nir_function_impl *impl,
5500                                           nir_instr_filter_cb filter,
5501                                           nir_lower_instr_cb lower,
5502                                           void *cb_data);
5503 bool nir_shader_lower_instructions(nir_shader *shader,
5504                                    nir_instr_filter_cb filter,
5505                                    nir_lower_instr_cb lower,
5506                                    void *cb_data);
5507 
5508 void nir_calc_dominance_impl(nir_function_impl *impl);
5509 void nir_calc_dominance(nir_shader *shader);
5510 
5511 nir_block *nir_dominance_lca(nir_block *b1, nir_block *b2);
5512 bool nir_block_dominates(nir_block *parent, nir_block *child);
5513 bool nir_block_is_unreachable(nir_block *block);
5514 
5515 void nir_dump_dom_tree_impl(nir_function_impl *impl, FILE *fp);
5516 void nir_dump_dom_tree(nir_shader *shader, FILE *fp);
5517 
5518 void nir_dump_dom_frontier_impl(nir_function_impl *impl, FILE *fp);
5519 void nir_dump_dom_frontier(nir_shader *shader, FILE *fp);
5520 
5521 void nir_dump_cfg_impl(nir_function_impl *impl, FILE *fp);
5522 void nir_dump_cfg(nir_shader *shader, FILE *fp);
5523 
5524 void nir_gs_count_vertices_and_primitives(const nir_shader *shader,
5525                                           int *out_vtxcnt,
5526                                           int *out_prmcnt,
5527                                           int *out_decomposed_prmcnt,
5528                                           unsigned num_streams);
5529 
5530 typedef enum {
5531    nir_group_all,
5532    nir_group_same_resource_only,
5533 } nir_load_grouping;
5534 
5535 void nir_group_loads(nir_shader *shader, nir_load_grouping grouping,
5536                      unsigned max_distance);
5537 
5538 bool nir_shrink_vec_array_vars(nir_shader *shader, nir_variable_mode modes);
5539 bool nir_split_array_vars(nir_shader *shader, nir_variable_mode modes);
5540 bool nir_split_var_copies(nir_shader *shader);
5541 bool nir_split_per_member_structs(nir_shader *shader);
5542 bool nir_split_struct_vars(nir_shader *shader, nir_variable_mode modes);
5543 
5544 bool nir_lower_returns_impl(nir_function_impl *impl);
5545 bool nir_lower_returns(nir_shader *shader);
5546 
5547 void nir_inline_function_impl(struct nir_builder *b,
5548                               const nir_function_impl *impl,
5549                               nir_def **params,
5550                               struct hash_table *shader_var_remap);
5551 bool nir_inline_functions(nir_shader *shader);
5552 void nir_cleanup_functions(nir_shader *shader);
5553 bool nir_link_shader_functions(nir_shader *shader,
5554                                const nir_shader *link_shader);
5555 bool nir_lower_calls_to_builtins(nir_shader *s);
5556 
5557 void nir_find_inlinable_uniforms(nir_shader *shader);
5558 void nir_inline_uniforms(nir_shader *shader, unsigned num_uniforms,
5559                          const uint32_t *uniform_values,
5560                          const uint16_t *uniform_dw_offsets);
5561 bool nir_collect_src_uniforms(const nir_src *src, int component,
5562                               uint32_t *uni_offsets, uint8_t *num_offsets,
5563                               unsigned max_num_bo, unsigned max_offset);
5564 void nir_add_inlinable_uniforms(const nir_src *cond, nir_loop_info *info,
5565                                 uint32_t *uni_offsets, uint8_t *num_offsets,
5566                                 unsigned max_num_bo, unsigned max_offset);
5567 
5568 bool nir_propagate_invariant(nir_shader *shader, bool invariant_prim);
5569 
5570 void nir_lower_var_copy_instr(nir_intrinsic_instr *copy, nir_shader *shader);
5571 void nir_lower_deref_copy_instr(struct nir_builder *b,
5572                                 nir_intrinsic_instr *copy);
5573 bool nir_lower_var_copies(nir_shader *shader);
5574 
5575 bool nir_opt_memcpy(nir_shader *shader);
5576 bool nir_lower_memcpy(nir_shader *shader);
5577 
5578 void nir_fixup_deref_modes(nir_shader *shader);
5579 void nir_fixup_deref_types(nir_shader *shader);
5580 
5581 bool nir_lower_global_vars_to_local(nir_shader *shader);
5582 void nir_lower_constant_to_temp(nir_shader *shader);
5583 
5584 typedef enum {
5585    nir_lower_direct_array_deref_of_vec_load = (1 << 0),
5586    nir_lower_indirect_array_deref_of_vec_load = (1 << 1),
5587    nir_lower_direct_array_deref_of_vec_store = (1 << 2),
5588    nir_lower_indirect_array_deref_of_vec_store = (1 << 3),
5589 } nir_lower_array_deref_of_vec_options;
5590 
5591 bool nir_lower_array_deref_of_vec(nir_shader *shader, nir_variable_mode modes,
5592                                   bool (*filter)(nir_variable *),
5593                                   nir_lower_array_deref_of_vec_options options);
5594 
5595 bool nir_lower_indirect_derefs(nir_shader *shader, nir_variable_mode modes,
5596                                uint32_t max_lower_array_len);
5597 
5598 bool nir_lower_indirect_var_derefs(nir_shader *shader,
5599                                    const struct set *vars);
5600 
5601 bool nir_lower_locals_to_regs(nir_shader *shader, uint8_t bool_bitsize);
5602 
5603 bool nir_lower_io_to_temporaries(nir_shader *shader,
5604                                  nir_function_impl *entrypoint,
5605                                  bool outputs, bool inputs);
5606 
5607 bool nir_lower_vars_to_scratch(nir_shader *shader,
5608                                nir_variable_mode modes,
5609                                int size_threshold,
5610                                glsl_type_size_align_func variable_size_align,
5611                                glsl_type_size_align_func scratch_layout_size_align);
5612 
5613 bool nir_lower_scratch_to_var(nir_shader *nir);
5614 
5615 void nir_lower_clip_halfz(nir_shader *shader);
5616 
5617 void nir_shader_gather_info(nir_shader *shader, nir_function_impl *entrypoint);
5618 
5619 void nir_gather_types(nir_function_impl *impl,
5620                       BITSET_WORD *float_types,
5621                       BITSET_WORD *int_types);
5622 
5623 typedef struct {
5624    /* Whether all invocations write tess level outputs.
5625     *
5626     * This is useful when a pass wants to read tess level values at the end
5627     * of the shader. If this is true, the pass doesn't have to insert a barrier
5628     * and use output loads, it can just use the SSA defs that are being stored
5629     * (or phis thereof) to get the tess level output values.
5630     */
5631    bool all_invocations_define_tess_levels;
5632 
5633    /* Whether any of the outer tess level components is effectively 0, meaning
5634     * that the shader discards the patch. NaNs and negative values are included
5635     * in this. If the patch is discarded, inner tess levels have no effect.
5636     */
5637    bool all_tess_levels_are_effectively_zero;
5638 
5639    /* Whether all tess levels are effectively 1, meaning that the tessellator
5640     * behaves as if they were 1. There is a range of values that lead to that
5641     * behavior depending on the tessellation spacing.
5642     */
5643    bool all_tess_levels_are_effectively_one;
5644 
5645    /* Whether the shader uses a barrier synchronizing TCS output stores.
5646     * For example, passes that write an output at the beginning of the shader
5647     * and load it at the end can use this to determine whether they have to
5648     * insert a barrier or whether the shader already contains a barrier.
5649     */
5650    bool always_executes_barrier;
5651 
5652    /* Whether outer tess levels <= 0 are written anywhere in the shader. */
5653    bool discards_patches;
5654 } nir_tcs_info;
5655 
5656 void
5657 nir_gather_tcs_info(const nir_shader *nir, nir_tcs_info *info,
5658                     enum tess_primitive_mode prim,
5659                     enum gl_tess_spacing spacing);
5660 
5661 void nir_assign_var_locations(nir_shader *shader, nir_variable_mode mode,
5662                               unsigned *size,
5663                               int (*type_size)(const struct glsl_type *, bool));
5664 
5665 /* Some helpers to do very simple linking */
5666 bool nir_remove_unused_varyings(nir_shader *producer, nir_shader *consumer);
5667 bool nir_remove_unused_io_vars(nir_shader *shader, nir_variable_mode mode,
5668                                uint64_t *used_by_other_stage,
5669                                uint64_t *used_by_other_stage_patches);
5670 void nir_compact_varyings(nir_shader *producer, nir_shader *consumer,
5671                           bool default_to_smooth_interp);
5672 void nir_link_xfb_varyings(nir_shader *producer, nir_shader *consumer);
5673 bool nir_link_opt_varyings(nir_shader *producer, nir_shader *consumer);
5674 void nir_link_varying_precision(nir_shader *producer, nir_shader *consumer);
5675 nir_variable *nir_clone_uniform_variable(nir_shader *nir,
5676                                          nir_variable *uniform, bool spirv);
5677 nir_deref_instr *nir_clone_deref_instr(struct nir_builder *b,
5678                                        nir_variable *var,
5679                                        nir_deref_instr *deref);
5680 
5681 
5682 /* Return status from nir_opt_varyings. */
5683 typedef enum {
5684    /* Whether the IR changed such that NIR optimizations should be run, such
5685     * as due to removal of loads and stores. IO semantic changes such as
5686     * compaction don't count as IR changes because they don't affect NIR
5687     * optimizations.
5688     */
5689    nir_progress_producer = BITFIELD_BIT(0),
5690    nir_progress_consumer = BITFIELD_BIT(1),
5691 } nir_opt_varyings_progress;
5692 
5693 nir_opt_varyings_progress
5694 nir_opt_varyings(nir_shader *producer, nir_shader *consumer, bool spirv,
5695                  unsigned max_uniform_components, unsigned max_ubos_per_stage);
5696 
5697 bool nir_slot_is_sysval_output(gl_varying_slot slot,
5698                                gl_shader_stage next_shader);
5699 bool nir_slot_is_varying(gl_varying_slot slot, gl_shader_stage next_shader);
5700 bool nir_slot_is_sysval_output_and_varying(gl_varying_slot slot,
5701                                            gl_shader_stage next_shader);
5702 bool nir_remove_varying(nir_intrinsic_instr *intr, gl_shader_stage next_shader);
5703 bool nir_remove_sysval_output(nir_intrinsic_instr *intr, gl_shader_stage next_shader);
5704 
5705 bool nir_lower_amul(nir_shader *shader,
5706                     int (*type_size)(const struct glsl_type *, bool));
5707 
5708 bool nir_lower_ubo_vec4(nir_shader *shader);
5709 
5710 void nir_sort_variables_by_location(nir_shader *shader, nir_variable_mode mode);
5711 void nir_assign_io_var_locations(nir_shader *shader,
5712                                  nir_variable_mode mode,
5713                                  unsigned *size,
5714                                  gl_shader_stage stage);
5715 
5716 bool nir_opt_clip_cull_const(nir_shader *shader);
5717 
5718 typedef enum {
5719    /* If set, this causes all 64-bit IO operations to be lowered on-the-fly
5720     * to 32-bit operations.  This is only valid for nir_var_shader_in/out
5721     * modes.
5722     *
5723     * Note that this destroys dual-slot information i.e. whether an input
5724     * occupies the low or high half of dvec4. Instead, it adds an offset of 1
5725     * to the load (which is ambiguous) and expects driver locations of inputs
5726     * to be final, which prevents any further optimizations.
5727     *
5728     * TODO: remove this in favor of nir_lower_io_lower_64bit_to_32_new.
5729     */
5730    nir_lower_io_lower_64bit_to_32 = (1 << 0),
5731 
5732    /* If set, this causes the subset of 64-bit IO operations involving floats to be lowered on-the-fly
5733     * to 32-bit operations.  This is only valid for nir_var_shader_in/out
5734     * modes.
5735     */
5736    nir_lower_io_lower_64bit_float_to_32 = (1 << 1),
5737 
5738    /* This causes all 64-bit IO operations to be lowered to 32-bit operations.
5739     * This is only valid for nir_var_shader_in/out modes.
5740     *
5741     * Only VS inputs: Dual slot information is preserved as nir_io_semantics::
5742     * high_dvec2 and gathered into shader_info::dual_slot_inputs, so that
5743     * the shader can be arbitrarily optimized and the low or high half of
5744     * dvec4 can be DCE'd independently without affecting the other half.
5745     */
5746    nir_lower_io_lower_64bit_to_32_new = (1 << 2),
5747 
5748    /**
5749     * Should nir_lower_io() create load_interpolated_input intrinsics?
5750     *
5751     * If not, it generates regular load_input intrinsics and interpolation
5752     * information must be inferred from the list of input nir_variables.
5753     */
5754    nir_lower_io_use_interpolated_input_intrinsics = (1 << 3),
5755 } nir_lower_io_options;
5756 bool nir_lower_io(nir_shader *shader,
5757                   nir_variable_mode modes,
5758                   int (*type_size)(const struct glsl_type *, bool),
5759                   nir_lower_io_options);
5760 
5761 bool nir_io_add_const_offset_to_base(nir_shader *nir, nir_variable_mode modes);
5762 bool nir_lower_color_inputs(nir_shader *nir);
5763 void nir_lower_io_passes(nir_shader *nir, bool renumber_vs_inputs);
5764 bool nir_io_add_intrinsic_xfb_info(nir_shader *nir);
5765 
5766 bool
5767 nir_lower_vars_to_explicit_types(nir_shader *shader,
5768                                  nir_variable_mode modes,
5769                                  glsl_type_size_align_func type_info);
5770 void
5771 nir_gather_explicit_io_initializers(nir_shader *shader,
5772                                     void *dst, size_t dst_size,
5773                                     nir_variable_mode mode);
5774 
5775 bool nir_lower_vec3_to_vec4(nir_shader *shader, nir_variable_mode modes);
5776 
5777 typedef enum {
5778    /**
5779     * An address format which is a simple 32-bit global GPU address.
5780     */
5781    nir_address_format_32bit_global,
5782 
5783    /**
5784     * An address format which is a simple 64-bit global GPU address.
5785     */
5786    nir_address_format_64bit_global,
5787 
5788    /**
5789     * An address format which is a 64-bit global GPU address encoded as a
5790     * 2x32-bit vector.
5791     */
5792    nir_address_format_2x32bit_global,
5793 
5794    /**
5795     * An address format which is a 64-bit global base address and a 32-bit
5796     * offset.
5797     *
5798     * This is identical to 64bit_bounded_global except that bounds checking
5799     * is not applied when lowering to global access.  Even though the size is
5800     * never used for an actual bounds check, it needs to be valid so we can
5801     * lower deref_buffer_array_length properly.
5802     */
5803    nir_address_format_64bit_global_32bit_offset,
5804 
5805    /**
5806     * An address format which is a bounds-checked 64-bit global GPU address.
5807     *
5808     * The address is comprised as a 32-bit vec4 where .xy are a uint64_t base
5809     * address stored with the low bits in .x and high bits in .y, .z is a
5810     * size, and .w is an offset.  When the final I/O operation is lowered, .w
5811     * is checked against .z and the operation is predicated on the result.
5812     */
5813    nir_address_format_64bit_bounded_global,
5814 
5815    /**
5816     * An address format which is comprised of a vec2 where the first
5817     * component is a buffer index and the second is an offset.
5818     */
5819    nir_address_format_32bit_index_offset,
5820 
5821    /**
5822     * An address format which is a 64-bit value, where the high 32 bits
5823     * are a buffer index, and the low 32 bits are an offset.
5824     */
5825    nir_address_format_32bit_index_offset_pack64,
5826 
5827    /**
5828     * An address format which is comprised of a vec3 where the first two
5829     * components specify the buffer and the third is an offset.
5830     */
5831    nir_address_format_vec2_index_32bit_offset,
5832 
5833    /**
5834     * An address format which represents generic pointers with a 62-bit
5835     * pointer and a 2-bit enum in the top two bits.  The top two bits have
5836     * the following meanings:
5837     *
5838     *  - 0x0: Global memory
5839     *  - 0x1: Shared memory
5840     *  - 0x2: Scratch memory
5841     *  - 0x3: Global memory
5842     *
5843     * The redundancy between 0x0 and 0x3 is because of Intel sign-extension of
5844     * addresses.  Valid global memory addresses may naturally have either 0 or
5845     * ~0 as their high bits.
5846     *
5847     * Shared and scratch pointers are represented as 32-bit offsets with the
5848     * top 32 bits only being used for the enum.  This allows us to avoid
5849     * 64-bit address calculations in a bunch of cases.
5850     */
5851    nir_address_format_62bit_generic,
5852 
5853    /**
5854     * An address format which is a simple 32-bit offset.
5855     */
5856    nir_address_format_32bit_offset,
5857 
5858    /**
5859     * An address format which is a simple 32-bit offset cast to 64-bit.
5860     */
5861    nir_address_format_32bit_offset_as_64bit,
5862 
5863    /**
5864     * An address format representing a purely logical addressing model.  In
5865     * this model, all deref chains must be complete from the dereference
5866     * operation to the variable.  Cast derefs are not allowed.  These
5867     * addresses will be 32-bit scalars but the format is immaterial because
5868     * you can always chase the chain.
5869     */
5870    nir_address_format_logical,
5871 } nir_address_format;
5872 
5873 unsigned
5874 nir_address_format_bit_size(nir_address_format addr_format);
5875 
5876 unsigned
5877 nir_address_format_num_components(nir_address_format addr_format);
5878 
5879 static inline const struct glsl_type *
nir_address_format_to_glsl_type(nir_address_format addr_format)5880 nir_address_format_to_glsl_type(nir_address_format addr_format)
5881 {
5882    unsigned bit_size = nir_address_format_bit_size(addr_format);
5883    assert(bit_size == 32 || bit_size == 64);
5884    return glsl_vector_type(bit_size == 32 ? GLSL_TYPE_UINT : GLSL_TYPE_UINT64,
5885                            nir_address_format_num_components(addr_format));
5886 }
5887 
5888 const nir_const_value *nir_address_format_null_value(nir_address_format addr_format);
5889 
5890 nir_def *nir_build_addr_iadd(struct nir_builder *b, nir_def *addr,
5891                              nir_address_format addr_format,
5892                              nir_variable_mode modes,
5893                              nir_def *offset);
5894 
5895 nir_def *nir_build_addr_iadd_imm(struct nir_builder *b, nir_def *addr,
5896                                  nir_address_format addr_format,
5897                                  nir_variable_mode modes,
5898                                  int64_t offset);
5899 
5900 nir_def *nir_build_addr_ieq(struct nir_builder *b, nir_def *addr0, nir_def *addr1,
5901                             nir_address_format addr_format);
5902 
5903 nir_def *nir_build_addr_isub(struct nir_builder *b, nir_def *addr0, nir_def *addr1,
5904                              nir_address_format addr_format);
5905 
5906 nir_def *nir_explicit_io_address_from_deref(struct nir_builder *b,
5907                                             nir_deref_instr *deref,
5908                                             nir_def *base_addr,
5909                                             nir_address_format addr_format);
5910 
5911 bool nir_get_explicit_deref_align(nir_deref_instr *deref,
5912                                   bool default_to_type_align,
5913                                   uint32_t *align_mul,
5914                                   uint32_t *align_offset);
5915 
5916 void nir_lower_explicit_io_instr(struct nir_builder *b,
5917                                  nir_intrinsic_instr *io_instr,
5918                                  nir_def *addr,
5919                                  nir_address_format addr_format);
5920 
5921 bool nir_lower_explicit_io(nir_shader *shader,
5922                            nir_variable_mode modes,
5923                            nir_address_format);
5924 
5925 typedef enum {
5926    /* Use open-coded funnel shifts for each component. */
5927    nir_mem_access_shift_method_scalar,
5928    /* Prefer to use 64-bit shifts to do the same with less instructions. Useful
5929     * if 64-bit shifts are cheap.
5930     */
5931    nir_mem_access_shift_method_shift64,
5932    /* If nir_op_alignbyte_amd can be used, this is the best option with just a
5933     * single nir_op_alignbyte_amd for each 32-bit components.
5934     */
5935    nir_mem_access_shift_method_bytealign_amd,
5936 } nir_mem_access_shift_method;
5937 
5938 typedef struct {
5939    uint8_t num_components;
5940    uint8_t bit_size;
5941    uint16_t align;
5942    /* If a load's alignment is increased, this specifies how the data should be
5943     * shifted before converting to the original bit size.
5944     */
5945    nir_mem_access_shift_method shift;
5946 } nir_mem_access_size_align;
5947 
5948 /* clang-format off */
5949 typedef nir_mem_access_size_align
5950    (*nir_lower_mem_access_bit_sizes_cb)(nir_intrinsic_op intrin,
5951                                         uint8_t bytes,
5952                                         uint8_t bit_size,
5953                                         uint32_t align_mul,
5954                                         uint32_t align_offset,
5955                                         bool offset_is_const,
5956                                         enum gl_access_qualifier,
5957                                         const void *cb_data);
5958 /* clang-format on */
5959 
5960 typedef struct {
5961    nir_lower_mem_access_bit_sizes_cb callback;
5962    nir_variable_mode modes;
5963    bool may_lower_unaligned_stores_to_atomics;
5964    void *cb_data;
5965 } nir_lower_mem_access_bit_sizes_options;
5966 
5967 bool nir_lower_mem_access_bit_sizes(nir_shader *shader,
5968                                     const nir_lower_mem_access_bit_sizes_options *options);
5969 
5970 bool nir_lower_robust_access(nir_shader *s,
5971                              nir_intrin_filter_cb filter, const void *data);
5972 
5973 /* clang-format off */
5974 typedef bool (*nir_should_vectorize_mem_func)(unsigned align_mul,
5975                                               unsigned align_offset,
5976                                               unsigned bit_size,
5977                                               unsigned num_components,
5978                                               /* The hole between low and
5979                                                * high if they are not adjacent. */
5980                                               int64_t hole_size,
5981                                               nir_intrinsic_instr *low,
5982                                               nir_intrinsic_instr *high,
5983                                               void *data);
5984 /* clang-format on */
5985 
5986 typedef struct {
5987    nir_should_vectorize_mem_func callback;
5988    nir_variable_mode modes;
5989    nir_variable_mode robust_modes;
5990    void *cb_data;
5991    bool has_shared2_amd;
5992 } nir_load_store_vectorize_options;
5993 
5994 bool nir_opt_load_store_vectorize(nir_shader *shader, const nir_load_store_vectorize_options *options);
5995 bool nir_opt_load_store_update_alignments(nir_shader *shader);
5996 
5997 typedef bool (*nir_lower_shader_calls_should_remat_func)(nir_instr *instr, void *data);
5998 
5999 typedef struct nir_lower_shader_calls_options {
6000    /* Address format used for load/store operations on the call stack. */
6001    nir_address_format address_format;
6002 
6003    /* Stack alignment */
6004    unsigned stack_alignment;
6005 
6006    /* Put loads from the stack as close as possible from where they're needed.
6007     * You might want to disable combined_loads for best effects.
6008     */
6009    bool localized_loads;
6010 
6011    /* If this function pointer is not NULL, lower_shader_calls will run
6012     * nir_opt_load_store_vectorize for stack load/store operations. Otherwise
6013     * the optimizaion is not run.
6014     */
6015    nir_should_vectorize_mem_func vectorizer_callback;
6016 
6017    /* Data passed to vectorizer_callback */
6018    void *vectorizer_data;
6019 
6020    /* If this function pointer is not NULL, lower_shader_calls will call this
6021     * function on instructions that require spill/fill/rematerialization of
6022     * their value. If this function returns true, lower_shader_calls will
6023     * ensure that the instruction is rematerialized, adding the sources of the
6024     * instruction to be spilled/filled.
6025     */
6026    nir_lower_shader_calls_should_remat_func should_remat_callback;
6027 
6028    /* Data passed to should_remat_callback */
6029    void *should_remat_data;
6030 } nir_lower_shader_calls_options;
6031 
6032 bool
6033 nir_lower_shader_calls(nir_shader *shader,
6034                        const nir_lower_shader_calls_options *options,
6035                        nir_shader ***resume_shaders_out,
6036                        uint32_t *num_resume_shaders_out,
6037                        void *mem_ctx);
6038 
6039 int nir_get_io_offset_src_number(const nir_intrinsic_instr *instr);
6040 int nir_get_io_arrayed_index_src_number(const nir_intrinsic_instr *instr);
6041 
6042 nir_src *nir_get_io_offset_src(nir_intrinsic_instr *instr);
6043 nir_src *nir_get_io_arrayed_index_src(nir_intrinsic_instr *instr);
6044 nir_src *nir_get_shader_call_payload_src(nir_intrinsic_instr *call);
6045 
6046 bool nir_is_arrayed_io(const nir_variable *var, gl_shader_stage stage);
6047 
6048 bool nir_lower_reg_intrinsics_to_ssa_impl(nir_function_impl *impl);
6049 bool nir_lower_reg_intrinsics_to_ssa(nir_shader *shader);
6050 bool nir_lower_vars_to_ssa(nir_shader *shader);
6051 
6052 bool nir_remove_dead_derefs(nir_shader *shader);
6053 bool nir_remove_dead_derefs_impl(nir_function_impl *impl);
6054 
6055 typedef struct nir_remove_dead_variables_options {
6056    bool (*can_remove_var)(nir_variable *var, void *data);
6057    void *can_remove_var_data;
6058 } nir_remove_dead_variables_options;
6059 
6060 bool nir_remove_dead_variables(nir_shader *shader, nir_variable_mode modes,
6061                                const nir_remove_dead_variables_options *options);
6062 
6063 bool nir_lower_variable_initializers(nir_shader *shader,
6064                                      nir_variable_mode modes);
6065 bool nir_zero_initialize_shared_memory(nir_shader *shader,
6066                                        const unsigned shared_size,
6067                                        const unsigned chunk_size);
6068 bool nir_clear_shared_memory(nir_shader *shader,
6069                              const unsigned shared_size,
6070                              const unsigned chunk_size);
6071 
6072 bool nir_move_vec_src_uses_to_dest(nir_shader *shader, bool skip_const_srcs);
6073 bool nir_lower_vec_to_regs(nir_shader *shader, nir_instr_writemask_filter_cb cb,
6074                            const void *_data);
6075 bool nir_lower_alpha_test(nir_shader *shader, enum compare_func func,
6076                           bool alpha_to_one,
6077                           const gl_state_index16 *alpha_ref_state_tokens);
6078 bool nir_lower_alu(nir_shader *shader);
6079 
6080 bool nir_lower_flrp(nir_shader *shader, unsigned lowering_mask,
6081                     bool always_precise);
6082 
6083 bool nir_scale_fdiv(nir_shader *shader);
6084 
6085 bool nir_lower_alu_to_scalar(nir_shader *shader, nir_instr_filter_cb cb, const void *data);
6086 bool nir_lower_alu_width(nir_shader *shader, nir_vectorize_cb cb, const void *data);
6087 bool nir_lower_alu_vec8_16_srcs(nir_shader *shader);
6088 bool nir_lower_bool_to_bitsize(nir_shader *shader);
6089 bool nir_lower_bool_to_float(nir_shader *shader, bool has_fcsel_ne);
6090 bool nir_lower_bool_to_int32(nir_shader *shader);
6091 bool nir_opt_simplify_convert_alu_types(nir_shader *shader);
6092 bool nir_lower_const_arrays_to_uniforms(nir_shader *shader,
6093                                         unsigned max_uniform_components);
6094 bool nir_lower_convert_alu_types(nir_shader *shader,
6095                                  bool (*should_lower)(nir_intrinsic_instr *));
6096 bool nir_lower_constant_convert_alu_types(nir_shader *shader);
6097 bool nir_lower_alu_conversion_to_intrinsic(nir_shader *shader);
6098 bool nir_lower_int_to_float(nir_shader *shader);
6099 bool nir_lower_load_const_to_scalar(nir_shader *shader);
6100 bool nir_lower_read_invocation_to_scalar(nir_shader *shader);
6101 bool nir_lower_phis_to_scalar(nir_shader *shader, bool lower_all);
6102 void nir_lower_io_arrays_to_elements(nir_shader *producer, nir_shader *consumer);
6103 bool nir_lower_io_arrays_to_elements_no_indirects(nir_shader *shader,
6104                                                   bool outputs_only);
6105 bool nir_lower_io_to_scalar(nir_shader *shader, nir_variable_mode mask, nir_instr_filter_cb filter, void *filter_data);
6106 bool nir_lower_io_to_scalar_early(nir_shader *shader, nir_variable_mode mask);
6107 bool nir_lower_io_to_vector(nir_shader *shader, nir_variable_mode mask);
6108 bool nir_vectorize_tess_levels(nir_shader *shader);
6109 nir_shader *nir_create_passthrough_tcs_impl(const nir_shader_compiler_options *options,
6110                                             unsigned *locations, unsigned num_locations,
6111                                             uint8_t patch_vertices);
6112 nir_shader *nir_create_passthrough_tcs(const nir_shader_compiler_options *options,
6113                                        const nir_shader *vs, uint8_t patch_vertices);
6114 nir_shader *nir_create_passthrough_gs(const nir_shader_compiler_options *options,
6115                                       const nir_shader *prev_stage,
6116                                       enum mesa_prim primitive_type,
6117                                       enum mesa_prim output_primitive_type,
6118                                       bool emulate_edgeflags,
6119                                       bool force_line_strip_out,
6120                                       bool passthrough_prim_id);
6121 
6122 bool nir_lower_fragcolor(nir_shader *shader, unsigned max_cbufs);
6123 bool nir_lower_fragcoord_wtrans(nir_shader *shader);
6124 bool nir_opt_frag_coord_to_pixel_coord(nir_shader *shader);
6125 bool nir_lower_frag_coord_to_pixel_coord(nir_shader *shader);
6126 bool nir_lower_viewport_transform(nir_shader *shader);
6127 bool nir_lower_uniforms_to_ubo(nir_shader *shader, bool dword_packed, bool load_vec4);
6128 
6129 bool nir_lower_is_helper_invocation(nir_shader *shader);
6130 
6131 bool nir_lower_single_sampled(nir_shader *shader);
6132 
6133 bool nir_lower_atomics(nir_shader *shader, nir_instr_filter_cb filter);
6134 
6135 typedef struct nir_lower_subgroups_options {
6136    /* In addition to the boolean lowering options below, this optional callback
6137     * will filter instructions for lowering if non-NULL. The data passed will be
6138     * filter_data.
6139     */
6140    nir_instr_filter_cb filter;
6141 
6142    /* Extra data passed to the filter. */
6143    const void *filter_data;
6144 
6145    /* In case the exact subgroup size is not known, subgroup_size should be
6146     * set to 0. In that case, the maximum subgroup size will be calculated by
6147     * ballot_components * ballot_bit_size.
6148     */
6149    uint8_t subgroup_size;
6150    uint8_t ballot_bit_size;
6151    uint8_t ballot_components;
6152    bool lower_to_scalar : 1;
6153    bool lower_vote_trivial : 1;
6154    bool lower_vote_eq : 1;
6155    bool lower_vote_bool_eq : 1;
6156    bool lower_first_invocation_to_ballot : 1;
6157    bool lower_read_first_invocation : 1;
6158    bool lower_subgroup_masks : 1;
6159    bool lower_relative_shuffle : 1;
6160    bool lower_shuffle_to_32bit : 1;
6161    bool lower_shuffle_to_swizzle_amd : 1;
6162    bool lower_shuffle : 1;
6163    bool lower_quad : 1;
6164    bool lower_quad_broadcast_dynamic : 1;
6165    bool lower_quad_broadcast_dynamic_to_const : 1;
6166    bool lower_quad_vote : 1;
6167    bool lower_elect : 1;
6168    bool lower_read_invocation_to_cond : 1;
6169    bool lower_rotate_to_shuffle : 1;
6170    bool lower_rotate_clustered_to_shuffle : 1;
6171    bool lower_ballot_bit_count_to_mbcnt_amd : 1;
6172    bool lower_inverse_ballot : 1;
6173    bool lower_reduce : 1;
6174    bool lower_boolean_reduce : 1;
6175    bool lower_boolean_shuffle : 1;
6176 } nir_lower_subgroups_options;
6177 
6178 bool nir_lower_subgroups(nir_shader *shader,
6179                          const nir_lower_subgroups_options *options);
6180 
6181 bool nir_lower_system_values(nir_shader *shader);
6182 
6183 nir_def *
6184 nir_build_lowered_load_helper_invocation(struct nir_builder *b);
6185 
6186 typedef struct nir_lower_compute_system_values_options {
6187    bool has_base_global_invocation_id : 1;
6188    bool has_base_workgroup_id : 1;
6189    bool has_global_size : 1;
6190    bool shuffle_local_ids_for_quad_derivatives : 1;
6191    bool lower_local_invocation_index : 1;
6192    bool lower_cs_local_id_to_index : 1;
6193    bool lower_workgroup_id_to_index : 1;
6194    bool global_id_is_32bit : 1;
6195    /* At shader execution time, check if WorkGroupId should be 1D
6196     * and compute it quickly. Fall back to slow computation if not.
6197     */
6198    bool shortcut_1d_workgroup_id : 1;
6199    uint32_t num_workgroups[3]; /* Compile-time-known dispatch sizes, or 0 if unknown. */
6200 } nir_lower_compute_system_values_options;
6201 
6202 bool nir_lower_compute_system_values(nir_shader *shader,
6203                                      const nir_lower_compute_system_values_options *options);
6204 
6205 struct nir_lower_sysvals_to_varyings_options {
6206    bool frag_coord : 1;
6207    bool front_face : 1;
6208    bool point_coord : 1;
6209 };
6210 
6211 bool
6212 nir_lower_sysvals_to_varyings(nir_shader *shader,
6213                               const struct nir_lower_sysvals_to_varyings_options *options);
6214 
6215 /***/
6216 enum ENUM_PACKED nir_lower_tex_packing {
6217    /** No packing */
6218    nir_lower_tex_packing_none = 0,
6219    /**
6220     * The sampler returns up to 2 32-bit words of half floats or 16-bit signed
6221     * or unsigned ints based on the sampler type
6222     */
6223    nir_lower_tex_packing_16,
6224    /** The sampler returns 1 32-bit word of 4x8 unorm */
6225    nir_lower_tex_packing_8,
6226 };
6227 
6228 /***/
6229 typedef struct nir_lower_tex_options {
6230    /**
6231     * bitmask of (1 << GLSL_SAMPLER_DIM_x) to control for which
6232     * sampler types a texture projector is lowered.
6233     */
6234    unsigned lower_txp;
6235 
6236    /**
6237     * If true, lower texture projector for any array sampler dims
6238     */
6239    bool lower_txp_array;
6240 
6241    /**
6242     * If true, lower away nir_tex_src_offset for all texelfetch instructions.
6243     */
6244    bool lower_txf_offset;
6245 
6246    /**
6247     * If true, lower away nir_tex_src_offset for all rect textures.
6248     */
6249    bool lower_rect_offset;
6250 
6251    /**
6252     * If not NULL, this filter will return true for tex instructions that
6253     * should lower away nir_tex_src_offset.
6254     */
6255    nir_instr_filter_cb lower_offset_filter;
6256 
6257    /**
6258     * If true, lower rect textures to 2D, using txs to fetch the
6259     * texture dimensions and dividing the texture coords by the
6260     * texture dims to normalize.
6261     */
6262    bool lower_rect;
6263 
6264    /**
6265     * If true, lower 1D textures to 2D. This requires the GL/VK driver to map 1D
6266     * textures to 2D textures with height=1.
6267     *
6268     * lower_1d_shadow does this lowering for shadow textures only.
6269     */
6270    bool lower_1d;
6271    bool lower_1d_shadow;
6272 
6273    /**
6274     * If true, convert yuv to rgb.
6275     */
6276    unsigned lower_y_uv_external;
6277    unsigned lower_y_vu_external;
6278    unsigned lower_y_u_v_external;
6279    unsigned lower_yx_xuxv_external;
6280    unsigned lower_yx_xvxu_external;
6281    unsigned lower_xy_uxvx_external;
6282    unsigned lower_xy_vxux_external;
6283    unsigned lower_ayuv_external;
6284    unsigned lower_xyuv_external;
6285    unsigned lower_yuv_external;
6286    unsigned lower_yu_yv_external;
6287    unsigned lower_yv_yu_external;
6288    unsigned lower_y41x_external;
6289    unsigned bt709_external;
6290    unsigned bt2020_external;
6291    unsigned yuv_full_range_external;
6292 
6293    /**
6294     * To emulate certain texture wrap modes, this can be used
6295     * to saturate the specified tex coord to [0.0, 1.0].  The
6296     * bits are according to sampler #, ie. if, for example:
6297     *
6298     *   (conf->saturate_s & (1 << n))
6299     *
6300     * is true, then the s coord for sampler n is saturated.
6301     *
6302     * Note that clamping must happen *after* projector lowering
6303     * so any projected texture sample instruction with a clamped
6304     * coordinate gets automatically lowered, regardless of the
6305     * 'lower_txp' setting.
6306     */
6307    unsigned saturate_s;
6308    unsigned saturate_t;
6309    unsigned saturate_r;
6310 
6311    /* Bitmask of textures that need swizzling.
6312     *
6313     * If (swizzle_result & (1 << texture_index)), then the swizzle in
6314     * swizzles[texture_index] is applied to the result of the texturing
6315     * operation.
6316     */
6317    unsigned swizzle_result;
6318 
6319    /* A swizzle for each texture.  Values 0-3 represent x, y, z, or w swizzles
6320     * while 4 and 5 represent 0 and 1 respectively.
6321     *
6322     * Indexed by texture-id.
6323     */
6324    uint8_t swizzles[32][4];
6325 
6326    /* Can be used to scale sampled values in range required by the
6327     * format.
6328     *
6329     * Indexed by texture-id.
6330     */
6331    float scale_factors[32];
6332 
6333    /**
6334     * Bitmap of textures that need srgb to linear conversion.  If
6335     * (lower_srgb & (1 << texture_index)) then the rgb (xyz) components
6336     * of the texture are lowered to linear.
6337     */
6338    unsigned lower_srgb;
6339 
6340    /**
6341     * If true, lower nir_texop_txd on cube maps with nir_texop_txl.
6342     */
6343    bool lower_txd_cube_map;
6344 
6345    /**
6346     * If true, lower nir_texop_txd on 3D surfaces with nir_texop_txl.
6347     */
6348    bool lower_txd_3d;
6349 
6350    /**
6351     * If true, lower nir_texop_txd any array surfaces with nir_texop_txl.
6352     */
6353    bool lower_txd_array;
6354 
6355    /**
6356     * If true, lower nir_texop_txd on shadow samplers (except cube maps)
6357     * with nir_texop_txl. Notice that cube map shadow samplers are lowered
6358     * with lower_txd_cube_map.
6359     */
6360    bool lower_txd_shadow;
6361 
6362    /**
6363     * If true, lower nir_texop_txd on all samplers to a nir_texop_txl.
6364     * Implies lower_txd_cube_map and lower_txd_shadow.
6365     */
6366    bool lower_txd;
6367 
6368    /**
6369     * If true, lower nir_texop_txd  when it uses min_lod.
6370     */
6371    bool lower_txd_clamp;
6372 
6373    /**
6374     * If true, lower nir_texop_txb that try to use shadow compare and min_lod
6375     * at the same time to a nir_texop_lod, some math, and nir_texop_tex.
6376     */
6377    bool lower_txb_shadow_clamp;
6378 
6379    /**
6380     * If true, lower nir_texop_txd on shadow samplers when it uses min_lod
6381     * with nir_texop_txl.  This includes cube maps.
6382     */
6383    bool lower_txd_shadow_clamp;
6384 
6385    /**
6386     * If true, lower nir_texop_txd on when it uses both offset and min_lod
6387     * with nir_texop_txl.  This includes cube maps.
6388     */
6389    bool lower_txd_offset_clamp;
6390 
6391    /**
6392     * If true, lower nir_texop_txd with min_lod to a nir_texop_txl if the
6393     * sampler is bindless.
6394     */
6395    bool lower_txd_clamp_bindless_sampler;
6396 
6397    /**
6398     * If true, lower nir_texop_txd with min_lod to a nir_texop_txl if the
6399     * sampler index is not statically determinable to be less than 16.
6400     */
6401    bool lower_txd_clamp_if_sampler_index_not_lt_16;
6402 
6403    /**
6404     * If true, lower nir_texop_txs with a non-0-lod into nir_texop_txs with
6405     * 0-lod followed by a nir_ishr.
6406     */
6407    bool lower_txs_lod;
6408 
6409    /**
6410     * If true, lower nir_texop_txs for cube arrays to a nir_texop_txs with a
6411     * 2D array type followed by a nir_idiv by 6.
6412     */
6413    bool lower_txs_cube_array;
6414 
6415    /**
6416     * If true, apply a .bagr swizzle on tg4 results to handle Broadcom's
6417     * mixed-up tg4 locations.
6418     */
6419    bool lower_tg4_broadcom_swizzle;
6420 
6421    /**
6422     * If true, lowers tg4 with 4 constant offsets to 4 tg4 calls
6423     */
6424    bool lower_tg4_offsets;
6425 
6426    /**
6427     * Lower txf_ms to fragment_mask_fetch and fragment_fetch and samples_identical to
6428     * fragment_mask_fetch.
6429     */
6430    bool lower_to_fragment_fetch_amd;
6431 
6432    /**
6433     * To lower packed sampler return formats. This will be called for all
6434     * tex instructions.
6435     */
6436    enum nir_lower_tex_packing (*lower_tex_packing_cb)(const nir_tex_instr *tex, const void *data);
6437    const void *lower_tex_packing_data;
6438 
6439    /**
6440     * If true, lower nir_texop_lod to return -FLT_MAX if the sum of the
6441     * absolute values of derivatives is 0 for all coordinates.
6442     */
6443    bool lower_lod_zero_width;
6444 
6445    /* Turns nir_op_tex and other ops with an implicit derivative, in stages
6446     * without implicit derivatives (like the vertex shader) to have an explicit
6447     * LOD with a value of 0.
6448     */
6449    bool lower_invalid_implicit_lod;
6450 
6451    /* If true, texture_index (sampler_index) will be zero if a texture_offset
6452     * (sampler_offset) source is present. This is convenient for backends that
6453     * support indirect indexing of textures (samplers) but not offsetting it.
6454     */
6455    bool lower_index_to_offset;
6456 
6457    /**
6458     * Payload data to be sent to callback / filter functions.
6459     */
6460    void *callback_data;
6461 } nir_lower_tex_options;
6462 
6463 /** Lowers complex texture instructions to simpler ones */
6464 bool nir_lower_tex(nir_shader *shader,
6465                    const nir_lower_tex_options *options);
6466 
6467 typedef struct nir_lower_tex_shadow_swizzle {
6468    unsigned swizzle_r : 3;
6469    unsigned swizzle_g : 3;
6470    unsigned swizzle_b : 3;
6471    unsigned swizzle_a : 3;
6472 } nir_lower_tex_shadow_swizzle;
6473 
6474 bool
6475 nir_lower_tex_shadow(nir_shader *s,
6476                      unsigned n_states,
6477                      enum compare_func *compare_func,
6478                      nir_lower_tex_shadow_swizzle *tex_swizzles);
6479 
6480 typedef struct nir_lower_image_options {
6481    /**
6482     * If true, lower cube size operations.
6483     */
6484    bool lower_cube_size;
6485 
6486    /**
6487     * Lower multi sample image load and samples_identical to use fragment_mask_load.
6488     */
6489    bool lower_to_fragment_mask_load_amd;
6490 
6491    /**
6492     * Lower image_samples to a constant in case the driver doesn't support multisampled
6493     * images.
6494     */
6495    bool lower_image_samples_to_one;
6496 } nir_lower_image_options;
6497 
6498 bool nir_lower_image(nir_shader *nir,
6499                      const nir_lower_image_options *options);
6500 
6501 bool
6502 nir_lower_image_atomics_to_global(nir_shader *s);
6503 
6504 bool nir_lower_readonly_images_to_tex(nir_shader *shader, bool per_variable);
6505 
6506 enum nir_lower_non_uniform_access_type {
6507    nir_lower_non_uniform_ubo_access = (1 << 0),
6508    nir_lower_non_uniform_ssbo_access = (1 << 1),
6509    nir_lower_non_uniform_texture_access = (1 << 2),
6510    nir_lower_non_uniform_image_access = (1 << 3),
6511    nir_lower_non_uniform_get_ssbo_size = (1 << 4),
6512    nir_lower_non_uniform_access_type_count = 5,
6513 };
6514 
6515 /* Given the nir_src used for the resource, return the channels which might be non-uniform. */
6516 typedef nir_component_mask_t (*nir_lower_non_uniform_access_callback)(const nir_src *, void *);
6517 
6518 typedef struct nir_lower_non_uniform_access_options {
6519    enum nir_lower_non_uniform_access_type types;
6520    nir_lower_non_uniform_access_callback callback;
6521    void *callback_data;
6522 } nir_lower_non_uniform_access_options;
6523 
6524 bool nir_has_non_uniform_access(nir_shader *shader, enum nir_lower_non_uniform_access_type types);
6525 bool nir_opt_non_uniform_access(nir_shader *shader);
6526 bool nir_lower_non_uniform_access(nir_shader *shader,
6527                                   const nir_lower_non_uniform_access_options *options);
6528 
6529 typedef struct {
6530    /* Whether 16-bit floating point arithmetic should be allowed in 8-bit
6531     * division lowering
6532     */
6533    bool allow_fp16;
6534 } nir_lower_idiv_options;
6535 
6536 bool nir_lower_idiv(nir_shader *shader, const nir_lower_idiv_options *options);
6537 
6538 typedef struct nir_input_attachment_options {
6539    bool use_fragcoord_sysval;
6540    bool use_layer_id_sysval;
6541    bool use_view_id_for_layer;
6542    bool unscaled_depth_stencil_ir3;
6543    uint32_t unscaled_input_attachment_ir3;
6544 } nir_input_attachment_options;
6545 
6546 bool nir_lower_input_attachments(nir_shader *shader,
6547                                  const nir_input_attachment_options *options);
6548 
6549 bool nir_lower_clip_vs(nir_shader *shader, unsigned ucp_enables,
6550                        bool use_vars,
6551                        bool use_clipdist_array,
6552                        const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH]);
6553 bool nir_lower_clip_gs(nir_shader *shader, unsigned ucp_enables,
6554                        bool use_clipdist_array,
6555                        const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH]);
6556 bool nir_lower_clip_fs(nir_shader *shader, unsigned ucp_enables,
6557                        bool use_clipdist_array, bool use_load_interp);
6558 
6559 bool nir_lower_clip_cull_distance_to_vec4s(nir_shader *shader);
6560 bool nir_lower_clip_cull_distance_arrays(nir_shader *nir);
6561 bool nir_lower_clip_disable(nir_shader *shader, unsigned clip_plane_enable);
6562 
6563 bool nir_lower_point_size_mov(nir_shader *shader,
6564                               const gl_state_index16 *pointsize_state_tokens);
6565 
6566 bool nir_lower_frexp(nir_shader *nir);
6567 
6568 bool nir_lower_two_sided_color(nir_shader *shader, bool face_sysval);
6569 
6570 bool nir_lower_clamp_color_outputs(nir_shader *shader);
6571 
6572 bool nir_lower_flatshade(nir_shader *shader);
6573 
6574 bool nir_lower_passthrough_edgeflags(nir_shader *shader);
6575 bool nir_lower_patch_vertices(nir_shader *nir, unsigned static_count,
6576                               const gl_state_index16 *uniform_state_tokens);
6577 
6578 typedef struct nir_lower_wpos_ytransform_options {
6579    gl_state_index16 state_tokens[STATE_LENGTH];
6580    bool fs_coord_origin_upper_left : 1;
6581    bool fs_coord_origin_lower_left : 1;
6582    bool fs_coord_pixel_center_integer : 1;
6583    bool fs_coord_pixel_center_half_integer : 1;
6584 } nir_lower_wpos_ytransform_options;
6585 
6586 bool nir_lower_wpos_ytransform(nir_shader *shader,
6587                                const nir_lower_wpos_ytransform_options *options);
6588 bool nir_lower_wpos_center(nir_shader *shader);
6589 
6590 bool nir_lower_pntc_ytransform(nir_shader *shader,
6591                                const gl_state_index16 clipplane_state_tokens[][STATE_LENGTH]);
6592 
6593 bool nir_lower_wrmasks(nir_shader *shader, nir_instr_filter_cb cb, const void *data);
6594 
6595 bool nir_lower_fb_read(nir_shader *shader);
6596 
6597 typedef struct nir_lower_drawpixels_options {
6598    gl_state_index16 texcoord_state_tokens[STATE_LENGTH];
6599    gl_state_index16 scale_state_tokens[STATE_LENGTH];
6600    gl_state_index16 bias_state_tokens[STATE_LENGTH];
6601    unsigned drawpix_sampler;
6602    unsigned pixelmap_sampler;
6603    bool pixel_maps : 1;
6604    bool scale_and_bias : 1;
6605 } nir_lower_drawpixels_options;
6606 
6607 bool nir_lower_drawpixels(nir_shader *shader,
6608                           const nir_lower_drawpixels_options *options);
6609 
6610 typedef struct nir_lower_bitmap_options {
6611    unsigned sampler;
6612    bool swizzle_xxxx;
6613 } nir_lower_bitmap_options;
6614 
6615 bool nir_lower_bitmap(nir_shader *shader, const nir_lower_bitmap_options *options);
6616 
6617 bool nir_lower_atomics_to_ssbo(nir_shader *shader, unsigned offset_align_state);
6618 
6619 typedef enum {
6620    nir_lower_gs_intrinsics_per_stream = 1 << 0,
6621    nir_lower_gs_intrinsics_count_primitives = 1 << 1,
6622    nir_lower_gs_intrinsics_count_vertices_per_primitive = 1 << 2,
6623    nir_lower_gs_intrinsics_overwrite_incomplete = 1 << 3,
6624    nir_lower_gs_intrinsics_always_end_primitive = 1 << 4,
6625    nir_lower_gs_intrinsics_count_decomposed_primitives = 1 << 5,
6626 } nir_lower_gs_intrinsics_flags;
6627 
6628 bool nir_lower_gs_intrinsics(nir_shader *shader, nir_lower_gs_intrinsics_flags options);
6629 
6630 bool nir_lower_tess_coord_z(nir_shader *shader, bool triangles);
6631 
6632 typedef struct {
6633    bool payload_to_shared_for_atomics : 1;
6634    bool payload_to_shared_for_small_types : 1;
6635    uint32_t payload_offset_in_bytes;
6636 } nir_lower_task_shader_options;
6637 
6638 bool nir_lower_task_shader(nir_shader *shader, nir_lower_task_shader_options options);
6639 
6640 typedef unsigned (*nir_lower_bit_size_callback)(const nir_instr *, void *);
6641 
6642 bool nir_lower_bit_size(nir_shader *shader,
6643                         nir_lower_bit_size_callback callback,
6644                         void *callback_data);
6645 bool nir_lower_64bit_phis(nir_shader *shader);
6646 
6647 bool nir_split_64bit_vec3_and_vec4(nir_shader *shader);
6648 
6649 nir_lower_int64_options nir_lower_int64_op_to_options_mask(nir_op opcode);
6650 bool nir_lower_int64(nir_shader *shader);
6651 bool nir_lower_int64_float_conversions(nir_shader *shader);
6652 
6653 nir_lower_doubles_options nir_lower_doubles_op_to_options_mask(nir_op opcode);
6654 bool nir_lower_doubles(nir_shader *shader, const nir_shader *softfp64,
6655                        nir_lower_doubles_options options);
6656 bool nir_lower_pack(nir_shader *shader);
6657 
6658 bool nir_recompute_io_bases(nir_shader *nir, nir_variable_mode modes);
6659 bool nir_lower_mediump_vars(nir_shader *nir, nir_variable_mode modes);
6660 bool nir_lower_mediump_io(nir_shader *nir, nir_variable_mode modes,
6661                           uint64_t varying_mask, bool use_16bit_slots);
6662 bool nir_force_mediump_io(nir_shader *nir, nir_variable_mode modes,
6663                           nir_alu_type types);
6664 bool nir_unpack_16bit_varying_slots(nir_shader *nir, nir_variable_mode modes);
6665 
6666 struct nir_opt_tex_srcs_options {
6667    unsigned sampler_dims;
6668    unsigned src_types;
6669 };
6670 
6671 struct nir_opt_16bit_tex_image_options {
6672    nir_rounding_mode rounding_mode;
6673    nir_alu_type opt_tex_dest_types;
6674    nir_alu_type opt_image_dest_types;
6675    bool integer_dest_saturates;
6676    bool opt_image_store_data;
6677    bool opt_image_srcs;
6678    unsigned opt_srcs_options_count;
6679    struct nir_opt_tex_srcs_options *opt_srcs_options;
6680 };
6681 
6682 bool nir_opt_16bit_tex_image(nir_shader *nir,
6683                              struct nir_opt_16bit_tex_image_options *options);
6684 
6685 typedef struct {
6686    bool legalize_type;         /* whether this src should be legalized */
6687    uint8_t bit_size;           /* bit_size to enforce */
6688    nir_tex_src_type match_src; /* if bit_size is 0, match bit size of this */
6689 } nir_tex_src_type_constraint, nir_tex_src_type_constraints[nir_num_tex_src_types];
6690 
6691 bool nir_legalize_16bit_sampler_srcs(nir_shader *nir,
6692                                      nir_tex_src_type_constraints constraints);
6693 
6694 bool nir_lower_point_size(nir_shader *shader, float min, float max);
6695 
6696 void nir_lower_texcoord_replace(nir_shader *s, unsigned coord_replace,
6697                                 bool point_coord_is_sysval, bool yinvert);
6698 
6699 bool nir_lower_texcoord_replace_late(nir_shader *s, unsigned coord_replace,
6700                                      bool point_coord_is_sysval);
6701 
6702 typedef enum {
6703    nir_lower_interpolation_at_sample = (1 << 1),
6704    nir_lower_interpolation_at_offset = (1 << 2),
6705    nir_lower_interpolation_centroid = (1 << 3),
6706    nir_lower_interpolation_pixel = (1 << 4),
6707    nir_lower_interpolation_sample = (1 << 5),
6708 } nir_lower_interpolation_options;
6709 
6710 bool nir_lower_interpolation(nir_shader *shader,
6711                              nir_lower_interpolation_options options);
6712 
6713 typedef enum {
6714    nir_lower_discard_if_to_cf = (1 << 0),
6715    nir_lower_demote_if_to_cf = (1 << 1),
6716    nir_lower_terminate_if_to_cf = (1 << 2),
6717 } nir_lower_discard_if_options;
6718 
6719 bool nir_lower_discard_if(nir_shader *shader, nir_lower_discard_if_options options);
6720 
6721 bool nir_lower_terminate_to_demote(nir_shader *nir);
6722 
6723 bool nir_lower_memory_model(nir_shader *shader);
6724 
6725 bool nir_lower_goto_ifs(nir_shader *shader);
6726 bool nir_lower_continue_constructs(nir_shader *shader);
6727 
6728 typedef struct nir_lower_multiview_options {
6729    uint32_t view_mask;
6730 
6731    /**
6732     * Bitfield of output locations that may be converted to a per-view array.
6733     *
6734     * If a variable exists in an allowed location, it will be converted to an
6735     * array even if its value does not depend on the view index.
6736     */
6737    uint64_t allowed_per_view_outputs;
6738 } nir_lower_multiview_options;
6739 
6740 bool nir_shader_uses_view_index(nir_shader *shader);
6741 bool nir_can_lower_multiview(nir_shader *shader, nir_lower_multiview_options options);
6742 bool nir_lower_multiview(nir_shader *shader, nir_lower_multiview_options options);
6743 
6744 bool nir_lower_view_index_to_device_index(nir_shader *shader);
6745 
6746 typedef enum {
6747    nir_lower_fp16_rtz = (1 << 0),
6748    nir_lower_fp16_rtne = (1 << 1),
6749    nir_lower_fp16_ru = (1 << 2),
6750    nir_lower_fp16_rd = (1 << 3),
6751    nir_lower_fp16_all = 0xf,
6752    nir_lower_fp16_split_fp64 = (1 << 4),
6753 } nir_lower_fp16_cast_options;
6754 bool nir_lower_fp16_casts(nir_shader *shader, nir_lower_fp16_cast_options options);
6755 bool nir_normalize_cubemap_coords(nir_shader *shader);
6756 
6757 bool nir_shader_supports_implicit_lod(nir_shader *shader);
6758 
6759 void nir_live_defs_impl(nir_function_impl *impl);
6760 
6761 const BITSET_WORD *nir_get_live_defs(nir_cursor cursor, void *mem_ctx);
6762 
6763 void nir_loop_analyze_impl(nir_function_impl *impl,
6764                            nir_variable_mode indirect_mask,
6765                            bool force_unroll_sampler_indirect);
6766 
6767 bool nir_defs_interfere(nir_def *a, nir_def *b);
6768 
6769 bool nir_repair_ssa_impl(nir_function_impl *impl);
6770 bool nir_repair_ssa(nir_shader *shader);
6771 
6772 void nir_convert_loop_to_lcssa(nir_loop *loop);
6773 bool nir_convert_to_lcssa(nir_shader *shader, bool skip_invariants, bool skip_bool_invariants);
6774 void nir_divergence_analysis_impl(nir_function_impl *impl, nir_divergence_options options);
6775 void nir_divergence_analysis(nir_shader *shader);
6776 void nir_vertex_divergence_analysis(nir_shader *shader);
6777 bool nir_has_divergent_loop(nir_shader *shader);
6778 void nir_clear_divergence_info(nir_shader *nir);
6779 
6780 void
6781 nir_rewrite_uses_to_load_reg(struct nir_builder *b, nir_def *old,
6782                              nir_def *reg);
6783 
6784 /* If phi_webs_only is true, only convert SSA values involved in phi nodes to
6785  * registers.  If false, convert all values (even those not involved in a phi
6786  * node) to registers.
6787  */
6788 bool nir_convert_from_ssa(nir_shader *shader,
6789                           bool phi_webs_only);
6790 
6791 bool nir_lower_phis_to_regs_block(nir_block *block);
6792 bool nir_lower_ssa_defs_to_regs_block(nir_block *block);
6793 
6794 bool nir_rematerialize_deref_in_use_blocks(nir_deref_instr *instr);
6795 bool nir_rematerialize_derefs_in_use_blocks_impl(nir_function_impl *impl);
6796 
6797 bool nir_lower_samplers(nir_shader *shader);
6798 bool nir_lower_cl_images(nir_shader *shader, bool lower_image_derefs, bool lower_sampler_derefs);
6799 bool nir_dedup_inline_samplers(nir_shader *shader);
6800 
6801 typedef struct nir_lower_ssbo_options {
6802    bool native_loads;
6803    bool native_offset;
6804 } nir_lower_ssbo_options;
6805 
6806 bool nir_lower_ssbo(nir_shader *shader, const nir_lower_ssbo_options *opts);
6807 
6808 bool nir_lower_helper_writes(nir_shader *shader, bool lower_plain_stores);
6809 
6810 typedef struct nir_lower_printf_options {
6811    unsigned max_buffer_size;
6812    unsigned ptr_bit_size;
6813    bool use_printf_base_identifier;
6814    bool hash_format_strings;
6815 } nir_lower_printf_options;
6816 
6817 bool nir_lower_printf(nir_shader *nir, const nir_lower_printf_options *options);
6818 bool nir_lower_printf_buffer(nir_shader *nir, uint64_t address, uint32_t size);
6819 
6820 /* This is here for unit tests. */
6821 bool nir_opt_comparison_pre_impl(nir_function_impl *impl);
6822 
6823 bool nir_opt_comparison_pre(nir_shader *shader);
6824 
6825 typedef struct nir_opt_access_options {
6826    bool is_vulkan;
6827 } nir_opt_access_options;
6828 
6829 bool nir_opt_access(nir_shader *shader, const nir_opt_access_options *options);
6830 bool nir_opt_algebraic(nir_shader *shader);
6831 bool nir_opt_algebraic_before_ffma(nir_shader *shader);
6832 bool nir_opt_algebraic_before_lower_int64(nir_shader *shader);
6833 bool nir_opt_algebraic_late(nir_shader *shader);
6834 bool nir_opt_algebraic_distribute_src_mods(nir_shader *shader);
6835 bool nir_opt_constant_folding(nir_shader *shader);
6836 
6837 /* Try to combine a and b into a.  Return true if combination was possible,
6838  * which will result in b being removed by the pass.  Return false if
6839  * combination wasn't possible.
6840  */
6841 typedef bool (*nir_combine_barrier_cb)(
6842    nir_intrinsic_instr *a, nir_intrinsic_instr *b, void *data);
6843 
6844 bool nir_opt_combine_barriers(nir_shader *shader,
6845                               nir_combine_barrier_cb combine_cb,
6846                               void *data);
6847 bool nir_opt_barrier_modes(nir_shader *shader);
6848 
6849 bool nir_opt_combine_stores(nir_shader *shader, nir_variable_mode modes);
6850 
6851 bool nir_copy_prop_impl(nir_function_impl *impl);
6852 bool nir_copy_prop(nir_shader *shader);
6853 
6854 bool nir_opt_copy_prop_vars(nir_shader *shader);
6855 
6856 bool nir_opt_cse(nir_shader *shader);
6857 
6858 bool nir_opt_dce(nir_shader *shader);
6859 
6860 bool nir_opt_dead_cf(nir_shader *shader);
6861 
6862 bool nir_opt_dead_write_vars(nir_shader *shader);
6863 
6864 bool nir_opt_deref_impl(nir_function_impl *impl);
6865 bool nir_opt_deref(nir_shader *shader);
6866 
6867 bool nir_opt_find_array_copies(nir_shader *shader);
6868 
6869 bool nir_def_is_frag_coord_z(nir_def *def);
6870 bool nir_opt_fragdepth(nir_shader *shader);
6871 
6872 bool nir_opt_gcm(nir_shader *shader, bool value_number);
6873 
6874 bool nir_opt_generate_bfi(nir_shader *shader);
6875 
6876 bool nir_opt_idiv_const(nir_shader *shader, unsigned min_bit_size);
6877 
6878 bool nir_opt_mqsad(nir_shader *shader);
6879 
6880 typedef enum {
6881    nir_opt_if_optimize_phi_true_false = (1 << 0),
6882    nir_opt_if_avoid_64bit_phis = (1 << 1),
6883 } nir_opt_if_options;
6884 
6885 bool nir_opt_if(nir_shader *shader, nir_opt_if_options options);
6886 
6887 bool nir_opt_intrinsics(nir_shader *shader);
6888 
6889 bool nir_opt_large_constants(nir_shader *shader,
6890                              glsl_type_size_align_func size_align,
6891                              unsigned threshold);
6892 
6893 bool nir_opt_licm(nir_shader *shader);
6894 bool nir_opt_loop(nir_shader *shader);
6895 
6896 bool nir_opt_loop_unroll(nir_shader *shader);
6897 
6898 typedef enum {
6899    nir_move_const_undef = (1 << 0),
6900    nir_move_load_ubo = (1 << 1),
6901    nir_move_load_input = (1 << 2),
6902    nir_move_comparisons = (1 << 3),
6903    nir_move_copies = (1 << 4),
6904    nir_move_load_ssbo = (1 << 5),
6905    nir_move_load_uniform = (1 << 6),
6906    nir_move_alu = (1 << 7),
6907 } nir_move_options;
6908 
6909 bool nir_can_move_instr(nir_instr *instr, nir_move_options options);
6910 
6911 bool nir_opt_sink(nir_shader *shader, nir_move_options options);
6912 
6913 bool nir_opt_move(nir_shader *shader, nir_move_options options);
6914 
6915 typedef struct {
6916    /** nir_load_uniform max base offset */
6917    uint32_t uniform_max;
6918 
6919    /** nir_load_ubo_vec4 max base offset */
6920    uint32_t ubo_vec4_max;
6921 
6922    /** nir_var_mem_shared max base offset */
6923    uint32_t shared_max;
6924 
6925    /** nir_var_mem_shared atomic max base offset */
6926    uint32_t shared_atomic_max;
6927 
6928    /** nir_load/store_buffer_amd max base offset */
6929    uint32_t buffer_max;
6930 
6931    /**
6932     * Callback to get the max base offset for instructions for which the
6933     * corresponding value above is zero.
6934     */
6935    uint32_t (*max_offset_cb)(nir_intrinsic_instr *intr, const void *data);
6936 
6937    /** Data to pass to max_offset_cb. */
6938    const void *max_offset_data;
6939 
6940    /**
6941     * Allow the offset calculation to wrap. If false, constant additions that
6942     * might wrap will not be folded into the offset.
6943     */
6944    bool allow_offset_wrap;
6945 } nir_opt_offsets_options;
6946 
6947 bool nir_opt_offsets(nir_shader *shader, const nir_opt_offsets_options *options);
6948 
6949 bool nir_opt_peephole_select(nir_shader *shader, unsigned limit,
6950                              bool indirect_load_ok, bool expensive_alu_ok);
6951 
6952 bool nir_opt_reassociate_bfi(nir_shader *shader);
6953 
6954 bool nir_opt_rematerialize_compares(nir_shader *shader);
6955 
6956 bool nir_opt_remove_phis(nir_shader *shader);
6957 bool nir_remove_single_src_phis_block(nir_block *block);
6958 
6959 bool nir_opt_phi_precision(nir_shader *shader);
6960 
6961 bool nir_opt_shrink_stores(nir_shader *shader, bool shrink_image_store);
6962 
6963 bool nir_opt_shrink_vectors(nir_shader *shader, bool shrink_start);
6964 
6965 bool nir_opt_undef(nir_shader *shader);
6966 
6967 bool nir_lower_undef_to_zero(nir_shader *shader);
6968 
6969 bool nir_opt_uniform_atomics(nir_shader *shader, bool fs_atomics_predicated);
6970 
6971 bool nir_opt_uniform_subgroup(nir_shader *shader,
6972                               const nir_lower_subgroups_options *);
6973 
6974 bool nir_opt_vectorize(nir_shader *shader, nir_vectorize_cb filter,
6975                        void *data);
6976 bool nir_opt_vectorize_io(nir_shader *shader, nir_variable_mode modes);
6977 
6978 bool nir_opt_conditional_discard(nir_shader *shader);
6979 bool nir_opt_move_discards_to_top(nir_shader *shader);
6980 
6981 bool nir_opt_ray_queries(nir_shader *shader);
6982 
6983 bool nir_opt_ray_query_ranges(nir_shader *shader);
6984 
6985 void nir_sweep(nir_shader *shader);
6986 
6987 void nir_remap_dual_slot_attributes(nir_shader *shader,
6988                                     uint64_t *dual_slot_inputs);
6989 uint64_t nir_get_single_slot_attribs_mask(uint64_t attribs, uint64_t dual_slot);
6990 
6991 nir_intrinsic_op nir_intrinsic_from_system_value(gl_system_value val);
6992 gl_system_value nir_system_value_from_intrinsic(nir_intrinsic_op intrin);
6993 
6994 static inline bool
nir_variable_is_in_ubo(const nir_variable * var)6995 nir_variable_is_in_ubo(const nir_variable *var)
6996 {
6997    return (var->data.mode == nir_var_mem_ubo &&
6998            var->interface_type != NULL);
6999 }
7000 
7001 static inline bool
nir_variable_is_in_ssbo(const nir_variable * var)7002 nir_variable_is_in_ssbo(const nir_variable *var)
7003 {
7004    return (var->data.mode == nir_var_mem_ssbo &&
7005            var->interface_type != NULL);
7006 }
7007 
7008 static inline bool
nir_variable_is_in_block(const nir_variable * var)7009 nir_variable_is_in_block(const nir_variable *var)
7010 {
7011    return nir_variable_is_in_ubo(var) || nir_variable_is_in_ssbo(var);
7012 }
7013 
7014 static inline unsigned
nir_variable_count_slots(const nir_variable * var,const struct glsl_type * type)7015 nir_variable_count_slots(const nir_variable *var, const struct glsl_type *type)
7016 {
7017    return var->data.compact ? DIV_ROUND_UP(var->data.location_frac + glsl_get_length(type), 4) : glsl_count_attribute_slots(type, false);
7018 }
7019 
7020 static inline unsigned
nir_deref_count_slots(nir_deref_instr * deref,nir_variable * var)7021 nir_deref_count_slots(nir_deref_instr *deref, nir_variable *var)
7022 {
7023    if (var->data.compact) {
7024       switch (deref->deref_type) {
7025       case nir_deref_type_array:
7026          return 1;
7027       case nir_deref_type_var:
7028          return nir_variable_count_slots(var, deref->type);
7029       default:
7030          unreachable("illegal deref type");
7031       }
7032    }
7033    return glsl_count_attribute_slots(deref->type, false);
7034 }
7035 
7036 /* See default_ub_config in nir_range_analysis.c for documentation. */
7037 typedef struct nir_unsigned_upper_bound_config {
7038    unsigned min_subgroup_size;
7039    unsigned max_subgroup_size;
7040    unsigned max_workgroup_invocations;
7041    unsigned max_workgroup_count[3];
7042    unsigned max_workgroup_size[3];
7043 
7044    uint32_t vertex_attrib_max[32];
7045 } nir_unsigned_upper_bound_config;
7046 
7047 uint32_t
7048 nir_unsigned_upper_bound(nir_shader *shader, struct hash_table *range_ht,
7049                          nir_scalar scalar,
7050                          const nir_unsigned_upper_bound_config *config);
7051 
7052 bool
7053 nir_addition_might_overflow(nir_shader *shader, struct hash_table *range_ht,
7054                             nir_scalar ssa, unsigned const_val,
7055                             const nir_unsigned_upper_bound_config *config);
7056 
7057 typedef struct {
7058    /* True if gl_DrawID is considered uniform, i.e. if the preamble is run
7059     * at least once per "internal" draw rather than per user-visible draw.
7060     */
7061    bool drawid_uniform;
7062 
7063    /* True if the subgroup size is uniform. */
7064    bool subgroup_size_uniform;
7065 
7066    /* True if load_workgroup_size is supported in the preamble. */
7067    bool load_workgroup_size_allowed;
7068 
7069    /* size/align for load/store_preamble. */
7070    void (*def_size)(nir_def *def, unsigned *size, unsigned *align);
7071 
7072    /* Total available size for load/store_preamble storage, in units
7073     * determined by def_size.
7074     */
7075    unsigned preamble_storage_size;
7076 
7077    /* Give the cost for an instruction. nir_opt_preamble will prioritize
7078     * instructions with higher costs. Instructions with cost 0 may still be
7079     * lifted, but only when required to lift other instructions with non-0
7080     * cost (e.g. a load_const source of an expression).
7081     */
7082    float (*instr_cost_cb)(nir_instr *instr, const void *data);
7083 
7084    /* Give the cost of rewriting the instruction to use load_preamble. This
7085     * may happen from inserting move instructions, etc. If the benefit doesn't
7086     * exceed the cost here then we won't rewrite it.
7087     */
7088    float (*rewrite_cost_cb)(nir_def *def, const void *data);
7089 
7090    /* Instructions whose definitions should not be rewritten. These could
7091     * still be moved to the preamble, but they shouldn't be the root of a
7092     * replacement expression. Instructions with cost 0 and derefs are
7093     * automatically included by the pass.
7094     */
7095    nir_instr_filter_cb avoid_instr_cb;
7096 
7097    const void *cb_data;
7098 } nir_opt_preamble_options;
7099 
7100 bool
7101 nir_opt_preamble(nir_shader *shader,
7102                  const nir_opt_preamble_options *options,
7103                  unsigned *size);
7104 
7105 nir_function_impl *nir_shader_get_preamble(nir_shader *shader);
7106 
7107 bool nir_lower_point_smooth(nir_shader *shader, bool set_barycentrics);
7108 bool nir_lower_poly_line_smooth(nir_shader *shader, unsigned num_smooth_aa_sample);
7109 
7110 bool nir_mod_analysis(nir_scalar val, nir_alu_type val_type, unsigned div, unsigned *mod);
7111 
7112 bool
7113 nir_remove_tex_shadow(nir_shader *shader, unsigned textures_bitmask);
7114 
7115 void
7116 nir_trivialize_registers(nir_shader *s);
7117 
7118 unsigned
7119 nir_static_workgroup_size(const nir_shader *s);
7120 
7121 static inline nir_intrinsic_instr *
nir_reg_get_decl(nir_def * reg)7122 nir_reg_get_decl(nir_def *reg)
7123 {
7124    assert(reg->parent_instr->type == nir_instr_type_intrinsic);
7125    nir_intrinsic_instr *decl = nir_instr_as_intrinsic(reg->parent_instr);
7126    assert(decl->intrinsic == nir_intrinsic_decl_reg);
7127 
7128    return decl;
7129 }
7130 
7131 static inline nir_intrinsic_instr *
nir_next_decl_reg(nir_intrinsic_instr * prev,nir_function_impl * impl)7132 nir_next_decl_reg(nir_intrinsic_instr *prev, nir_function_impl *impl)
7133 {
7134    nir_instr *start;
7135    if (prev != NULL)
7136       start = nir_instr_next(&prev->instr);
7137    else if (impl != NULL)
7138       start = nir_block_first_instr(nir_start_block(impl));
7139    else
7140       return NULL;
7141 
7142    for (nir_instr *instr = start; instr; instr = nir_instr_next(instr)) {
7143       if (instr->type != nir_instr_type_intrinsic)
7144          continue;
7145 
7146       nir_intrinsic_instr *intrin = nir_instr_as_intrinsic(instr);
7147       if (intrin->intrinsic == nir_intrinsic_decl_reg)
7148          return intrin;
7149    }
7150 
7151    return NULL;
7152 }
7153 
7154 #define nir_foreach_reg_decl(reg, impl)                           \
7155    for (nir_intrinsic_instr *reg = nir_next_decl_reg(NULL, impl); \
7156         reg; reg = nir_next_decl_reg(reg, NULL))
7157 
7158 #define nir_foreach_reg_decl_safe(reg, impl)                       \
7159    for (nir_intrinsic_instr *reg = nir_next_decl_reg(NULL, impl),  \
7160                             *next_ = nir_next_decl_reg(reg, NULL); \
7161         reg; reg = next_, next_ = nir_next_decl_reg(next_, NULL))
7162 
7163 static inline nir_cursor
nir_after_reg_decls(nir_function_impl * impl)7164 nir_after_reg_decls(nir_function_impl *impl)
7165 {
7166    nir_intrinsic_instr *last_reg_decl = NULL;
7167    nir_foreach_reg_decl(reg_decl, impl)
7168       last_reg_decl = reg_decl;
7169 
7170    if (last_reg_decl != NULL)
7171       return nir_after_instr(&last_reg_decl->instr);
7172    return nir_before_impl(impl);
7173 }
7174 
7175 static inline bool
nir_is_load_reg(nir_intrinsic_instr * intr)7176 nir_is_load_reg(nir_intrinsic_instr *intr)
7177 {
7178    return intr->intrinsic == nir_intrinsic_load_reg ||
7179           intr->intrinsic == nir_intrinsic_load_reg_indirect;
7180 }
7181 
7182 static inline bool
nir_is_store_reg(nir_intrinsic_instr * intr)7183 nir_is_store_reg(nir_intrinsic_instr *intr)
7184 {
7185    return intr->intrinsic == nir_intrinsic_store_reg ||
7186           intr->intrinsic == nir_intrinsic_store_reg_indirect;
7187 }
7188 
7189 #define nir_foreach_reg_load(load, reg)              \
7190    assert(reg->intrinsic == nir_intrinsic_decl_reg); \
7191                                                      \
7192    nir_foreach_use(load, &reg->def)             \
7193       if (nir_is_load_reg(nir_instr_as_intrinsic(nir_src_parent_instr(load))))
7194 
7195 #define nir_foreach_reg_load_safe(load, reg)         \
7196    assert(reg->intrinsic == nir_intrinsic_decl_reg); \
7197                                                      \
7198    nir_foreach_use_safe(load, &reg->def)             \
7199       if (nir_is_load_reg(nir_instr_as_intrinsic(nir_src_parent_instr(load))))
7200 
7201 #define nir_foreach_reg_store(store, reg)            \
7202    assert(reg->intrinsic == nir_intrinsic_decl_reg); \
7203                                                      \
7204    nir_foreach_use(store, &reg->def)            \
7205       if (nir_is_store_reg(nir_instr_as_intrinsic(nir_src_parent_instr(store))))
7206 
7207 #define nir_foreach_reg_store_safe(store, reg)       \
7208    assert(reg->intrinsic == nir_intrinsic_decl_reg); \
7209                                                      \
7210    nir_foreach_use_safe(store, &reg->def)            \
7211       if (nir_is_store_reg(nir_instr_as_intrinsic(nir_src_parent_instr(store))))
7212 
7213 static inline nir_intrinsic_instr *
nir_load_reg_for_def(const nir_def * def)7214 nir_load_reg_for_def(const nir_def *def)
7215 {
7216    if (def->parent_instr->type != nir_instr_type_intrinsic)
7217       return NULL;
7218 
7219    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(def->parent_instr);
7220    if (!nir_is_load_reg(intr))
7221       return NULL;
7222 
7223    return intr;
7224 }
7225 
7226 static inline nir_intrinsic_instr *
nir_store_reg_for_def(const nir_def * def)7227 nir_store_reg_for_def(const nir_def *def)
7228 {
7229    /* Look for the trivial store: single use of our destination by a
7230     * store_register intrinsic.
7231     */
7232    if (!list_is_singular(&def->uses))
7233       return NULL;
7234 
7235    nir_src *src = list_first_entry(&def->uses, nir_src, use_link);
7236    if (nir_src_is_if(src))
7237       return NULL;
7238 
7239    nir_instr *parent = nir_src_parent_instr(src);
7240    if (parent->type != nir_instr_type_intrinsic)
7241       return NULL;
7242 
7243    nir_intrinsic_instr *intr = nir_instr_as_intrinsic(parent);
7244    if (!nir_is_store_reg(intr))
7245       return NULL;
7246 
7247    /* The first value is data. Third is indirect index, ignore that one. */
7248    if (&intr->src[0] != src)
7249       return NULL;
7250 
7251    return intr;
7252 }
7253 
7254 struct nir_use_dominance_state;
7255 
7256 struct nir_use_dominance_state *
7257 nir_calc_use_dominance_impl(nir_function_impl *impl, bool post_dominance);
7258 
7259 nir_instr *
7260 nir_get_immediate_use_dominator(struct nir_use_dominance_state *state,
7261                                 nir_instr *instr);
7262 nir_instr *nir_use_dominance_lca(struct nir_use_dominance_state *state,
7263                                  nir_instr *i1, nir_instr *i2);
7264 bool nir_instr_dominates_use(struct nir_use_dominance_state *state,
7265                              nir_instr *parent, nir_instr *child);
7266 void nir_print_use_dominators(struct nir_use_dominance_state *state,
7267                               nir_instr **instructions,
7268                               unsigned num_instructions);
7269 
7270 #include "nir_inline_helpers.h"
7271 
7272 #ifdef __cplusplus
7273 } /* extern "C" */
7274 #endif
7275 
7276 #endif /* NIR_H */
7277