1 /*
2  * Copyright 2012 Advanced Micro Devices, Inc.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * on the rights to use, copy, modify, merge, publish, distribute, sub
9  * license, and/or sell copies of the Software, and to permit persons to whom
10  * the Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22  * USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24 
25 /* The compiler middle-end architecture: Explaining (non-)monolithic shaders
26  * -------------------------------------------------------------------------
27  *
28  * Typically, there is one-to-one correspondence between API and HW shaders,
29  * that is, for every API shader, there is exactly one shader binary in
30  * the driver.
31  *
32  * The problem with that is that we also have to emulate some API states
33  * (e.g. alpha-test, and many others) in shaders too. The two obvious ways
34  * to deal with it are:
35  * - each shader has multiple variants for each combination of emulated states,
36  *   and the variants are compiled on demand, possibly relying on a shader
37  *   cache for good performance
38  * - patch shaders at the binary level
39  *
40  * This driver uses something completely different. The emulated states are
41  * usually implemented at the beginning or end of shaders. Therefore, we can
42  * split the shader into 3 parts:
43  * - prolog part (shader code dependent on states)
44  * - main part (the API shader)
45  * - epilog part (shader code dependent on states)
46  *
47  * Each part is compiled as a separate shader and the final binaries are
48  * concatenated. This type of shader is called non-monolithic, because it
49  * consists of multiple independent binaries. Creating a new shader variant
50  * is therefore only a concatenation of shader parts (binaries) and doesn't
51  * involve any compilation. The main shader parts are the only parts that are
52  * compiled when applications create shader objects. The prolog and epilog
53  * parts are compiled on the first use and saved, so that their binaries can
54  * be reused by many other shaders.
55  *
56  * One of the roles of the prolog part is to compute vertex buffer addresses
57  * for vertex shaders. A few of the roles of the epilog part are color buffer
58  * format conversions in pixel shaders that we have to do manually, and write
59  * tessellation factors in tessellation control shaders. The prolog and epilog
60  * have many other important responsibilities in various shader stages.
61  * They don't just "emulate legacy stuff".
62  *
63  * Monolithic shaders are shaders where the parts are combined before LLVM
64  * compilation, and the whole thing is compiled and optimized as one unit with
65  * one binary on the output. The result is the same as the non-monolithic
66  * shader, but the final code can be better, because LLVM can optimize across
67  * all shader parts. Monolithic shaders aren't usually used except for these
68  * special cases:
69  *
70  * 1) Some rarely-used states require modification of the main shader part
71  *    itself, and in such cases, only the monolithic shader variant is
72  *    compiled, and that's always done on the first use.
73  *
74  * 2) When we do cross-stage optimizations for separate shader objects and
75  *    e.g. eliminate unused shader varyings, the resulting optimized shader
76  *    variants are always compiled as monolithic shaders, and always
77  *    asynchronously (i.e. not stalling ongoing rendering). We call them
78  *    "optimized monolithic" shaders. The important property here is that
79  *    the non-monolithic unoptimized shader variant is always available for use
80  *    when the asynchronous compilation of the optimized shader is not done
81  *    yet.
82  *
83  * Starting with GFX9 chips, some shader stages are merged, and the number of
84  * shader parts per shader increased. The complete new list of shader parts is:
85  * - 1st shader: prolog part
86  * - 1st shader: main part
87  * - 2nd shader: prolog part
88  * - 2nd shader: main part
89  * - 2nd shader: epilog part
90  */
91 
92 /* How linking shader inputs and outputs between vertex, tessellation, and
93  * geometry shaders works.
94  *
95  * Inputs and outputs between shaders are stored in a buffer. This buffer
96  * lives in LDS (typical case for tessellation), but it can also live
97  * in memory (ESGS). Each input or output has a fixed location within a vertex.
98  * The highest used input or output determines the stride between vertices.
99  *
100  * Since GS and tessellation are only possible in the OpenGL core profile,
101  * only these semantics are valid for per-vertex data:
102  *
103  *   Name             Location
104  *
105  *   POSITION         0
106  *   PSIZE            1
107  *   CLIPDIST0..1     2..3
108  *   CULLDIST0..1     (not implemented)
109  *   GENERIC0..31     4..35
110  *
111  * For example, a shader only writing GENERIC0 has the output stride of 5.
112  *
113  * Only these semantics are valid for per-patch data:
114  *
115  *   Name             Location
116  *
117  *   TESSOUTER        0
118  *   TESSINNER        1
119  *   PATCH0..29       2..31
120  *
121  * That's how independent shaders agree on input and output locations.
122  * The si_shader_io_get_unique_index function assigns the locations.
123  *
124  * For tessellation, other required information for calculating the input and
125  * output addresses like the vertex stride, the patch stride, and the offsets
126  * where per-vertex and per-patch data start, is passed to the shader via
127  * user data SGPRs. The offsets and strides are calculated at draw time and
128  * aren't available at compile time.
129  */
130 
131 #ifndef SI_SHADER_H
132 #define SI_SHADER_H
133 
134 #include "ac_binary.h"
135 #include "ac_llvm_build.h"
136 #include "ac_llvm_util.h"
137 #include "util/simple_mtx.h"
138 #include "util/u_inlines.h"
139 #include "util/u_live_shader_cache.h"
140 #include "util/u_queue.h"
141 
142 #include <stdio.h>
143 
144 // Use LDS symbols when supported by LLVM. Can be disabled for testing the old
145 // path on newer LLVM for now. Should be removed in the long term.
146 #define USE_LDS_SYMBOLS (true)
147 
148 struct nir_shader;
149 struct si_shader;
150 struct si_context;
151 
152 #define SI_MAX_ATTRIBS    16
153 #define SI_MAX_VS_OUTPUTS 40
154 
155 /* Shader IO unique indices are supported for TGSI_SEMANTIC_GENERIC with an
156  * index smaller than this.
157  */
158 #define SI_MAX_IO_GENERIC 32
159 
160 #define SI_NGG_PRIM_EDGE_FLAG_BITS ((1 << 9) | (1 << 19) | (1 << 29))
161 
162 /* SGPR user data indices */
163 enum
164 {
165    SI_SGPR_RW_BUFFERS, /* rings (& stream-out, VS only) */
166    SI_SGPR_BINDLESS_SAMPLERS_AND_IMAGES,
167    SI_SGPR_CONST_AND_SHADER_BUFFERS, /* or just a constant buffer 0 pointer */
168    SI_SGPR_SAMPLERS_AND_IMAGES,
169    SI_NUM_RESOURCE_SGPRS,
170 
171    /* API VS, TES without GS, GS copy shader */
172    SI_SGPR_VS_STATE_BITS = SI_NUM_RESOURCE_SGPRS,
173    SI_NUM_VS_STATE_RESOURCE_SGPRS,
174 
175    /* all VS variants */
176    SI_SGPR_BASE_VERTEX = SI_NUM_VS_STATE_RESOURCE_SGPRS,
177    SI_SGPR_START_INSTANCE,
178    SI_SGPR_DRAWID,
179    SI_VS_NUM_USER_SGPR,
180 
181    SI_SGPR_VS_BLIT_DATA = SI_SGPR_CONST_AND_SHADER_BUFFERS,
182 
183    /* TES */
184    SI_SGPR_TES_OFFCHIP_LAYOUT = SI_NUM_VS_STATE_RESOURCE_SGPRS,
185    SI_SGPR_TES_OFFCHIP_ADDR,
186    SI_TES_NUM_USER_SGPR,
187 
188    /* GFX6-8: TCS only */
189    GFX6_SGPR_TCS_OFFCHIP_LAYOUT = SI_NUM_RESOURCE_SGPRS,
190    GFX6_SGPR_TCS_OUT_OFFSETS,
191    GFX6_SGPR_TCS_OUT_LAYOUT,
192    GFX6_SGPR_TCS_IN_LAYOUT,
193    GFX6_TCS_NUM_USER_SGPR,
194 
195    /* GFX9: Merged shaders. */
196    /* 2ND_CONST_AND_SHADER_BUFFERS is set in USER_DATA_ADDR_LO (SGPR0). */
197    /* 2ND_SAMPLERS_AND_IMAGES is set in USER_DATA_ADDR_HI (SGPR1). */
198    GFX9_MERGED_NUM_USER_SGPR = SI_VS_NUM_USER_SGPR,
199 
200    /* GFX9: Merged LS-HS (VS-TCS) only. */
201    GFX9_SGPR_TCS_OFFCHIP_LAYOUT = GFX9_MERGED_NUM_USER_SGPR,
202    GFX9_SGPR_TCS_OUT_OFFSETS,
203    GFX9_SGPR_TCS_OUT_LAYOUT,
204    GFX9_TCS_NUM_USER_SGPR,
205 
206    /* GS limits */
207    GFX6_GS_NUM_USER_SGPR = SI_NUM_RESOURCE_SGPRS,
208    GFX9_VSGS_NUM_USER_SGPR = SI_VS_NUM_USER_SGPR,
209    GFX9_TESGS_NUM_USER_SGPR = SI_TES_NUM_USER_SGPR,
210    SI_GSCOPY_NUM_USER_SGPR = SI_NUM_VS_STATE_RESOURCE_SGPRS,
211 
212    /* PS only */
213    SI_SGPR_ALPHA_REF = SI_NUM_RESOURCE_SGPRS,
214    SI_PS_NUM_USER_SGPR,
215 
216    /* The value has to be 12, because the hw requires that descriptors
217     * are aligned to 4 SGPRs.
218     */
219    SI_SGPR_VS_VB_DESCRIPTOR_FIRST = 12,
220 };
221 
222 /* LLVM function parameter indices */
223 enum
224 {
225    SI_NUM_RESOURCE_PARAMS = 4,
226 
227    /* PS only parameters */
228    SI_PARAM_ALPHA_REF = SI_NUM_RESOURCE_PARAMS,
229    SI_PARAM_PRIM_MASK,
230    SI_PARAM_PERSP_SAMPLE,
231    SI_PARAM_PERSP_CENTER,
232    SI_PARAM_PERSP_CENTROID,
233    SI_PARAM_PERSP_PULL_MODEL,
234    SI_PARAM_LINEAR_SAMPLE,
235    SI_PARAM_LINEAR_CENTER,
236    SI_PARAM_LINEAR_CENTROID,
237    SI_PARAM_LINE_STIPPLE_TEX,
238    SI_PARAM_POS_X_FLOAT,
239    SI_PARAM_POS_Y_FLOAT,
240    SI_PARAM_POS_Z_FLOAT,
241    SI_PARAM_POS_W_FLOAT,
242    SI_PARAM_FRONT_FACE,
243    SI_PARAM_ANCILLARY,
244    SI_PARAM_SAMPLE_COVERAGE,
245    SI_PARAM_POS_FIXED_PT,
246 
247    SI_NUM_PARAMS = SI_PARAM_POS_FIXED_PT + 9, /* +8 for COLOR[0..1] */
248 };
249 
250 /* Fields of driver-defined VS state SGPR. */
251 #define S_VS_STATE_CLAMP_VERTEX_COLOR(x)      (((unsigned)(x)&0x1) << 0)
252 #define C_VS_STATE_CLAMP_VERTEX_COLOR         0xFFFFFFFE
253 #define S_VS_STATE_INDEXED(x)                 (((unsigned)(x)&0x1) << 1)
254 #define C_VS_STATE_INDEXED                    0xFFFFFFFD
255 #define S_VS_STATE_OUTPRIM(x)                 (((unsigned)(x)&0x3) << 2)
256 #define C_VS_STATE_OUTPRIM                    0xFFFFFFF3
257 #define S_VS_STATE_PROVOKING_VTX_INDEX(x)     (((unsigned)(x)&0x3) << 4)
258 #define C_VS_STATE_PROVOKING_VTX_INDEX        0xFFFFFFCF
259 #define S_VS_STATE_STREAMOUT_QUERY_ENABLED(x) (((unsigned)(x)&0x1) << 6)
260 #define C_VS_STATE_STREAMOUT_QUERY_ENABLED    0xFFFFFFBF
261 #define S_VS_STATE_SMALL_PRIM_PRECISION(x)    (((unsigned)(x)&0xF) << 7)
262 #define C_VS_STATE_SMALL_PRIM_PRECISION       0xFFFFF87F
263 #define S_VS_STATE_LS_OUT_PATCH_SIZE(x)       (((unsigned)(x)&0x1FFF) << 11)
264 #define C_VS_STATE_LS_OUT_PATCH_SIZE          0xFF0007FF
265 #define S_VS_STATE_LS_OUT_VERTEX_SIZE(x)      (((unsigned)(x)&0xFF) << 24)
266 #define C_VS_STATE_LS_OUT_VERTEX_SIZE         0x00FFFFFF
267 
268 enum
269 {
270    /* Use a property enum that CS wouldn't use. */
271    TGSI_PROPERTY_CS_LOCAL_SIZE = TGSI_PROPERTY_FS_COORD_ORIGIN,
272 
273    /* These represent the number of SGPRs the shader uses. */
274    SI_VS_BLIT_SGPRS_POS = 3,
275    SI_VS_BLIT_SGPRS_POS_COLOR = 7,
276    SI_VS_BLIT_SGPRS_POS_TEXCOORD = 9,
277 };
278 
279 #define SI_NGG_CULL_VIEW_SMALLPRIMS          (1 << 0)   /* view.xy + small prims */
280 #define SI_NGG_CULL_BACK_FACE                (1 << 1)   /* back faces */
281 #define SI_NGG_CULL_FRONT_FACE               (1 << 2)   /* front faces */
282 #define SI_NGG_CULL_GS_FAST_LAUNCH_TRI_LIST  (1 << 3)   /* GS fast launch: triangles */
283 #define SI_NGG_CULL_GS_FAST_LAUNCH_TRI_STRIP (1 << 4)   /* GS fast launch: triangle strip */
284 #define SI_NGG_CULL_GS_FAST_LAUNCH_ALL       (0x3 << 3) /* GS fast launch (both prim types) */
285 
286 /**
287  * For VS shader keys, describe any fixups required for vertex fetch.
288  *
289  * \ref log_size, \ref format, and the number of channels are interpreted as
290  * by \ref ac_build_opencoded_load_format.
291  *
292  * Note: all bits 0 (size = 1 byte, num channels = 1, format = float) is an
293  * impossible format and indicates that no fixup is needed (just use
294  * buffer_load_format_xyzw).
295  */
296 union si_vs_fix_fetch {
297    struct {
298       uint8_t log_size : 2;        /* 1, 2, 4, 8 or bytes per channel */
299       uint8_t num_channels_m1 : 2; /* number of channels minus 1 */
300       uint8_t format : 3;          /* AC_FETCH_FORMAT_xxx */
301       uint8_t reverse : 1;         /* reverse XYZ channels */
302    } u;
303    uint8_t bits;
304 };
305 
306 struct si_shader;
307 
308 /* State of the context creating the shader object. */
309 struct si_compiler_ctx_state {
310    /* Should only be used by si_init_shader_selector_async and
311     * si_build_shader_variant if thread_index == -1 (non-threaded). */
312    struct ac_llvm_compiler *compiler;
313 
314    /* Used if thread_index == -1 or if debug.async is true. */
315    struct pipe_debug_callback debug;
316 
317    /* Used for creating the log string for gallium/ddebug. */
318    bool is_debug_context;
319 };
320 
321 struct si_shader_info {
322    ubyte num_inputs;
323    ubyte num_outputs;
324    ubyte input_semantic_name[PIPE_MAX_SHADER_INPUTS]; /**< TGSI_SEMANTIC_x */
325    ubyte input_semantic_index[PIPE_MAX_SHADER_INPUTS];
326    ubyte input_interpolate[PIPE_MAX_SHADER_INPUTS];
327    ubyte input_interpolate_loc[PIPE_MAX_SHADER_INPUTS];
328    ubyte input_usage_mask[PIPE_MAX_SHADER_INPUTS];
329    ubyte output_semantic_name[PIPE_MAX_SHADER_OUTPUTS]; /**< TGSI_SEMANTIC_x */
330    ubyte output_semantic_index[PIPE_MAX_SHADER_OUTPUTS];
331    ubyte output_usagemask[PIPE_MAX_SHADER_OUTPUTS];
332    ubyte output_streams[PIPE_MAX_SHADER_OUTPUTS];
333 
334    ubyte processor;
335 
336    int constbuf0_num_slots;
337    unsigned const_buffers_declared; /**< bitmask of declared const buffers */
338    unsigned samplers_declared;      /**< bitmask of declared samplers */
339    ubyte num_stream_output_components[4];
340 
341    uint num_memory_instructions; /**< sampler, buffer, and image instructions */
342 
343    /**
344     * If a tessellation control shader reads outputs, this describes which ones.
345     */
346    bool reads_pervertex_outputs;
347    bool reads_perpatch_outputs;
348    bool reads_tessfactor_outputs;
349 
350    ubyte colors_read; /**< which color components are read by the FS */
351    ubyte colors_written;
352    bool reads_samplemask;   /**< does fragment shader read sample mask? */
353    bool reads_tess_factors; /**< If TES reads TESSINNER or TESSOUTER */
354    bool writes_z;           /**< does fragment shader write Z value? */
355    bool writes_stencil;     /**< does fragment shader write stencil value? */
356    bool writes_samplemask;  /**< does fragment shader write sample mask? */
357    bool writes_edgeflag;    /**< vertex shader outputs edgeflag */
358    bool uses_kill;          /**< KILL or KILL_IF instruction used? */
359    bool uses_persp_center;
360    bool uses_persp_centroid;
361    bool uses_persp_sample;
362    bool uses_linear_center;
363    bool uses_linear_centroid;
364    bool uses_linear_sample;
365    bool uses_persp_opcode_interp_sample;
366    bool uses_linear_opcode_interp_sample;
367    bool uses_instanceid;
368    bool uses_vertexid;
369    bool uses_vertexid_nobase;
370    bool uses_basevertex;
371    bool uses_drawid;
372    bool uses_primid;
373    bool uses_frontface;
374    bool uses_invocationid;
375    bool uses_thread_id[3];
376    bool uses_block_id[3];
377    bool uses_block_size;
378    bool uses_grid_size;
379    bool uses_subgroup_info;
380    bool writes_position;
381    bool writes_psize;
382    bool writes_clipvertex;
383    bool writes_primid;
384    bool writes_viewport_index;
385    bool writes_layer;
386    bool writes_memory; /**< contains stores or atomics to buffers or images */
387    bool uses_derivatives;
388    bool uses_bindless_samplers;
389    bool uses_bindless_images;
390    bool uses_fbfetch;
391    unsigned clipdist_writemask;
392    unsigned culldist_writemask;
393    unsigned num_written_culldistance;
394    unsigned num_written_clipdistance;
395 
396    unsigned images_declared;         /**< bitmask of declared images */
397    unsigned image_buffers;           /**< bitmask of images that are buffers */
398    unsigned msaa_images_declared;    /**< bitmask of declared MSAA images */
399    unsigned shader_buffers_declared; /**< bitmask of declared shader buffers */
400 
401    unsigned properties[TGSI_PROPERTY_COUNT]; /* index with TGSI_PROPERTY_ */
402 
403    /** Whether all codepaths write tess factors in all invocations. */
404    bool tessfactors_are_def_in_all_invocs;
405 };
406 
407 /* A shader selector is a gallium CSO and contains shader variants and
408  * binaries for one NIR program. This can be shared by multiple contexts.
409  */
410 struct si_shader_selector {
411    struct util_live_shader base;
412    struct si_screen *screen;
413    struct util_queue_fence ready;
414    struct si_compiler_ctx_state compiler_ctx_state;
415 
416    simple_mtx_t mutex;
417    struct si_shader *first_variant; /* immutable after the first variant */
418    struct si_shader *last_variant;  /* mutable */
419 
420    /* The compiled NIR shader without a prolog and/or epilog (not
421     * uploaded to a buffer object).
422     */
423    struct si_shader *main_shader_part;
424    struct si_shader *main_shader_part_ls;     /* as_ls is set in the key */
425    struct si_shader *main_shader_part_es;     /* as_es is set in the key */
426    struct si_shader *main_shader_part_ngg;    /* as_ngg is set in the key */
427    struct si_shader *main_shader_part_ngg_es; /* for Wave32 TES before legacy GS */
428 
429    struct si_shader *gs_copy_shader;
430 
431    struct nir_shader *nir;
432    void *nir_binary;
433    unsigned nir_size;
434 
435    struct pipe_stream_output_info so;
436    struct si_shader_info info;
437 
438    /* PIPE_SHADER_[VERTEX|FRAGMENT|...] */
439    enum pipe_shader_type type;
440    bool vs_needs_prolog;
441    bool prim_discard_cs_allowed;
442    bool ngg_culling_allowed;
443    ubyte cs_shaderbufs_sgpr_index;
444    ubyte cs_num_shaderbufs_in_user_sgprs;
445    ubyte cs_images_sgpr_index;
446    ubyte cs_images_num_sgprs;
447    ubyte cs_num_images_in_user_sgprs;
448    unsigned num_vs_inputs;
449    unsigned num_vbos_in_user_sgprs;
450    unsigned pa_cl_vs_out_cntl;
451    ubyte clipdist_mask;
452    ubyte culldist_mask;
453    unsigned rast_prim;
454 
455    /* ES parameters. */
456    unsigned esgs_itemsize; /* vertex stride */
457    unsigned lshs_vertex_stride;
458 
459    /* GS parameters. */
460    unsigned gs_input_verts_per_prim;
461    unsigned gs_output_prim;
462    unsigned gs_max_out_vertices;
463    unsigned gs_num_invocations;
464    unsigned max_gs_stream; /* count - 1 */
465    unsigned gsvs_vertex_size;
466    unsigned max_gsvs_emit_size;
467    unsigned enabled_streamout_buffer_mask;
468    bool tess_turns_off_ngg;
469 
470    /* PS parameters. */
471    unsigned color_attr_index[2];
472    unsigned db_shader_control;
473    /* Set 0xf or 0x0 (4 bits) per each written output.
474     * ANDed with spi_shader_col_format.
475     */
476    unsigned colors_written_4bit;
477 
478    uint64_t outputs_written_before_ps; /* "get_unique_index" bits */
479    uint64_t outputs_written;           /* "get_unique_index" bits */
480    uint32_t patch_outputs_written;     /* "get_unique_index_patch" bits */
481 
482    uint64_t inputs_read; /* "get_unique_index" bits */
483 
484    /* bitmasks of used descriptor slots */
485    uint64_t active_const_and_shader_buffers;
486    uint64_t active_samplers_and_images;
487 };
488 
489 /* Valid shader configurations:
490  *
491  * API shaders           VS | TCS | TES | GS |pass| PS
492  * are compiled as:         |     |     |    |thru|
493  *                          |     |     |    |    |
494  * Only VS & PS:         VS |     |     |    |    | PS
495  * GFX6     - with GS:   ES |     |     | GS | VS | PS
496  *          - with tess: LS | HS  | VS  |    |    | PS
497  *          - with both: LS | HS  | ES  | GS | VS | PS
498  * GFX9     - with GS:   -> |     |     | GS | VS | PS
499  *          - with tess: -> | HS  | VS  |    |    | PS
500  *          - with both: -> | HS  | ->  | GS | VS | PS
501  *                          |     |     |    |    |
502  * NGG      - VS & PS:   GS |     |     |    |    | PS
503  * (GFX10+) - with GS:   -> |     |     | GS |    | PS
504  *          - with tess: -> | HS  | GS  |    |    | PS
505  *          - with both: -> | HS  | ->  | GS |    | PS
506  *
507  * -> = merged with the next stage
508  */
509 
510 /* Use the byte alignment for all following structure members for optimal
511  * shader key memory footprint.
512  */
513 #pragma pack(push, 1)
514 
515 /* Common VS bits between the shader key and the prolog key. */
516 struct si_vs_prolog_bits {
517    /* - If neither "is_one" nor "is_fetched" has a bit set, the instance
518     *   divisor is 0.
519     * - If "is_one" has a bit set, the instance divisor is 1.
520     * - If "is_fetched" has a bit set, the instance divisor will be loaded
521     *   from the constant buffer.
522     */
523    uint16_t instance_divisor_is_one;     /* bitmask of inputs */
524    uint16_t instance_divisor_is_fetched; /* bitmask of inputs */
525    unsigned ls_vgpr_fix : 1;
526    unsigned unpack_instance_id_from_vertex_id : 1;
527 };
528 
529 /* Common TCS bits between the shader key and the epilog key. */
530 struct si_tcs_epilog_bits {
531    unsigned prim_mode : 3;
532    unsigned invoc0_tess_factors_are_def : 1;
533    unsigned tes_reads_tess_factors : 1;
534 };
535 
536 struct si_gs_prolog_bits {
537    unsigned tri_strip_adj_fix : 1;
538    unsigned gfx9_prev_is_vs : 1;
539 };
540 
541 /* Common PS bits between the shader key and the prolog key. */
542 struct si_ps_prolog_bits {
543    unsigned color_two_side : 1;
544    unsigned flatshade_colors : 1;
545    unsigned poly_stipple : 1;
546    unsigned force_persp_sample_interp : 1;
547    unsigned force_linear_sample_interp : 1;
548    unsigned force_persp_center_interp : 1;
549    unsigned force_linear_center_interp : 1;
550    unsigned bc_optimize_for_persp : 1;
551    unsigned bc_optimize_for_linear : 1;
552    unsigned samplemask_log_ps_iter : 3;
553 };
554 
555 /* Common PS bits between the shader key and the epilog key. */
556 struct si_ps_epilog_bits {
557    unsigned spi_shader_col_format;
558    unsigned color_is_int8 : 8;
559    unsigned color_is_int10 : 8;
560    unsigned last_cbuf : 3;
561    unsigned alpha_func : 3;
562    unsigned alpha_to_one : 1;
563    unsigned poly_line_smoothing : 1;
564    unsigned clamp_color : 1;
565 };
566 
567 union si_shader_part_key {
568    struct {
569       struct si_vs_prolog_bits states;
570       unsigned num_input_sgprs : 6;
571       /* For merged stages such as LS-HS, HS input VGPRs are first. */
572       unsigned num_merged_next_stage_vgprs : 3;
573       unsigned num_inputs : 5;
574       unsigned as_ls : 1;
575       unsigned as_es : 1;
576       unsigned as_ngg : 1;
577       unsigned as_prim_discard_cs : 1;
578       unsigned has_ngg_cull_inputs : 1;      /* from the NGG cull shader */
579       unsigned gs_fast_launch_tri_list : 1;  /* for NGG culling */
580       unsigned gs_fast_launch_tri_strip : 1; /* for NGG culling */
581       /* Prologs for monolithic shaders shouldn't set EXEC. */
582       unsigned is_monolithic : 1;
583    } vs_prolog;
584    struct {
585       struct si_tcs_epilog_bits states;
586    } tcs_epilog;
587    struct {
588       struct si_gs_prolog_bits states;
589       /* Prologs of monolithic shaders shouldn't set EXEC. */
590       unsigned is_monolithic : 1;
591       unsigned as_ngg : 1;
592    } gs_prolog;
593    struct {
594       struct si_ps_prolog_bits states;
595       unsigned num_input_sgprs : 6;
596       unsigned num_input_vgprs : 5;
597       /* Color interpolation and two-side color selection. */
598       unsigned colors_read : 8;       /* color input components read */
599       unsigned num_interp_inputs : 5; /* BCOLOR is at this location */
600       unsigned face_vgpr_index : 5;
601       unsigned ancillary_vgpr_index : 5;
602       unsigned wqm : 1;
603       char color_attr_index[2];
604       signed char color_interp_vgpr_index[2]; /* -1 == constant */
605    } ps_prolog;
606    struct {
607       struct si_ps_epilog_bits states;
608       unsigned colors_written : 8;
609       unsigned writes_z : 1;
610       unsigned writes_stencil : 1;
611       unsigned writes_samplemask : 1;
612    } ps_epilog;
613 };
614 
615 struct si_shader_key {
616    /* Prolog and epilog flags. */
617    union {
618       struct {
619          struct si_vs_prolog_bits prolog;
620       } vs;
621       struct {
622          struct si_vs_prolog_bits ls_prolog; /* for merged LS-HS */
623          struct si_shader_selector *ls;      /* for merged LS-HS */
624          struct si_tcs_epilog_bits epilog;
625       } tcs; /* tessellation control shader */
626       struct {
627          struct si_vs_prolog_bits vs_prolog; /* for merged ES-GS */
628          struct si_shader_selector *es;      /* for merged ES-GS */
629          struct si_gs_prolog_bits prolog;
630       } gs;
631       struct {
632          struct si_ps_prolog_bits prolog;
633          struct si_ps_epilog_bits epilog;
634       } ps;
635    } part;
636 
637    /* These three are initially set according to the NEXT_SHADER property,
638     * or guessed if the property doesn't seem correct.
639     */
640    unsigned as_es : 1;  /* export shader, which precedes GS */
641    unsigned as_ls : 1;  /* local shader, which precedes TCS */
642    unsigned as_ngg : 1; /* VS, TES, or GS compiled as NGG primitive shader */
643 
644    /* Flags for monolithic compilation only. */
645    struct {
646       /* Whether fetch should be opencoded according to vs_fix_fetch.
647        * Otherwise, if vs_fix_fetch is non-zero, buffer_load_format_xyzw
648        * with minimal fixups is used. */
649       uint16_t vs_fetch_opencode;
650       union si_vs_fix_fetch vs_fix_fetch[SI_MAX_ATTRIBS];
651 
652       union {
653          uint64_t ff_tcs_inputs_to_copy; /* for fixed-func TCS */
654          /* When PS needs PrimID and GS is disabled. */
655          unsigned vs_export_prim_id : 1;
656          struct {
657             unsigned interpolate_at_sample_force_center : 1;
658             unsigned fbfetch_msaa : 1;
659             unsigned fbfetch_is_1D : 1;
660             unsigned fbfetch_layered : 1;
661          } ps;
662       } u;
663    } mono;
664 
665    /* Optimization flags for asynchronous compilation only. */
666    struct {
667       /* For HW VS (it can be VS, TES, GS) */
668       uint64_t kill_outputs; /* "get_unique_index" bits */
669       unsigned clip_disable : 1;
670 
671       /* For NGG VS and TES. */
672       unsigned ngg_culling : 5; /* SI_NGG_CULL_* */
673 
674       /* For shaders where monolithic variants have better code.
675        *
676        * This is a flag that has no effect on code generation,
677        * but forces monolithic shaders to be used as soon as
678        * possible, because it's in the "opt" group.
679        */
680       unsigned prefer_mono : 1;
681 
682       /* Primitive discard compute shader. */
683       unsigned vs_as_prim_discard_cs : 1;
684       unsigned cs_prim_type : 4;
685       unsigned cs_indexed : 1;
686       unsigned cs_instancing : 1;
687       unsigned cs_primitive_restart : 1;
688       unsigned cs_provoking_vertex_first : 1;
689       unsigned cs_need_correct_orientation : 1;
690       unsigned cs_cull_front : 1;
691       unsigned cs_cull_back : 1;
692       unsigned cs_cull_z : 1;
693       unsigned cs_halfz_clip_space : 1;
694    } opt;
695 };
696 
697 /* Restore the pack alignment to default. */
698 #pragma pack(pop)
699 
700 /* GCN-specific shader info. */
701 struct si_shader_binary_info {
702    ubyte vs_output_param_offset[SI_MAX_VS_OUTPUTS];
703    ubyte num_input_sgprs;
704    ubyte num_input_vgprs;
705    signed char face_vgpr_index;
706    signed char ancillary_vgpr_index;
707    bool uses_instanceid;
708    ubyte nr_pos_exports;
709    ubyte nr_param_exports;
710    unsigned private_mem_vgprs;
711    unsigned max_simd_waves;
712 };
713 
714 struct si_shader_binary {
715    const char *elf_buffer;
716    size_t elf_size;
717 
718    char *llvm_ir_string;
719 };
720 
721 struct gfx9_gs_info {
722    unsigned es_verts_per_subgroup;
723    unsigned gs_prims_per_subgroup;
724    unsigned gs_inst_prims_in_subgroup;
725    unsigned max_prims_per_subgroup;
726    unsigned esgs_ring_size; /* in bytes */
727 };
728 
729 struct si_shader {
730    struct si_compiler_ctx_state compiler_ctx_state;
731 
732    struct si_shader_selector *selector;
733    struct si_shader_selector *previous_stage_sel; /* for refcounting */
734    struct si_shader *next_variant;
735 
736    struct si_shader_part *prolog;
737    struct si_shader *previous_stage; /* for GFX9 */
738    struct si_shader_part *prolog2;
739    struct si_shader_part *epilog;
740 
741    struct si_pm4_state *pm4;
742    struct si_resource *bo;
743    struct si_resource *scratch_bo;
744    struct si_shader_key key;
745    struct util_queue_fence ready;
746    bool compilation_failed;
747    bool is_monolithic;
748    bool is_optimized;
749    bool is_binary_shared;
750    bool is_gs_copy_shader;
751 
752    /* The following data is all that's needed for binary shaders. */
753    struct si_shader_binary binary;
754    struct ac_shader_config config;
755    struct si_shader_binary_info info;
756 
757    struct {
758       uint16_t ngg_emit_size; /* in dwords */
759       uint16_t hw_max_esverts;
760       uint16_t max_gsprims;
761       uint16_t max_out_verts;
762       uint16_t prim_amp_factor;
763       bool max_vert_out_per_gs_instance;
764    } ngg;
765 
766    /* Shader key + LLVM IR + disassembly + statistics.
767     * Generated for debug contexts only.
768     */
769    char *shader_log;
770    size_t shader_log_size;
771 
772    struct gfx9_gs_info gs_info;
773 
774    /* For save precompute context registers values. */
775    union {
776       struct {
777          unsigned vgt_gsvs_ring_offset_1;
778          unsigned vgt_gsvs_ring_offset_2;
779          unsigned vgt_gsvs_ring_offset_3;
780          unsigned vgt_gsvs_ring_itemsize;
781          unsigned vgt_gs_max_vert_out;
782          unsigned vgt_gs_vert_itemsize;
783          unsigned vgt_gs_vert_itemsize_1;
784          unsigned vgt_gs_vert_itemsize_2;
785          unsigned vgt_gs_vert_itemsize_3;
786          unsigned vgt_gs_instance_cnt;
787          unsigned vgt_gs_onchip_cntl;
788          unsigned vgt_gs_max_prims_per_subgroup;
789          unsigned vgt_esgs_ring_itemsize;
790       } gs;
791 
792       struct {
793          unsigned ge_max_output_per_subgroup;
794          unsigned ge_ngg_subgrp_cntl;
795          unsigned vgt_primitiveid_en;
796          unsigned vgt_gs_onchip_cntl;
797          unsigned vgt_gs_instance_cnt;
798          unsigned vgt_esgs_ring_itemsize;
799          unsigned spi_vs_out_config;
800          unsigned spi_shader_idx_format;
801          unsigned spi_shader_pos_format;
802          unsigned pa_cl_vte_cntl;
803          unsigned pa_cl_ngg_cntl;
804          unsigned vgt_gs_max_vert_out; /* for API GS */
805          unsigned ge_pc_alloc;         /* uconfig register */
806       } ngg;
807 
808       struct {
809          unsigned vgt_gs_mode;
810          unsigned vgt_primitiveid_en;
811          unsigned vgt_reuse_off;
812          unsigned spi_vs_out_config;
813          unsigned spi_shader_pos_format;
814          unsigned pa_cl_vte_cntl;
815          unsigned ge_pc_alloc; /* uconfig register */
816       } vs;
817 
818       struct {
819          unsigned spi_ps_input_ena;
820          unsigned spi_ps_input_addr;
821          unsigned spi_baryc_cntl;
822          unsigned spi_ps_in_control;
823          unsigned spi_shader_z_format;
824          unsigned spi_shader_col_format;
825          unsigned cb_shader_mask;
826       } ps;
827    } ctx_reg;
828 
829    /*For save precompute registers value */
830    unsigned vgt_tf_param;                /* VGT_TF_PARAM */
831    unsigned vgt_vertex_reuse_block_cntl; /* VGT_VERTEX_REUSE_BLOCK_CNTL */
832    unsigned pa_cl_vs_out_cntl;
833    unsigned ge_cntl;
834 };
835 
836 struct si_shader_part {
837    struct si_shader_part *next;
838    union si_shader_part_key key;
839    struct si_shader_binary binary;
840    struct ac_shader_config config;
841 };
842 
843 /* si_shader.c */
844 bool si_compile_shader(struct si_screen *sscreen, struct ac_llvm_compiler *compiler,
845                        struct si_shader *shader, struct pipe_debug_callback *debug);
846 bool si_create_shader_variant(struct si_screen *sscreen, struct ac_llvm_compiler *compiler,
847                               struct si_shader *shader, struct pipe_debug_callback *debug);
848 void si_shader_destroy(struct si_shader *shader);
849 unsigned si_shader_io_get_unique_index_patch(unsigned semantic_name, unsigned index);
850 unsigned si_shader_io_get_unique_index(unsigned semantic_name, unsigned index, unsigned is_varying);
851 bool si_shader_binary_upload(struct si_screen *sscreen, struct si_shader *shader,
852                              uint64_t scratch_va);
853 void si_shader_dump(struct si_screen *sscreen, struct si_shader *shader,
854                     struct pipe_debug_callback *debug, FILE *f, bool check_debug_option);
855 void si_shader_dump_stats_for_shader_db(struct si_screen *screen, struct si_shader *shader,
856                                         struct pipe_debug_callback *debug);
857 void si_multiwave_lds_size_workaround(struct si_screen *sscreen, unsigned *lds_size);
858 const char *si_get_shader_name(const struct si_shader *shader);
859 void si_shader_binary_clean(struct si_shader_binary *binary);
860 
861 /* si_shader_llvm_gs.c */
862 struct si_shader *si_generate_gs_copy_shader(struct si_screen *sscreen,
863                                              struct ac_llvm_compiler *compiler,
864                                              struct si_shader_selector *gs_selector,
865                                              struct pipe_debug_callback *debug);
866 
867 /* si_shader_nir.c */
868 void si_nir_scan_shader(const struct nir_shader *nir, struct si_shader_info *info);
869 void si_nir_adjust_driver_locations(struct nir_shader *nir);
870 void si_finalize_nir(struct pipe_screen *screen, void *nirptr, bool optimize);
871 
872 /* si_state_shaders.c */
873 void gfx9_get_gs_info(struct si_shader_selector *es, struct si_shader_selector *gs,
874                       struct gfx9_gs_info *out);
875 
876 /* Inline helpers. */
877 
878 /* Return the pointer to the main shader part's pointer. */
si_get_main_shader_part(struct si_shader_selector * sel,struct si_shader_key * key)879 static inline struct si_shader **si_get_main_shader_part(struct si_shader_selector *sel,
880                                                          struct si_shader_key *key)
881 {
882    if (key->as_ls)
883       return &sel->main_shader_part_ls;
884    if (key->as_es && key->as_ngg)
885       return &sel->main_shader_part_ngg_es;
886    if (key->as_es)
887       return &sel->main_shader_part_es;
888    if (key->as_ngg)
889       return &sel->main_shader_part_ngg;
890    return &sel->main_shader_part;
891 }
892 
gfx10_is_ngg_passthrough(struct si_shader * shader)893 static inline bool gfx10_is_ngg_passthrough(struct si_shader *shader)
894 {
895    struct si_shader_selector *sel = shader->selector;
896 
897    return sel->type != PIPE_SHADER_GEOMETRY && !sel->so.num_outputs && !sel->info.writes_edgeflag &&
898           !shader->key.opt.ngg_culling &&
899           (sel->type != PIPE_SHADER_VERTEX || !shader->key.mono.u.vs_export_prim_id);
900 }
901 
si_shader_uses_bindless_samplers(struct si_shader_selector * selector)902 static inline bool si_shader_uses_bindless_samplers(struct si_shader_selector *selector)
903 {
904    return selector ? selector->info.uses_bindless_samplers : false;
905 }
906 
si_shader_uses_bindless_images(struct si_shader_selector * selector)907 static inline bool si_shader_uses_bindless_images(struct si_shader_selector *selector)
908 {
909    return selector ? selector->info.uses_bindless_images : false;
910 }
911 
912 #endif
913