• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2016 Red Hat.
3  * Copyright © 2016 Bas Nieuwenhuizen
4  *
5  * based in part on anv driver which is:
6  * Copyright © 2015 Intel Corporation
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice (including the next
16  * paragraph) shall be included in all copies or substantial portions of the
17  * Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
22  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
25  * IN THE SOFTWARE.
26  */
27 
28 #include "meta/radv_meta.h"
29 #include "nir/nir.h"
30 #include "nir/nir_builder.h"
31 #include "nir/nir_serialize.h"
32 #include "nir/radv_nir.h"
33 #include "spirv/nir_spirv.h"
34 #include "util/disk_cache.h"
35 #include "util/mesa-sha1.h"
36 #include "util/os_time.h"
37 #include "util/u_atomic.h"
38 #include "radv_cs.h"
39 #include "radv_debug.h"
40 #include "radv_private.h"
41 #include "radv_shader.h"
42 #include "radv_shader_args.h"
43 #include "vk_nir_convert_ycbcr.h"
44 #include "vk_pipeline.h"
45 #include "vk_render_pass.h"
46 #include "vk_util.h"
47 
48 #include "util/u_debug.h"
49 #include "ac_binary.h"
50 #include "ac_nir.h"
51 #include "ac_shader_util.h"
52 #include "aco_interface.h"
53 #include "sid.h"
54 #include "vk_format.h"
55 
56 struct radv_blend_state {
57    uint32_t spi_shader_col_format;
58    uint32_t cb_shader_mask;
59 };
60 
61 static bool
radv_is_static_vrs_enabled(const struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state)62 radv_is_static_vrs_enabled(const struct radv_graphics_pipeline *pipeline,
63                            const struct vk_graphics_pipeline_state *state)
64 {
65    if (!state->fsr)
66       return false;
67 
68    return state->fsr->fragment_size.width != 1 || state->fsr->fragment_size.height != 1 ||
69           state->fsr->combiner_ops[0] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR ||
70           state->fsr->combiner_ops[1] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR;
71 }
72 
73 static bool
radv_is_vrs_enabled(const struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state)74 radv_is_vrs_enabled(const struct radv_graphics_pipeline *pipeline, const struct vk_graphics_pipeline_state *state)
75 {
76    return radv_is_static_vrs_enabled(pipeline, state) ||
77           (pipeline->dynamic_states & RADV_DYNAMIC_FRAGMENT_SHADING_RATE);
78 }
79 
80 static bool
radv_pipeline_has_ds_attachments(const struct vk_render_pass_state * rp)81 radv_pipeline_has_ds_attachments(const struct vk_render_pass_state *rp)
82 {
83    return rp->depth_attachment_format != VK_FORMAT_UNDEFINED || rp->stencil_attachment_format != VK_FORMAT_UNDEFINED;
84 }
85 
86 static bool
radv_pipeline_has_color_attachments(const struct vk_render_pass_state * rp)87 radv_pipeline_has_color_attachments(const struct vk_render_pass_state *rp)
88 {
89    for (uint32_t i = 0; i < rp->color_attachment_count; ++i) {
90       if (rp->color_attachment_formats[i] != VK_FORMAT_UNDEFINED)
91          return true;
92    }
93 
94    return false;
95 }
96 
97 bool
radv_pipeline_has_ngg(const struct radv_graphics_pipeline * pipeline)98 radv_pipeline_has_ngg(const struct radv_graphics_pipeline *pipeline)
99 {
100    struct radv_shader *shader = pipeline->base.shaders[pipeline->last_vgt_api_stage];
101 
102    return shader->info.is_ngg;
103 }
104 
105 bool
radv_pipeline_has_ngg_passthrough(const struct radv_graphics_pipeline * pipeline)106 radv_pipeline_has_ngg_passthrough(const struct radv_graphics_pipeline *pipeline)
107 {
108    assert(radv_pipeline_has_ngg(pipeline));
109 
110    struct radv_shader *shader = pipeline->base.shaders[pipeline->last_vgt_api_stage];
111 
112    return shader->info.is_ngg_passthrough;
113 }
114 
115 bool
radv_pipeline_has_gs_copy_shader(const struct radv_pipeline * pipeline)116 radv_pipeline_has_gs_copy_shader(const struct radv_pipeline *pipeline)
117 {
118    return !!pipeline->gs_copy_shader;
119 }
120 
121 /**
122  * Get rid of DST in the blend factors by commuting the operands:
123  *    func(src * DST, dst * 0) ---> func(src * 0, dst * SRC)
124  */
125 void
radv_blend_remove_dst(VkBlendOp * func,VkBlendFactor * src_factor,VkBlendFactor * dst_factor,VkBlendFactor expected_dst,VkBlendFactor replacement_src)126 radv_blend_remove_dst(VkBlendOp *func, VkBlendFactor *src_factor, VkBlendFactor *dst_factor, VkBlendFactor expected_dst,
127                       VkBlendFactor replacement_src)
128 {
129    if (*src_factor == expected_dst && *dst_factor == VK_BLEND_FACTOR_ZERO) {
130       *src_factor = VK_BLEND_FACTOR_ZERO;
131       *dst_factor = replacement_src;
132 
133       /* Commuting the operands requires reversing subtractions. */
134       if (*func == VK_BLEND_OP_SUBTRACT)
135          *func = VK_BLEND_OP_REVERSE_SUBTRACT;
136       else if (*func == VK_BLEND_OP_REVERSE_SUBTRACT)
137          *func = VK_BLEND_OP_SUBTRACT;
138    }
139 }
140 
141 static unsigned
radv_choose_spi_color_format(const struct radv_device * device,VkFormat vk_format,bool blend_enable,bool blend_need_alpha)142 radv_choose_spi_color_format(const struct radv_device *device, VkFormat vk_format, bool blend_enable,
143                              bool blend_need_alpha)
144 {
145    const struct util_format_description *desc = vk_format_description(vk_format);
146    bool use_rbplus = device->physical_device->rad_info.rbplus_allowed;
147    struct ac_spi_color_formats formats = {0};
148    unsigned format, ntype, swap;
149 
150    format = ac_get_cb_format(device->physical_device->rad_info.gfx_level, desc->format);
151    ntype = ac_get_cb_number_type(desc->format);
152    swap = radv_translate_colorswap(vk_format, false);
153 
154    ac_choose_spi_color_formats(format, swap, ntype, false, use_rbplus, &formats);
155 
156    if (blend_enable && blend_need_alpha)
157       return formats.blend_alpha;
158    else if (blend_need_alpha)
159       return formats.alpha;
160    else if (blend_enable)
161       return formats.blend;
162    else
163       return formats.normal;
164 }
165 
166 static bool
format_is_int8(VkFormat format)167 format_is_int8(VkFormat format)
168 {
169    const struct util_format_description *desc = vk_format_description(format);
170    int channel = vk_format_get_first_non_void_channel(format);
171 
172    return channel >= 0 && desc->channel[channel].pure_integer && desc->channel[channel].size == 8;
173 }
174 
175 static bool
format_is_int10(VkFormat format)176 format_is_int10(VkFormat format)
177 {
178    const struct util_format_description *desc = vk_format_description(format);
179 
180    if (desc->nr_channels != 4)
181       return false;
182    for (unsigned i = 0; i < 4; i++) {
183       if (desc->channel[i].pure_integer && desc->channel[i].size == 10)
184          return true;
185    }
186    return false;
187 }
188 
189 static bool
format_is_float32(VkFormat format)190 format_is_float32(VkFormat format)
191 {
192    const struct util_format_description *desc = vk_format_description(format);
193    int channel = vk_format_get_first_non_void_channel(format);
194 
195    return channel >= 0 && desc->channel[channel].type == UTIL_FORMAT_TYPE_FLOAT && desc->channel[channel].size == 32;
196 }
197 
198 unsigned
radv_compact_spi_shader_col_format(const struct radv_shader * ps,uint32_t spi_shader_col_format)199 radv_compact_spi_shader_col_format(const struct radv_shader *ps, uint32_t spi_shader_col_format)
200 {
201    unsigned value = 0, num_mrts = 0;
202    unsigned i, num_targets;
203 
204    /* Make sure to clear color attachments without exports because MRT holes are removed during
205     * compilation for optimal performance.
206     */
207    spi_shader_col_format &= ps->info.ps.colors_written;
208 
209    /* Compute the number of MRTs. */
210    num_targets = DIV_ROUND_UP(util_last_bit(spi_shader_col_format), 4);
211 
212    /* Remove holes in spi_shader_col_format. */
213    for (i = 0; i < num_targets; i++) {
214       unsigned spi_format = (spi_shader_col_format >> (i * 4)) & 0xf;
215 
216       if (spi_format) {
217          value |= spi_format << (num_mrts * 4);
218          num_mrts++;
219       }
220    }
221 
222    return value;
223 }
224 
225 /*
226  * Ordered so that for each i,
227  * radv_format_meta_fs_key(radv_fs_key_format_exemplars[i]) == i.
228  */
229 const VkFormat radv_fs_key_format_exemplars[NUM_META_FS_KEYS] = {
230    VK_FORMAT_R32_SFLOAT,         VK_FORMAT_R32G32_SFLOAT,           VK_FORMAT_R8G8B8A8_UNORM,
231    VK_FORMAT_R16G16B16A16_UNORM, VK_FORMAT_R16G16B16A16_SNORM,      VK_FORMAT_R16G16B16A16_UINT,
232    VK_FORMAT_R16G16B16A16_SINT,  VK_FORMAT_R32G32B32A32_SFLOAT,     VK_FORMAT_R8G8B8A8_UINT,
233    VK_FORMAT_R8G8B8A8_SINT,      VK_FORMAT_A2R10G10B10_UINT_PACK32, VK_FORMAT_A2R10G10B10_SINT_PACK32,
234 };
235 
236 unsigned
radv_format_meta_fs_key(struct radv_device * device,VkFormat format)237 radv_format_meta_fs_key(struct radv_device *device, VkFormat format)
238 {
239    unsigned col_format = radv_choose_spi_color_format(device, format, false, false);
240    assert(col_format != V_028714_SPI_SHADER_32_AR);
241 
242    bool is_int8 = format_is_int8(format);
243    bool is_int10 = format_is_int10(format);
244 
245    if (col_format == V_028714_SPI_SHADER_UINT16_ABGR && is_int8)
246       return 8;
247    else if (col_format == V_028714_SPI_SHADER_SINT16_ABGR && is_int8)
248       return 9;
249    else if (col_format == V_028714_SPI_SHADER_UINT16_ABGR && is_int10)
250       return 10;
251    else if (col_format == V_028714_SPI_SHADER_SINT16_ABGR && is_int10)
252       return 11;
253    else {
254       if (col_format >= V_028714_SPI_SHADER_32_AR)
255          --col_format; /* Skip V_028714_SPI_SHADER_32_AR  since there is no such VkFormat */
256 
257       --col_format; /* Skip V_028714_SPI_SHADER_ZERO */
258       return col_format;
259    }
260 }
261 
262 static bool
radv_pipeline_needs_ps_epilog(const struct radv_graphics_pipeline * pipeline,VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)263 radv_pipeline_needs_ps_epilog(const struct radv_graphics_pipeline *pipeline,
264                               VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)
265 {
266    /* Use a PS epilog when the fragment shader is compiled without the fragment output interface. */
267    if ((pipeline->active_stages & VK_SHADER_STAGE_FRAGMENT_BIT) &&
268        (lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT) &&
269        !(lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_OUTPUT_INTERFACE_BIT_EXT))
270       return true;
271 
272    /* These dynamic states need to compile PS epilogs on-demand. */
273    if (pipeline->dynamic_states & (RADV_DYNAMIC_COLOR_BLEND_ENABLE | RADV_DYNAMIC_COLOR_WRITE_MASK |
274                                    RADV_DYNAMIC_ALPHA_TO_COVERAGE_ENABLE | RADV_DYNAMIC_COLOR_BLEND_EQUATION))
275       return true;
276 
277    return false;
278 }
279 
280 static struct radv_blend_state
radv_pipeline_init_blend_state(struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state,VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)281 radv_pipeline_init_blend_state(struct radv_graphics_pipeline *pipeline, const struct vk_graphics_pipeline_state *state,
282                                VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)
283 {
284    const struct radv_shader *ps = pipeline->base.shaders[MESA_SHADER_FRAGMENT];
285    struct radv_blend_state blend = {0};
286    unsigned spi_shader_col_format = 0;
287 
288    if (radv_pipeline_needs_ps_epilog(pipeline, lib_flags))
289       return blend;
290 
291    if (ps) {
292       spi_shader_col_format = ps->info.ps.spi_shader_col_format;
293    }
294 
295    blend.cb_shader_mask = ac_get_cb_shader_mask(spi_shader_col_format);
296    blend.spi_shader_col_format = spi_shader_col_format;
297 
298    return blend;
299 }
300 
301 static bool
radv_pipeline_uses_vrs_attachment(const struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state)302 radv_pipeline_uses_vrs_attachment(const struct radv_graphics_pipeline *pipeline,
303                                   const struct vk_graphics_pipeline_state *state)
304 {
305    VkPipelineCreateFlags2KHR create_flags = pipeline->base.create_flags;
306    if (state->rp)
307       create_flags |= state->pipeline_flags;
308 
309    return (create_flags & VK_PIPELINE_CREATE_2_RENDERING_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR) != 0;
310 }
311 
312 static void
radv_pipeline_init_multisample_state(const struct radv_device * device,struct radv_graphics_pipeline * pipeline,const VkGraphicsPipelineCreateInfo * pCreateInfo,const struct vk_graphics_pipeline_state * state)313 radv_pipeline_init_multisample_state(const struct radv_device *device, struct radv_graphics_pipeline *pipeline,
314                                      const VkGraphicsPipelineCreateInfo *pCreateInfo,
315                                      const struct vk_graphics_pipeline_state *state)
316 {
317    struct radv_multisample_state *ms = &pipeline->ms;
318 
319    /* From the Vulkan 1.1.129 spec, 26.7. Sample Shading:
320     *
321     * "Sample shading is enabled for a graphics pipeline:
322     *
323     * - If the interface of the fragment shader entry point of the
324     *   graphics pipeline includes an input variable decorated
325     *   with SampleId or SamplePosition. In this case
326     *   minSampleShadingFactor takes the value 1.0.
327     * - Else if the sampleShadingEnable member of the
328     *   VkPipelineMultisampleStateCreateInfo structure specified
329     *   when creating the graphics pipeline is set to VK_TRUE. In
330     *   this case minSampleShadingFactor takes the value of
331     *   VkPipelineMultisampleStateCreateInfo::minSampleShading.
332     *
333     * Otherwise, sample shading is considered disabled."
334     */
335    if (state->ms && state->ms->sample_shading_enable) {
336       ms->sample_shading_enable = true;
337       ms->min_sample_shading = state->ms->min_sample_shading;
338    }
339 }
340 
341 static uint32_t
radv_conv_tess_prim_to_gs_out(enum tess_primitive_mode prim)342 radv_conv_tess_prim_to_gs_out(enum tess_primitive_mode prim)
343 {
344    switch (prim) {
345    case TESS_PRIMITIVE_TRIANGLES:
346    case TESS_PRIMITIVE_QUADS:
347       return V_028A6C_TRISTRIP;
348    case TESS_PRIMITIVE_ISOLINES:
349       return V_028A6C_LINESTRIP;
350    default:
351       assert(0);
352       return 0;
353    }
354 }
355 
356 static uint32_t
radv_conv_gl_prim_to_gs_out(unsigned gl_prim)357 radv_conv_gl_prim_to_gs_out(unsigned gl_prim)
358 {
359    switch (gl_prim) {
360    case MESA_PRIM_POINTS:
361       return V_028A6C_POINTLIST;
362    case MESA_PRIM_LINES:
363    case MESA_PRIM_LINE_STRIP:
364    case MESA_PRIM_LINES_ADJACENCY:
365       return V_028A6C_LINESTRIP;
366 
367    case MESA_PRIM_TRIANGLES:
368    case MESA_PRIM_TRIANGLE_STRIP_ADJACENCY:
369    case MESA_PRIM_TRIANGLE_STRIP:
370    case MESA_PRIM_QUADS:
371       return V_028A6C_TRISTRIP;
372    default:
373       assert(0);
374       return 0;
375    }
376 }
377 
378 static uint64_t
radv_dynamic_state_mask(VkDynamicState state)379 radv_dynamic_state_mask(VkDynamicState state)
380 {
381    switch (state) {
382    case VK_DYNAMIC_STATE_VIEWPORT:
383    case VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT:
384       return RADV_DYNAMIC_VIEWPORT;
385    case VK_DYNAMIC_STATE_SCISSOR:
386    case VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT:
387       return RADV_DYNAMIC_SCISSOR;
388    case VK_DYNAMIC_STATE_LINE_WIDTH:
389       return RADV_DYNAMIC_LINE_WIDTH;
390    case VK_DYNAMIC_STATE_DEPTH_BIAS:
391       return RADV_DYNAMIC_DEPTH_BIAS;
392    case VK_DYNAMIC_STATE_BLEND_CONSTANTS:
393       return RADV_DYNAMIC_BLEND_CONSTANTS;
394    case VK_DYNAMIC_STATE_DEPTH_BOUNDS:
395       return RADV_DYNAMIC_DEPTH_BOUNDS;
396    case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK:
397       return RADV_DYNAMIC_STENCIL_COMPARE_MASK;
398    case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK:
399       return RADV_DYNAMIC_STENCIL_WRITE_MASK;
400    case VK_DYNAMIC_STATE_STENCIL_REFERENCE:
401       return RADV_DYNAMIC_STENCIL_REFERENCE;
402    case VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT:
403       return RADV_DYNAMIC_DISCARD_RECTANGLE;
404    case VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT:
405       return RADV_DYNAMIC_SAMPLE_LOCATIONS;
406    case VK_DYNAMIC_STATE_LINE_STIPPLE_KHR:
407       return RADV_DYNAMIC_LINE_STIPPLE;
408    case VK_DYNAMIC_STATE_CULL_MODE:
409       return RADV_DYNAMIC_CULL_MODE;
410    case VK_DYNAMIC_STATE_FRONT_FACE:
411       return RADV_DYNAMIC_FRONT_FACE;
412    case VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY:
413       return RADV_DYNAMIC_PRIMITIVE_TOPOLOGY;
414    case VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE:
415       return RADV_DYNAMIC_DEPTH_TEST_ENABLE;
416    case VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE:
417       return RADV_DYNAMIC_DEPTH_WRITE_ENABLE;
418    case VK_DYNAMIC_STATE_DEPTH_COMPARE_OP:
419       return RADV_DYNAMIC_DEPTH_COMPARE_OP;
420    case VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE:
421       return RADV_DYNAMIC_DEPTH_BOUNDS_TEST_ENABLE;
422    case VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE:
423       return RADV_DYNAMIC_STENCIL_TEST_ENABLE;
424    case VK_DYNAMIC_STATE_STENCIL_OP:
425       return RADV_DYNAMIC_STENCIL_OP;
426    case VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE:
427       return RADV_DYNAMIC_VERTEX_INPUT_BINDING_STRIDE;
428    case VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR:
429       return RADV_DYNAMIC_FRAGMENT_SHADING_RATE;
430    case VK_DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT:
431       return RADV_DYNAMIC_PATCH_CONTROL_POINTS;
432    case VK_DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE:
433       return RADV_DYNAMIC_RASTERIZER_DISCARD_ENABLE;
434    case VK_DYNAMIC_STATE_DEPTH_BIAS_ENABLE:
435       return RADV_DYNAMIC_DEPTH_BIAS_ENABLE;
436    case VK_DYNAMIC_STATE_LOGIC_OP_EXT:
437       return RADV_DYNAMIC_LOGIC_OP;
438    case VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE:
439       return RADV_DYNAMIC_PRIMITIVE_RESTART_ENABLE;
440    case VK_DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT:
441       return RADV_DYNAMIC_COLOR_WRITE_ENABLE;
442    case VK_DYNAMIC_STATE_VERTEX_INPUT_EXT:
443       return RADV_DYNAMIC_VERTEX_INPUT;
444    case VK_DYNAMIC_STATE_POLYGON_MODE_EXT:
445       return RADV_DYNAMIC_POLYGON_MODE;
446    case VK_DYNAMIC_STATE_TESSELLATION_DOMAIN_ORIGIN_EXT:
447       return RADV_DYNAMIC_TESS_DOMAIN_ORIGIN;
448    case VK_DYNAMIC_STATE_LOGIC_OP_ENABLE_EXT:
449       return RADV_DYNAMIC_LOGIC_OP_ENABLE;
450    case VK_DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT:
451       return RADV_DYNAMIC_LINE_STIPPLE_ENABLE;
452    case VK_DYNAMIC_STATE_ALPHA_TO_COVERAGE_ENABLE_EXT:
453       return RADV_DYNAMIC_ALPHA_TO_COVERAGE_ENABLE;
454    case VK_DYNAMIC_STATE_SAMPLE_MASK_EXT:
455       return RADV_DYNAMIC_SAMPLE_MASK;
456    case VK_DYNAMIC_STATE_DEPTH_CLIP_ENABLE_EXT:
457       return RADV_DYNAMIC_DEPTH_CLIP_ENABLE;
458    case VK_DYNAMIC_STATE_CONSERVATIVE_RASTERIZATION_MODE_EXT:
459       return RADV_DYNAMIC_CONSERVATIVE_RAST_MODE;
460    case VK_DYNAMIC_STATE_DEPTH_CLIP_NEGATIVE_ONE_TO_ONE_EXT:
461       return RADV_DYNAMIC_DEPTH_CLIP_NEGATIVE_ONE_TO_ONE;
462    case VK_DYNAMIC_STATE_PROVOKING_VERTEX_MODE_EXT:
463       return RADV_DYNAMIC_PROVOKING_VERTEX_MODE;
464    case VK_DYNAMIC_STATE_DEPTH_CLAMP_ENABLE_EXT:
465       return RADV_DYNAMIC_DEPTH_CLAMP_ENABLE;
466    case VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT:
467       return RADV_DYNAMIC_COLOR_WRITE_MASK;
468    case VK_DYNAMIC_STATE_COLOR_BLEND_ENABLE_EXT:
469       return RADV_DYNAMIC_COLOR_BLEND_ENABLE;
470    case VK_DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT:
471       return RADV_DYNAMIC_RASTERIZATION_SAMPLES;
472    case VK_DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT:
473       return RADV_DYNAMIC_LINE_RASTERIZATION_MODE;
474    case VK_DYNAMIC_STATE_COLOR_BLEND_EQUATION_EXT:
475       return RADV_DYNAMIC_COLOR_BLEND_EQUATION;
476    case VK_DYNAMIC_STATE_DISCARD_RECTANGLE_ENABLE_EXT:
477       return RADV_DYNAMIC_DISCARD_RECTANGLE_ENABLE;
478    case VK_DYNAMIC_STATE_DISCARD_RECTANGLE_MODE_EXT:
479       return RADV_DYNAMIC_DISCARD_RECTANGLE_MODE;
480    case VK_DYNAMIC_STATE_ATTACHMENT_FEEDBACK_LOOP_ENABLE_EXT:
481       return RADV_DYNAMIC_ATTACHMENT_FEEDBACK_LOOP_ENABLE;
482    case VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_ENABLE_EXT:
483       return RADV_DYNAMIC_SAMPLE_LOCATIONS_ENABLE;
484    default:
485       unreachable("Unhandled dynamic state");
486    }
487 }
488 
489 #define RADV_DYNAMIC_CB_STATES                                                                                         \
490    (RADV_DYNAMIC_LOGIC_OP_ENABLE | RADV_DYNAMIC_LOGIC_OP | RADV_DYNAMIC_COLOR_WRITE_ENABLE |                           \
491     RADV_DYNAMIC_COLOR_WRITE_MASK | RADV_DYNAMIC_COLOR_BLEND_ENABLE | RADV_DYNAMIC_COLOR_BLEND_EQUATION |              \
492     RADV_DYNAMIC_BLEND_CONSTANTS)
493 
494 static bool
radv_pipeline_is_blend_enabled(const struct radv_graphics_pipeline * pipeline,const struct vk_color_blend_state * cb)495 radv_pipeline_is_blend_enabled(const struct radv_graphics_pipeline *pipeline, const struct vk_color_blend_state *cb)
496 {
497    /* If we don't know then we have to assume that blend may be enabled. cb may also be NULL in this
498     * case.
499     */
500    if (pipeline->dynamic_states & (RADV_DYNAMIC_COLOR_BLEND_ENABLE | RADV_DYNAMIC_COLOR_WRITE_MASK))
501       return true;
502 
503    /* If we have the blend enable state, then cb being NULL indicates no attachments are written. */
504    if (cb) {
505       for (uint32_t i = 0; i < cb->attachment_count; i++) {
506          if (cb->attachments[i].write_mask && cb->attachments[i].blend_enable)
507             return true;
508       }
509    }
510 
511    return false;
512 }
513 
514 static uint64_t
radv_pipeline_needed_dynamic_state(const struct radv_device * device,const struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state)515 radv_pipeline_needed_dynamic_state(const struct radv_device *device, const struct radv_graphics_pipeline *pipeline,
516                                    const struct vk_graphics_pipeline_state *state)
517 {
518    bool has_color_att = radv_pipeline_has_color_attachments(state->rp);
519    bool raster_enabled =
520       !state->rs->rasterizer_discard_enable || (pipeline->dynamic_states & RADV_DYNAMIC_RASTERIZER_DISCARD_ENABLE);
521    uint64_t states = RADV_DYNAMIC_ALL;
522 
523    if (device->physical_device->rad_info.gfx_level < GFX10_3)
524       states &= ~RADV_DYNAMIC_FRAGMENT_SHADING_RATE;
525 
526    /* Disable dynamic states that are useless to mesh shading. */
527    if (radv_pipeline_has_stage(pipeline, MESA_SHADER_MESH)) {
528       if (!raster_enabled)
529          return RADV_DYNAMIC_RASTERIZER_DISCARD_ENABLE;
530 
531       states &= ~(RADV_DYNAMIC_VERTEX_INPUT | RADV_DYNAMIC_VERTEX_INPUT_BINDING_STRIDE |
532                   RADV_DYNAMIC_PRIMITIVE_RESTART_ENABLE | RADV_DYNAMIC_PRIMITIVE_TOPOLOGY);
533    }
534 
535    /* Disable dynamic states that are useless when rasterization is disabled. */
536    if (!raster_enabled) {
537       states = RADV_DYNAMIC_PRIMITIVE_TOPOLOGY | RADV_DYNAMIC_VERTEX_INPUT_BINDING_STRIDE |
538                RADV_DYNAMIC_PRIMITIVE_RESTART_ENABLE | RADV_DYNAMIC_RASTERIZER_DISCARD_ENABLE |
539                RADV_DYNAMIC_VERTEX_INPUT;
540 
541       if (pipeline->active_stages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT)
542          states |= RADV_DYNAMIC_PATCH_CONTROL_POINTS | RADV_DYNAMIC_TESS_DOMAIN_ORIGIN;
543 
544       return states;
545    }
546 
547    if (!state->rs->depth_bias.enable && !(pipeline->dynamic_states & RADV_DYNAMIC_DEPTH_BIAS_ENABLE))
548       states &= ~RADV_DYNAMIC_DEPTH_BIAS;
549 
550    if (!(pipeline->dynamic_states & RADV_DYNAMIC_DEPTH_BOUNDS_TEST_ENABLE) &&
551        (!state->ds || !state->ds->depth.bounds_test.enable))
552       states &= ~RADV_DYNAMIC_DEPTH_BOUNDS;
553 
554    if (!(pipeline->dynamic_states & RADV_DYNAMIC_STENCIL_TEST_ENABLE) &&
555        (!state->ds || !state->ds->stencil.test_enable))
556       states &= ~(RADV_DYNAMIC_STENCIL_COMPARE_MASK | RADV_DYNAMIC_STENCIL_WRITE_MASK | RADV_DYNAMIC_STENCIL_REFERENCE |
557                   RADV_DYNAMIC_STENCIL_OP);
558 
559    if (!(pipeline->dynamic_states & RADV_DYNAMIC_DISCARD_RECTANGLE_ENABLE) && !state->dr->rectangle_count)
560       states &= ~RADV_DYNAMIC_DISCARD_RECTANGLE;
561 
562    if (!(pipeline->dynamic_states & RADV_DYNAMIC_SAMPLE_LOCATIONS_ENABLE) &&
563        (!state->ms || !state->ms->sample_locations_enable))
564       states &= ~RADV_DYNAMIC_SAMPLE_LOCATIONS;
565 
566    if (!has_color_att || !radv_pipeline_is_blend_enabled(pipeline, state->cb))
567       states &= ~RADV_DYNAMIC_BLEND_CONSTANTS;
568 
569    if (!(pipeline->active_stages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT))
570       states &= ~(RADV_DYNAMIC_PATCH_CONTROL_POINTS | RADV_DYNAMIC_TESS_DOMAIN_ORIGIN);
571 
572    return states;
573 }
574 
575 struct radv_ia_multi_vgt_param_helpers
radv_compute_ia_multi_vgt_param(const struct radv_device * device,struct radv_shader * const * shaders)576 radv_compute_ia_multi_vgt_param(const struct radv_device *device, struct radv_shader *const *shaders)
577 {
578    const struct radv_physical_device *pdevice = device->physical_device;
579    struct radv_ia_multi_vgt_param_helpers ia_multi_vgt_param = {0};
580 
581    ia_multi_vgt_param.ia_switch_on_eoi = false;
582    if (shaders[MESA_SHADER_FRAGMENT] && shaders[MESA_SHADER_FRAGMENT]->info.ps.prim_id_input)
583       ia_multi_vgt_param.ia_switch_on_eoi = true;
584    if (shaders[MESA_SHADER_GEOMETRY] && shaders[MESA_SHADER_GEOMETRY]->info.uses_prim_id)
585       ia_multi_vgt_param.ia_switch_on_eoi = true;
586    if (shaders[MESA_SHADER_TESS_CTRL]) {
587       /* SWITCH_ON_EOI must be set if PrimID is used. */
588       if (shaders[MESA_SHADER_TESS_CTRL]->info.uses_prim_id ||
589           radv_get_shader(shaders, MESA_SHADER_TESS_EVAL)->info.uses_prim_id)
590          ia_multi_vgt_param.ia_switch_on_eoi = true;
591    }
592 
593    ia_multi_vgt_param.partial_vs_wave = false;
594    if (shaders[MESA_SHADER_TESS_CTRL]) {
595       /* Bug with tessellation and GS on Bonaire and older 2 SE chips. */
596       if ((pdevice->rad_info.family == CHIP_TAHITI || pdevice->rad_info.family == CHIP_PITCAIRN ||
597            pdevice->rad_info.family == CHIP_BONAIRE) &&
598           shaders[MESA_SHADER_GEOMETRY])
599          ia_multi_vgt_param.partial_vs_wave = true;
600       /* Needed for 028B6C_DISTRIBUTION_MODE != 0 */
601       if (pdevice->rad_info.has_distributed_tess) {
602          if (shaders[MESA_SHADER_GEOMETRY]) {
603             if (pdevice->rad_info.gfx_level <= GFX8)
604                ia_multi_vgt_param.partial_es_wave = true;
605          } else {
606             ia_multi_vgt_param.partial_vs_wave = true;
607          }
608       }
609    }
610 
611    if (shaders[MESA_SHADER_GEOMETRY]) {
612       /* On these chips there is the possibility of a hang if the
613        * pipeline uses a GS and partial_vs_wave is not set.
614        *
615        * This mostly does not hit 4-SE chips, as those typically set
616        * ia_switch_on_eoi and then partial_vs_wave is set for pipelines
617        * with GS due to another workaround.
618        *
619        * Reproducer: https://bugs.freedesktop.org/show_bug.cgi?id=109242
620        */
621       if (pdevice->rad_info.family == CHIP_TONGA || pdevice->rad_info.family == CHIP_FIJI ||
622           pdevice->rad_info.family == CHIP_POLARIS10 || pdevice->rad_info.family == CHIP_POLARIS11 ||
623           pdevice->rad_info.family == CHIP_POLARIS12 || pdevice->rad_info.family == CHIP_VEGAM) {
624          ia_multi_vgt_param.partial_vs_wave = true;
625       }
626    }
627 
628    ia_multi_vgt_param.base =
629       /* The following field was moved to VGT_SHADER_STAGES_EN in GFX9. */
630       S_028AA8_MAX_PRIMGRP_IN_WAVE(pdevice->rad_info.gfx_level == GFX8 ? 2 : 0) |
631       S_030960_EN_INST_OPT_BASIC(pdevice->rad_info.gfx_level >= GFX9) |
632       S_030960_EN_INST_OPT_ADV(pdevice->rad_info.gfx_level >= GFX9);
633 
634    return ia_multi_vgt_param;
635 }
636 
637 static uint32_t
radv_get_attrib_stride(const VkPipelineVertexInputStateCreateInfo * vi,uint32_t attrib_binding)638 radv_get_attrib_stride(const VkPipelineVertexInputStateCreateInfo *vi, uint32_t attrib_binding)
639 {
640    for (uint32_t i = 0; i < vi->vertexBindingDescriptionCount; i++) {
641       const VkVertexInputBindingDescription *input_binding = &vi->pVertexBindingDescriptions[i];
642 
643       if (input_binding->binding == attrib_binding)
644          return input_binding->stride;
645    }
646 
647    return 0;
648 }
649 
650 #define ALL_GRAPHICS_LIB_FLAGS                                                                                         \
651    (VK_GRAPHICS_PIPELINE_LIBRARY_VERTEX_INPUT_INTERFACE_BIT_EXT |                                                      \
652     VK_GRAPHICS_PIPELINE_LIBRARY_PRE_RASTERIZATION_SHADERS_BIT_EXT |                                                   \
653     VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT |                                                             \
654     VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_OUTPUT_INTERFACE_BIT_EXT)
655 
656 static VkGraphicsPipelineLibraryFlagBitsEXT
shader_stage_to_pipeline_library_flags(VkShaderStageFlagBits stage)657 shader_stage_to_pipeline_library_flags(VkShaderStageFlagBits stage)
658 {
659    assert(util_bitcount(stage) == 1);
660    switch (stage) {
661    case VK_SHADER_STAGE_VERTEX_BIT:
662    case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
663    case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
664    case VK_SHADER_STAGE_GEOMETRY_BIT:
665    case VK_SHADER_STAGE_TASK_BIT_EXT:
666    case VK_SHADER_STAGE_MESH_BIT_EXT:
667       return VK_GRAPHICS_PIPELINE_LIBRARY_PRE_RASTERIZATION_SHADERS_BIT_EXT;
668    case VK_SHADER_STAGE_FRAGMENT_BIT:
669       return VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT;
670    default:
671       unreachable("Invalid shader stage");
672    }
673 }
674 
675 static VkResult
radv_pipeline_import_graphics_info(struct radv_device * device,struct radv_graphics_pipeline * pipeline,struct vk_graphics_pipeline_state * state,struct radv_pipeline_layout * layout,const VkGraphicsPipelineCreateInfo * pCreateInfo,VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)676 radv_pipeline_import_graphics_info(struct radv_device *device, struct radv_graphics_pipeline *pipeline,
677                                    struct vk_graphics_pipeline_state *state, struct radv_pipeline_layout *layout,
678                                    const VkGraphicsPipelineCreateInfo *pCreateInfo,
679                                    VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)
680 {
681    RADV_FROM_HANDLE(radv_pipeline_layout, pipeline_layout, pCreateInfo->layout);
682    VkResult result;
683 
684    /* Mark all states declared dynamic at pipeline creation. */
685    if (pCreateInfo->pDynamicState) {
686       uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
687       for (uint32_t s = 0; s < count; s++) {
688          pipeline->dynamic_states |= radv_dynamic_state_mask(pCreateInfo->pDynamicState->pDynamicStates[s]);
689       }
690    }
691 
692    /* Mark all active stages at pipeline creation. */
693    for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
694       const VkPipelineShaderStageCreateInfo *sinfo = &pCreateInfo->pStages[i];
695 
696       /* Ignore shader stages that don't need to be imported. */
697       if (!(shader_stage_to_pipeline_library_flags(sinfo->stage) & lib_flags))
698          continue;
699 
700       pipeline->active_stages |= sinfo->stage;
701    }
702 
703    result = vk_graphics_pipeline_state_fill(&device->vk, state, pCreateInfo, NULL, 0, NULL, NULL,
704                                             VK_SYSTEM_ALLOCATION_SCOPE_OBJECT, &pipeline->state_data);
705    if (result != VK_SUCCESS)
706       return result;
707 
708    if (pipeline->active_stages & VK_SHADER_STAGE_MESH_BIT_EXT) {
709       pipeline->last_vgt_api_stage = MESA_SHADER_MESH;
710    } else {
711       pipeline->last_vgt_api_stage = util_last_bit(pipeline->active_stages & BITFIELD_MASK(MESA_SHADER_FRAGMENT)) - 1;
712    }
713 
714    if (lib_flags == ALL_GRAPHICS_LIB_FLAGS) {
715       radv_pipeline_layout_finish(device, layout);
716       radv_pipeline_layout_init(device, layout, false /* independent_sets */);
717    }
718 
719    if (pipeline_layout) {
720       /* As explained in the specification, the application can provide a non
721        * compatible pipeline layout when doing optimized linking :
722        *
723        *    "However, in the specific case that a final link is being
724        *     performed between stages and
725        *     `VK_PIPELINE_CREATE_2_LINK_TIME_OPTIMIZATION_BIT_EXT` is specified,
726        *     the application can override the pipeline layout with one that is
727        *     compatible with that union but does not have the
728        *     `VK_PIPELINE_LAYOUT_CREATE_INDEPENDENT_SETS_BIT_EXT` flag set,
729        *     allowing a more optimal pipeline layout to be used when
730        *     generating the final pipeline."
731        *
732        * In that case discard whatever was imported before.
733        */
734       if (pipeline->base.create_flags & VK_PIPELINE_CREATE_2_LINK_TIME_OPTIMIZATION_BIT_EXT &&
735           !pipeline_layout->independent_sets) {
736          radv_pipeline_layout_finish(device, layout);
737          radv_pipeline_layout_init(device, layout, false /* independent_sets */);
738       } else {
739          /* Otherwise if we include a layout that had independent_sets,
740           * propagate that property.
741           */
742          layout->independent_sets |= pipeline_layout->independent_sets;
743       }
744 
745       for (uint32_t s = 0; s < pipeline_layout->num_sets; s++) {
746          if (pipeline_layout->set[s].layout == NULL)
747             continue;
748 
749          radv_pipeline_layout_add_set(layout, s, pipeline_layout->set[s].layout);
750       }
751 
752       layout->push_constant_size = pipeline_layout->push_constant_size;
753    }
754 
755    return result;
756 }
757 
758 static void
radv_graphics_pipeline_import_lib(const struct radv_device * device,struct radv_graphics_pipeline * pipeline,struct vk_graphics_pipeline_state * state,struct radv_pipeline_layout * layout,struct radv_graphics_lib_pipeline * lib,bool link_optimize)759 radv_graphics_pipeline_import_lib(const struct radv_device *device, struct radv_graphics_pipeline *pipeline,
760                                   struct vk_graphics_pipeline_state *state, struct radv_pipeline_layout *layout,
761                                   struct radv_graphics_lib_pipeline *lib, bool link_optimize)
762 {
763    bool import_binaries = false;
764 
765    /* There should be no common blocks between a lib we import and the current
766     * pipeline we're building.
767     */
768    assert((pipeline->active_stages & lib->base.active_stages) == 0);
769 
770    pipeline->dynamic_states |= lib->base.dynamic_states;
771    pipeline->active_stages |= lib->base.active_stages;
772 
773    vk_graphics_pipeline_state_merge(state, &lib->graphics_state);
774 
775    /* Import binaries when LTO is disabled and when the library doesn't retain any shaders. */
776    if (!link_optimize && !pipeline->retain_shaders) {
777       import_binaries = true;
778    }
779 
780    if (import_binaries) {
781       /* Import the compiled shaders. */
782       for (uint32_t s = 0; s < ARRAY_SIZE(lib->base.base.shaders); s++) {
783          if (!lib->base.base.shaders[s])
784             continue;
785 
786          pipeline->base.shaders[s] = radv_shader_ref(lib->base.base.shaders[s]);
787       }
788 
789       /* Import the GS copy shader if present. */
790       if (lib->base.base.gs_copy_shader) {
791          assert(!pipeline->base.gs_copy_shader);
792          pipeline->base.gs_copy_shader = radv_shader_ref(lib->base.base.gs_copy_shader);
793       }
794    }
795 
796    /* Import the pipeline layout. */
797    struct radv_pipeline_layout *lib_layout = &lib->layout;
798    for (uint32_t s = 0; s < lib_layout->num_sets; s++) {
799       if (!lib_layout->set[s].layout)
800          continue;
801 
802       radv_pipeline_layout_add_set(layout, s, lib_layout->set[s].layout);
803    }
804 
805    layout->independent_sets = lib_layout->independent_sets;
806    layout->push_constant_size = MAX2(layout->push_constant_size, lib_layout->push_constant_size);
807 }
808 
809 static void
radv_pipeline_init_input_assembly_state(const struct radv_device * device,struct radv_graphics_pipeline * pipeline)810 radv_pipeline_init_input_assembly_state(const struct radv_device *device, struct radv_graphics_pipeline *pipeline)
811 {
812    pipeline->ia_multi_vgt_param = radv_compute_ia_multi_vgt_param(device, pipeline->base.shaders);
813 }
814 
815 static bool
radv_pipeline_uses_ds_feedback_loop(const struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state)816 radv_pipeline_uses_ds_feedback_loop(const struct radv_graphics_pipeline *pipeline,
817                                     const struct vk_graphics_pipeline_state *state)
818 {
819    VkPipelineCreateFlags2KHR create_flags = pipeline->base.create_flags;
820    if (state->rp)
821       create_flags |= state->pipeline_flags;
822 
823    return (create_flags & VK_PIPELINE_CREATE_2_DEPTH_STENCIL_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT) != 0;
824 }
825 
826 static void
radv_pipeline_init_dynamic_state(const struct radv_device * device,struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state,const VkGraphicsPipelineCreateInfo * pCreateInfo)827 radv_pipeline_init_dynamic_state(const struct radv_device *device, struct radv_graphics_pipeline *pipeline,
828                                  const struct vk_graphics_pipeline_state *state,
829                                  const VkGraphicsPipelineCreateInfo *pCreateInfo)
830 {
831    uint64_t needed_states = radv_pipeline_needed_dynamic_state(device, pipeline, state);
832    struct radv_dynamic_state *dynamic = &pipeline->dynamic_state;
833    uint64_t states = needed_states;
834 
835    /* Initialize non-zero values for default dynamic state. */
836    dynamic->vk.rs.line.width = 1.0f;
837    dynamic->vk.fsr.fragment_size.width = 1u;
838    dynamic->vk.fsr.fragment_size.height = 1u;
839    dynamic->vk.ds.depth.bounds_test.max = 1.0f;
840    dynamic->vk.ds.stencil.front.compare_mask = ~0;
841    dynamic->vk.ds.stencil.front.write_mask = ~0;
842    dynamic->vk.ds.stencil.back.compare_mask = ~0;
843    dynamic->vk.ds.stencil.back.write_mask = ~0;
844    dynamic->vk.ms.rasterization_samples = VK_SAMPLE_COUNT_1_BIT;
845 
846    pipeline->needed_dynamic_state = needed_states;
847 
848    states &= ~pipeline->dynamic_states;
849 
850    /* Input assembly. */
851    if (states & RADV_DYNAMIC_PRIMITIVE_TOPOLOGY) {
852       dynamic->vk.ia.primitive_topology = radv_translate_prim(state->ia->primitive_topology);
853    }
854 
855    if (states & RADV_DYNAMIC_PRIMITIVE_RESTART_ENABLE) {
856       dynamic->vk.ia.primitive_restart_enable = state->ia->primitive_restart_enable;
857    }
858 
859    /* Tessellation. */
860    if (states & RADV_DYNAMIC_PATCH_CONTROL_POINTS) {
861       dynamic->vk.ts.patch_control_points = state->ts->patch_control_points;
862    }
863 
864    if (states & RADV_DYNAMIC_TESS_DOMAIN_ORIGIN) {
865       dynamic->vk.ts.domain_origin = state->ts->domain_origin;
866    }
867 
868    /* Viewport. */
869    if (needed_states & RADV_DYNAMIC_VIEWPORT) {
870       dynamic->vk.vp.viewport_count = state->vp->viewport_count;
871       if (states & RADV_DYNAMIC_VIEWPORT) {
872          typed_memcpy(dynamic->vk.vp.viewports, state->vp->viewports, state->vp->viewport_count);
873          for (unsigned i = 0; i < dynamic->vk.vp.viewport_count; i++)
874             radv_get_viewport_xform(&dynamic->vk.vp.viewports[i], dynamic->hw_vp.xform[i].scale,
875                                     dynamic->hw_vp.xform[i].translate);
876       }
877    }
878 
879    if (needed_states & RADV_DYNAMIC_SCISSOR) {
880       dynamic->vk.vp.scissor_count = state->vp->scissor_count;
881       if (states & RADV_DYNAMIC_SCISSOR) {
882          typed_memcpy(dynamic->vk.vp.scissors, state->vp->scissors, state->vp->scissor_count);
883       }
884    }
885 
886    if (states & RADV_DYNAMIC_DEPTH_CLIP_NEGATIVE_ONE_TO_ONE) {
887       dynamic->vk.vp.depth_clip_negative_one_to_one = state->vp->depth_clip_negative_one_to_one;
888    }
889 
890    /* Discard rectangles. */
891    if (needed_states & RADV_DYNAMIC_DISCARD_RECTANGLE) {
892       dynamic->vk.dr.rectangle_count = state->dr->rectangle_count;
893       if (states & RADV_DYNAMIC_DISCARD_RECTANGLE) {
894          typed_memcpy(dynamic->vk.dr.rectangles, state->dr->rectangles, state->dr->rectangle_count);
895       }
896    }
897 
898    /* Rasterization. */
899    if (states & RADV_DYNAMIC_LINE_WIDTH) {
900       dynamic->vk.rs.line.width = state->rs->line.width;
901    }
902 
903    if (states & RADV_DYNAMIC_DEPTH_BIAS) {
904       dynamic->vk.rs.depth_bias.constant = state->rs->depth_bias.constant;
905       dynamic->vk.rs.depth_bias.clamp = state->rs->depth_bias.clamp;
906       dynamic->vk.rs.depth_bias.slope = state->rs->depth_bias.slope;
907       dynamic->vk.rs.depth_bias.representation = state->rs->depth_bias.representation;
908    }
909 
910    if (states & RADV_DYNAMIC_CULL_MODE) {
911       dynamic->vk.rs.cull_mode = state->rs->cull_mode;
912    }
913 
914    if (states & RADV_DYNAMIC_FRONT_FACE) {
915       dynamic->vk.rs.front_face = state->rs->front_face;
916    }
917 
918    if (states & RADV_DYNAMIC_LINE_STIPPLE) {
919       dynamic->vk.rs.line.stipple.factor = state->rs->line.stipple.factor;
920       dynamic->vk.rs.line.stipple.pattern = state->rs->line.stipple.pattern;
921    }
922 
923    if (states & RADV_DYNAMIC_DEPTH_BIAS_ENABLE) {
924       dynamic->vk.rs.depth_bias.enable = state->rs->depth_bias.enable;
925    }
926 
927    if (states & RADV_DYNAMIC_RASTERIZER_DISCARD_ENABLE) {
928       dynamic->vk.rs.rasterizer_discard_enable = state->rs->rasterizer_discard_enable;
929    }
930 
931    if (states & RADV_DYNAMIC_POLYGON_MODE) {
932       dynamic->vk.rs.polygon_mode = radv_translate_fill(state->rs->polygon_mode);
933    }
934 
935    if (states & RADV_DYNAMIC_LINE_STIPPLE_ENABLE) {
936       dynamic->vk.rs.line.stipple.enable = state->rs->line.stipple.enable;
937    }
938 
939    if (states & RADV_DYNAMIC_DEPTH_CLIP_ENABLE) {
940       dynamic->vk.rs.depth_clip_enable = state->rs->depth_clip_enable;
941    }
942 
943    if (states & RADV_DYNAMIC_CONSERVATIVE_RAST_MODE) {
944       dynamic->vk.rs.conservative_mode = state->rs->conservative_mode;
945    }
946 
947    if (states & RADV_DYNAMIC_PROVOKING_VERTEX_MODE) {
948       dynamic->vk.rs.provoking_vertex = state->rs->provoking_vertex;
949    }
950 
951    if (states & RADV_DYNAMIC_DEPTH_CLAMP_ENABLE) {
952       dynamic->vk.rs.depth_clamp_enable = state->rs->depth_clamp_enable;
953    }
954 
955    if (states & RADV_DYNAMIC_LINE_RASTERIZATION_MODE) {
956       dynamic->vk.rs.line.mode = state->rs->line.mode;
957    }
958 
959    /* Fragment shading rate. */
960    if (states & RADV_DYNAMIC_FRAGMENT_SHADING_RATE) {
961       dynamic->vk.fsr = *state->fsr;
962    }
963 
964    /* Multisample. */
965    if (states & RADV_DYNAMIC_ALPHA_TO_COVERAGE_ENABLE) {
966       dynamic->vk.ms.alpha_to_coverage_enable = state->ms->alpha_to_coverage_enable;
967    }
968 
969    if (states & RADV_DYNAMIC_SAMPLE_MASK) {
970       dynamic->vk.ms.sample_mask = state->ms->sample_mask & 0xffff;
971    }
972 
973    if (states & RADV_DYNAMIC_RASTERIZATION_SAMPLES) {
974       dynamic->vk.ms.rasterization_samples = state->ms->rasterization_samples;
975    }
976 
977    if (states & RADV_DYNAMIC_SAMPLE_LOCATIONS_ENABLE) {
978       dynamic->vk.ms.sample_locations_enable = state->ms->sample_locations_enable;
979    }
980 
981    if (states & RADV_DYNAMIC_SAMPLE_LOCATIONS) {
982       unsigned count = state->ms->sample_locations->per_pixel * state->ms->sample_locations->grid_size.width *
983                        state->ms->sample_locations->grid_size.height;
984 
985       dynamic->sample_location.per_pixel = state->ms->sample_locations->per_pixel;
986       dynamic->sample_location.grid_size = state->ms->sample_locations->grid_size;
987       dynamic->sample_location.count = count;
988       typed_memcpy(&dynamic->sample_location.locations[0], state->ms->sample_locations->locations, count);
989    }
990 
991    /* Depth stencil. */
992    /* If there is no depthstencil attachment, then don't read
993     * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
994     * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
995     * no need to override the depthstencil defaults in
996     * radv_pipeline::dynamic_state when there is no depthstencil attachment.
997     *
998     * Section 9.2 of the Vulkan 1.0.15 spec says:
999     *
1000     *    pDepthStencilState is [...] NULL if the pipeline has rasterization
1001     *    disabled or if the subpass of the render pass the pipeline is created
1002     *    against does not use a depth/stencil attachment.
1003     */
1004    if (needed_states && radv_pipeline_has_ds_attachments(state->rp)) {
1005       if (states & RADV_DYNAMIC_DEPTH_BOUNDS) {
1006          dynamic->vk.ds.depth.bounds_test.min = state->ds->depth.bounds_test.min;
1007          dynamic->vk.ds.depth.bounds_test.max = state->ds->depth.bounds_test.max;
1008       }
1009 
1010       if (states & RADV_DYNAMIC_STENCIL_COMPARE_MASK) {
1011          dynamic->vk.ds.stencil.front.compare_mask = state->ds->stencil.front.compare_mask;
1012          dynamic->vk.ds.stencil.back.compare_mask = state->ds->stencil.back.compare_mask;
1013       }
1014 
1015       if (states & RADV_DYNAMIC_STENCIL_WRITE_MASK) {
1016          dynamic->vk.ds.stencil.front.write_mask = state->ds->stencil.front.write_mask;
1017          dynamic->vk.ds.stencil.back.write_mask = state->ds->stencil.back.write_mask;
1018       }
1019 
1020       if (states & RADV_DYNAMIC_STENCIL_REFERENCE) {
1021          dynamic->vk.ds.stencil.front.reference = state->ds->stencil.front.reference;
1022          dynamic->vk.ds.stencil.back.reference = state->ds->stencil.back.reference;
1023       }
1024 
1025       if (states & RADV_DYNAMIC_DEPTH_TEST_ENABLE) {
1026          dynamic->vk.ds.depth.test_enable = state->ds->depth.test_enable;
1027       }
1028 
1029       if (states & RADV_DYNAMIC_DEPTH_WRITE_ENABLE) {
1030          dynamic->vk.ds.depth.write_enable = state->ds->depth.write_enable;
1031       }
1032 
1033       if (states & RADV_DYNAMIC_DEPTH_COMPARE_OP) {
1034          dynamic->vk.ds.depth.compare_op = state->ds->depth.compare_op;
1035       }
1036 
1037       if (states & RADV_DYNAMIC_DEPTH_BOUNDS_TEST_ENABLE) {
1038          dynamic->vk.ds.depth.bounds_test.enable = state->ds->depth.bounds_test.enable;
1039       }
1040 
1041       if (states & RADV_DYNAMIC_STENCIL_TEST_ENABLE) {
1042          dynamic->vk.ds.stencil.test_enable = state->ds->stencil.test_enable;
1043       }
1044 
1045       if (states & RADV_DYNAMIC_STENCIL_OP) {
1046          dynamic->vk.ds.stencil.front.op.compare = state->ds->stencil.front.op.compare;
1047          dynamic->vk.ds.stencil.front.op.fail = state->ds->stencil.front.op.fail;
1048          dynamic->vk.ds.stencil.front.op.pass = state->ds->stencil.front.op.pass;
1049          dynamic->vk.ds.stencil.front.op.depth_fail = state->ds->stencil.front.op.depth_fail;
1050 
1051          dynamic->vk.ds.stencil.back.op.compare = state->ds->stencil.back.op.compare;
1052          dynamic->vk.ds.stencil.back.op.fail = state->ds->stencil.back.op.fail;
1053          dynamic->vk.ds.stencil.back.op.pass = state->ds->stencil.back.op.pass;
1054          dynamic->vk.ds.stencil.back.op.depth_fail = state->ds->stencil.back.op.depth_fail;
1055       }
1056    }
1057 
1058    /* Color blend. */
1059    /* Section 9.2 of the Vulkan 1.0.15 spec says:
1060     *
1061     *    pColorBlendState is [...] NULL if the pipeline has rasterization
1062     *    disabled or if the subpass of the render pass the pipeline is
1063     *    created against does not use any color attachments.
1064     */
1065    if (states & RADV_DYNAMIC_BLEND_CONSTANTS) {
1066       typed_memcpy(dynamic->vk.cb.blend_constants, state->cb->blend_constants, 4);
1067    }
1068 
1069    if (radv_pipeline_has_color_attachments(state->rp)) {
1070       if (states & RADV_DYNAMIC_LOGIC_OP) {
1071          if ((pipeline->dynamic_states & RADV_DYNAMIC_LOGIC_OP_ENABLE) || state->cb->logic_op_enable) {
1072             dynamic->vk.cb.logic_op = radv_translate_blend_logic_op(state->cb->logic_op);
1073          }
1074       }
1075 
1076       if (states & RADV_DYNAMIC_COLOR_WRITE_ENABLE) {
1077          dynamic->vk.cb.color_write_enables = state->cb->color_write_enables;
1078       }
1079 
1080       if (states & RADV_DYNAMIC_LOGIC_OP_ENABLE) {
1081          dynamic->vk.cb.logic_op_enable = state->cb->logic_op_enable;
1082       }
1083 
1084       if (states & RADV_DYNAMIC_COLOR_WRITE_MASK) {
1085          for (unsigned i = 0; i < state->cb->attachment_count; i++) {
1086             dynamic->vk.cb.attachments[i].write_mask = state->cb->attachments[i].write_mask;
1087          }
1088       }
1089 
1090       if (states & RADV_DYNAMIC_COLOR_BLEND_ENABLE) {
1091          for (unsigned i = 0; i < state->cb->attachment_count; i++) {
1092             dynamic->vk.cb.attachments[i].blend_enable = state->cb->attachments[i].blend_enable;
1093          }
1094       }
1095 
1096       if (states & RADV_DYNAMIC_COLOR_BLEND_EQUATION) {
1097          for (unsigned i = 0; i < state->cb->attachment_count; i++) {
1098             const struct vk_color_blend_attachment_state *att = &state->cb->attachments[i];
1099 
1100             dynamic->vk.cb.attachments[i].src_color_blend_factor = att->src_color_blend_factor;
1101             dynamic->vk.cb.attachments[i].dst_color_blend_factor = att->dst_color_blend_factor;
1102             dynamic->vk.cb.attachments[i].color_blend_op = att->color_blend_op;
1103             dynamic->vk.cb.attachments[i].src_alpha_blend_factor = att->src_alpha_blend_factor;
1104             dynamic->vk.cb.attachments[i].dst_alpha_blend_factor = att->dst_alpha_blend_factor;
1105             dynamic->vk.cb.attachments[i].alpha_blend_op = att->alpha_blend_op;
1106          }
1107       }
1108    }
1109 
1110    if (states & RADV_DYNAMIC_DISCARD_RECTANGLE_ENABLE) {
1111       dynamic->vk.dr.enable = state->dr->rectangle_count > 0;
1112    }
1113 
1114    if (states & RADV_DYNAMIC_DISCARD_RECTANGLE_MODE) {
1115       dynamic->vk.dr.mode = state->dr->mode;
1116    }
1117 
1118    if (states & RADV_DYNAMIC_ATTACHMENT_FEEDBACK_LOOP_ENABLE) {
1119       bool uses_ds_feedback_loop = radv_pipeline_uses_ds_feedback_loop(pipeline, state);
1120 
1121       dynamic->feedback_loop_aspects =
1122          uses_ds_feedback_loop ? (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) : VK_IMAGE_ASPECT_NONE;
1123    }
1124 
1125    pipeline->dynamic_state.mask = states;
1126 }
1127 
1128 static void
gfx10_emit_ge_pc_alloc(struct radeon_cmdbuf * cs,enum amd_gfx_level gfx_level,uint32_t oversub_pc_lines)1129 gfx10_emit_ge_pc_alloc(struct radeon_cmdbuf *cs, enum amd_gfx_level gfx_level, uint32_t oversub_pc_lines)
1130 {
1131    radeon_set_uconfig_reg(cs, R_030980_GE_PC_ALLOC,
1132                           S_030980_OVERSUB_EN(oversub_pc_lines > 0) | S_030980_NUM_PC_LINES(oversub_pc_lines - 1));
1133 }
1134 
1135 struct radv_shader *
radv_get_shader(struct radv_shader * const * shaders,gl_shader_stage stage)1136 radv_get_shader(struct radv_shader *const *shaders, gl_shader_stage stage)
1137 {
1138    if (stage == MESA_SHADER_VERTEX) {
1139       if (shaders[MESA_SHADER_VERTEX])
1140          return shaders[MESA_SHADER_VERTEX];
1141       if (shaders[MESA_SHADER_TESS_CTRL])
1142          return shaders[MESA_SHADER_TESS_CTRL];
1143       if (shaders[MESA_SHADER_GEOMETRY])
1144          return shaders[MESA_SHADER_GEOMETRY];
1145    } else if (stage == MESA_SHADER_TESS_EVAL) {
1146       if (!shaders[MESA_SHADER_TESS_CTRL])
1147          return NULL;
1148       if (shaders[MESA_SHADER_TESS_EVAL])
1149          return shaders[MESA_SHADER_TESS_EVAL];
1150       if (shaders[MESA_SHADER_GEOMETRY])
1151          return shaders[MESA_SHADER_GEOMETRY];
1152    }
1153    return shaders[stage];
1154 }
1155 
1156 static const struct radv_shader *
radv_get_last_vgt_shader(const struct radv_graphics_pipeline * pipeline)1157 radv_get_last_vgt_shader(const struct radv_graphics_pipeline *pipeline)
1158 {
1159    if (radv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY))
1160       if (radv_pipeline_has_ngg(pipeline))
1161          return pipeline->base.shaders[MESA_SHADER_GEOMETRY];
1162       else
1163          return pipeline->base.gs_copy_shader;
1164    else if (radv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_CTRL))
1165       return pipeline->base.shaders[MESA_SHADER_TESS_EVAL];
1166    else if (radv_pipeline_has_stage(pipeline, MESA_SHADER_MESH))
1167       return pipeline->base.shaders[MESA_SHADER_MESH];
1168    else
1169       return pipeline->base.shaders[MESA_SHADER_VERTEX];
1170 }
1171 
1172 static const struct radv_vs_output_info *
get_vs_output_info(const struct radv_graphics_pipeline * pipeline)1173 get_vs_output_info(const struct radv_graphics_pipeline *pipeline)
1174 {
1175    return &radv_get_last_vgt_shader(pipeline)->info.outinfo;
1176 }
1177 
1178 static bool
radv_should_export_multiview(const struct radv_shader_stage * stage,const struct radv_graphics_state_key * gfx_state)1179 radv_should_export_multiview(const struct radv_shader_stage *stage, const struct radv_graphics_state_key *gfx_state)
1180 {
1181    /* Export the layer in the last VGT stage if multiview is used.
1182     * Also checks for NONE stage, which happens when we have depth-only rendering.
1183     * When the next stage is unknown (with graphics pipeline library), the layer is exported unconditionally.
1184     */
1185    return gfx_state->has_multiview_view_index &&
1186           (stage->info.next_stage == MESA_SHADER_FRAGMENT || stage->info.next_stage == MESA_SHADER_NONE ||
1187            !(gfx_state->lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT)) &&
1188           !(stage->nir->info.outputs_written & VARYING_BIT_LAYER);
1189 }
1190 
1191 static void
radv_remove_point_size(const struct radv_graphics_state_key * gfx_state,nir_shader * producer,nir_shader * consumer)1192 radv_remove_point_size(const struct radv_graphics_state_key *gfx_state, nir_shader *producer, nir_shader *consumer)
1193 {
1194    if ((consumer->info.inputs_read & VARYING_BIT_PSIZ) || !(producer->info.outputs_written & VARYING_BIT_PSIZ))
1195       return;
1196 
1197    /* Do not remove PSIZ if the shader uses XFB because it might be stored. */
1198    if (producer->xfb_info)
1199       return;
1200 
1201    /* Do not remove PSIZ if the rasterization primitive uses points. */
1202    if (consumer->info.stage == MESA_SHADER_FRAGMENT &&
1203        ((producer->info.stage == MESA_SHADER_TESS_EVAL && producer->info.tess.point_mode) ||
1204         (producer->info.stage == MESA_SHADER_GEOMETRY && producer->info.gs.output_primitive == MESA_PRIM_POINTS) ||
1205         (producer->info.stage == MESA_SHADER_MESH && producer->info.mesh.primitive_type == MESA_PRIM_POINTS)))
1206       return;
1207 
1208    nir_variable *var = nir_find_variable_with_location(producer, nir_var_shader_out, VARYING_SLOT_PSIZ);
1209    assert(var);
1210 
1211    /* Change PSIZ to a global variable which allows it to be DCE'd. */
1212    var->data.location = 0;
1213    var->data.mode = nir_var_shader_temp;
1214 
1215    producer->info.outputs_written &= ~VARYING_BIT_PSIZ;
1216    NIR_PASS_V(producer, nir_fixup_deref_modes);
1217    NIR_PASS(_, producer, nir_remove_dead_variables, nir_var_shader_temp, NULL);
1218    NIR_PASS(_, producer, nir_opt_dce);
1219 }
1220 
1221 static void
radv_remove_color_exports(const struct radv_graphics_state_key * gfx_state,nir_shader * nir)1222 radv_remove_color_exports(const struct radv_graphics_state_key *gfx_state, nir_shader *nir)
1223 {
1224    bool fixup_derefs = false;
1225 
1226    /* Do not remove color exports when a PS epilog is used because the format isn't known and the color write mask can
1227     * be dynamic. */
1228    if (gfx_state->ps.has_epilog)
1229       return;
1230 
1231    nir_foreach_shader_out_variable (var, nir) {
1232       int idx = var->data.location;
1233       idx -= FRAG_RESULT_DATA0;
1234 
1235       if (idx < 0)
1236          continue;
1237 
1238       unsigned col_format = (gfx_state->ps.epilog.spi_shader_col_format >> (4 * idx)) & 0xf;
1239 
1240       if (col_format == V_028714_SPI_SHADER_ZERO) {
1241          /* Remove the color export if it's unused or in presence of holes. */
1242          nir->info.outputs_written &= ~BITFIELD64_BIT(var->data.location);
1243          var->data.location = 0;
1244          var->data.mode = nir_var_shader_temp;
1245          fixup_derefs = true;
1246       }
1247    }
1248 
1249    if (fixup_derefs) {
1250       NIR_PASS_V(nir, nir_fixup_deref_modes);
1251       NIR_PASS(_, nir, nir_remove_dead_variables, nir_var_shader_temp, NULL);
1252       NIR_PASS(_, nir, nir_opt_dce);
1253    }
1254 }
1255 
1256 static void
merge_tess_info(struct shader_info * tes_info,struct shader_info * tcs_info)1257 merge_tess_info(struct shader_info *tes_info, struct shader_info *tcs_info)
1258 {
1259    /* The Vulkan 1.0.38 spec, section 21.1 Tessellator says:
1260     *
1261     *    "PointMode. Controls generation of points rather than triangles
1262     *     or lines. This functionality defaults to disabled, and is
1263     *     enabled if either shader stage includes the execution mode.
1264     *
1265     * and about Triangles, Quads, IsoLines, VertexOrderCw, VertexOrderCcw,
1266     * PointMode, SpacingEqual, SpacingFractionalEven, SpacingFractionalOdd,
1267     * and OutputVertices, it says:
1268     *
1269     *    "One mode must be set in at least one of the tessellation
1270     *     shader stages."
1271     *
1272     * So, the fields can be set in either the TCS or TES, but they must
1273     * agree if set in both.  Our backend looks at TES, so bitwise-or in
1274     * the values from the TCS.
1275     */
1276    assert(tcs_info->tess.tcs_vertices_out == 0 || tes_info->tess.tcs_vertices_out == 0 ||
1277           tcs_info->tess.tcs_vertices_out == tes_info->tess.tcs_vertices_out);
1278    tes_info->tess.tcs_vertices_out |= tcs_info->tess.tcs_vertices_out;
1279 
1280    assert(tcs_info->tess.spacing == TESS_SPACING_UNSPECIFIED || tes_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
1281           tcs_info->tess.spacing == tes_info->tess.spacing);
1282    tes_info->tess.spacing |= tcs_info->tess.spacing;
1283 
1284    assert(tcs_info->tess._primitive_mode == TESS_PRIMITIVE_UNSPECIFIED ||
1285           tes_info->tess._primitive_mode == TESS_PRIMITIVE_UNSPECIFIED ||
1286           tcs_info->tess._primitive_mode == tes_info->tess._primitive_mode);
1287    tes_info->tess._primitive_mode |= tcs_info->tess._primitive_mode;
1288    tes_info->tess.ccw |= tcs_info->tess.ccw;
1289    tes_info->tess.point_mode |= tcs_info->tess.point_mode;
1290 
1291    /* Copy the merged info back to the TCS */
1292    tcs_info->tess.tcs_vertices_out = tes_info->tess.tcs_vertices_out;
1293    tcs_info->tess._primitive_mode = tes_info->tess._primitive_mode;
1294 }
1295 
1296 static void
radv_link_shaders(const struct radv_device * device,struct radv_shader_stage * producer_stage,struct radv_shader_stage * consumer_stage,const struct radv_graphics_state_key * gfx_state)1297 radv_link_shaders(const struct radv_device *device, struct radv_shader_stage *producer_stage,
1298                   struct radv_shader_stage *consumer_stage, const struct radv_graphics_state_key *gfx_state)
1299 {
1300    const enum amd_gfx_level gfx_level = device->physical_device->rad_info.gfx_level;
1301    nir_shader *producer = producer_stage->nir;
1302    nir_shader *consumer = consumer_stage->nir;
1303    bool progress;
1304 
1305    if (consumer->info.stage == MESA_SHADER_FRAGMENT) {
1306       /* Lower the viewport index to zero when the last vertex stage doesn't export it. */
1307       if ((consumer->info.inputs_read & VARYING_BIT_VIEWPORT) &&
1308           !(producer->info.outputs_written & VARYING_BIT_VIEWPORT)) {
1309          NIR_PASS(_, consumer, radv_nir_lower_viewport_to_zero);
1310       }
1311 
1312       /* Lower the view index to map on the layer. */
1313       NIR_PASS(_, consumer, radv_nir_lower_view_index, producer->info.stage == MESA_SHADER_MESH);
1314    }
1315 
1316    if (producer_stage->key.optimisations_disabled || consumer_stage->key.optimisations_disabled)
1317       return;
1318 
1319    if (consumer->info.stage == MESA_SHADER_FRAGMENT && producer->info.has_transform_feedback_varyings) {
1320       nir_link_xfb_varyings(producer, consumer);
1321    }
1322 
1323    unsigned array_deref_of_vec_options =
1324       nir_lower_direct_array_deref_of_vec_load | nir_lower_indirect_array_deref_of_vec_load |
1325       nir_lower_direct_array_deref_of_vec_store | nir_lower_indirect_array_deref_of_vec_store;
1326 
1327    NIR_PASS(progress, producer, nir_lower_array_deref_of_vec, nir_var_shader_out, array_deref_of_vec_options);
1328    NIR_PASS(progress, consumer, nir_lower_array_deref_of_vec, nir_var_shader_in, array_deref_of_vec_options);
1329 
1330    nir_lower_io_arrays_to_elements(producer, consumer);
1331    nir_validate_shader(producer, "after nir_lower_io_arrays_to_elements");
1332    nir_validate_shader(consumer, "after nir_lower_io_arrays_to_elements");
1333 
1334    radv_nir_lower_io_to_scalar_early(producer, nir_var_shader_out);
1335    radv_nir_lower_io_to_scalar_early(consumer, nir_var_shader_in);
1336 
1337    /* Remove PSIZ from shaders when it's not needed.
1338     * This is typically produced by translation layers like Zink or D9VK.
1339     */
1340    if (gfx_state->enable_remove_point_size)
1341       radv_remove_point_size(gfx_state, producer, consumer);
1342 
1343    if (nir_link_opt_varyings(producer, consumer)) {
1344       nir_validate_shader(producer, "after nir_link_opt_varyings");
1345       nir_validate_shader(consumer, "after nir_link_opt_varyings");
1346 
1347       NIR_PASS(_, consumer, nir_opt_constant_folding);
1348       NIR_PASS(_, consumer, nir_opt_algebraic);
1349       NIR_PASS(_, consumer, nir_opt_dce);
1350    }
1351 
1352    NIR_PASS(_, producer, nir_remove_dead_variables, nir_var_shader_out, NULL);
1353    NIR_PASS(_, consumer, nir_remove_dead_variables, nir_var_shader_in, NULL);
1354 
1355    progress = nir_remove_unused_varyings(producer, consumer);
1356 
1357    nir_compact_varyings(producer, consumer, true);
1358 
1359    /* nir_compact_varyings changes deleted varyings into shader_temp.
1360     * We need to remove these otherwise we risk them being lowered to scratch.
1361     * This can especially happen to arrayed outputs.
1362     */
1363    NIR_PASS(_, producer, nir_remove_dead_variables, nir_var_shader_temp, NULL);
1364    NIR_PASS(_, consumer, nir_remove_dead_variables, nir_var_shader_temp, NULL);
1365 
1366    nir_validate_shader(producer, "after nir_compact_varyings");
1367    nir_validate_shader(consumer, "after nir_compact_varyings");
1368 
1369    if (producer->info.stage == MESA_SHADER_MESH) {
1370       /* nir_compact_varyings can change the location of per-vertex and per-primitive outputs */
1371       nir_shader_gather_info(producer, nir_shader_get_entrypoint(producer));
1372    }
1373 
1374    const bool has_geom_or_tess =
1375       consumer->info.stage == MESA_SHADER_GEOMETRY || consumer->info.stage == MESA_SHADER_TESS_CTRL;
1376    const bool merged_gs = consumer->info.stage == MESA_SHADER_GEOMETRY && gfx_level >= GFX9;
1377 
1378    if (producer->info.stage == MESA_SHADER_TESS_CTRL || producer->info.stage == MESA_SHADER_MESH ||
1379        (producer->info.stage == MESA_SHADER_VERTEX && has_geom_or_tess) ||
1380        (producer->info.stage == MESA_SHADER_TESS_EVAL && merged_gs)) {
1381       NIR_PASS(_, producer, nir_lower_io_to_vector, nir_var_shader_out);
1382 
1383       if (producer->info.stage == MESA_SHADER_TESS_CTRL)
1384          NIR_PASS(_, producer, nir_vectorize_tess_levels);
1385 
1386       NIR_PASS(_, producer, nir_opt_combine_stores, nir_var_shader_out);
1387    }
1388 
1389    if (consumer->info.stage == MESA_SHADER_GEOMETRY || consumer->info.stage == MESA_SHADER_TESS_CTRL ||
1390        consumer->info.stage == MESA_SHADER_TESS_EVAL) {
1391       NIR_PASS(_, consumer, nir_lower_io_to_vector, nir_var_shader_in);
1392    }
1393 
1394    if (progress) {
1395       progress = false;
1396       NIR_PASS(progress, producer, nir_lower_global_vars_to_local);
1397       if (progress) {
1398          ac_nir_lower_indirect_derefs(producer, gfx_level);
1399          /* remove dead writes, which can remove input loads */
1400          NIR_PASS(_, producer, nir_lower_vars_to_ssa);
1401          NIR_PASS(_, producer, nir_opt_dce);
1402       }
1403 
1404       progress = false;
1405       NIR_PASS(progress, consumer, nir_lower_global_vars_to_local);
1406       if (progress) {
1407          ac_nir_lower_indirect_derefs(consumer, gfx_level);
1408       }
1409    }
1410 }
1411 
1412 static const gl_shader_stage graphics_shader_order[] = {
1413    MESA_SHADER_VERTEX,   MESA_SHADER_TESS_CTRL, MESA_SHADER_TESS_EVAL, MESA_SHADER_GEOMETRY,
1414 
1415    MESA_SHADER_TASK,     MESA_SHADER_MESH,
1416 
1417    MESA_SHADER_FRAGMENT,
1418 };
1419 
1420 static void
radv_link_vs(const struct radv_device * device,struct radv_shader_stage * vs_stage,struct radv_shader_stage * next_stage,const struct radv_graphics_state_key * gfx_state)1421 radv_link_vs(const struct radv_device *device, struct radv_shader_stage *vs_stage, struct radv_shader_stage *next_stage,
1422              const struct radv_graphics_state_key *gfx_state)
1423 {
1424    assert(vs_stage->nir->info.stage == MESA_SHADER_VERTEX);
1425 
1426    if (radv_should_export_multiview(vs_stage, gfx_state)) {
1427       NIR_PASS(_, vs_stage->nir, radv_nir_export_multiview);
1428    }
1429 
1430    if (next_stage) {
1431       assert(next_stage->nir->info.stage == MESA_SHADER_TESS_CTRL ||
1432              next_stage->nir->info.stage == MESA_SHADER_GEOMETRY ||
1433              next_stage->nir->info.stage == MESA_SHADER_FRAGMENT);
1434 
1435       radv_link_shaders(device, vs_stage, next_stage, gfx_state);
1436    }
1437 
1438    nir_foreach_shader_in_variable (var, vs_stage->nir) {
1439       var->data.driver_location = var->data.location;
1440    }
1441 
1442    if (next_stage && next_stage->nir->info.stage == MESA_SHADER_TESS_CTRL) {
1443       nir_linked_io_var_info vs2tcs = nir_assign_linked_io_var_locations(vs_stage->nir, next_stage->nir);
1444 
1445       vs_stage->info.vs.num_linked_outputs = vs2tcs.num_linked_io_vars;
1446       vs_stage->info.outputs_linked = true;
1447 
1448       next_stage->info.tcs.num_linked_inputs = vs2tcs.num_linked_io_vars;
1449       next_stage->info.inputs_linked = true;
1450    } else if (next_stage && next_stage->nir->info.stage == MESA_SHADER_GEOMETRY) {
1451       nir_linked_io_var_info vs2gs = nir_assign_linked_io_var_locations(vs_stage->nir, next_stage->nir);
1452 
1453       vs_stage->info.vs.num_linked_outputs = vs2gs.num_linked_io_vars;
1454       vs_stage->info.outputs_linked = true;
1455 
1456       next_stage->info.gs.num_linked_inputs = vs2gs.num_linked_io_vars;
1457       next_stage->info.inputs_linked = true;
1458    } else {
1459       nir_foreach_shader_out_variable (var, vs_stage->nir) {
1460          var->data.driver_location = var->data.location;
1461       }
1462    }
1463 }
1464 
1465 static void
radv_link_tcs(const struct radv_device * device,struct radv_shader_stage * tcs_stage,struct radv_shader_stage * tes_stage,const struct radv_graphics_state_key * gfx_state)1466 radv_link_tcs(const struct radv_device *device, struct radv_shader_stage *tcs_stage,
1467               struct radv_shader_stage *tes_stage, const struct radv_graphics_state_key *gfx_state)
1468 {
1469    if (!tes_stage)
1470       return;
1471 
1472    assert(tcs_stage->nir->info.stage == MESA_SHADER_TESS_CTRL);
1473    assert(tes_stage->nir->info.stage == MESA_SHADER_TESS_EVAL);
1474 
1475    radv_link_shaders(device, tcs_stage, tes_stage, gfx_state);
1476 
1477    /* Copy TCS info into the TES info */
1478    merge_tess_info(&tes_stage->nir->info, &tcs_stage->nir->info);
1479 
1480    nir_linked_io_var_info tcs2tes = nir_assign_linked_io_var_locations(tcs_stage->nir, tes_stage->nir);
1481 
1482    tcs_stage->info.tcs.num_linked_outputs = tcs2tes.num_linked_io_vars;
1483    tcs_stage->info.tcs.num_linked_patch_outputs = tcs2tes.num_linked_patch_io_vars;
1484    tcs_stage->info.outputs_linked = true;
1485 
1486    tes_stage->info.tes.num_linked_inputs = tcs2tes.num_linked_io_vars;
1487    tes_stage->info.inputs_linked = true;
1488 }
1489 
1490 static void
radv_link_tes(const struct radv_device * device,struct radv_shader_stage * tes_stage,struct radv_shader_stage * next_stage,const struct radv_graphics_state_key * gfx_state)1491 radv_link_tes(const struct radv_device *device, struct radv_shader_stage *tes_stage,
1492               struct radv_shader_stage *next_stage, const struct radv_graphics_state_key *gfx_state)
1493 {
1494    assert(tes_stage->nir->info.stage == MESA_SHADER_TESS_EVAL);
1495 
1496    if (radv_should_export_multiview(tes_stage, gfx_state)) {
1497       NIR_PASS(_, tes_stage->nir, radv_nir_export_multiview);
1498    }
1499 
1500    if (next_stage) {
1501       assert(next_stage->nir->info.stage == MESA_SHADER_GEOMETRY ||
1502              next_stage->nir->info.stage == MESA_SHADER_FRAGMENT);
1503 
1504       radv_link_shaders(device, tes_stage, next_stage, gfx_state);
1505    }
1506 
1507    if (next_stage && next_stage->nir->info.stage == MESA_SHADER_GEOMETRY) {
1508       nir_linked_io_var_info tes2gs = nir_assign_linked_io_var_locations(tes_stage->nir, next_stage->nir);
1509 
1510       tes_stage->info.tes.num_linked_outputs = tes2gs.num_linked_io_vars;
1511       tes_stage->info.outputs_linked = true;
1512 
1513       next_stage->info.gs.num_linked_inputs = tes2gs.num_linked_io_vars;
1514       next_stage->info.inputs_linked = true;
1515    } else {
1516       nir_foreach_shader_out_variable (var, tes_stage->nir) {
1517          var->data.driver_location = var->data.location;
1518       }
1519    }
1520 }
1521 
1522 static void
radv_link_gs(const struct radv_device * device,struct radv_shader_stage * gs_stage,struct radv_shader_stage * fs_stage,const struct radv_graphics_state_key * gfx_state)1523 radv_link_gs(const struct radv_device *device, struct radv_shader_stage *gs_stage, struct radv_shader_stage *fs_stage,
1524              const struct radv_graphics_state_key *gfx_state)
1525 {
1526    assert(gs_stage->nir->info.stage == MESA_SHADER_GEOMETRY);
1527 
1528    if (radv_should_export_multiview(gs_stage, gfx_state)) {
1529       NIR_PASS(_, gs_stage->nir, radv_nir_export_multiview);
1530    }
1531 
1532    if (fs_stage) {
1533       assert(fs_stage->nir->info.stage == MESA_SHADER_FRAGMENT);
1534 
1535       radv_link_shaders(device, gs_stage, fs_stage, gfx_state);
1536    }
1537 
1538    nir_foreach_shader_out_variable (var, gs_stage->nir) {
1539       var->data.driver_location = var->data.location;
1540    }
1541 }
1542 
1543 static void
radv_link_task(const struct radv_device * device,struct radv_shader_stage * task_stage,struct radv_shader_stage * mesh_stage,const struct radv_graphics_state_key * gfx_state)1544 radv_link_task(const struct radv_device *device, struct radv_shader_stage *task_stage,
1545                struct radv_shader_stage *mesh_stage, const struct radv_graphics_state_key *gfx_state)
1546 {
1547    assert(task_stage->nir->info.stage == MESA_SHADER_TASK);
1548 
1549    if (mesh_stage) {
1550       assert(mesh_stage->nir->info.stage == MESA_SHADER_MESH);
1551 
1552       /* Linking task and mesh shaders shouldn't do anything for now but keep it for consistency. */
1553       radv_link_shaders(device, task_stage, mesh_stage, gfx_state);
1554    }
1555 }
1556 
1557 static void
radv_link_mesh(const struct radv_device * device,struct radv_shader_stage * mesh_stage,struct radv_shader_stage * fs_stage,const struct radv_graphics_state_key * gfx_state)1558 radv_link_mesh(const struct radv_device *device, struct radv_shader_stage *mesh_stage,
1559                struct radv_shader_stage *fs_stage, const struct radv_graphics_state_key *gfx_state)
1560 {
1561    assert(mesh_stage->nir->info.stage == MESA_SHADER_MESH);
1562 
1563    if (fs_stage) {
1564       assert(fs_stage->nir->info.stage == MESA_SHADER_FRAGMENT);
1565 
1566       nir_foreach_shader_in_variable (var, fs_stage->nir) {
1567          /* These variables are per-primitive when used with a mesh shader. */
1568          if (var->data.location == VARYING_SLOT_PRIMITIVE_ID || var->data.location == VARYING_SLOT_VIEWPORT ||
1569              var->data.location == VARYING_SLOT_LAYER) {
1570             var->data.per_primitive = true;
1571          }
1572       }
1573 
1574       radv_link_shaders(device, mesh_stage, fs_stage, gfx_state);
1575    }
1576 
1577    /* ac_nir_lower_ngg ignores driver locations for mesh shaders, but set them to all zero just to
1578     * be on the safe side.
1579     */
1580    nir_foreach_shader_out_variable (var, mesh_stage->nir) {
1581       var->data.driver_location = 0;
1582    }
1583 }
1584 
1585 static void
radv_link_fs(struct radv_shader_stage * fs_stage,const struct radv_graphics_state_key * gfx_state)1586 radv_link_fs(struct radv_shader_stage *fs_stage, const struct radv_graphics_state_key *gfx_state)
1587 {
1588    assert(fs_stage->nir->info.stage == MESA_SHADER_FRAGMENT);
1589 
1590    radv_remove_color_exports(gfx_state, fs_stage->nir);
1591 
1592    nir_foreach_shader_out_variable (var, fs_stage->nir) {
1593       var->data.driver_location = var->data.location + var->data.index;
1594    }
1595 }
1596 
1597 static bool
radv_pipeline_needs_noop_fs(struct radv_graphics_pipeline * pipeline,const struct radv_graphics_state_key * gfx_state)1598 radv_pipeline_needs_noop_fs(struct radv_graphics_pipeline *pipeline, const struct radv_graphics_state_key *gfx_state)
1599 {
1600    if (pipeline->base.type == RADV_PIPELINE_GRAPHICS &&
1601        !(radv_pipeline_to_graphics(&pipeline->base)->active_stages & VK_SHADER_STAGE_FRAGMENT_BIT))
1602       return true;
1603 
1604    if (pipeline->base.type == RADV_PIPELINE_GRAPHICS_LIB &&
1605        (gfx_state->lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT) &&
1606        !(radv_pipeline_to_graphics_lib(&pipeline->base)->base.active_stages & VK_SHADER_STAGE_FRAGMENT_BIT))
1607       return true;
1608 
1609    return false;
1610 }
1611 
1612 static void
radv_remove_varyings(nir_shader * nir)1613 radv_remove_varyings(nir_shader *nir)
1614 {
1615    /* We can't demote mesh outputs to nir_var_shader_temp yet, because
1616     * they don't support array derefs of vectors.
1617     */
1618    if (nir->info.stage == MESA_SHADER_MESH)
1619       return;
1620 
1621    bool fixup_derefs = false;
1622 
1623    nir_foreach_shader_out_variable (var, nir) {
1624       if (var->data.always_active_io)
1625          continue;
1626 
1627       if (var->data.location < VARYING_SLOT_VAR0)
1628          continue;
1629 
1630       nir->info.outputs_written &= ~BITFIELD64_BIT(var->data.location);
1631       var->data.location = 0;
1632       var->data.mode = nir_var_shader_temp;
1633       fixup_derefs = true;
1634    }
1635 
1636    if (fixup_derefs) {
1637       NIR_PASS_V(nir, nir_fixup_deref_modes);
1638       NIR_PASS(_, nir, nir_remove_dead_variables, nir_var_shader_temp, NULL);
1639       NIR_PASS(_, nir, nir_opt_dce);
1640    }
1641 }
1642 
1643 static void
radv_graphics_shaders_link(const struct radv_device * device,const struct radv_graphics_state_key * gfx_state,struct radv_shader_stage * stages)1644 radv_graphics_shaders_link(const struct radv_device *device, const struct radv_graphics_state_key *gfx_state,
1645                            struct radv_shader_stage *stages)
1646 {
1647    /* Walk backwards to link */
1648    struct radv_shader_stage *next_stage = NULL;
1649    for (int i = ARRAY_SIZE(graphics_shader_order) - 1; i >= 0; i--) {
1650       gl_shader_stage s = graphics_shader_order[i];
1651       if (!stages[s].nir)
1652          continue;
1653 
1654       switch (s) {
1655       case MESA_SHADER_VERTEX:
1656          radv_link_vs(device, &stages[s], next_stage, gfx_state);
1657          break;
1658       case MESA_SHADER_TESS_CTRL:
1659          radv_link_tcs(device, &stages[s], next_stage, gfx_state);
1660          break;
1661       case MESA_SHADER_TESS_EVAL:
1662          radv_link_tes(device, &stages[s], next_stage, gfx_state);
1663          break;
1664       case MESA_SHADER_GEOMETRY:
1665          radv_link_gs(device, &stages[s], next_stage, gfx_state);
1666          break;
1667       case MESA_SHADER_TASK:
1668          radv_link_task(device, &stages[s], next_stage, gfx_state);
1669          break;
1670       case MESA_SHADER_MESH:
1671          radv_link_mesh(device, &stages[s], next_stage, gfx_state);
1672          break;
1673       case MESA_SHADER_FRAGMENT:
1674          radv_link_fs(&stages[s], gfx_state);
1675          break;
1676       default:
1677          unreachable("Invalid graphics shader stage");
1678       }
1679 
1680       next_stage = &stages[s];
1681    }
1682 }
1683 
1684 struct radv_ps_epilog_key
radv_generate_ps_epilog_key(const struct radv_device * device,const struct radv_ps_epilog_state * state)1685 radv_generate_ps_epilog_key(const struct radv_device *device, const struct radv_ps_epilog_state *state)
1686 {
1687    unsigned col_format = 0, is_int8 = 0, is_int10 = 0, is_float32 = 0, z_format = 0;
1688    struct radv_ps_epilog_key key;
1689 
1690    memset(&key, 0, sizeof(key));
1691 
1692    for (unsigned i = 0; i < state->color_attachment_count; ++i) {
1693       unsigned cf;
1694       VkFormat fmt = state->color_attachment_formats[i];
1695 
1696       if (fmt == VK_FORMAT_UNDEFINED || !(state->color_write_mask & (0xfu << (i * 4)))) {
1697          cf = V_028714_SPI_SHADER_ZERO;
1698       } else {
1699          bool blend_enable = state->color_blend_enable & (0xfu << (i * 4));
1700 
1701          cf = radv_choose_spi_color_format(device, fmt, blend_enable, state->need_src_alpha & (1 << i));
1702 
1703          if (format_is_int8(fmt))
1704             is_int8 |= 1 << i;
1705          if (format_is_int10(fmt))
1706             is_int10 |= 1 << i;
1707          if (format_is_float32(fmt))
1708             is_float32 |= 1 << i;
1709       }
1710 
1711       col_format |= cf << (4 * i);
1712    }
1713 
1714    if (!(col_format & 0xf) && state->need_src_alpha & (1 << 0)) {
1715       /* When a subpass doesn't have any color attachments, write the alpha channel of MRT0 when
1716        * alpha coverage is enabled because the depth attachment needs it.
1717        */
1718       col_format |= V_028714_SPI_SHADER_32_AR;
1719    }
1720 
1721    /* The output for dual source blending should have the same format as the first output. */
1722    if (state->mrt0_is_dual_src) {
1723       assert(!(col_format >> 4));
1724       col_format |= (col_format & 0xf) << 4;
1725    }
1726 
1727    if (state->alpha_to_coverage_via_mrtz)
1728       z_format = ac_get_spi_shader_z_format(state->export_depth, state->export_stencil, state->export_sample_mask,
1729                                             state->alpha_to_coverage_via_mrtz);
1730 
1731    key.spi_shader_col_format = col_format;
1732    key.color_is_int8 = device->physical_device->rad_info.gfx_level < GFX8 ? is_int8 : 0;
1733    key.color_is_int10 = device->physical_device->rad_info.gfx_level < GFX8 ? is_int10 : 0;
1734    key.enable_mrt_output_nan_fixup = device->instance->drirc.enable_mrt_output_nan_fixup ? is_float32 : 0;
1735    key.colors_written = state->colors_written;
1736    key.mrt0_is_dual_src = state->mrt0_is_dual_src;
1737    key.export_depth = state->export_depth;
1738    key.export_stencil = state->export_stencil;
1739    key.export_sample_mask = state->export_sample_mask;
1740    key.alpha_to_coverage_via_mrtz = state->alpha_to_coverage_via_mrtz;
1741    key.spi_shader_z_format = z_format;
1742 
1743    return key;
1744 }
1745 
1746 static struct radv_ps_epilog_key
radv_pipeline_generate_ps_epilog_key(const struct radv_device * device,const struct vk_graphics_pipeline_state * state)1747 radv_pipeline_generate_ps_epilog_key(const struct radv_device *device, const struct vk_graphics_pipeline_state *state)
1748 {
1749    struct radv_ps_epilog_state ps_epilog = {0};
1750 
1751    if (state->ms && state->ms->alpha_to_coverage_enable)
1752       ps_epilog.need_src_alpha |= 0x1;
1753 
1754    if (state->cb) {
1755       for (uint32_t i = 0; i < state->cb->attachment_count; i++) {
1756          VkBlendOp eqRGB = state->cb->attachments[i].color_blend_op;
1757          VkBlendFactor srcRGB = state->cb->attachments[i].src_color_blend_factor;
1758          VkBlendFactor dstRGB = state->cb->attachments[i].dst_color_blend_factor;
1759 
1760          /* Ignore other blend targets if dual-source blending is enabled to prevent wrong
1761           * behaviour.
1762           */
1763          if (i > 0 && ps_epilog.mrt0_is_dual_src)
1764             continue;
1765 
1766          ps_epilog.color_write_mask |= (unsigned)state->cb->attachments[i].write_mask << (4 * i);
1767          if (!((ps_epilog.color_write_mask >> (i * 4)) & 0xf))
1768             continue;
1769 
1770          if (state->cb->attachments[i].blend_enable)
1771             ps_epilog.color_blend_enable |= 0xfu << (i * 4);
1772 
1773          if (!((ps_epilog.color_blend_enable >> (i * 4)) & 0xf))
1774             continue;
1775 
1776          if (i == 0 && radv_can_enable_dual_src(&state->cb->attachments[i])) {
1777             ps_epilog.mrt0_is_dual_src = true;
1778          }
1779 
1780          if (eqRGB == VK_BLEND_OP_MIN || eqRGB == VK_BLEND_OP_MAX) {
1781             srcRGB = VK_BLEND_FACTOR_ONE;
1782             dstRGB = VK_BLEND_FACTOR_ONE;
1783          }
1784 
1785          if (srcRGB == VK_BLEND_FACTOR_SRC_ALPHA || dstRGB == VK_BLEND_FACTOR_SRC_ALPHA ||
1786              srcRGB == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE || dstRGB == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE ||
1787              srcRGB == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA || dstRGB == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA)
1788             ps_epilog.need_src_alpha |= 1 << i;
1789       }
1790    }
1791 
1792    if (state->rp) {
1793       ps_epilog.color_attachment_count = state->rp->color_attachment_count;
1794 
1795       for (uint32_t i = 0; i < ps_epilog.color_attachment_count; i++) {
1796          ps_epilog.color_attachment_formats[i] = state->rp->color_attachment_formats[i];
1797       }
1798    }
1799 
1800    return radv_generate_ps_epilog_key(device, &ps_epilog);
1801 }
1802 
1803 static struct radv_graphics_state_key
radv_generate_graphics_state_key(const struct radv_device * device,const struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state,VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)1804 radv_generate_graphics_state_key(const struct radv_device *device, const struct radv_graphics_pipeline *pipeline,
1805                                  const struct vk_graphics_pipeline_state *state,
1806                                  VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)
1807 {
1808    const struct radv_physical_device *pdevice = device->physical_device;
1809    struct radv_graphics_state_key key;
1810 
1811    memset(&key, 0, sizeof(key));
1812 
1813    key.lib_flags = lib_flags;
1814    key.has_multiview_view_index = state->rp ? !!state->rp->view_mask : 0;
1815 
1816    if (pipeline->dynamic_states & RADV_DYNAMIC_VERTEX_INPUT) {
1817       key.vs.has_prolog = true;
1818    }
1819 
1820    /* Compile the pre-rasterization stages only when the vertex input interface is missing. */
1821    if ((lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_PRE_RASTERIZATION_SHADERS_BIT_EXT) &&
1822        !(lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_VERTEX_INPUT_INTERFACE_BIT_EXT)) {
1823       key.vs.has_prolog = true;
1824    }
1825 
1826    /* Vertex input state */
1827    if (state->vi) {
1828       u_foreach_bit (i, state->vi->attributes_valid) {
1829          uint32_t binding = state->vi->attributes[i].binding;
1830          uint32_t offset = state->vi->attributes[i].offset;
1831          enum pipe_format format = vk_format_to_pipe_format(state->vi->attributes[i].format);
1832 
1833          key.vi.vertex_attribute_formats[i] = format;
1834          key.vi.vertex_attribute_bindings[i] = binding;
1835          key.vi.vertex_attribute_offsets[i] = offset;
1836          key.vi.instance_rate_divisors[i] = state->vi->bindings[binding].divisor;
1837 
1838          /* vertex_attribute_strides is only needed to workaround GFX6/7 offset>=stride checks. */
1839          if (!(pipeline->dynamic_states & RADV_DYNAMIC_VERTEX_INPUT_BINDING_STRIDE) &&
1840              pdevice->rad_info.gfx_level < GFX8) {
1841             /* From the Vulkan spec 1.2.157:
1842              *
1843              * "If the bound pipeline state object was created with the
1844              * VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE dynamic state enabled then pStrides[i]
1845              * specifies the distance in bytes between two consecutive elements within the
1846              * corresponding buffer. In this case the VkVertexInputBindingDescription::stride state
1847              * from the pipeline state object is ignored."
1848              *
1849              * Make sure the vertex attribute stride is zero to avoid computing a wrong offset if
1850              * it's initialized to something else than zero.
1851              */
1852             key.vi.vertex_attribute_strides[i] = state->vi->bindings[binding].stride;
1853          }
1854 
1855          if (state->vi->bindings[binding].input_rate) {
1856             key.vi.instance_rate_inputs |= 1u << i;
1857          }
1858 
1859          const struct ac_vtx_format_info *vtx_info =
1860             ac_get_vtx_format_info(pdevice->rad_info.gfx_level, pdevice->rad_info.family, format);
1861          unsigned attrib_align = vtx_info->chan_byte_size ? vtx_info->chan_byte_size : vtx_info->element_size;
1862 
1863          /* If offset is misaligned, then the buffer offset must be too. Just skip updating
1864           * vertex_binding_align in this case.
1865           */
1866          if (offset % attrib_align == 0) {
1867             key.vi.vertex_binding_align[binding] = MAX2(key.vi.vertex_binding_align[binding], attrib_align);
1868          }
1869       }
1870    }
1871 
1872    if (state->ts)
1873       key.ts.patch_control_points = state->ts->patch_control_points;
1874 
1875    if (state->ms) {
1876       key.ms.sample_shading_enable = state->ms->sample_shading_enable;
1877       if (!(pipeline->dynamic_states & RADV_DYNAMIC_RASTERIZATION_SAMPLES) && state->ms->rasterization_samples > 1) {
1878          key.ms.rasterization_samples = state->ms->rasterization_samples;
1879       }
1880    }
1881 
1882    if (device->physical_device->rad_info.gfx_level >= GFX11 && state->ms) {
1883       key.ms.alpha_to_coverage_via_mrtz = state->ms->alpha_to_coverage_enable;
1884    }
1885 
1886    if (state->ia) {
1887       key.ia.topology = radv_translate_prim(state->ia->primitive_topology);
1888    }
1889 
1890    if (pipeline->base.type == RADV_PIPELINE_GRAPHICS_LIB &&
1891        (!(lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_VERTEX_INPUT_INTERFACE_BIT_EXT) ||
1892         !(lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_PRE_RASTERIZATION_SHADERS_BIT_EXT))) {
1893       key.unknown_rast_prim = true;
1894    }
1895 
1896    if (device->physical_device->rad_info.gfx_level >= GFX10 && state->rs) {
1897       key.rs.provoking_vtx_last = state->rs->provoking_vertex == VK_PROVOKING_VERTEX_MODE_LAST_VERTEX_EXT;
1898    }
1899 
1900    key.ps.force_vrs_enabled = device->force_vrs_enabled && !radv_is_static_vrs_enabled(pipeline, state);
1901 
1902    if ((radv_is_vrs_enabled(pipeline, state) || key.ps.force_vrs_enabled) &&
1903        (device->physical_device->rad_info.family == CHIP_NAVI21 ||
1904         device->physical_device->rad_info.family == CHIP_NAVI22 ||
1905         device->physical_device->rad_info.family == CHIP_VANGOGH))
1906       key.adjust_frag_coord_z = true;
1907 
1908    if (radv_pipeline_needs_ps_epilog(pipeline, lib_flags))
1909       key.ps.has_epilog = true;
1910 
1911    key.ps.epilog = radv_pipeline_generate_ps_epilog_key(device, state);
1912 
1913    if (device->physical_device->rad_info.gfx_level >= GFX11) {
1914       /* On GFX11, alpha to coverage is exported via MRTZ when depth/stencil/samplemask are also
1915        * exported. Though, when a PS epilog is needed and the MS state is NULL (with dynamic
1916        * rendering), it's not possible to know the info at compile time and MRTZ needs to be
1917        * exported in the epilog.
1918        */
1919       key.ps.exports_mrtz_via_epilog =
1920          key.ps.has_epilog && (!state->ms || (pipeline->dynamic_states & RADV_DYNAMIC_ALPHA_TO_COVERAGE_ENABLE));
1921    }
1922 
1923    key.dynamic_rasterization_samples = !!(pipeline->dynamic_states & RADV_DYNAMIC_RASTERIZATION_SAMPLES) ||
1924                                        (!!(pipeline->active_stages & VK_SHADER_STAGE_FRAGMENT_BIT) && !state->ms);
1925 
1926    if (device->physical_device->use_ngg) {
1927       VkShaderStageFlags ngg_stage;
1928 
1929       if (pipeline->active_stages & VK_SHADER_STAGE_GEOMETRY_BIT) {
1930          ngg_stage = VK_SHADER_STAGE_GEOMETRY_BIT;
1931       } else if (pipeline->active_stages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
1932          ngg_stage = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
1933       } else {
1934          ngg_stage = VK_SHADER_STAGE_VERTEX_BIT;
1935       }
1936 
1937       key.dynamic_provoking_vtx_mode =
1938          !!(pipeline->dynamic_states & RADV_DYNAMIC_PROVOKING_VERTEX_MODE) &&
1939          (ngg_stage == VK_SHADER_STAGE_VERTEX_BIT || ngg_stage == VK_SHADER_STAGE_GEOMETRY_BIT);
1940    }
1941 
1942    if (!(pipeline->dynamic_states & RADV_DYNAMIC_PRIMITIVE_TOPOLOGY) && state->ia &&
1943        state->ia->primitive_topology != VK_PRIMITIVE_TOPOLOGY_POINT_LIST &&
1944        !(pipeline->dynamic_states & RADV_DYNAMIC_POLYGON_MODE) && state->rs &&
1945        state->rs->polygon_mode != VK_POLYGON_MODE_POINT) {
1946       key.enable_remove_point_size = true;
1947    }
1948 
1949    if (device->vk.enabled_features.smoothLines) {
1950       /* For GPL, when the fragment shader is compiled without any pre-rasterization information,
1951        * ensure the line rasterization mode is considered dynamic because we can't know if it's
1952        * going to draw lines or not.
1953        */
1954       if (pipeline->dynamic_states & RADV_DYNAMIC_LINE_RASTERIZATION_MODE ||
1955           ((lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT) &&
1956            !(lib_flags & VK_GRAPHICS_PIPELINE_LIBRARY_PRE_RASTERIZATION_SHADERS_BIT_EXT))) {
1957          key.dynamic_line_rast_mode = true;
1958       } else {
1959          key.rs.line_smooth_enabled =
1960             state->rs && state->rs->line.mode == VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_KHR;
1961       }
1962    }
1963 
1964    return key;
1965 }
1966 
1967 static struct radv_graphics_pipeline_key
radv_generate_graphics_pipeline_key(const struct radv_device * device,const struct radv_graphics_pipeline * pipeline,const VkGraphicsPipelineCreateInfo * pCreateInfo,const struct vk_graphics_pipeline_state * state,VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)1968 radv_generate_graphics_pipeline_key(const struct radv_device *device, const struct radv_graphics_pipeline *pipeline,
1969                                     const VkGraphicsPipelineCreateInfo *pCreateInfo,
1970                                     const struct vk_graphics_pipeline_state *state,
1971                                     VkGraphicsPipelineLibraryFlagBitsEXT lib_flags)
1972 {
1973    struct radv_graphics_pipeline_key key = {0};
1974 
1975    key.gfx_state = radv_generate_graphics_state_key(device, pipeline, state, lib_flags);
1976 
1977    for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
1978       const VkPipelineShaderStageCreateInfo *stage = &pCreateInfo->pStages[i];
1979       gl_shader_stage s = vk_to_mesa_shader_stage(stage->stage);
1980 
1981       key.stage_info[s] = radv_pipeline_get_shader_key(device, stage, pipeline->base.create_flags, pCreateInfo->pNext);
1982 
1983       if (s == MESA_SHADER_MESH && (pipeline->active_stages & VK_SHADER_STAGE_TASK_BIT_EXT))
1984          key.stage_info[s].has_task_shader = true;
1985    }
1986 
1987    return key;
1988 }
1989 
1990 static void
radv_fill_shader_info_ngg(struct radv_device * device,struct radv_shader_stage * stages,VkShaderStageFlagBits active_nir_stages)1991 radv_fill_shader_info_ngg(struct radv_device *device, struct radv_shader_stage *stages,
1992                           VkShaderStageFlagBits active_nir_stages)
1993 {
1994    if (!device->physical_device->cache_key.use_ngg)
1995       return;
1996 
1997    if (stages[MESA_SHADER_VERTEX].nir && stages[MESA_SHADER_VERTEX].info.next_stage != MESA_SHADER_TESS_CTRL) {
1998       stages[MESA_SHADER_VERTEX].info.is_ngg = true;
1999    } else if (stages[MESA_SHADER_TESS_EVAL].nir) {
2000       stages[MESA_SHADER_TESS_EVAL].info.is_ngg = true;
2001    } else if (stages[MESA_SHADER_MESH].nir) {
2002       stages[MESA_SHADER_MESH].info.is_ngg = true;
2003    }
2004 
2005    if (device->physical_device->rad_info.gfx_level >= GFX11) {
2006       if (stages[MESA_SHADER_GEOMETRY].nir)
2007          stages[MESA_SHADER_GEOMETRY].info.is_ngg = true;
2008    } else {
2009       /* GFX10/GFX10.3 can't always enable NGG due to HW bugs/limitations. */
2010       if (stages[MESA_SHADER_TESS_EVAL].nir && stages[MESA_SHADER_GEOMETRY].nir &&
2011           stages[MESA_SHADER_GEOMETRY].nir->info.gs.invocations *
2012                 stages[MESA_SHADER_GEOMETRY].nir->info.gs.vertices_out >
2013              256) {
2014          /* Fallback to the legacy path if tessellation is
2015           * enabled with extreme geometry because
2016           * EN_MAX_VERT_OUT_PER_GS_INSTANCE doesn't work and it
2017           * might hang.
2018           */
2019          stages[MESA_SHADER_TESS_EVAL].info.is_ngg = false;
2020       }
2021 
2022       struct radv_shader_stage *last_vgt_stage = NULL;
2023       radv_foreach_stage(i, active_nir_stages)
2024       {
2025          if (radv_is_last_vgt_stage(&stages[i])) {
2026             last_vgt_stage = &stages[i];
2027          }
2028       }
2029 
2030       if ((last_vgt_stage && last_vgt_stage->nir->xfb_info) ||
2031           ((device->instance->debug_flags & RADV_DEBUG_NO_NGG_GS) && stages[MESA_SHADER_GEOMETRY].nir)) {
2032          /* NGG needs to be disabled on GFX10/GFX10.3 when:
2033           * - streamout is used because NGG streamout isn't supported
2034           * - NGG GS is explictly disabled to workaround performance issues
2035           */
2036          if (stages[MESA_SHADER_TESS_EVAL].nir)
2037             stages[MESA_SHADER_TESS_EVAL].info.is_ngg = false;
2038          else
2039             stages[MESA_SHADER_VERTEX].info.is_ngg = false;
2040       }
2041 
2042       if (stages[MESA_SHADER_GEOMETRY].nir) {
2043          if (stages[MESA_SHADER_TESS_EVAL].nir)
2044             stages[MESA_SHADER_GEOMETRY].info.is_ngg = stages[MESA_SHADER_TESS_EVAL].info.is_ngg;
2045          else
2046             stages[MESA_SHADER_GEOMETRY].info.is_ngg = stages[MESA_SHADER_VERTEX].info.is_ngg;
2047       }
2048    }
2049 }
2050 
2051 static bool
radv_consider_force_vrs(const struct radv_graphics_state_key * gfx_state,const struct radv_shader_stage * last_vgt_stage,const struct radv_shader_stage * fs_stage)2052 radv_consider_force_vrs(const struct radv_graphics_state_key *gfx_state, const struct radv_shader_stage *last_vgt_stage,
2053                         const struct radv_shader_stage *fs_stage)
2054 {
2055    if (!gfx_state->ps.force_vrs_enabled)
2056       return false;
2057 
2058    /* Mesh shaders aren't considered. */
2059    if (last_vgt_stage->info.stage == MESA_SHADER_MESH)
2060       return false;
2061 
2062    if (last_vgt_stage->nir->info.outputs_written & BITFIELD64_BIT(VARYING_SLOT_PRIMITIVE_SHADING_RATE))
2063       return false;
2064 
2065    /* VRS has no effect if there is no pixel shader. */
2066    if (last_vgt_stage->info.next_stage == MESA_SHADER_NONE)
2067       return false;
2068 
2069    /* Do not enable if the PS uses gl_FragCoord because it breaks postprocessing in some games, or with Primitive
2070     * Ordered Pixel Shading (regardless of whether per-pixel data is addressed with gl_FragCoord or a custom
2071     * interpolator) as that'd result in races between adjacent primitives with no common fine pixels.
2072     */
2073    nir_shader *fs_shader = fs_stage->nir;
2074    if (fs_shader && (BITSET_TEST(fs_shader->info.system_values_read, SYSTEM_VALUE_FRAG_COORD) ||
2075                      fs_shader->info.fs.sample_interlock_ordered || fs_shader->info.fs.sample_interlock_unordered ||
2076                      fs_shader->info.fs.pixel_interlock_ordered || fs_shader->info.fs.pixel_interlock_unordered)) {
2077       return false;
2078    }
2079 
2080    return true;
2081 }
2082 
2083 static gl_shader_stage
radv_get_next_stage(gl_shader_stage stage,VkShaderStageFlagBits active_nir_stages)2084 radv_get_next_stage(gl_shader_stage stage, VkShaderStageFlagBits active_nir_stages)
2085 {
2086    switch (stage) {
2087    case MESA_SHADER_VERTEX:
2088       if (active_nir_stages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) {
2089          return MESA_SHADER_TESS_CTRL;
2090       } else if (active_nir_stages & VK_SHADER_STAGE_GEOMETRY_BIT) {
2091          return MESA_SHADER_GEOMETRY;
2092       } else if (active_nir_stages & VK_SHADER_STAGE_FRAGMENT_BIT) {
2093          return MESA_SHADER_FRAGMENT;
2094       } else {
2095          return MESA_SHADER_NONE;
2096       }
2097    case MESA_SHADER_TESS_CTRL:
2098       return MESA_SHADER_TESS_EVAL;
2099    case MESA_SHADER_TESS_EVAL:
2100       if (active_nir_stages & VK_SHADER_STAGE_GEOMETRY_BIT) {
2101          return MESA_SHADER_GEOMETRY;
2102       } else if (active_nir_stages & VK_SHADER_STAGE_FRAGMENT_BIT) {
2103          return MESA_SHADER_FRAGMENT;
2104       } else {
2105          return MESA_SHADER_NONE;
2106       }
2107    case MESA_SHADER_GEOMETRY:
2108    case MESA_SHADER_MESH:
2109       if (active_nir_stages & VK_SHADER_STAGE_FRAGMENT_BIT) {
2110          return MESA_SHADER_FRAGMENT;
2111       } else {
2112          return MESA_SHADER_NONE;
2113       }
2114    case MESA_SHADER_TASK:
2115       return MESA_SHADER_MESH;
2116    case MESA_SHADER_FRAGMENT:
2117       return MESA_SHADER_NONE;
2118    default:
2119       unreachable("invalid graphics shader stage");
2120    }
2121 }
2122 
2123 static void
radv_fill_shader_info(struct radv_device * device,const enum radv_pipeline_type pipeline_type,const struct radv_graphics_state_key * gfx_state,struct radv_shader_stage * stages,VkShaderStageFlagBits active_nir_stages)2124 radv_fill_shader_info(struct radv_device *device, const enum radv_pipeline_type pipeline_type,
2125                       const struct radv_graphics_state_key *gfx_state, struct radv_shader_stage *stages,
2126                       VkShaderStageFlagBits active_nir_stages)
2127 {
2128    radv_foreach_stage(i, active_nir_stages)
2129    {
2130       bool consider_force_vrs = false;
2131 
2132       if (radv_is_last_vgt_stage(&stages[i])) {
2133          consider_force_vrs = radv_consider_force_vrs(gfx_state, &stages[i], &stages[MESA_SHADER_FRAGMENT]);
2134       }
2135 
2136       radv_nir_shader_info_pass(device, stages[i].nir, &stages[i].layout, &stages[i].key, gfx_state, pipeline_type,
2137                                 consider_force_vrs, &stages[i].info);
2138    }
2139 
2140    radv_nir_shader_info_link(device, gfx_state, stages);
2141 }
2142 
2143 static void
radv_declare_pipeline_args(struct radv_device * device,struct radv_shader_stage * stages,const struct radv_graphics_state_key * gfx_state,VkShaderStageFlagBits active_nir_stages)2144 radv_declare_pipeline_args(struct radv_device *device, struct radv_shader_stage *stages,
2145                            const struct radv_graphics_state_key *gfx_state, VkShaderStageFlagBits active_nir_stages)
2146 {
2147    enum amd_gfx_level gfx_level = device->physical_device->rad_info.gfx_level;
2148 
2149    if (gfx_level >= GFX9 && stages[MESA_SHADER_TESS_CTRL].nir) {
2150       radv_declare_shader_args(device, gfx_state, &stages[MESA_SHADER_TESS_CTRL].info, MESA_SHADER_TESS_CTRL,
2151                                MESA_SHADER_VERTEX, &stages[MESA_SHADER_TESS_CTRL].args);
2152       stages[MESA_SHADER_TESS_CTRL].info.user_sgprs_locs = stages[MESA_SHADER_TESS_CTRL].args.user_sgprs_locs;
2153       stages[MESA_SHADER_TESS_CTRL].info.inline_push_constant_mask =
2154          stages[MESA_SHADER_TESS_CTRL].args.ac.inline_push_const_mask;
2155 
2156       stages[MESA_SHADER_VERTEX].info.user_sgprs_locs = stages[MESA_SHADER_TESS_CTRL].info.user_sgprs_locs;
2157       stages[MESA_SHADER_VERTEX].info.inline_push_constant_mask =
2158          stages[MESA_SHADER_TESS_CTRL].info.inline_push_constant_mask;
2159       stages[MESA_SHADER_VERTEX].args = stages[MESA_SHADER_TESS_CTRL].args;
2160 
2161       active_nir_stages &= ~(1 << MESA_SHADER_VERTEX);
2162       active_nir_stages &= ~(1 << MESA_SHADER_TESS_CTRL);
2163    }
2164 
2165    if (gfx_level >= GFX9 && stages[MESA_SHADER_GEOMETRY].nir) {
2166       gl_shader_stage pre_stage = stages[MESA_SHADER_TESS_EVAL].nir ? MESA_SHADER_TESS_EVAL : MESA_SHADER_VERTEX;
2167       radv_declare_shader_args(device, gfx_state, &stages[MESA_SHADER_GEOMETRY].info, MESA_SHADER_GEOMETRY, pre_stage,
2168                                &stages[MESA_SHADER_GEOMETRY].args);
2169       stages[MESA_SHADER_GEOMETRY].info.user_sgprs_locs = stages[MESA_SHADER_GEOMETRY].args.user_sgprs_locs;
2170       stages[MESA_SHADER_GEOMETRY].info.inline_push_constant_mask =
2171          stages[MESA_SHADER_GEOMETRY].args.ac.inline_push_const_mask;
2172 
2173       stages[pre_stage].info.user_sgprs_locs = stages[MESA_SHADER_GEOMETRY].info.user_sgprs_locs;
2174       stages[pre_stage].info.inline_push_constant_mask = stages[MESA_SHADER_GEOMETRY].info.inline_push_constant_mask;
2175       stages[pre_stage].args = stages[MESA_SHADER_GEOMETRY].args;
2176       active_nir_stages &= ~(1 << pre_stage);
2177       active_nir_stages &= ~(1 << MESA_SHADER_GEOMETRY);
2178    }
2179 
2180    u_foreach_bit (i, active_nir_stages) {
2181       radv_declare_shader_args(device, gfx_state, &stages[i].info, i, MESA_SHADER_NONE, &stages[i].args);
2182       stages[i].info.user_sgprs_locs = stages[i].args.user_sgprs_locs;
2183       stages[i].info.inline_push_constant_mask = stages[i].args.ac.inline_push_const_mask;
2184    }
2185 }
2186 
2187 static struct radv_shader *
radv_create_gs_copy_shader(struct radv_device * device,struct vk_pipeline_cache * cache,struct radv_shader_stage * gs_stage,const struct radv_graphics_state_key * gfx_state,bool keep_executable_info,bool keep_statistic_info,struct radv_shader_binary ** gs_copy_binary)2188 radv_create_gs_copy_shader(struct radv_device *device, struct vk_pipeline_cache *cache,
2189                            struct radv_shader_stage *gs_stage, const struct radv_graphics_state_key *gfx_state,
2190                            bool keep_executable_info, bool keep_statistic_info,
2191                            struct radv_shader_binary **gs_copy_binary)
2192 {
2193    const struct radv_shader_info *gs_info = &gs_stage->info;
2194    ac_nir_gs_output_info output_info = {
2195       .streams = gs_info->gs.output_streams,
2196       .usage_mask = gs_info->gs.output_usage_mask,
2197    };
2198    nir_shader *nir = ac_nir_create_gs_copy_shader(
2199       gs_stage->nir, device->physical_device->rad_info.gfx_level,
2200       gs_info->outinfo.clip_dist_mask | gs_info->outinfo.cull_dist_mask, gs_info->outinfo.vs_output_param_offset,
2201       gs_info->outinfo.param_exports, false, false, false, gs_info->force_vrs_per_vertex, &output_info);
2202 
2203    nir_validate_shader(nir, "after ac_nir_create_gs_copy_shader");
2204    nir_shader_gather_info(nir, nir_shader_get_entrypoint(nir));
2205 
2206    struct radv_shader_stage gs_copy_stage = {
2207       .stage = MESA_SHADER_VERTEX,
2208       .shader_sha1 = {0},
2209       .key =
2210          {
2211             .optimisations_disabled = gs_stage->key.optimisations_disabled,
2212          },
2213    };
2214    radv_nir_shader_info_init(gs_copy_stage.stage, MESA_SHADER_FRAGMENT, &gs_copy_stage.info);
2215    radv_nir_shader_info_pass(device, nir, &gs_stage->layout, &gs_stage->key, gfx_state, RADV_PIPELINE_GRAPHICS, false,
2216                              &gs_copy_stage.info);
2217    gs_copy_stage.info.wave_size = 64;      /* Wave32 not supported. */
2218    gs_copy_stage.info.workgroup_size = 64; /* HW VS: separate waves, no workgroups */
2219    gs_copy_stage.info.so = gs_info->so;
2220    gs_copy_stage.info.outinfo = gs_info->outinfo;
2221    gs_copy_stage.info.force_vrs_per_vertex = gs_info->force_vrs_per_vertex;
2222    gs_copy_stage.info.type = RADV_SHADER_TYPE_GS_COPY;
2223 
2224    radv_declare_shader_args(device, gfx_state, &gs_copy_stage.info, MESA_SHADER_VERTEX, MESA_SHADER_NONE,
2225                             &gs_copy_stage.args);
2226    gs_copy_stage.info.user_sgprs_locs = gs_copy_stage.args.user_sgprs_locs;
2227    gs_copy_stage.info.inline_push_constant_mask = gs_copy_stage.args.ac.inline_push_const_mask;
2228 
2229    NIR_PASS_V(nir, ac_nir_lower_intrinsics_to_args, device->physical_device->rad_info.gfx_level, AC_HW_VERTEX_SHADER,
2230               &gs_copy_stage.args.ac);
2231    NIR_PASS_V(nir, radv_nir_lower_abi, device->physical_device->rad_info.gfx_level, &gs_copy_stage, gfx_state,
2232               device->physical_device->rad_info.address32_hi);
2233 
2234    struct radv_graphics_pipeline_key key = {0};
2235    bool dump_shader = radv_can_dump_shader(device, nir, true);
2236 
2237    *gs_copy_binary = radv_shader_nir_to_asm(device, &gs_copy_stage, &nir, 1, &key.gfx_state, keep_executable_info,
2238                                             keep_statistic_info);
2239    struct radv_shader *copy_shader =
2240       radv_shader_create(device, cache, *gs_copy_binary, keep_executable_info || dump_shader);
2241    if (copy_shader)
2242       radv_shader_generate_debug_info(device, dump_shader, keep_executable_info, *gs_copy_binary, copy_shader, &nir, 1,
2243                                       &gs_copy_stage.info);
2244    return copy_shader;
2245 }
2246 
2247 static void
radv_graphics_shaders_nir_to_asm(struct radv_device * device,struct vk_pipeline_cache * cache,struct radv_shader_stage * stages,const struct radv_graphics_state_key * gfx_state,bool keep_executable_info,bool keep_statistic_info,VkShaderStageFlagBits active_nir_stages,struct radv_shader ** shaders,struct radv_shader_binary ** binaries,struct radv_shader ** gs_copy_shader,struct radv_shader_binary ** gs_copy_binary)2248 radv_graphics_shaders_nir_to_asm(struct radv_device *device, struct vk_pipeline_cache *cache,
2249                                  struct radv_shader_stage *stages, const struct radv_graphics_state_key *gfx_state,
2250                                  bool keep_executable_info, bool keep_statistic_info,
2251                                  VkShaderStageFlagBits active_nir_stages, struct radv_shader **shaders,
2252                                  struct radv_shader_binary **binaries, struct radv_shader **gs_copy_shader,
2253                                  struct radv_shader_binary **gs_copy_binary)
2254 {
2255    for (int s = MESA_VULKAN_SHADER_STAGES - 1; s >= 0; s--) {
2256       if (!(active_nir_stages & (1 << s)))
2257          continue;
2258 
2259       nir_shader *nir_shaders[2] = {stages[s].nir, NULL};
2260       unsigned shader_count = 1;
2261 
2262       /* On GFX9+, TES is merged with GS and VS is merged with TCS or GS. */
2263       if (device->physical_device->rad_info.gfx_level >= GFX9 &&
2264           ((s == MESA_SHADER_GEOMETRY &&
2265             (active_nir_stages & (VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT))) ||
2266            (s == MESA_SHADER_TESS_CTRL && (active_nir_stages & VK_SHADER_STAGE_VERTEX_BIT)))) {
2267          gl_shader_stage pre_stage;
2268 
2269          if (s == MESA_SHADER_GEOMETRY && (active_nir_stages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)) {
2270             pre_stage = MESA_SHADER_TESS_EVAL;
2271          } else {
2272             pre_stage = MESA_SHADER_VERTEX;
2273          }
2274 
2275          nir_shaders[0] = stages[pre_stage].nir;
2276          nir_shaders[1] = stages[s].nir;
2277          shader_count = 2;
2278       }
2279 
2280       int64_t stage_start = os_time_get_nano();
2281 
2282       bool dump_shader = radv_can_dump_shader(device, nir_shaders[0], false);
2283 
2284       binaries[s] = radv_shader_nir_to_asm(device, &stages[s], nir_shaders, shader_count, gfx_state,
2285                                            keep_executable_info, keep_statistic_info);
2286       shaders[s] = radv_shader_create(device, cache, binaries[s], keep_executable_info || dump_shader);
2287       radv_shader_generate_debug_info(device, dump_shader, keep_executable_info, binaries[s], shaders[s], nir_shaders,
2288                                       shader_count, &stages[s].info);
2289 
2290       if (s == MESA_SHADER_GEOMETRY && !stages[s].info.is_ngg) {
2291          *gs_copy_shader = radv_create_gs_copy_shader(device, cache, &stages[MESA_SHADER_GEOMETRY], gfx_state,
2292                                                       keep_executable_info, keep_statistic_info, gs_copy_binary);
2293       }
2294 
2295       stages[s].feedback.duration += os_time_get_nano() - stage_start;
2296 
2297       active_nir_stages &= ~(1 << nir_shaders[0]->info.stage);
2298       if (nir_shaders[1])
2299          active_nir_stages &= ~(1 << nir_shaders[1]->info.stage);
2300    }
2301 }
2302 
2303 static void
radv_pipeline_retain_shaders(struct radv_retained_shaders * retained_shaders,struct radv_shader_stage * stages)2304 radv_pipeline_retain_shaders(struct radv_retained_shaders *retained_shaders, struct radv_shader_stage *stages)
2305 {
2306    for (unsigned s = 0; s < MESA_VULKAN_SHADER_STAGES; s++) {
2307       if (!stages[s].entrypoint)
2308          continue;
2309 
2310       int64_t stage_start = os_time_get_nano();
2311 
2312       /* Serialize the NIR shader to reduce memory pressure. */
2313       struct blob blob;
2314 
2315       blob_init(&blob);
2316       nir_serialize(&blob, stages[s].nir, true);
2317       blob_finish_get_buffer(&blob, &retained_shaders->stages[s].serialized_nir,
2318                              &retained_shaders->stages[s].serialized_nir_size);
2319 
2320       memcpy(retained_shaders->stages[s].shader_sha1, stages[s].shader_sha1, sizeof(stages[s].shader_sha1));
2321       memcpy(&retained_shaders->stages[s].key, &stages[s].key, sizeof(stages[s].key));
2322 
2323       stages[s].feedback.duration += os_time_get_nano() - stage_start;
2324    }
2325 }
2326 
2327 static void
radv_pipeline_import_retained_shaders(const struct radv_device * device,struct radv_graphics_pipeline * pipeline,struct radv_graphics_lib_pipeline * lib,struct radv_shader_stage * stages)2328 radv_pipeline_import_retained_shaders(const struct radv_device *device, struct radv_graphics_pipeline *pipeline,
2329                                       struct radv_graphics_lib_pipeline *lib, struct radv_shader_stage *stages)
2330 {
2331    struct radv_retained_shaders *retained_shaders = &lib->retained_shaders;
2332 
2333    /* Import the stages (SPIR-V only in case of cache hits). */
2334    for (uint32_t i = 0; i < lib->stage_count; i++) {
2335       const VkPipelineShaderStageCreateInfo *sinfo = &lib->stages[i];
2336       gl_shader_stage s = vk_to_mesa_shader_stage(sinfo->stage);
2337 
2338       /* Ignore graphics shader stages that don't need to be imported. */
2339       if (!(shader_stage_to_pipeline_library_flags(sinfo->stage) & lib->lib_flags))
2340          continue;
2341 
2342       radv_pipeline_stage_init(sinfo, &lib->layout, &lib->stage_keys[s], &stages[s]);
2343    }
2344 
2345    /* Import the NIR shaders (after SPIRV->NIR). */
2346    for (uint32_t s = 0; s < ARRAY_SIZE(lib->base.base.shaders); s++) {
2347       if (!retained_shaders->stages[s].serialized_nir_size)
2348          continue;
2349 
2350       int64_t stage_start = os_time_get_nano();
2351 
2352       /* Deserialize the NIR shader. */
2353       const struct nir_shader_compiler_options *options = &device->physical_device->nir_options[s];
2354       struct blob_reader blob_reader;
2355       blob_reader_init(&blob_reader, retained_shaders->stages[s].serialized_nir,
2356                        retained_shaders->stages[s].serialized_nir_size);
2357 
2358       stages[s].stage = s;
2359       stages[s].nir = nir_deserialize(NULL, options, &blob_reader);
2360       stages[s].entrypoint = nir_shader_get_entrypoint(stages[s].nir)->function->name;
2361       memcpy(stages[s].shader_sha1, retained_shaders->stages[s].shader_sha1, sizeof(stages[s].shader_sha1));
2362       memcpy(&stages[s].key, &retained_shaders->stages[s].key, sizeof(stages[s].key));
2363 
2364       radv_shader_layout_init(&lib->layout, s, &stages[s].layout);
2365 
2366       stages[s].feedback.flags |= VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT;
2367 
2368       stages[s].feedback.duration += os_time_get_nano() - stage_start;
2369    }
2370 }
2371 
2372 static void
radv_pipeline_load_retained_shaders(const struct radv_device * device,struct radv_graphics_pipeline * pipeline,const VkGraphicsPipelineCreateInfo * pCreateInfo,struct radv_shader_stage * stages)2373 radv_pipeline_load_retained_shaders(const struct radv_device *device, struct radv_graphics_pipeline *pipeline,
2374                                     const VkGraphicsPipelineCreateInfo *pCreateInfo, struct radv_shader_stage *stages)
2375 {
2376    const VkPipelineLibraryCreateInfoKHR *libs_info =
2377       vk_find_struct_const(pCreateInfo->pNext, PIPELINE_LIBRARY_CREATE_INFO_KHR);
2378    const bool link_optimize = (pipeline->base.create_flags & VK_PIPELINE_CREATE_2_LINK_TIME_OPTIMIZATION_BIT_EXT) != 0;
2379 
2380    /* Nothing to load if no libs are imported. */
2381    if (!libs_info)
2382       return;
2383 
2384    /* Nothing to load if fast-linking is enabled and if there is no retained shaders. */
2385    if (!link_optimize && !pipeline->retain_shaders)
2386       return;
2387 
2388    for (uint32_t i = 0; i < libs_info->libraryCount; i++) {
2389       RADV_FROM_HANDLE(radv_pipeline, pipeline_lib, libs_info->pLibraries[i]);
2390       struct radv_graphics_lib_pipeline *gfx_pipeline_lib = radv_pipeline_to_graphics_lib(pipeline_lib);
2391 
2392       radv_pipeline_import_retained_shaders(device, pipeline, gfx_pipeline_lib, stages);
2393    }
2394 }
2395 
2396 static unsigned
radv_get_rasterization_prim(const struct radv_shader_stage * stages,const struct radv_graphics_state_key * gfx_state)2397 radv_get_rasterization_prim(const struct radv_shader_stage *stages, const struct radv_graphics_state_key *gfx_state)
2398 {
2399    unsigned rast_prim;
2400 
2401    if (gfx_state->unknown_rast_prim)
2402       return -1;
2403 
2404    if (stages[MESA_SHADER_GEOMETRY].nir) {
2405       rast_prim = radv_conv_gl_prim_to_gs_out(stages[MESA_SHADER_GEOMETRY].nir->info.gs.output_primitive);
2406    } else if (stages[MESA_SHADER_TESS_EVAL].nir) {
2407       if (stages[MESA_SHADER_TESS_EVAL].nir->info.tess.point_mode) {
2408          rast_prim = V_028A6C_POINTLIST;
2409       } else {
2410          rast_prim = radv_conv_tess_prim_to_gs_out(stages[MESA_SHADER_TESS_EVAL].nir->info.tess._primitive_mode);
2411       }
2412    } else if (stages[MESA_SHADER_MESH].nir) {
2413       rast_prim = radv_conv_gl_prim_to_gs_out(stages[MESA_SHADER_MESH].nir->info.mesh.primitive_type);
2414    } else {
2415       rast_prim = radv_conv_prim_to_gs_out(gfx_state->ia.topology, false);
2416    }
2417 
2418    return rast_prim;
2419 }
2420 
2421 static bool
radv_skip_graphics_pipeline_compile(const struct radv_device * device,const struct radv_graphics_pipeline * pipeline,VkGraphicsPipelineLibraryFlagBitsEXT lib_flags,bool fast_linking_enabled)2422 radv_skip_graphics_pipeline_compile(const struct radv_device *device, const struct radv_graphics_pipeline *pipeline,
2423                                     VkGraphicsPipelineLibraryFlagBitsEXT lib_flags, bool fast_linking_enabled)
2424 {
2425    VkShaderStageFlagBits binary_stages = 0;
2426 
2427    /* Do not skip when fast-linking isn't enabled. */
2428    if (!fast_linking_enabled)
2429       return false;
2430 
2431    /* Determine which shader stages have been imported. */
2432    if (pipeline->base.shaders[MESA_SHADER_MESH]) {
2433       binary_stages |= VK_SHADER_STAGE_MESH_BIT_EXT;
2434       if (pipeline->base.shaders[MESA_SHADER_TASK]) {
2435          binary_stages |= VK_SHADER_STAGE_TASK_BIT_EXT;
2436       }
2437    } else {
2438       for (uint32_t i = 0; i < MESA_SHADER_COMPUTE; i++) {
2439          if (!pipeline->base.shaders[i])
2440             continue;
2441 
2442          binary_stages |= mesa_to_vk_shader_stage(i);
2443       }
2444 
2445       if (device->physical_device->rad_info.gfx_level >= GFX9) {
2446          /* On GFX9+, TES is merged with GS and VS is merged with TCS or GS. */
2447          if (binary_stages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) {
2448             binary_stages |= VK_SHADER_STAGE_VERTEX_BIT;
2449          }
2450 
2451          if (binary_stages & VK_SHADER_STAGE_GEOMETRY_BIT) {
2452             if (binary_stages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) {
2453                binary_stages |= VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
2454             } else {
2455                binary_stages |= VK_SHADER_STAGE_VERTEX_BIT;
2456             }
2457          }
2458       }
2459    }
2460 
2461    /* Only skip compilation when all binaries have been imported. */
2462    return binary_stages == pipeline->active_stages;
2463 }
2464 
2465 void
radv_graphics_shaders_compile(struct radv_device * device,struct vk_pipeline_cache * cache,struct radv_shader_stage * stages,const struct radv_graphics_state_key * gfx_state,bool keep_executable_info,bool keep_statistic_info,bool is_internal,struct radv_retained_shaders * retained_shaders,bool noop_fs,struct radv_shader ** shaders,struct radv_shader_binary ** binaries,struct radv_shader ** gs_copy_shader,struct radv_shader_binary ** gs_copy_binary)2466 radv_graphics_shaders_compile(struct radv_device *device, struct vk_pipeline_cache *cache,
2467                               struct radv_shader_stage *stages, const struct radv_graphics_state_key *gfx_state,
2468                               bool keep_executable_info, bool keep_statistic_info, bool is_internal,
2469                               struct radv_retained_shaders *retained_shaders, bool noop_fs,
2470                               struct radv_shader **shaders, struct radv_shader_binary **binaries,
2471                               struct radv_shader **gs_copy_shader, struct radv_shader_binary **gs_copy_binary)
2472 {
2473    const bool nir_cache = device->instance->perftest_flags & RADV_PERFTEST_NIR_CACHE;
2474    for (unsigned s = 0; s < MESA_VULKAN_SHADER_STAGES; s++) {
2475       if (!stages[s].entrypoint)
2476          continue;
2477 
2478       int64_t stage_start = os_time_get_nano();
2479 
2480       /* NIR might already have been imported from a library. */
2481       if (!stages[s].nir) {
2482          struct radv_spirv_to_nir_options options = {
2483             .lower_view_index_to_zero = !gfx_state->has_multiview_view_index,
2484             .fix_dual_src_mrt1_export =
2485                gfx_state->ps.epilog.mrt0_is_dual_src && device->instance->drirc.dual_color_blend_by_location,
2486          };
2487          blake3_hash key;
2488 
2489          if (nir_cache) {
2490             radv_hash_graphics_spirv_to_nir(key, &stages[s], &options);
2491             stages[s].nir = radv_pipeline_cache_lookup_nir(device, cache, s, key);
2492          }
2493          if (!stages[s].nir) {
2494             stages[s].nir = radv_shader_spirv_to_nir(device, &stages[s], &options, is_internal);
2495             if (nir_cache)
2496                radv_pipeline_cache_insert_nir(device, cache, key, stages[s].nir);
2497          }
2498       }
2499 
2500       stages[s].feedback.duration += os_time_get_nano() - stage_start;
2501    }
2502 
2503    if (retained_shaders) {
2504       radv_pipeline_retain_shaders(retained_shaders, stages);
2505    }
2506 
2507    VkShaderStageFlagBits active_nir_stages = 0;
2508    for (int i = 0; i < MESA_VULKAN_SHADER_STAGES; i++) {
2509       if (stages[i].nir)
2510          active_nir_stages |= mesa_to_vk_shader_stage(i);
2511    }
2512 
2513    if (!device->physical_device->mesh_fast_launch_2 && stages[MESA_SHADER_MESH].nir &&
2514        BITSET_TEST(stages[MESA_SHADER_MESH].nir->info.system_values_read, SYSTEM_VALUE_WORKGROUP_ID)) {
2515       nir_shader *mesh = stages[MESA_SHADER_MESH].nir;
2516       nir_shader *task = stages[MESA_SHADER_TASK].nir;
2517 
2518       /* Mesh shaders only have a 1D "vertex index" which we use
2519        * as "workgroup index" to emulate the 3D workgroup ID.
2520        */
2521       nir_lower_compute_system_values_options o = {
2522          .lower_workgroup_id_to_index = true,
2523          .shortcut_1d_workgroup_id = true,
2524          .num_workgroups[0] = task ? task->info.mesh.ts_mesh_dispatch_dimensions[0] : 0,
2525          .num_workgroups[1] = task ? task->info.mesh.ts_mesh_dispatch_dimensions[1] : 0,
2526          .num_workgroups[2] = task ? task->info.mesh.ts_mesh_dispatch_dimensions[2] : 0,
2527       };
2528 
2529       NIR_PASS(_, mesh, nir_lower_compute_system_values, &o);
2530    }
2531 
2532    radv_foreach_stage(i, active_nir_stages)
2533    {
2534       gl_shader_stage next_stage;
2535 
2536       if (stages[i].next_stage != MESA_SHADER_NONE) {
2537          next_stage = stages[i].next_stage;
2538       } else {
2539          next_stage = radv_get_next_stage(i, active_nir_stages);
2540       }
2541 
2542       radv_nir_shader_info_init(i, next_stage, &stages[i].info);
2543    }
2544 
2545    /* Determine if shaders uses NGG before linking because it's needed for some NIR pass. */
2546    radv_fill_shader_info_ngg(device, stages, active_nir_stages);
2547 
2548    if (stages[MESA_SHADER_GEOMETRY].nir) {
2549       unsigned nir_gs_flags = nir_lower_gs_intrinsics_per_stream;
2550 
2551       if (stages[MESA_SHADER_GEOMETRY].info.is_ngg) {
2552          nir_gs_flags |= nir_lower_gs_intrinsics_count_primitives |
2553                          nir_lower_gs_intrinsics_count_vertices_per_primitive |
2554                          nir_lower_gs_intrinsics_overwrite_incomplete;
2555       }
2556 
2557       NIR_PASS(_, stages[MESA_SHADER_GEOMETRY].nir, nir_lower_gs_intrinsics, nir_gs_flags);
2558    }
2559 
2560    /* Remove all varyings when the fragment shader is a noop. */
2561    if (noop_fs) {
2562       radv_foreach_stage(i, active_nir_stages)
2563       {
2564          if (radv_is_last_vgt_stage(&stages[i])) {
2565             radv_remove_varyings(stages[i].nir);
2566             break;
2567          }
2568       }
2569    }
2570 
2571    radv_graphics_shaders_link(device, gfx_state, stages);
2572 
2573    if (stages[MESA_SHADER_FRAGMENT].nir) {
2574       unsigned rast_prim = radv_get_rasterization_prim(stages, gfx_state);
2575 
2576       NIR_PASS(_, stages[MESA_SHADER_FRAGMENT].nir, radv_nir_lower_fs_barycentric, gfx_state, rast_prim);
2577    }
2578 
2579    radv_foreach_stage(i, active_nir_stages)
2580    {
2581       int64_t stage_start = os_time_get_nano();
2582 
2583       radv_optimize_nir(stages[i].nir, stages[i].key.optimisations_disabled);
2584 
2585       /* Gather info again, information such as outputs_read can be out-of-date. */
2586       nir_shader_gather_info(stages[i].nir, nir_shader_get_entrypoint(stages[i].nir));
2587       radv_nir_lower_io(device, stages[i].nir);
2588 
2589       stages[i].feedback.duration += os_time_get_nano() - stage_start;
2590    }
2591 
2592    if (stages[MESA_SHADER_FRAGMENT].nir) {
2593       radv_nir_lower_poly_line_smooth(stages[MESA_SHADER_FRAGMENT].nir, gfx_state);
2594    }
2595 
2596    radv_fill_shader_info(device, RADV_PIPELINE_GRAPHICS, gfx_state, stages, active_nir_stages);
2597 
2598    radv_declare_pipeline_args(device, stages, gfx_state, active_nir_stages);
2599 
2600    radv_foreach_stage(i, active_nir_stages)
2601    {
2602       int64_t stage_start = os_time_get_nano();
2603 
2604       radv_postprocess_nir(device, gfx_state, &stages[i]);
2605 
2606       stages[i].feedback.duration += os_time_get_nano() - stage_start;
2607 
2608       if (radv_can_dump_shader(device, stages[i].nir, false))
2609          nir_print_shader(stages[i].nir, stderr);
2610    }
2611 
2612    /* Compile NIR shaders to AMD assembly. */
2613    radv_graphics_shaders_nir_to_asm(device, cache, stages, gfx_state, keep_executable_info, keep_statistic_info,
2614                                     active_nir_stages, shaders, binaries, gs_copy_shader, gs_copy_binary);
2615 
2616    if (keep_executable_info) {
2617       for (int i = 0; i < MESA_VULKAN_SHADER_STAGES; ++i) {
2618          struct radv_shader *shader = shaders[i];
2619          if (!shader)
2620             continue;
2621 
2622          if (!stages[i].spirv.size)
2623             continue;
2624 
2625          shader->spirv = malloc(stages[i].spirv.size);
2626          memcpy(shader->spirv, stages[i].spirv.data, stages[i].spirv.size);
2627          shader->spirv_size = stages[i].spirv.size;
2628       }
2629    }
2630 }
2631 
2632 static bool
radv_should_compute_pipeline_hash(const struct radv_device * device,const struct radv_graphics_pipeline * pipeline,bool fast_linking_enabled)2633 radv_should_compute_pipeline_hash(const struct radv_device *device, const struct radv_graphics_pipeline *pipeline,
2634                                   bool fast_linking_enabled)
2635 {
2636    /* Skip computing the pipeline hash when GPL fast-linking is enabled because these shaders aren't
2637     * supposed to be cached and computing the hash is costly. Though, make sure it's always computed
2638     * when RGP is enabled, otherwise ISA isn't reported.
2639     */
2640    return !fast_linking_enabled ||
2641           ((device->instance->vk.trace_mode & RADV_TRACE_MODE_RGP) && pipeline->base.type == RADV_PIPELINE_GRAPHICS);
2642 }
2643 
2644 static VkResult
radv_graphics_pipeline_compile(struct radv_graphics_pipeline * pipeline,const VkGraphicsPipelineCreateInfo * pCreateInfo,struct radv_pipeline_layout * pipeline_layout,struct radv_device * device,struct vk_pipeline_cache * cache,const struct radv_graphics_pipeline_key * pipeline_key,VkGraphicsPipelineLibraryFlagBitsEXT lib_flags,bool fast_linking_enabled)2645 radv_graphics_pipeline_compile(struct radv_graphics_pipeline *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo,
2646                                struct radv_pipeline_layout *pipeline_layout, struct radv_device *device,
2647                                struct vk_pipeline_cache *cache, const struct radv_graphics_pipeline_key *pipeline_key,
2648                                VkGraphicsPipelineLibraryFlagBitsEXT lib_flags, bool fast_linking_enabled)
2649 {
2650    struct radv_shader_binary *binaries[MESA_VULKAN_SHADER_STAGES] = {NULL};
2651    struct radv_shader_binary *gs_copy_binary = NULL;
2652    unsigned char hash[20];
2653    bool keep_executable_info = radv_pipeline_capture_shaders(device, pipeline->base.create_flags);
2654    bool keep_statistic_info = radv_pipeline_capture_shader_stats(device, pipeline->base.create_flags);
2655    struct radv_shader_stage stages[MESA_VULKAN_SHADER_STAGES];
2656    const VkPipelineCreationFeedbackCreateInfo *creation_feedback =
2657       vk_find_struct_const(pCreateInfo->pNext, PIPELINE_CREATION_FEEDBACK_CREATE_INFO);
2658    VkPipelineCreationFeedback pipeline_feedback = {
2659       .flags = VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT,
2660    };
2661    bool skip_shaders_cache = false;
2662    VkResult result = VK_SUCCESS;
2663    const bool retain_shaders =
2664       !!(pipeline->base.create_flags & VK_PIPELINE_CREATE_2_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT);
2665    struct radv_retained_shaders *retained_shaders = NULL;
2666 
2667    int64_t pipeline_start = os_time_get_nano();
2668 
2669    for (unsigned i = 0; i < MESA_VULKAN_SHADER_STAGES; i++) {
2670       stages[i].entrypoint = NULL;
2671       stages[i].nir = NULL;
2672       stages[i].spirv.size = 0;
2673       stages[i].next_stage = MESA_SHADER_NONE;
2674    }
2675 
2676    for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2677       const VkPipelineShaderStageCreateInfo *sinfo = &pCreateInfo->pStages[i];
2678       gl_shader_stage stage = vk_to_mesa_shader_stage(sinfo->stage);
2679 
2680       /* Ignore graphics shader stages that don't need to be imported. */
2681       if (!(shader_stage_to_pipeline_library_flags(sinfo->stage) & lib_flags))
2682          continue;
2683 
2684       radv_pipeline_stage_init(sinfo, pipeline_layout, &pipeline_key->stage_info[stage], &stages[stage]);
2685    }
2686 
2687    radv_pipeline_load_retained_shaders(device, pipeline, pCreateInfo, stages);
2688 
2689    if (radv_should_compute_pipeline_hash(device, pipeline, fast_linking_enabled)) {
2690       radv_hash_shaders(device, hash, stages, MESA_VULKAN_SHADER_STAGES, pipeline_layout, &pipeline_key->gfx_state);
2691 
2692       pipeline->base.pipeline_hash = *(uint64_t *)hash;
2693    }
2694 
2695    /* Skip the shaders cache when any of the below are true:
2696     * - fast-linking is enabled because it's useless to cache unoptimized pipelines
2697     * - shaders are captured because it's for debugging purposes
2698     * - graphics pipeline libraries are created with the RETAIN_LINK_TIME_OPTIMIZATION flag and
2699     *   module identifiers are used (ie. no SPIR-V provided).
2700     */
2701    if (fast_linking_enabled || keep_executable_info) {
2702       skip_shaders_cache = true;
2703    } else if (retain_shaders) {
2704       assert(pipeline->base.create_flags & VK_PIPELINE_CREATE_2_LIBRARY_BIT_KHR);
2705       for (uint32_t i = 0; i < MESA_VULKAN_SHADER_STAGES; i++) {
2706          if (stages[i].entrypoint && !stages[i].spirv.size) {
2707             skip_shaders_cache = true;
2708             break;
2709          }
2710       }
2711    }
2712 
2713    bool found_in_application_cache = true;
2714    if (!skip_shaders_cache &&
2715        radv_pipeline_cache_search(device, cache, &pipeline->base, hash, &found_in_application_cache)) {
2716       if (found_in_application_cache)
2717          pipeline_feedback.flags |= VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT;
2718 
2719       if (retain_shaders) {
2720          /* For graphics pipeline libraries created with the RETAIN_LINK_TIME_OPTIMIZATION flag, we
2721           * need to retain the stage info because we can't know if the LTO pipelines will
2722           * be find in the shaders cache.
2723           */
2724          struct radv_graphics_lib_pipeline *gfx_pipeline_lib = radv_pipeline_to_graphics_lib(&pipeline->base);
2725 
2726          gfx_pipeline_lib->stages = radv_copy_shader_stage_create_info(device, pCreateInfo->stageCount,
2727                                                                        pCreateInfo->pStages, gfx_pipeline_lib->mem_ctx);
2728          if (!gfx_pipeline_lib->stages)
2729             return VK_ERROR_OUT_OF_HOST_MEMORY;
2730 
2731          gfx_pipeline_lib->stage_count = pCreateInfo->stageCount;
2732 
2733          for (unsigned i = 0; i < pCreateInfo->stageCount; i++) {
2734             gl_shader_stage s = vk_to_mesa_shader_stage(pCreateInfo->pStages[i].stage);
2735             gfx_pipeline_lib->stage_keys[s] = pipeline_key->stage_info[s];
2736          }
2737       }
2738 
2739       result = VK_SUCCESS;
2740       goto done;
2741    }
2742 
2743    if (pipeline->base.create_flags & VK_PIPELINE_CREATE_2_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_KHR)
2744       return VK_PIPELINE_COMPILE_REQUIRED;
2745 
2746    if (retain_shaders) {
2747       struct radv_graphics_lib_pipeline *gfx_pipeline_lib = radv_pipeline_to_graphics_lib(&pipeline->base);
2748       retained_shaders = &gfx_pipeline_lib->retained_shaders;
2749    }
2750 
2751    const bool noop_fs = radv_pipeline_needs_noop_fs(pipeline, &pipeline_key->gfx_state);
2752 
2753    radv_graphics_shaders_compile(device, cache, stages, &pipeline_key->gfx_state, keep_executable_info,
2754                                  keep_statistic_info, pipeline->base.is_internal, retained_shaders, noop_fs,
2755                                  pipeline->base.shaders, binaries, &pipeline->base.gs_copy_shader, &gs_copy_binary);
2756 
2757    if (!skip_shaders_cache) {
2758       radv_pipeline_cache_insert(device, cache, &pipeline->base, hash);
2759    }
2760 
2761    free(gs_copy_binary);
2762    for (int i = 0; i < MESA_VULKAN_SHADER_STAGES; ++i) {
2763       free(binaries[i]);
2764       if (stages[i].nir) {
2765          if (radv_can_dump_shader_stats(device, stages[i].nir) && pipeline->base.shaders[i]) {
2766             radv_dump_shader_stats(device, &pipeline->base, pipeline->base.shaders[i], i, stderr);
2767          }
2768       }
2769    }
2770 
2771 done:
2772    for (int i = 0; i < MESA_VULKAN_SHADER_STAGES; ++i) {
2773       ralloc_free(stages[i].nir);
2774    }
2775    pipeline_feedback.duration = os_time_get_nano() - pipeline_start;
2776 
2777    if (creation_feedback) {
2778       *creation_feedback->pPipelineCreationFeedback = pipeline_feedback;
2779 
2780       if (creation_feedback->pipelineStageCreationFeedbackCount > 0) {
2781          uint32_t num_feedbacks = 0;
2782 
2783          for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
2784             gl_shader_stage s = vk_to_mesa_shader_stage(pCreateInfo->pStages[i].stage);
2785             creation_feedback->pPipelineStageCreationFeedbacks[num_feedbacks++] = stages[s].feedback;
2786          }
2787 
2788          /* Stages imported from graphics pipeline libraries are defined as additional entries in the
2789           * order they were imported.
2790           */
2791          const VkPipelineLibraryCreateInfoKHR *libs_info =
2792             vk_find_struct_const(pCreateInfo->pNext, PIPELINE_LIBRARY_CREATE_INFO_KHR);
2793          if (libs_info) {
2794             for (uint32_t i = 0; i < libs_info->libraryCount; i++) {
2795                RADV_FROM_HANDLE(radv_pipeline, pipeline_lib, libs_info->pLibraries[i]);
2796                struct radv_graphics_lib_pipeline *gfx_pipeline_lib = radv_pipeline_to_graphics_lib(pipeline_lib);
2797 
2798                if (!gfx_pipeline_lib->base.active_stages)
2799                   continue;
2800 
2801                radv_foreach_stage(s, gfx_pipeline_lib->base.active_stages)
2802                {
2803                   creation_feedback->pPipelineStageCreationFeedbacks[num_feedbacks++] = stages[s].feedback;
2804                }
2805             }
2806          }
2807 
2808          assert(num_feedbacks == creation_feedback->pipelineStageCreationFeedbackCount);
2809       }
2810    }
2811 
2812    return result;
2813 }
2814 
2815 static void
radv_pipeline_emit_blend_state(struct radeon_cmdbuf * ctx_cs,const struct radv_graphics_pipeline * pipeline,const struct radv_blend_state * blend)2816 radv_pipeline_emit_blend_state(struct radeon_cmdbuf *ctx_cs, const struct radv_graphics_pipeline *pipeline,
2817                                const struct radv_blend_state *blend)
2818 {
2819    struct radv_shader *ps = pipeline->base.shaders[MESA_SHADER_FRAGMENT];
2820 
2821    if (ps && ps->info.has_epilog)
2822       return;
2823 
2824    radeon_set_context_reg(ctx_cs, R_028714_SPI_SHADER_COL_FORMAT, blend->spi_shader_col_format);
2825 
2826    radeon_set_context_reg(ctx_cs, R_02823C_CB_SHADER_MASK, blend->cb_shader_mask);
2827 }
2828 
2829 void
radv_emit_vgt_gs_mode(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,const struct radv_shader * last_vgt_api_shader)2830 radv_emit_vgt_gs_mode(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs,
2831                       const struct radv_shader *last_vgt_api_shader)
2832 {
2833    const struct radv_physical_device *pdevice = device->physical_device;
2834    const struct radv_shader_info *info = &last_vgt_api_shader->info;
2835    unsigned vgt_primitiveid_en = 0;
2836    uint32_t vgt_gs_mode = 0;
2837 
2838    if (info->is_ngg)
2839       return;
2840 
2841    if (info->stage == MESA_SHADER_GEOMETRY) {
2842       vgt_gs_mode = ac_vgt_gs_mode(info->gs.vertices_out, pdevice->rad_info.gfx_level);
2843    } else if (info->outinfo.export_prim_id || info->uses_prim_id) {
2844       vgt_gs_mode = S_028A40_MODE(V_028A40_GS_SCENARIO_A);
2845       vgt_primitiveid_en |= S_028A84_PRIMITIVEID_EN(1);
2846    }
2847 
2848    radeon_set_context_reg(ctx_cs, R_028A84_VGT_PRIMITIVEID_EN, vgt_primitiveid_en);
2849    radeon_set_context_reg(ctx_cs, R_028A40_VGT_GS_MODE, vgt_gs_mode);
2850 }
2851 
2852 static void
radv_emit_hw_vs(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,struct radeon_cmdbuf * cs,const struct radv_shader * shader)2853 radv_emit_hw_vs(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, struct radeon_cmdbuf *cs,
2854                 const struct radv_shader *shader)
2855 {
2856    const struct radv_physical_device *pdevice = device->physical_device;
2857    uint64_t va = radv_shader_get_va(shader);
2858 
2859    radeon_set_sh_reg_seq(cs, R_00B120_SPI_SHADER_PGM_LO_VS, 4);
2860    radeon_emit(cs, va >> 8);
2861    radeon_emit(cs, S_00B124_MEM_BASE(va >> 40));
2862    radeon_emit(cs, shader->config.rsrc1);
2863    radeon_emit(cs, shader->config.rsrc2);
2864 
2865    const struct radv_vs_output_info *outinfo = &shader->info.outinfo;
2866    unsigned clip_dist_mask, cull_dist_mask, total_mask;
2867    clip_dist_mask = outinfo->clip_dist_mask;
2868    cull_dist_mask = outinfo->cull_dist_mask;
2869    total_mask = clip_dist_mask | cull_dist_mask;
2870 
2871    bool misc_vec_ena = outinfo->writes_pointsize || outinfo->writes_layer || outinfo->writes_viewport_index ||
2872                        outinfo->writes_primitive_shading_rate;
2873    unsigned spi_vs_out_config, nparams;
2874 
2875    /* VS is required to export at least one param. */
2876    nparams = MAX2(outinfo->param_exports, 1);
2877    spi_vs_out_config = S_0286C4_VS_EXPORT_COUNT(nparams - 1);
2878 
2879    if (pdevice->rad_info.gfx_level >= GFX10) {
2880       spi_vs_out_config |= S_0286C4_NO_PC_EXPORT(outinfo->param_exports == 0);
2881    }
2882 
2883    radeon_set_context_reg(ctx_cs, R_0286C4_SPI_VS_OUT_CONFIG, spi_vs_out_config);
2884 
2885    radeon_set_context_reg(
2886       ctx_cs, R_02870C_SPI_SHADER_POS_FORMAT,
2887       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
2888          S_02870C_POS1_EXPORT_FORMAT(outinfo->pos_exports > 1 ? V_02870C_SPI_SHADER_4COMP : V_02870C_SPI_SHADER_NONE) |
2889          S_02870C_POS2_EXPORT_FORMAT(outinfo->pos_exports > 2 ? V_02870C_SPI_SHADER_4COMP : V_02870C_SPI_SHADER_NONE) |
2890          S_02870C_POS3_EXPORT_FORMAT(outinfo->pos_exports > 3 ? V_02870C_SPI_SHADER_4COMP : V_02870C_SPI_SHADER_NONE));
2891 
2892    radeon_set_context_reg(
2893       ctx_cs, R_02881C_PA_CL_VS_OUT_CNTL,
2894       S_02881C_USE_VTX_POINT_SIZE(outinfo->writes_pointsize) |
2895          S_02881C_USE_VTX_RENDER_TARGET_INDX(outinfo->writes_layer) |
2896          S_02881C_USE_VTX_VIEWPORT_INDX(outinfo->writes_viewport_index) |
2897          S_02881C_USE_VTX_VRS_RATE(outinfo->writes_primitive_shading_rate) |
2898          S_02881C_VS_OUT_MISC_VEC_ENA(misc_vec_ena) |
2899          S_02881C_VS_OUT_MISC_SIDE_BUS_ENA(misc_vec_ena ||
2900                                            (pdevice->rad_info.gfx_level >= GFX10_3 && outinfo->pos_exports > 1)) |
2901          S_02881C_VS_OUT_CCDIST0_VEC_ENA((total_mask & 0x0f) != 0) |
2902          S_02881C_VS_OUT_CCDIST1_VEC_ENA((total_mask & 0xf0) != 0) | total_mask << 8 | clip_dist_mask);
2903 
2904    if (pdevice->rad_info.gfx_level <= GFX8)
2905       radeon_set_context_reg(ctx_cs, R_028AB4_VGT_REUSE_OFF, outinfo->writes_viewport_index);
2906 
2907    unsigned late_alloc_wave64, cu_mask;
2908    ac_compute_late_alloc(&pdevice->rad_info, false, false, shader->config.scratch_bytes_per_wave > 0,
2909                          &late_alloc_wave64, &cu_mask);
2910 
2911    if (pdevice->rad_info.gfx_level >= GFX7) {
2912       radeon_set_sh_reg_idx(
2913          pdevice, cs, R_00B118_SPI_SHADER_PGM_RSRC3_VS, 3,
2914          ac_apply_cu_en(S_00B118_CU_EN(cu_mask) | S_00B118_WAVE_LIMIT(0x3F), C_00B118_CU_EN, 0, &pdevice->rad_info));
2915       radeon_set_sh_reg(cs, R_00B11C_SPI_SHADER_LATE_ALLOC_VS, S_00B11C_LIMIT(late_alloc_wave64));
2916    }
2917    if (pdevice->rad_info.gfx_level >= GFX10) {
2918       uint32_t oversub_pc_lines = late_alloc_wave64 ? pdevice->rad_info.pc_lines / 4 : 0;
2919       gfx10_emit_ge_pc_alloc(cs, pdevice->rad_info.gfx_level, oversub_pc_lines);
2920 
2921       /* Required programming for tessellation (legacy pipeline only). */
2922       if (shader->info.stage == MESA_SHADER_TESS_EVAL) {
2923          radeon_set_context_reg(ctx_cs, R_028A44_VGT_GS_ONCHIP_CNTL,
2924                                 S_028A44_ES_VERTS_PER_SUBGRP(250) | S_028A44_GS_PRIMS_PER_SUBGRP(126) |
2925                                    S_028A44_GS_INST_PRIMS_IN_SUBGRP(126));
2926       }
2927    }
2928 }
2929 
2930 static void
radv_emit_hw_es(struct radeon_cmdbuf * cs,const struct radv_shader * shader)2931 radv_emit_hw_es(struct radeon_cmdbuf *cs, const struct radv_shader *shader)
2932 {
2933    uint64_t va = radv_shader_get_va(shader);
2934 
2935    radeon_set_sh_reg_seq(cs, R_00B320_SPI_SHADER_PGM_LO_ES, 4);
2936    radeon_emit(cs, va >> 8);
2937    radeon_emit(cs, S_00B324_MEM_BASE(va >> 40));
2938    radeon_emit(cs, shader->config.rsrc1);
2939    radeon_emit(cs, shader->config.rsrc2);
2940 }
2941 
2942 static void
radv_emit_hw_ls(struct radeon_cmdbuf * cs,const struct radv_shader * shader)2943 radv_emit_hw_ls(struct radeon_cmdbuf *cs, const struct radv_shader *shader)
2944 {
2945    uint64_t va = radv_shader_get_va(shader);
2946 
2947    radeon_set_sh_reg(cs, R_00B520_SPI_SHADER_PGM_LO_LS, va >> 8);
2948 
2949    radeon_set_sh_reg(cs, R_00B528_SPI_SHADER_PGM_RSRC1_LS, shader->config.rsrc1);
2950 }
2951 
2952 static void
radv_emit_hw_ngg(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,struct radeon_cmdbuf * cs,const struct radv_shader * es,const struct radv_shader * shader)2953 radv_emit_hw_ngg(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, struct radeon_cmdbuf *cs,
2954                  const struct radv_shader *es, const struct radv_shader *shader)
2955 {
2956    const struct radv_physical_device *pdevice = device->physical_device;
2957    uint64_t va = radv_shader_get_va(shader);
2958    gl_shader_stage es_type;
2959    const struct gfx10_ngg_info *ngg_state = &shader->info.ngg_info;
2960 
2961    if (shader->info.stage == MESA_SHADER_GEOMETRY) {
2962       if (shader->info.merged_shader_compiled_separately) {
2963          es_type = es->info.stage;
2964       } else {
2965          es_type = shader->info.gs.es_type;
2966       }
2967    } else {
2968       es_type = shader->info.stage;
2969    }
2970 
2971    radeon_set_sh_reg(cs, R_00B320_SPI_SHADER_PGM_LO_ES, va >> 8);
2972 
2973    radeon_set_sh_reg_seq(cs, R_00B228_SPI_SHADER_PGM_RSRC1_GS, 2);
2974    radeon_emit(cs, shader->config.rsrc1);
2975    radeon_emit(cs, shader->config.rsrc2);
2976 
2977    const struct radv_vs_output_info *outinfo = &shader->info.outinfo;
2978    unsigned clip_dist_mask, cull_dist_mask, total_mask;
2979    clip_dist_mask = outinfo->clip_dist_mask;
2980    cull_dist_mask = outinfo->cull_dist_mask;
2981    total_mask = clip_dist_mask | cull_dist_mask;
2982 
2983    bool misc_vec_ena = outinfo->writes_pointsize || outinfo->writes_layer || outinfo->writes_viewport_index ||
2984                        outinfo->writes_primitive_shading_rate;
2985    bool es_enable_prim_id = outinfo->export_prim_id || (es && es->info.uses_prim_id);
2986    bool break_wave_at_eoi = false;
2987    unsigned ge_cntl;
2988 
2989    if (es_type == MESA_SHADER_TESS_EVAL) {
2990       if (es_enable_prim_id || (shader->info.uses_prim_id))
2991          break_wave_at_eoi = true;
2992    }
2993 
2994    bool no_pc_export = outinfo->param_exports == 0 && outinfo->prim_param_exports == 0;
2995    unsigned num_params = MAX2(outinfo->param_exports, 1);
2996    unsigned num_prim_params = outinfo->prim_param_exports;
2997    radeon_set_context_reg(ctx_cs, R_0286C4_SPI_VS_OUT_CONFIG,
2998                           S_0286C4_VS_EXPORT_COUNT(num_params - 1) | S_0286C4_PRIM_EXPORT_COUNT(num_prim_params) |
2999                              S_0286C4_NO_PC_EXPORT(no_pc_export));
3000 
3001    unsigned idx_format = V_028708_SPI_SHADER_1COMP;
3002    if (outinfo->writes_layer_per_primitive || outinfo->writes_viewport_index_per_primitive ||
3003        outinfo->writes_primitive_shading_rate_per_primitive)
3004       idx_format = V_028708_SPI_SHADER_2COMP;
3005 
3006    radeon_set_context_reg(ctx_cs, R_028708_SPI_SHADER_IDX_FORMAT, S_028708_IDX0_EXPORT_FORMAT(idx_format));
3007    radeon_set_context_reg(
3008       ctx_cs, R_02870C_SPI_SHADER_POS_FORMAT,
3009       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
3010          S_02870C_POS1_EXPORT_FORMAT(outinfo->pos_exports > 1 ? V_02870C_SPI_SHADER_4COMP : V_02870C_SPI_SHADER_NONE) |
3011          S_02870C_POS2_EXPORT_FORMAT(outinfo->pos_exports > 2 ? V_02870C_SPI_SHADER_4COMP : V_02870C_SPI_SHADER_NONE) |
3012          S_02870C_POS3_EXPORT_FORMAT(outinfo->pos_exports > 3 ? V_02870C_SPI_SHADER_4COMP : V_02870C_SPI_SHADER_NONE));
3013 
3014    radeon_set_context_reg(
3015       ctx_cs, R_02881C_PA_CL_VS_OUT_CNTL,
3016       S_02881C_USE_VTX_POINT_SIZE(outinfo->writes_pointsize) |
3017          S_02881C_USE_VTX_RENDER_TARGET_INDX(outinfo->writes_layer) |
3018          S_02881C_USE_VTX_VIEWPORT_INDX(outinfo->writes_viewport_index) |
3019          S_02881C_USE_VTX_VRS_RATE(outinfo->writes_primitive_shading_rate) |
3020          S_02881C_VS_OUT_MISC_VEC_ENA(misc_vec_ena) |
3021          S_02881C_VS_OUT_MISC_SIDE_BUS_ENA(misc_vec_ena ||
3022                                            (pdevice->rad_info.gfx_level >= GFX10_3 && outinfo->pos_exports > 1)) |
3023          S_02881C_VS_OUT_CCDIST0_VEC_ENA((total_mask & 0x0f) != 0) |
3024          S_02881C_VS_OUT_CCDIST1_VEC_ENA((total_mask & 0xf0) != 0) | total_mask << 8 | clip_dist_mask);
3025 
3026    radeon_set_context_reg(
3027       ctx_cs, R_028A84_VGT_PRIMITIVEID_EN,
3028       S_028A84_PRIMITIVEID_EN(es_enable_prim_id) | S_028A84_NGG_DISABLE_PROVOK_REUSE(outinfo->export_prim_id));
3029 
3030    /* NGG specific registers. */
3031    uint32_t gs_num_invocations = shader->info.stage == MESA_SHADER_GEOMETRY ? shader->info.gs.invocations : 1;
3032 
3033    if (pdevice->rad_info.gfx_level < GFX11) {
3034       radeon_set_context_reg(ctx_cs, R_028A44_VGT_GS_ONCHIP_CNTL,
3035                              S_028A44_ES_VERTS_PER_SUBGRP(ngg_state->hw_max_esverts) |
3036                                 S_028A44_GS_PRIMS_PER_SUBGRP(ngg_state->max_gsprims) |
3037                                 S_028A44_GS_INST_PRIMS_IN_SUBGRP(ngg_state->max_gsprims * gs_num_invocations));
3038    }
3039 
3040    radeon_set_context_reg(ctx_cs, R_0287FC_GE_MAX_OUTPUT_PER_SUBGROUP,
3041                           S_0287FC_MAX_VERTS_PER_SUBGROUP(ngg_state->max_out_verts));
3042    radeon_set_context_reg(
3043       ctx_cs, R_028B4C_GE_NGG_SUBGRP_CNTL,
3044       S_028B4C_PRIM_AMP_FACTOR(ngg_state->prim_amp_factor) | S_028B4C_THDS_PER_SUBGRP(0)); /* for fast launch */
3045    radeon_set_context_reg(ctx_cs, R_028B90_VGT_GS_INSTANCE_CNT,
3046                           S_028B90_CNT(gs_num_invocations) | S_028B90_ENABLE(gs_num_invocations > 1) |
3047                              S_028B90_EN_MAX_VERT_OUT_PER_GS_INSTANCE(ngg_state->max_vert_out_per_gs_instance));
3048 
3049    if (pdevice->rad_info.gfx_level >= GFX11) {
3050       ge_cntl = S_03096C_PRIMS_PER_SUBGRP(ngg_state->max_gsprims) |
3051                 S_03096C_VERTS_PER_SUBGRP(ngg_state->hw_max_esverts) |
3052                 S_03096C_BREAK_PRIMGRP_AT_EOI(break_wave_at_eoi) | S_03096C_PRIM_GRP_SIZE_GFX11(252);
3053    } else {
3054       ge_cntl = S_03096C_PRIM_GRP_SIZE_GFX10(ngg_state->max_gsprims) |
3055                 S_03096C_VERT_GRP_SIZE(ngg_state->hw_max_esverts) | S_03096C_BREAK_WAVE_AT_EOI(break_wave_at_eoi);
3056    }
3057 
3058    /* Bug workaround for a possible hang with non-tessellation cases.
3059     * Tessellation always sets GE_CNTL.VERT_GRP_SIZE = 0
3060     *
3061     * Requirement: GE_CNTL.VERT_GRP_SIZE = VGT_GS_ONCHIP_CNTL.ES_VERTS_PER_SUBGRP - 5
3062     */
3063    if (pdevice->rad_info.gfx_level == GFX10 && es_type != MESA_SHADER_TESS_EVAL && ngg_state->hw_max_esverts != 256) {
3064       ge_cntl &= C_03096C_VERT_GRP_SIZE;
3065 
3066       if (ngg_state->hw_max_esverts > 5) {
3067          ge_cntl |= S_03096C_VERT_GRP_SIZE(ngg_state->hw_max_esverts - 5);
3068       }
3069    }
3070 
3071    radeon_set_uconfig_reg(ctx_cs, R_03096C_GE_CNTL, ge_cntl);
3072 
3073    unsigned late_alloc_wave64, cu_mask;
3074    ac_compute_late_alloc(&pdevice->rad_info, true, shader->info.has_ngg_culling,
3075                          shader->config.scratch_bytes_per_wave > 0, &late_alloc_wave64, &cu_mask);
3076 
3077    radeon_set_sh_reg_idx(
3078       pdevice, cs, R_00B21C_SPI_SHADER_PGM_RSRC3_GS, 3,
3079       ac_apply_cu_en(S_00B21C_CU_EN(cu_mask) | S_00B21C_WAVE_LIMIT(0x3F), C_00B21C_CU_EN, 0, &pdevice->rad_info));
3080 
3081    if (pdevice->rad_info.gfx_level >= GFX11) {
3082       radeon_set_sh_reg_idx(
3083          pdevice, cs, R_00B204_SPI_SHADER_PGM_RSRC4_GS, 3,
3084          ac_apply_cu_en(S_00B204_CU_EN_GFX11(0x1) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(late_alloc_wave64),
3085                         C_00B204_CU_EN_GFX11, 16, &pdevice->rad_info));
3086    } else {
3087       radeon_set_sh_reg_idx(
3088          pdevice, cs, R_00B204_SPI_SHADER_PGM_RSRC4_GS, 3,
3089          ac_apply_cu_en(S_00B204_CU_EN_GFX10(0xffff) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(late_alloc_wave64),
3090                         C_00B204_CU_EN_GFX10, 16, &pdevice->rad_info));
3091    }
3092 
3093    uint32_t oversub_pc_lines = late_alloc_wave64 ? pdevice->rad_info.pc_lines / 4 : 0;
3094    if (shader->info.has_ngg_culling) {
3095       unsigned oversub_factor = 2;
3096 
3097       if (outinfo->param_exports > 4)
3098          oversub_factor = 4;
3099       else if (outinfo->param_exports > 2)
3100          oversub_factor = 3;
3101 
3102       oversub_pc_lines *= oversub_factor;
3103    }
3104 
3105    gfx10_emit_ge_pc_alloc(cs, pdevice->rad_info.gfx_level, oversub_pc_lines);
3106 }
3107 
3108 static void
radv_emit_hw_hs(const struct radv_device * device,struct radeon_cmdbuf * cs,const struct radv_shader * shader)3109 radv_emit_hw_hs(const struct radv_device *device, struct radeon_cmdbuf *cs, const struct radv_shader *shader)
3110 {
3111    const struct radv_physical_device *pdevice = device->physical_device;
3112    uint64_t va = radv_shader_get_va(shader);
3113 
3114    if (pdevice->rad_info.gfx_level >= GFX9) {
3115       if (pdevice->rad_info.gfx_level >= GFX10) {
3116          radeon_set_sh_reg(cs, R_00B520_SPI_SHADER_PGM_LO_LS, va >> 8);
3117       } else {
3118          radeon_set_sh_reg(cs, R_00B410_SPI_SHADER_PGM_LO_LS, va >> 8);
3119       }
3120 
3121       radeon_set_sh_reg(cs, R_00B428_SPI_SHADER_PGM_RSRC1_HS, shader->config.rsrc1);
3122    } else {
3123       radeon_set_sh_reg_seq(cs, R_00B420_SPI_SHADER_PGM_LO_HS, 4);
3124       radeon_emit(cs, va >> 8);
3125       radeon_emit(cs, S_00B424_MEM_BASE(va >> 40));
3126       radeon_emit(cs, shader->config.rsrc1);
3127       radeon_emit(cs, shader->config.rsrc2);
3128    }
3129 }
3130 
3131 void
radv_emit_vertex_shader(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,struct radeon_cmdbuf * cs,const struct radv_shader * vs,const struct radv_shader * next_stage)3132 radv_emit_vertex_shader(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, struct radeon_cmdbuf *cs,
3133                         const struct radv_shader *vs, const struct radv_shader *next_stage)
3134 {
3135    if (vs->info.merged_shader_compiled_separately) {
3136       const struct radv_userdata_info *loc = &vs->info.user_sgprs_locs.shader_data[AC_UD_NEXT_STAGE_PC];
3137       const uint32_t base_reg = vs->info.user_data_0;
3138 
3139       assert(loc->sgpr_idx != -1 && loc->num_sgprs == 1);
3140 
3141       if (!vs->info.vs.has_prolog) {
3142          uint32_t rsrc1, rsrc2;
3143 
3144          if (vs->info.next_stage == MESA_SHADER_TESS_CTRL) {
3145             radv_shader_combine_cfg_vs_tcs(vs, next_stage, &rsrc1, NULL);
3146 
3147             if (device->physical_device->rad_info.gfx_level >= GFX10) {
3148                radeon_set_sh_reg(cs, R_00B520_SPI_SHADER_PGM_LO_LS, vs->va >> 8);
3149             } else {
3150                radeon_set_sh_reg(cs, R_00B410_SPI_SHADER_PGM_LO_LS, vs->va >> 8);
3151             }
3152 
3153             radeon_set_sh_reg(cs, R_00B428_SPI_SHADER_PGM_RSRC1_HS, rsrc1);
3154          } else {
3155             radv_shader_combine_cfg_vs_gs(vs, next_stage, &rsrc1, &rsrc2);
3156 
3157             if (device->physical_device->rad_info.gfx_level >= GFX10) {
3158                radeon_set_sh_reg(cs, R_00B320_SPI_SHADER_PGM_LO_ES, vs->va >> 8);
3159             } else {
3160                radeon_set_sh_reg(cs, R_00B210_SPI_SHADER_PGM_LO_ES, vs->va >> 8);
3161             }
3162 
3163             radeon_set_sh_reg_seq(cs, R_00B228_SPI_SHADER_PGM_RSRC1_GS, 2);
3164             radeon_emit(cs, rsrc1);
3165             radeon_emit(cs, rsrc2 | S_00B22C_LDS_SIZE(next_stage->info.gs_ring_info.lds_size));
3166          }
3167       }
3168 
3169       radv_emit_shader_pointer(device, cs, base_reg + loc->sgpr_idx * 4, next_stage->va, false);
3170       return;
3171    }
3172 
3173    if (vs->info.vs.as_ls)
3174       radv_emit_hw_ls(cs, vs);
3175    else if (vs->info.vs.as_es)
3176       radv_emit_hw_es(cs, vs);
3177    else if (vs->info.is_ngg)
3178       radv_emit_hw_ngg(device, ctx_cs, cs, NULL, vs);
3179    else
3180       radv_emit_hw_vs(device, ctx_cs, cs, vs);
3181 }
3182 
3183 void
radv_emit_tess_ctrl_shader(const struct radv_device * device,struct radeon_cmdbuf * cs,const struct radv_shader * tcs)3184 radv_emit_tess_ctrl_shader(const struct radv_device *device, struct radeon_cmdbuf *cs, const struct radv_shader *tcs)
3185 {
3186    if (tcs->info.merged_shader_compiled_separately) {
3187       /* When VS+TCS are compiled separately on GFX9+, the VS will jump to the TCS and everything is
3188        * emitted as part of the VS.
3189        */
3190       return;
3191    }
3192 
3193    radv_emit_hw_hs(device, cs, tcs);
3194 }
3195 
3196 void
radv_emit_tess_eval_shader(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,struct radeon_cmdbuf * cs,const struct radv_shader * tes,const struct radv_shader * gs)3197 radv_emit_tess_eval_shader(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, struct radeon_cmdbuf *cs,
3198                            const struct radv_shader *tes, const struct radv_shader *gs)
3199 {
3200    if (tes->info.merged_shader_compiled_separately) {
3201       const struct radv_userdata_info *loc = &tes->info.user_sgprs_locs.shader_data[AC_UD_NEXT_STAGE_PC];
3202       const uint32_t base_reg = tes->info.user_data_0;
3203       uint32_t rsrc1, rsrc2;
3204 
3205       assert(loc->sgpr_idx != -1 && loc->num_sgprs == 1);
3206 
3207       radv_shader_combine_cfg_tes_gs(tes, gs, &rsrc1, &rsrc2);
3208 
3209       radeon_set_sh_reg(cs, R_00B210_SPI_SHADER_PGM_LO_ES, tes->va >> 8);
3210 
3211       radeon_set_sh_reg_seq(cs, R_00B228_SPI_SHADER_PGM_RSRC1_GS, 2);
3212       radeon_emit(cs, rsrc1);
3213       radeon_emit(cs, rsrc2 | S_00B22C_LDS_SIZE(gs->info.gs_ring_info.lds_size));
3214 
3215       radv_emit_shader_pointer(device, cs, base_reg + loc->sgpr_idx * 4, gs->va, false);
3216       return;
3217    }
3218 
3219    if (tes->info.is_ngg) {
3220       radv_emit_hw_ngg(device, ctx_cs, cs, NULL, tes);
3221    } else if (tes->info.tes.as_es) {
3222       radv_emit_hw_es(cs, tes);
3223    } else {
3224       radv_emit_hw_vs(device, ctx_cs, cs, tes);
3225    }
3226 }
3227 
3228 static void
radv_emit_hw_gs(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,struct radeon_cmdbuf * cs,const struct radv_shader * gs)3229 radv_emit_hw_gs(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, struct radeon_cmdbuf *cs,
3230                 const struct radv_shader *gs)
3231 {
3232    const struct radv_physical_device *pdevice = device->physical_device;
3233    const struct radv_legacy_gs_info *gs_state = &gs->info.gs_ring_info;
3234    unsigned gs_max_out_vertices;
3235    const uint8_t *num_components;
3236    uint8_t max_stream;
3237    unsigned offset;
3238    uint64_t va;
3239 
3240    gs_max_out_vertices = gs->info.gs.vertices_out;
3241    max_stream = gs->info.gs.max_stream;
3242    num_components = gs->info.gs.num_stream_output_components;
3243 
3244    offset = num_components[0] * gs_max_out_vertices;
3245 
3246    radeon_set_context_reg_seq(ctx_cs, R_028A60_VGT_GSVS_RING_OFFSET_1, 3);
3247    radeon_emit(ctx_cs, offset);
3248    if (max_stream >= 1)
3249       offset += num_components[1] * gs_max_out_vertices;
3250    radeon_emit(ctx_cs, offset);
3251    if (max_stream >= 2)
3252       offset += num_components[2] * gs_max_out_vertices;
3253    radeon_emit(ctx_cs, offset);
3254    if (max_stream >= 3)
3255       offset += num_components[3] * gs_max_out_vertices;
3256    radeon_set_context_reg(ctx_cs, R_028AB0_VGT_GSVS_RING_ITEMSIZE, offset);
3257 
3258    radeon_set_context_reg_seq(ctx_cs, R_028B5C_VGT_GS_VERT_ITEMSIZE, 4);
3259    radeon_emit(ctx_cs, num_components[0]);
3260    radeon_emit(ctx_cs, (max_stream >= 1) ? num_components[1] : 0);
3261    radeon_emit(ctx_cs, (max_stream >= 2) ? num_components[2] : 0);
3262    radeon_emit(ctx_cs, (max_stream >= 3) ? num_components[3] : 0);
3263 
3264    uint32_t gs_num_invocations = gs->info.gs.invocations;
3265    radeon_set_context_reg(ctx_cs, R_028B90_VGT_GS_INSTANCE_CNT,
3266                           S_028B90_CNT(MIN2(gs_num_invocations, 127)) | S_028B90_ENABLE(gs_num_invocations > 0));
3267 
3268    if (pdevice->rad_info.gfx_level <= GFX8) {
3269       /* GFX6-8: ESGS offchip ring buffer is allocated according to VGT_ESGS_RING_ITEMSIZE.
3270        * GFX9+: Only used to set the GS input VGPRs, emulated in shaders.
3271        */
3272       radeon_set_context_reg(ctx_cs, R_028AAC_VGT_ESGS_RING_ITEMSIZE, gs_state->vgt_esgs_ring_itemsize);
3273    }
3274 
3275    va = radv_shader_get_va(gs);
3276 
3277    if (pdevice->rad_info.gfx_level >= GFX9) {
3278       if (!gs->info.merged_shader_compiled_separately) {
3279 
3280          if (pdevice->rad_info.gfx_level >= GFX10) {
3281             radeon_set_sh_reg(cs, R_00B320_SPI_SHADER_PGM_LO_ES, va >> 8);
3282          } else {
3283             radeon_set_sh_reg(cs, R_00B210_SPI_SHADER_PGM_LO_ES, va >> 8);
3284          }
3285 
3286          radeon_set_sh_reg_seq(cs, R_00B228_SPI_SHADER_PGM_RSRC1_GS, 2);
3287          radeon_emit(cs, gs->config.rsrc1);
3288          radeon_emit(cs, gs->config.rsrc2 | S_00B22C_LDS_SIZE(gs_state->lds_size));
3289       }
3290 
3291       radeon_set_context_reg(ctx_cs, R_028A44_VGT_GS_ONCHIP_CNTL, gs_state->vgt_gs_onchip_cntl);
3292       radeon_set_context_reg(ctx_cs, R_028A94_VGT_GS_MAX_PRIMS_PER_SUBGROUP, gs_state->vgt_gs_max_prims_per_subgroup);
3293    } else {
3294       radeon_set_sh_reg_seq(cs, R_00B220_SPI_SHADER_PGM_LO_GS, 4);
3295       radeon_emit(cs, va >> 8);
3296       radeon_emit(cs, S_00B224_MEM_BASE(va >> 40));
3297       radeon_emit(cs, gs->config.rsrc1);
3298       radeon_emit(cs, gs->config.rsrc2);
3299    }
3300 
3301    radeon_set_sh_reg_idx(
3302       pdevice, cs, R_00B21C_SPI_SHADER_PGM_RSRC3_GS, 3,
3303       ac_apply_cu_en(S_00B21C_CU_EN(0xffff) | S_00B21C_WAVE_LIMIT(0x3F), C_00B21C_CU_EN, 0, &pdevice->rad_info));
3304 
3305    if (pdevice->rad_info.gfx_level >= GFX10) {
3306       radeon_set_sh_reg_idx(pdevice, cs, R_00B204_SPI_SHADER_PGM_RSRC4_GS, 3,
3307                             ac_apply_cu_en(S_00B204_CU_EN_GFX10(0xffff) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(0),
3308                                            C_00B204_CU_EN_GFX10, 16, &pdevice->rad_info));
3309    }
3310 }
3311 
3312 void
radv_emit_geometry_shader(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,struct radeon_cmdbuf * cs,const struct radv_shader * gs,const struct radv_shader * es,const struct radv_shader * gs_copy_shader)3313 radv_emit_geometry_shader(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, struct radeon_cmdbuf *cs,
3314                           const struct radv_shader *gs, const struct radv_shader *es,
3315                           const struct radv_shader *gs_copy_shader)
3316 {
3317    if (gs->info.is_ngg) {
3318       radv_emit_hw_ngg(device, ctx_cs, cs, es, gs);
3319    } else {
3320       radv_emit_hw_gs(device, ctx_cs, cs, gs);
3321       radv_emit_hw_vs(device, ctx_cs, cs, gs_copy_shader);
3322    }
3323 
3324    radeon_set_context_reg(ctx_cs, R_028B38_VGT_GS_MAX_VERT_OUT, gs->info.gs.vertices_out);
3325 
3326    if (gs->info.merged_shader_compiled_separately) {
3327       const struct radv_userdata_info *vgt_esgs_ring_itemsize = radv_get_user_sgpr(gs, AC_UD_VGT_ESGS_RING_ITEMSIZE);
3328 
3329       assert(vgt_esgs_ring_itemsize->sgpr_idx != -1 && vgt_esgs_ring_itemsize->num_sgprs == 1);
3330 
3331       radeon_set_sh_reg(cs, gs->info.user_data_0 + vgt_esgs_ring_itemsize->sgpr_idx * 4, es->info.esgs_itemsize / 4);
3332    }
3333 }
3334 
3335 void
radv_emit_mesh_shader(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,struct radeon_cmdbuf * cs,const struct radv_shader * ms)3336 radv_emit_mesh_shader(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, struct radeon_cmdbuf *cs,
3337                       const struct radv_shader *ms)
3338 {
3339    const struct radv_physical_device *pdevice = device->physical_device;
3340 
3341    radv_emit_hw_ngg(device, ctx_cs, cs, NULL, ms);
3342    radeon_set_context_reg(
3343       ctx_cs, R_028B38_VGT_GS_MAX_VERT_OUT,
3344       device->physical_device->mesh_fast_launch_2 ? ms->info.ngg_info.max_out_verts : ms->info.workgroup_size);
3345    radeon_set_uconfig_reg_idx(pdevice, ctx_cs, R_030908_VGT_PRIMITIVE_TYPE, 1, V_008958_DI_PT_POINTLIST);
3346 
3347    if (device->physical_device->mesh_fast_launch_2) {
3348       radeon_set_sh_reg_seq(cs, R_00B2B0_SPI_SHADER_GS_MESHLET_DIM, 2);
3349       radeon_emit(cs, S_00B2B0_MESHLET_NUM_THREAD_X(ms->info.cs.block_size[0] - 1) |
3350                          S_00B2B0_MESHLET_NUM_THREAD_Y(ms->info.cs.block_size[1] - 1) |
3351                          S_00B2B0_MESHLET_NUM_THREAD_Z(ms->info.cs.block_size[2] - 1) |
3352                          S_00B2B0_MESHLET_THREADGROUP_SIZE(ms->info.workgroup_size - 1));
3353       radeon_emit(cs, S_00B2B4_MAX_EXP_VERTS(ms->info.ngg_info.max_out_verts) |
3354                          S_00B2B4_MAX_EXP_PRIMS(ms->info.ngg_info.prim_amp_factor));
3355    }
3356 }
3357 
3358 static uint32_t
offset_to_ps_input(uint32_t offset,bool flat_shade,bool explicit,bool per_vertex,bool float16,bool per_prim_gfx11)3359 offset_to_ps_input(uint32_t offset, bool flat_shade, bool explicit, bool per_vertex, bool float16, bool per_prim_gfx11)
3360 {
3361    uint32_t ps_input_cntl;
3362    if (offset <= AC_EXP_PARAM_OFFSET_31) {
3363       ps_input_cntl = S_028644_OFFSET(offset) | S_028644_PRIM_ATTR(per_prim_gfx11);
3364       if (flat_shade || explicit || per_vertex)
3365          ps_input_cntl |= S_028644_FLAT_SHADE(1);
3366       if (explicit || per_vertex) {
3367          /* Force parameter cache to be read in passthrough
3368           * mode.
3369           */
3370          ps_input_cntl |= S_028644_OFFSET(1 << 5) | S_028644_ROTATE_PC_PTR(per_vertex);
3371       }
3372       if (float16) {
3373          ps_input_cntl |= S_028644_FP16_INTERP_MODE(1) | S_028644_ATTR0_VALID(1);
3374       }
3375    } else {
3376       /* The input is a DEFAULT_VAL constant. */
3377       assert(offset >= AC_EXP_PARAM_DEFAULT_VAL_0000 && offset <= AC_EXP_PARAM_DEFAULT_VAL_1111);
3378       offset -= AC_EXP_PARAM_DEFAULT_VAL_0000;
3379       ps_input_cntl = S_028644_OFFSET(0x20) | S_028644_DEFAULT_VAL(offset);
3380    }
3381    return ps_input_cntl;
3382 }
3383 
3384 static void
single_slot_to_ps_input(const struct radv_vs_output_info * outinfo,unsigned slot,uint32_t * ps_input_cntl,unsigned * ps_offset,bool skip_undef,bool use_default_0,bool flat_shade,bool per_prim_gfx11)3385 single_slot_to_ps_input(const struct radv_vs_output_info *outinfo, unsigned slot, uint32_t *ps_input_cntl,
3386                         unsigned *ps_offset, bool skip_undef, bool use_default_0, bool flat_shade, bool per_prim_gfx11)
3387 {
3388    unsigned vs_offset = outinfo->vs_output_param_offset[slot];
3389 
3390    if (vs_offset == AC_EXP_PARAM_UNDEFINED) {
3391       if (skip_undef)
3392          return;
3393       else if (use_default_0)
3394          vs_offset = AC_EXP_PARAM_DEFAULT_VAL_0000;
3395       else
3396          unreachable("vs_offset should not be AC_EXP_PARAM_UNDEFINED.");
3397    }
3398 
3399    ps_input_cntl[*ps_offset] = offset_to_ps_input(vs_offset, flat_shade, false, false, false, per_prim_gfx11);
3400    ++(*ps_offset);
3401 }
3402 
3403 static void
input_mask_to_ps_inputs(const struct radv_vs_output_info * outinfo,const struct radv_shader * ps,uint32_t input_mask,uint32_t * ps_input_cntl,unsigned * ps_offset,bool per_prim_gfx11)3404 input_mask_to_ps_inputs(const struct radv_vs_output_info *outinfo, const struct radv_shader *ps, uint32_t input_mask,
3405                         uint32_t *ps_input_cntl, unsigned *ps_offset, bool per_prim_gfx11)
3406 {
3407    u_foreach_bit (i, input_mask) {
3408       unsigned vs_offset = outinfo->vs_output_param_offset[VARYING_SLOT_VAR0 + i];
3409       if (vs_offset == AC_EXP_PARAM_UNDEFINED) {
3410          ps_input_cntl[*ps_offset] = S_028644_OFFSET(0x20);
3411          ++(*ps_offset);
3412          continue;
3413       }
3414 
3415       bool flat_shade = !!(ps->info.ps.flat_shaded_mask & (1u << *ps_offset));
3416       bool explicit = !!(ps->info.ps.explicit_shaded_mask & (1u << *ps_offset));
3417       bool per_vertex = !!(ps->info.ps.per_vertex_shaded_mask & (1u << *ps_offset));
3418       bool float16 = !!(ps->info.ps.float16_shaded_mask & (1u << *ps_offset));
3419 
3420       ps_input_cntl[*ps_offset] =
3421          offset_to_ps_input(vs_offset, flat_shade, explicit, per_vertex, float16, per_prim_gfx11);
3422       ++(*ps_offset);
3423    }
3424 }
3425 
3426 void
radv_emit_ps_inputs(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,const struct radv_shader * last_vgt_shader,const struct radv_shader * ps)3427 radv_emit_ps_inputs(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs,
3428                     const struct radv_shader *last_vgt_shader, const struct radv_shader *ps)
3429 {
3430    const struct radv_vs_output_info *outinfo = &last_vgt_shader->info.outinfo;
3431    bool mesh = last_vgt_shader->info.stage == MESA_SHADER_MESH;
3432    bool gfx11plus = device->physical_device->rad_info.gfx_level >= GFX11;
3433    uint32_t ps_input_cntl[32];
3434 
3435    unsigned ps_offset = 0;
3436 
3437    if (ps->info.ps.prim_id_input && !mesh)
3438       single_slot_to_ps_input(outinfo, VARYING_SLOT_PRIMITIVE_ID, ps_input_cntl, &ps_offset, true, false, true, false);
3439 
3440    if (ps->info.ps.layer_input && !mesh)
3441       single_slot_to_ps_input(outinfo, VARYING_SLOT_LAYER, ps_input_cntl, &ps_offset, false, true, true, false);
3442 
3443    if (ps->info.ps.viewport_index_input && !mesh)
3444       single_slot_to_ps_input(outinfo, VARYING_SLOT_VIEWPORT, ps_input_cntl, &ps_offset, false, true, true, false);
3445 
3446    if (ps->info.ps.has_pcoord)
3447       ps_input_cntl[ps_offset++] = S_028644_PT_SPRITE_TEX(1) | S_028644_OFFSET(0x20);
3448 
3449    if (ps->info.ps.num_input_clips_culls) {
3450       single_slot_to_ps_input(outinfo, VARYING_SLOT_CLIP_DIST0, ps_input_cntl, &ps_offset, true, false, false, false);
3451 
3452       if (ps->info.ps.num_input_clips_culls > 4)
3453          single_slot_to_ps_input(outinfo, VARYING_SLOT_CLIP_DIST1, ps_input_cntl, &ps_offset, true, false, false,
3454                                  false);
3455    }
3456 
3457    input_mask_to_ps_inputs(outinfo, ps, ps->info.ps.input_mask, ps_input_cntl, &ps_offset, false);
3458 
3459    /* Per-primitive PS inputs: the HW needs these to be last. */
3460 
3461    if (ps->info.ps.prim_id_input && mesh)
3462       single_slot_to_ps_input(outinfo, VARYING_SLOT_PRIMITIVE_ID, ps_input_cntl, &ps_offset, true, false, false,
3463                               gfx11plus);
3464 
3465    if (ps->info.ps.layer_input && mesh)
3466       single_slot_to_ps_input(outinfo, VARYING_SLOT_LAYER, ps_input_cntl, &ps_offset, false, true, false, gfx11plus);
3467 
3468    if (ps->info.ps.viewport_index_input && mesh)
3469       single_slot_to_ps_input(outinfo, VARYING_SLOT_VIEWPORT, ps_input_cntl, &ps_offset, false, true, false, gfx11plus);
3470 
3471    input_mask_to_ps_inputs(outinfo, ps, ps->info.ps.input_per_primitive_mask, ps_input_cntl, &ps_offset, gfx11plus);
3472    if (ps_offset) {
3473       radeon_set_context_reg_seq(ctx_cs, R_028644_SPI_PS_INPUT_CNTL_0, ps_offset);
3474       for (unsigned i = 0; i < ps_offset; i++) {
3475          radeon_emit(ctx_cs, ps_input_cntl[i]);
3476       }
3477    }
3478 }
3479 
3480 void
radv_emit_fragment_shader(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,struct radeon_cmdbuf * cs,const struct radv_shader * ps)3481 radv_emit_fragment_shader(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, struct radeon_cmdbuf *cs,
3482                           const struct radv_shader *ps)
3483 {
3484    const struct radv_physical_device *pdevice = device->physical_device;
3485    bool param_gen;
3486    uint64_t va;
3487 
3488    va = radv_shader_get_va(ps);
3489 
3490    radeon_set_sh_reg_seq(cs, R_00B020_SPI_SHADER_PGM_LO_PS, 4);
3491    radeon_emit(cs, va >> 8);
3492    radeon_emit(cs, S_00B024_MEM_BASE(va >> 40));
3493    radeon_emit(cs, ps->config.rsrc1);
3494    radeon_emit(cs, ps->config.rsrc2);
3495 
3496    radeon_set_context_reg_seq(ctx_cs, R_0286CC_SPI_PS_INPUT_ENA, 2);
3497    radeon_emit(ctx_cs, ps->config.spi_ps_input_ena);
3498    radeon_emit(ctx_cs, ps->config.spi_ps_input_addr);
3499 
3500    /* Workaround when there are no PS inputs but LDS is used. */
3501    param_gen = pdevice->rad_info.gfx_level >= GFX11 && !ps->info.ps.num_interp && ps->config.lds_size;
3502 
3503    radeon_set_context_reg(ctx_cs, R_0286D8_SPI_PS_IN_CONTROL,
3504                           S_0286D8_NUM_INTERP(ps->info.ps.num_interp) |
3505                              S_0286D8_NUM_PRIM_INTERP(ps->info.ps.num_prim_interp) |
3506                              S_0286D8_PS_W32_EN(ps->info.wave_size == 32) | S_0286D8_PARAM_GEN(param_gen));
3507 
3508    radeon_set_context_reg(ctx_cs, R_028710_SPI_SHADER_Z_FORMAT,
3509                           ac_get_spi_shader_z_format(ps->info.ps.writes_z, ps->info.ps.writes_stencil,
3510                                                      ps->info.ps.writes_sample_mask, ps->info.ps.writes_mrt0_alpha));
3511 
3512    if (pdevice->rad_info.gfx_level >= GFX9 && pdevice->rad_info.gfx_level < GFX11)
3513       radeon_set_context_reg(ctx_cs, R_028C40_PA_SC_SHADER_CONTROL, S_028C40_LOAD_COLLISION_WAVEID(ps->info.ps.pops));
3514 }
3515 
3516 void
radv_emit_vgt_vertex_reuse(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,const struct radv_shader * tes)3517 radv_emit_vgt_vertex_reuse(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs,
3518                            const struct radv_shader *tes)
3519 {
3520    const struct radv_physical_device *pdevice = device->physical_device;
3521 
3522    if (pdevice->rad_info.family < CHIP_POLARIS10 || pdevice->rad_info.gfx_level >= GFX10)
3523       return;
3524 
3525    unsigned vtx_reuse_depth = 30;
3526    if (tes && tes->info.tes.spacing == TESS_SPACING_FRACTIONAL_ODD) {
3527       vtx_reuse_depth = 14;
3528    }
3529    radeon_set_context_reg(ctx_cs, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL, S_028C58_VTX_REUSE_DEPTH(vtx_reuse_depth));
3530 }
3531 
3532 static struct radv_vgt_shader_key
radv_pipeline_generate_vgt_shader_key(const struct radv_device * device,const struct radv_graphics_pipeline * pipeline)3533 radv_pipeline_generate_vgt_shader_key(const struct radv_device *device, const struct radv_graphics_pipeline *pipeline)
3534 {
3535    uint8_t hs_size = 64, gs_size = 64, vs_size = 64;
3536    struct radv_vgt_shader_key key;
3537 
3538    memset(&key, 0, sizeof(key));
3539 
3540    if (radv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_CTRL))
3541       hs_size = pipeline->base.shaders[MESA_SHADER_TESS_CTRL]->info.wave_size;
3542 
3543    if (pipeline->base.shaders[MESA_SHADER_GEOMETRY]) {
3544       vs_size = gs_size = pipeline->base.shaders[MESA_SHADER_GEOMETRY]->info.wave_size;
3545       if (radv_pipeline_has_gs_copy_shader(&pipeline->base))
3546          vs_size = pipeline->base.gs_copy_shader->info.wave_size;
3547    } else if (pipeline->base.shaders[MESA_SHADER_TESS_EVAL])
3548       vs_size = pipeline->base.shaders[MESA_SHADER_TESS_EVAL]->info.wave_size;
3549    else if (pipeline->base.shaders[MESA_SHADER_VERTEX])
3550       vs_size = pipeline->base.shaders[MESA_SHADER_VERTEX]->info.wave_size;
3551    else if (pipeline->base.shaders[MESA_SHADER_MESH])
3552       vs_size = gs_size = pipeline->base.shaders[MESA_SHADER_MESH]->info.wave_size;
3553 
3554    if (radv_pipeline_has_ngg(pipeline)) {
3555       assert(!radv_pipeline_has_gs_copy_shader(&pipeline->base));
3556       gs_size = vs_size;
3557    }
3558 
3559    key.tess = radv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_CTRL);
3560    key.gs = radv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY);
3561    if (radv_pipeline_has_ngg(pipeline)) {
3562       key.ngg = 1;
3563       key.ngg_passthrough = radv_pipeline_has_ngg_passthrough(pipeline);
3564       key.ngg_streamout = !!pipeline->streamout_shader;
3565    }
3566    if (radv_pipeline_has_stage(pipeline, MESA_SHADER_MESH)) {
3567       key.mesh = 1;
3568       key.mesh_scratch_ring = pipeline->base.shaders[MESA_SHADER_MESH]->info.ms.needs_ms_scratch_ring;
3569    }
3570 
3571    key.hs_wave32 = hs_size == 32;
3572    key.vs_wave32 = vs_size == 32;
3573    key.gs_wave32 = gs_size == 32;
3574 
3575    return key;
3576 }
3577 
3578 void
radv_emit_vgt_shader_config(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,const struct radv_vgt_shader_key * key)3579 radv_emit_vgt_shader_config(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs,
3580                             const struct radv_vgt_shader_key *key)
3581 {
3582    const struct radv_physical_device *pdevice = device->physical_device;
3583    uint32_t stages = 0;
3584 
3585    if (key->tess) {
3586       stages |= S_028B54_LS_EN(V_028B54_LS_STAGE_ON) | S_028B54_HS_EN(1) | S_028B54_DYNAMIC_HS(1);
3587 
3588       if (key->gs)
3589          stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_DS) | S_028B54_GS_EN(1);
3590       else if (key->ngg)
3591          stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_DS);
3592       else
3593          stages |= S_028B54_VS_EN(V_028B54_VS_STAGE_DS);
3594    } else if (key->gs) {
3595       stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_REAL) | S_028B54_GS_EN(1);
3596    } else if (key->mesh) {
3597       assert(!key->ngg_passthrough);
3598       unsigned gs_fast_launch = device->physical_device->mesh_fast_launch_2 ? 2 : 1;
3599       stages |=
3600          S_028B54_GS_EN(1) | S_028B54_GS_FAST_LAUNCH(gs_fast_launch) | S_028B54_NGG_WAVE_ID_EN(key->mesh_scratch_ring);
3601    } else if (key->ngg) {
3602       stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_REAL);
3603    }
3604 
3605    if (key->ngg) {
3606       stages |= S_028B54_PRIMGEN_EN(1) | S_028B54_NGG_WAVE_ID_EN(key->ngg_streamout) |
3607                 S_028B54_PRIMGEN_PASSTHRU_EN(key->ngg_passthrough) |
3608                 S_028B54_PRIMGEN_PASSTHRU_NO_MSG(key->ngg_passthrough && pdevice->rad_info.family >= CHIP_NAVI23);
3609    } else if (key->gs) {
3610       stages |= S_028B54_VS_EN(V_028B54_VS_STAGE_COPY_SHADER);
3611    }
3612 
3613    if (pdevice->rad_info.gfx_level >= GFX9)
3614       stages |= S_028B54_MAX_PRIMGRP_IN_WAVE(2);
3615 
3616    if (pdevice->rad_info.gfx_level >= GFX10) {
3617       stages |= S_028B54_HS_W32_EN(key->hs_wave32) | S_028B54_GS_W32_EN(key->gs_wave32) |
3618                 S_028B54_VS_W32_EN(pdevice->rad_info.gfx_level < GFX11 && key->vs_wave32);
3619       /* Legacy GS only supports Wave64. Read it as an implication. */
3620       assert(!(key->gs && !key->ngg) || !key->gs_wave32);
3621    }
3622 
3623    radeon_set_context_reg(ctx_cs, R_028B54_VGT_SHADER_STAGES_EN, stages);
3624 }
3625 
3626 void
radv_emit_vgt_gs_out(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,uint32_t vgt_gs_out_prim_type)3627 radv_emit_vgt_gs_out(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, uint32_t vgt_gs_out_prim_type)
3628 {
3629    const struct radv_physical_device *pdevice = device->physical_device;
3630 
3631    if (pdevice->rad_info.gfx_level >= GFX11) {
3632       radeon_set_uconfig_reg(ctx_cs, R_030998_VGT_GS_OUT_PRIM_TYPE, vgt_gs_out_prim_type);
3633    } else {
3634       radeon_set_context_reg(ctx_cs, R_028A6C_VGT_GS_OUT_PRIM_TYPE, vgt_gs_out_prim_type);
3635    }
3636 }
3637 
3638 void
gfx103_emit_vgt_draw_payload_cntl(struct radeon_cmdbuf * ctx_cs,const struct radv_shader * mesh_shader,bool enable_vrs)3639 gfx103_emit_vgt_draw_payload_cntl(struct radeon_cmdbuf *ctx_cs, const struct radv_shader *mesh_shader, bool enable_vrs)
3640 {
3641    bool enable_prim_payload = false;
3642 
3643    /* Enables the second channel of the primitive export instruction.
3644     * This channel contains: VRS rate x, y, viewport and layer.
3645     */
3646    if (mesh_shader) {
3647       const struct radv_vs_output_info *outinfo = &mesh_shader->info.outinfo;
3648 
3649       enable_prim_payload = (outinfo->writes_viewport_index_per_primitive || outinfo->writes_layer_per_primitive ||
3650                              outinfo->writes_primitive_shading_rate_per_primitive);
3651    }
3652 
3653    radeon_set_context_reg(ctx_cs, R_028A98_VGT_DRAW_PAYLOAD_CNTL,
3654                           S_028A98_EN_VRS_RATE(enable_vrs) | S_028A98_EN_PRIM_PAYLOAD(enable_prim_payload));
3655 }
3656 
3657 static bool
gfx103_pipeline_vrs_coarse_shading(const struct radv_device * device,const struct radv_graphics_pipeline * pipeline)3658 gfx103_pipeline_vrs_coarse_shading(const struct radv_device *device, const struct radv_graphics_pipeline *pipeline)
3659 {
3660    struct radv_shader *ps = pipeline->base.shaders[MESA_SHADER_FRAGMENT];
3661 
3662    if (device->physical_device->rad_info.gfx_level != GFX10_3)
3663       return false;
3664 
3665    if (device->instance->debug_flags & RADV_DEBUG_NO_VRS_FLAT_SHADING)
3666       return false;
3667 
3668    if (ps && !ps->info.ps.allow_flat_shading)
3669       return false;
3670 
3671    return true;
3672 }
3673 
3674 void
gfx103_emit_vrs_state(const struct radv_device * device,struct radeon_cmdbuf * ctx_cs,const struct radv_shader * ps,bool enable_vrs,bool enable_vrs_coarse_shading,bool force_vrs_per_vertex)3675 gfx103_emit_vrs_state(const struct radv_device *device, struct radeon_cmdbuf *ctx_cs, const struct radv_shader *ps,
3676                       bool enable_vrs, bool enable_vrs_coarse_shading, bool force_vrs_per_vertex)
3677 {
3678    const struct radv_physical_device *pdevice = device->physical_device;
3679    uint32_t mode = V_028064_SC_VRS_COMB_MODE_PASSTHRU;
3680    uint8_t rate_x = 0, rate_y = 0;
3681 
3682    if (!enable_vrs && enable_vrs_coarse_shading) {
3683       /* When per-draw VRS is not enabled at all, try enabling VRS coarse shading 2x2 if the driver
3684        * determined that it's safe to enable.
3685        */
3686       mode = V_028064_SC_VRS_COMB_MODE_OVERRIDE;
3687       rate_x = rate_y = 1;
3688    } else if (force_vrs_per_vertex) {
3689       /* Otherwise, if per-draw VRS is not enabled statically, try forcing per-vertex VRS if
3690        * requested by the user. Note that vkd3d-proton always has to declare VRS as dynamic because
3691        * in DX12 it's fully dynamic.
3692        */
3693       radeon_set_context_reg(ctx_cs, R_028848_PA_CL_VRS_CNTL,
3694                              S_028848_SAMPLE_ITER_COMBINER_MODE(V_028848_SC_VRS_COMB_MODE_OVERRIDE) |
3695                                 S_028848_VERTEX_RATE_COMBINER_MODE(V_028848_SC_VRS_COMB_MODE_OVERRIDE));
3696 
3697       /* If the shader is using discard, turn off coarse shading because discard at 2x2 pixel
3698        * granularity degrades quality too much. MIN allows sample shading but not coarse shading.
3699        */
3700       mode = ps->info.ps.can_discard ? V_028064_SC_VRS_COMB_MODE_MIN : V_028064_SC_VRS_COMB_MODE_PASSTHRU;
3701    }
3702 
3703    if (pdevice->rad_info.gfx_level < GFX11) {
3704       radeon_set_context_reg(ctx_cs, R_028064_DB_VRS_OVERRIDE_CNTL,
3705                              S_028064_VRS_OVERRIDE_RATE_COMBINER_MODE(mode) | S_028064_VRS_OVERRIDE_RATE_X(rate_x) |
3706                                 S_028064_VRS_OVERRIDE_RATE_Y(rate_y));
3707    }
3708 }
3709 
3710 static void
radv_pipeline_emit_pm4(const struct radv_device * device,struct radv_graphics_pipeline * pipeline,const struct radv_blend_state * blend,uint32_t vgt_gs_out_prim_type,const struct vk_graphics_pipeline_state * state)3711 radv_pipeline_emit_pm4(const struct radv_device *device, struct radv_graphics_pipeline *pipeline,
3712                        const struct radv_blend_state *blend, uint32_t vgt_gs_out_prim_type,
3713                        const struct vk_graphics_pipeline_state *state)
3714 
3715 {
3716    const struct radv_physical_device *pdevice = device->physical_device;
3717    const struct radv_shader *last_vgt_shader = radv_get_last_vgt_shader(pipeline);
3718    const struct radv_shader *ps = pipeline->base.shaders[MESA_SHADER_FRAGMENT];
3719    struct radeon_cmdbuf *ctx_cs = &pipeline->base.ctx_cs;
3720    struct radeon_cmdbuf *cs = &pipeline->base.cs;
3721 
3722    cs->reserved_dw = cs->max_dw = 64;
3723    ctx_cs->reserved_dw = ctx_cs->max_dw = 256;
3724    cs->buf = malloc(4 * (cs->max_dw + ctx_cs->max_dw));
3725    ctx_cs->buf = cs->buf + cs->max_dw;
3726 
3727    struct radv_vgt_shader_key vgt_shader_key = radv_pipeline_generate_vgt_shader_key(device, pipeline);
3728 
3729    radv_pipeline_emit_blend_state(ctx_cs, pipeline, blend);
3730    radv_emit_vgt_gs_mode(device, ctx_cs, pipeline->base.shaders[pipeline->last_vgt_api_stage]);
3731 
3732    if (radv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX)) {
3733       radv_emit_vertex_shader(device, ctx_cs, cs, pipeline->base.shaders[MESA_SHADER_VERTEX], NULL);
3734    }
3735 
3736    if (radv_pipeline_has_stage(pipeline, MESA_SHADER_MESH)) {
3737       radv_emit_mesh_shader(device, ctx_cs, cs, pipeline->base.shaders[MESA_SHADER_MESH]);
3738    }
3739 
3740    if (radv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_CTRL)) {
3741       radv_emit_tess_ctrl_shader(device, cs, pipeline->base.shaders[MESA_SHADER_TESS_CTRL]);
3742 
3743       if (radv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
3744          radv_emit_tess_eval_shader(device, ctx_cs, cs, pipeline->base.shaders[MESA_SHADER_TESS_EVAL], NULL);
3745       }
3746    }
3747 
3748    if (radv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
3749       const struct radv_shader *gs = pipeline->base.shaders[MESA_SHADER_GEOMETRY];
3750       const struct radv_shader *es = pipeline->base.shaders[gs->info.gs.es_type];
3751 
3752       radv_emit_geometry_shader(device, ctx_cs, cs, gs, es, pipeline->base.gs_copy_shader);
3753    }
3754 
3755    if (ps) {
3756       radv_emit_fragment_shader(device, ctx_cs, cs, ps);
3757       radv_emit_ps_inputs(device, ctx_cs, last_vgt_shader, ps);
3758    }
3759 
3760    radv_emit_vgt_vertex_reuse(device, ctx_cs, radv_get_shader(pipeline->base.shaders, MESA_SHADER_TESS_EVAL));
3761    radv_emit_vgt_shader_config(device, ctx_cs, &vgt_shader_key);
3762    radv_emit_vgt_gs_out(device, ctx_cs, vgt_gs_out_prim_type);
3763 
3764    if (pdevice->rad_info.gfx_level >= GFX10_3) {
3765       const bool enable_vrs = radv_is_vrs_enabled(pipeline, state);
3766 
3767       gfx103_emit_vgt_draw_payload_cntl(ctx_cs, pipeline->base.shaders[MESA_SHADER_MESH], enable_vrs);
3768       gfx103_emit_vrs_state(device, ctx_cs, pipeline->base.shaders[MESA_SHADER_FRAGMENT], enable_vrs,
3769                             gfx103_pipeline_vrs_coarse_shading(device, pipeline), pipeline->force_vrs_per_vertex);
3770    }
3771 
3772    pipeline->base.ctx_cs_hash = _mesa_hash_data(ctx_cs->buf, ctx_cs->cdw * 4);
3773 
3774    assert(ctx_cs->cdw <= ctx_cs->max_dw);
3775    assert(cs->cdw <= cs->max_dw);
3776 }
3777 
3778 static void
radv_pipeline_init_vertex_input_state(const struct radv_device * device,struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state)3779 radv_pipeline_init_vertex_input_state(const struct radv_device *device, struct radv_graphics_pipeline *pipeline,
3780                                       const struct vk_graphics_pipeline_state *state)
3781 {
3782    const struct radv_physical_device *pdevice = device->physical_device;
3783    const struct radv_shader_info *vs_info = &radv_get_shader(pipeline->base.shaders, MESA_SHADER_VERTEX)->info;
3784 
3785    if (state->vi) {
3786       u_foreach_bit (i, state->vi->attributes_valid) {
3787          uint32_t binding = state->vi->attributes[i].binding;
3788          uint32_t offset = state->vi->attributes[i].offset;
3789          VkFormat format = state->vi->attributes[i].format;
3790 
3791          pipeline->attrib_ends[i] = offset + vk_format_get_blocksize(format);
3792          pipeline->attrib_bindings[i] = binding;
3793 
3794          if (state->vi->bindings[binding].stride) {
3795             pipeline->attrib_index_offset[i] = offset / state->vi->bindings[binding].stride;
3796          }
3797       }
3798 
3799       u_foreach_bit (i, state->vi->bindings_valid) {
3800          pipeline->binding_stride[i] = state->vi->bindings[i].stride;
3801       }
3802    }
3803 
3804    /* Prepare the VS input state for prologs created inside a library. */
3805    if (vs_info->vs.has_prolog && !(pipeline->dynamic_states & RADV_DYNAMIC_VERTEX_INPUT)) {
3806       const enum amd_gfx_level gfx_level = pdevice->rad_info.gfx_level;
3807       const enum radeon_family family = pdevice->rad_info.family;
3808       const struct ac_vtx_format_info *vtx_info_table = ac_get_vtx_format_info_table(gfx_level, family);
3809 
3810       pipeline->vs_input_state.bindings_match_attrib = true;
3811 
3812       u_foreach_bit (i, state->vi->attributes_valid) {
3813          uint32_t binding = state->vi->attributes[i].binding;
3814          uint32_t offset = state->vi->attributes[i].offset;
3815 
3816          pipeline->vs_input_state.attribute_mask |= BITFIELD_BIT(i);
3817          pipeline->vs_input_state.bindings[i] = binding;
3818          pipeline->vs_input_state.bindings_match_attrib &= binding == i;
3819 
3820          if (state->vi->bindings[binding].input_rate) {
3821             pipeline->vs_input_state.instance_rate_inputs |= BITFIELD_BIT(i);
3822             pipeline->vs_input_state.divisors[i] = state->vi->bindings[binding].divisor;
3823 
3824             if (state->vi->bindings[binding].divisor == 0) {
3825                pipeline->vs_input_state.zero_divisors |= BITFIELD_BIT(i);
3826             } else if (state->vi->bindings[binding].divisor > 1) {
3827                pipeline->vs_input_state.nontrivial_divisors |= BITFIELD_BIT(i);
3828             }
3829          }
3830 
3831          pipeline->vs_input_state.offsets[i] = offset;
3832 
3833          enum pipe_format format = vk_format_to_pipe_format(state->vi->attributes[i].format);
3834          const struct ac_vtx_format_info *vtx_info = &vtx_info_table[format];
3835 
3836          pipeline->vs_input_state.formats[i] = format;
3837          uint8_t align_req_minus_1 = vtx_info->chan_byte_size >= 4 ? 3 : (vtx_info->element_size - 1);
3838          pipeline->vs_input_state.format_align_req_minus_1[i] = align_req_minus_1;
3839          pipeline->vs_input_state.format_sizes[i] = vtx_info->element_size;
3840          pipeline->vs_input_state.alpha_adjust_lo |= (vtx_info->alpha_adjust & 0x1) << i;
3841          pipeline->vs_input_state.alpha_adjust_hi |= (vtx_info->alpha_adjust >> 1) << i;
3842          if (G_008F0C_DST_SEL_X(vtx_info->dst_sel) == V_008F0C_SQ_SEL_Z) {
3843             pipeline->vs_input_state.post_shuffle |= BITFIELD_BIT(i);
3844          }
3845 
3846          if (!(vtx_info->has_hw_format & BITFIELD_BIT(vtx_info->num_channels - 1))) {
3847             pipeline->vs_input_state.nontrivial_formats |= BITFIELD_BIT(i);
3848          }
3849       }
3850    }
3851 }
3852 
3853 static struct radv_shader *
radv_pipeline_get_streamout_shader(struct radv_graphics_pipeline * pipeline)3854 radv_pipeline_get_streamout_shader(struct radv_graphics_pipeline *pipeline)
3855 {
3856    int i;
3857 
3858    for (i = MESA_SHADER_GEOMETRY; i >= MESA_SHADER_VERTEX; i--) {
3859       struct radv_shader *shader = radv_get_shader(pipeline->base.shaders, i);
3860 
3861       if (shader && shader->info.so.num_outputs > 0)
3862          return shader;
3863    }
3864 
3865    return NULL;
3866 }
3867 static void
radv_pipeline_init_shader_stages_state(const struct radv_device * device,struct radv_graphics_pipeline * pipeline)3868 radv_pipeline_init_shader_stages_state(const struct radv_device *device, struct radv_graphics_pipeline *pipeline)
3869 {
3870    for (unsigned i = 0; i < MESA_VULKAN_SHADER_STAGES; i++) {
3871       bool shader_exists = !!pipeline->base.shaders[i];
3872       if (shader_exists || i < MESA_SHADER_COMPUTE) {
3873          if (shader_exists)
3874             pipeline->base.need_indirect_descriptor_sets |=
3875                radv_shader_need_indirect_descriptor_sets(pipeline->base.shaders[i]);
3876       }
3877    }
3878 
3879    gl_shader_stage first_stage =
3880       radv_pipeline_has_stage(pipeline, MESA_SHADER_MESH) ? MESA_SHADER_MESH : MESA_SHADER_VERTEX;
3881 
3882    const struct radv_shader *shader = radv_get_shader(pipeline->base.shaders, first_stage);
3883    const struct radv_userdata_info *loc = radv_get_user_sgpr(shader, AC_UD_VS_BASE_VERTEX_START_INSTANCE);
3884 
3885    if (loc->sgpr_idx != -1) {
3886       pipeline->vtx_base_sgpr = shader->info.user_data_0;
3887       pipeline->vtx_base_sgpr += loc->sgpr_idx * 4;
3888       pipeline->vtx_emit_num = loc->num_sgprs;
3889       pipeline->uses_drawid = radv_get_shader(pipeline->base.shaders, first_stage)->info.vs.needs_draw_id;
3890       pipeline->uses_baseinstance = radv_get_shader(pipeline->base.shaders, first_stage)->info.vs.needs_base_instance;
3891 
3892       assert(first_stage != MESA_SHADER_MESH || !pipeline->uses_baseinstance);
3893    }
3894 }
3895 
3896 uint32_t
radv_get_vgt_gs_out(struct radv_shader ** shaders,uint32_t primitive_topology)3897 radv_get_vgt_gs_out(struct radv_shader **shaders, uint32_t primitive_topology)
3898 {
3899    uint32_t gs_out;
3900 
3901    if (shaders[MESA_SHADER_GEOMETRY]) {
3902       gs_out = radv_conv_gl_prim_to_gs_out(shaders[MESA_SHADER_GEOMETRY]->info.gs.output_prim);
3903    } else if (shaders[MESA_SHADER_TESS_CTRL]) {
3904       if (shaders[MESA_SHADER_TESS_EVAL]->info.tes.point_mode) {
3905          gs_out = V_028A6C_POINTLIST;
3906       } else {
3907          gs_out = radv_conv_tess_prim_to_gs_out(shaders[MESA_SHADER_TESS_EVAL]->info.tes._primitive_mode);
3908       }
3909    } else if (shaders[MESA_SHADER_MESH]) {
3910       gs_out = radv_conv_gl_prim_to_gs_out(shaders[MESA_SHADER_MESH]->info.ms.output_prim);
3911    } else {
3912       gs_out = radv_conv_prim_to_gs_out(primitive_topology, false);
3913    }
3914 
3915    return gs_out;
3916 }
3917 
3918 static uint32_t
radv_pipeline_init_vgt_gs_out(struct radv_graphics_pipeline * pipeline,const struct vk_graphics_pipeline_state * state)3919 radv_pipeline_init_vgt_gs_out(struct radv_graphics_pipeline *pipeline, const struct vk_graphics_pipeline_state *state)
3920 {
3921    uint32_t primitive_topology = 0;
3922 
3923    if (pipeline->last_vgt_api_stage == MESA_SHADER_VERTEX)
3924       primitive_topology = radv_translate_prim(state->ia->primitive_topology);
3925 
3926    return radv_get_vgt_gs_out(pipeline->base.shaders, primitive_topology);
3927 }
3928 
3929 static void
radv_pipeline_init_extra(struct radv_graphics_pipeline * pipeline,const struct radv_graphics_pipeline_create_info * extra,struct radv_blend_state * blend_state,const struct vk_graphics_pipeline_state * state,uint32_t * vgt_gs_out_prim_type)3930 radv_pipeline_init_extra(struct radv_graphics_pipeline *pipeline,
3931                          const struct radv_graphics_pipeline_create_info *extra, struct radv_blend_state *blend_state,
3932                          const struct vk_graphics_pipeline_state *state, uint32_t *vgt_gs_out_prim_type)
3933 {
3934    if (extra->custom_blend_mode == V_028808_CB_ELIMINATE_FAST_CLEAR ||
3935        extra->custom_blend_mode == V_028808_CB_FMASK_DECOMPRESS ||
3936        extra->custom_blend_mode == V_028808_CB_DCC_DECOMPRESS_GFX8 ||
3937        extra->custom_blend_mode == V_028808_CB_DCC_DECOMPRESS_GFX11 ||
3938        extra->custom_blend_mode == V_028808_CB_RESOLVE) {
3939       /* According to the CB spec states, CB_SHADER_MASK should be set to enable writes to all four
3940        * channels of MRT0.
3941        */
3942       blend_state->cb_shader_mask = 0xf;
3943 
3944       pipeline->custom_blend_mode = extra->custom_blend_mode;
3945    }
3946 
3947    if (extra->use_rectlist) {
3948       struct radv_dynamic_state *dynamic = &pipeline->dynamic_state;
3949       dynamic->vk.ia.primitive_topology = V_008958_DI_PT_RECTLIST;
3950 
3951       *vgt_gs_out_prim_type =
3952          radv_conv_prim_to_gs_out(dynamic->vk.ia.primitive_topology, radv_pipeline_has_ngg(pipeline));
3953 
3954       pipeline->rast_prim = *vgt_gs_out_prim_type;
3955    }
3956 
3957    if (radv_pipeline_has_ds_attachments(state->rp)) {
3958       pipeline->db_render_control |= S_028000_DEPTH_CLEAR_ENABLE(extra->db_depth_clear);
3959       pipeline->db_render_control |= S_028000_STENCIL_CLEAR_ENABLE(extra->db_stencil_clear);
3960       pipeline->db_render_control |= S_028000_RESUMMARIZE_ENABLE(extra->resummarize_enable);
3961       pipeline->db_render_control |= S_028000_DEPTH_COMPRESS_DISABLE(extra->depth_compress_disable);
3962       pipeline->db_render_control |= S_028000_STENCIL_COMPRESS_DISABLE(extra->stencil_compress_disable);
3963    }
3964 }
3965 
3966 static bool
radv_is_fast_linking_enabled(const struct radv_graphics_pipeline * pipeline,const VkGraphicsPipelineCreateInfo * pCreateInfo)3967 radv_is_fast_linking_enabled(const struct radv_graphics_pipeline *pipeline,
3968                              const VkGraphicsPipelineCreateInfo *pCreateInfo)
3969 {
3970    const VkPipelineLibraryCreateInfoKHR *libs_info =
3971       vk_find_struct_const(pCreateInfo->pNext, PIPELINE_LIBRARY_CREATE_INFO_KHR);
3972 
3973    if (!libs_info)
3974       return false;
3975 
3976    return !(pipeline->base.create_flags & VK_PIPELINE_CREATE_2_LINK_TIME_OPTIMIZATION_BIT_EXT);
3977 }
3978 
3979 bool
radv_needs_null_export_workaround(const struct radv_device * device,const struct radv_shader * ps,unsigned custom_blend_mode)3980 radv_needs_null_export_workaround(const struct radv_device *device, const struct radv_shader *ps,
3981                                   unsigned custom_blend_mode)
3982 {
3983    const enum amd_gfx_level gfx_level = device->physical_device->rad_info.gfx_level;
3984 
3985    if (!ps)
3986       return false;
3987 
3988    /* Ensure that some export memory is always allocated, for two reasons:
3989     *
3990     * 1) Correctness: The hardware ignores the EXEC mask if no export
3991     *    memory is allocated, so KILL and alpha test do not work correctly
3992     *    without this.
3993     * 2) Performance: Every shader needs at least a NULL export, even when
3994     *    it writes no color/depth output. The NULL export instruction
3995     *    stalls without this setting.
3996     *
3997     * Don't add this to CB_SHADER_MASK.
3998     *
3999     * GFX10 supports pixel shaders without exports by setting both the
4000     * color and Z formats to SPI_SHADER_ZERO. The hw will skip export
4001     * instructions if any are present.
4002     *
4003     * GFX11 requires one color output, otherwise the DCC decompression does nothing.
4004     *
4005     * Primitive Ordered Pixel Shading also requires an export, otherwise interlocking doesn't work
4006     * correctly before GFX11, and a hang happens on GFX11.
4007     */
4008    return (gfx_level <= GFX9 || ps->info.ps.can_discard || ps->info.ps.pops ||
4009            (custom_blend_mode == V_028808_CB_DCC_DECOMPRESS_GFX11 && gfx_level >= GFX11)) &&
4010           !ps->info.ps.writes_z && !ps->info.ps.writes_stencil && !ps->info.ps.writes_sample_mask;
4011 }
4012 
4013 static VkResult
radv_graphics_pipeline_init(struct radv_graphics_pipeline * pipeline,struct radv_device * device,struct vk_pipeline_cache * cache,const VkGraphicsPipelineCreateInfo * pCreateInfo,const struct radv_graphics_pipeline_create_info * extra)4014 radv_graphics_pipeline_init(struct radv_graphics_pipeline *pipeline, struct radv_device *device,
4015                             struct vk_pipeline_cache *cache, const VkGraphicsPipelineCreateInfo *pCreateInfo,
4016                             const struct radv_graphics_pipeline_create_info *extra)
4017 {
4018    VkGraphicsPipelineLibraryFlagBitsEXT needed_lib_flags = ALL_GRAPHICS_LIB_FLAGS;
4019    bool fast_linking_enabled = radv_is_fast_linking_enabled(pipeline, pCreateInfo);
4020    struct radv_pipeline_layout pipeline_layout;
4021    struct vk_graphics_pipeline_state state = {0};
4022    VkResult result = VK_SUCCESS;
4023 
4024    pipeline->last_vgt_api_stage = MESA_SHADER_NONE;
4025 
4026    const VkPipelineLibraryCreateInfoKHR *libs_info =
4027       vk_find_struct_const(pCreateInfo->pNext, PIPELINE_LIBRARY_CREATE_INFO_KHR);
4028 
4029    radv_pipeline_layout_init(device, &pipeline_layout, false);
4030 
4031    /* If we have libraries, import them first. */
4032    if (libs_info) {
4033       const bool link_optimize =
4034          (pipeline->base.create_flags & VK_PIPELINE_CREATE_2_LINK_TIME_OPTIMIZATION_BIT_EXT) != 0;
4035 
4036       for (uint32_t i = 0; i < libs_info->libraryCount; i++) {
4037          RADV_FROM_HANDLE(radv_pipeline, pipeline_lib, libs_info->pLibraries[i]);
4038          struct radv_graphics_lib_pipeline *gfx_pipeline_lib = radv_pipeline_to_graphics_lib(pipeline_lib);
4039 
4040          assert(pipeline_lib->type == RADV_PIPELINE_GRAPHICS_LIB);
4041 
4042          /* If we have link time optimization, all libraries must be created with
4043           * VK_PIPELINE_CREATE_2_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT.
4044           */
4045          assert(!link_optimize || gfx_pipeline_lib->base.retain_shaders);
4046 
4047          radv_graphics_pipeline_import_lib(device, pipeline, &state, &pipeline_layout, gfx_pipeline_lib, link_optimize);
4048 
4049          needed_lib_flags &= ~gfx_pipeline_lib->lib_flags;
4050       }
4051    }
4052 
4053    /* Import graphics pipeline info that was not included in the libraries. */
4054    result =
4055       radv_pipeline_import_graphics_info(device, pipeline, &state, &pipeline_layout, pCreateInfo, needed_lib_flags);
4056    if (result != VK_SUCCESS) {
4057       radv_pipeline_layout_finish(device, &pipeline_layout);
4058       return result;
4059    }
4060 
4061    if (radv_should_compute_pipeline_hash(device, pipeline, fast_linking_enabled))
4062       radv_pipeline_layout_hash(&pipeline_layout);
4063 
4064    if (!radv_skip_graphics_pipeline_compile(device, pipeline, needed_lib_flags, fast_linking_enabled)) {
4065       struct radv_graphics_pipeline_key key =
4066          radv_generate_graphics_pipeline_key(device, pipeline, pCreateInfo, &state, needed_lib_flags);
4067 
4068       result = radv_graphics_pipeline_compile(pipeline, pCreateInfo, &pipeline_layout, device, cache, &key,
4069                                               needed_lib_flags, fast_linking_enabled);
4070       if (result != VK_SUCCESS) {
4071          radv_pipeline_layout_finish(device, &pipeline_layout);
4072          return result;
4073       }
4074    }
4075 
4076    uint32_t vgt_gs_out_prim_type = radv_pipeline_init_vgt_gs_out(pipeline, &state);
4077 
4078    radv_pipeline_init_multisample_state(device, pipeline, pCreateInfo, &state);
4079 
4080    if (!radv_pipeline_has_stage(pipeline, MESA_SHADER_MESH))
4081       radv_pipeline_init_input_assembly_state(device, pipeline);
4082    radv_pipeline_init_dynamic_state(device, pipeline, &state, pCreateInfo);
4083 
4084    struct radv_blend_state blend = radv_pipeline_init_blend_state(pipeline, &state, needed_lib_flags);
4085 
4086    /* Copy the non-compacted SPI_SHADER_COL_FORMAT which is used to emit RBPLUS state. */
4087    pipeline->col_format_non_compacted = blend.spi_shader_col_format;
4088 
4089    struct radv_shader *ps = pipeline->base.shaders[MESA_SHADER_FRAGMENT];
4090    bool enable_mrt_compaction = ps && !ps->info.has_epilog && !ps->info.ps.mrt0_is_dual_src;
4091    if (enable_mrt_compaction) {
4092       blend.spi_shader_col_format = radv_compact_spi_shader_col_format(ps, blend.spi_shader_col_format);
4093 
4094       /* In presence of MRT holes (ie. the FS exports MRT1 but not MRT0), the compiler will remap
4095        * them, so that only MRT0 is exported and the driver will compact SPI_SHADER_COL_FORMAT to
4096        * match what the FS actually exports. Though, to make sure the hw remapping works as
4097        * expected, we should also clear color attachments without exports in CB_SHADER_MASK.
4098        */
4099       blend.cb_shader_mask &= ps->info.ps.colors_written;
4100    }
4101 
4102    unsigned custom_blend_mode = extra ? extra->custom_blend_mode : 0;
4103    if (radv_needs_null_export_workaround(device, ps, custom_blend_mode) && !blend.spi_shader_col_format) {
4104       blend.spi_shader_col_format = V_028714_SPI_SHADER_32_R;
4105       pipeline->col_format_non_compacted = V_028714_SPI_SHADER_32_R;
4106    }
4107 
4108    if (!radv_pipeline_has_stage(pipeline, MESA_SHADER_MESH))
4109       radv_pipeline_init_vertex_input_state(device, pipeline, &state);
4110 
4111    radv_pipeline_init_shader_stages_state(device, pipeline);
4112 
4113    /* Find the last vertex shader stage that eventually uses streamout. */
4114    pipeline->streamout_shader = radv_pipeline_get_streamout_shader(pipeline);
4115 
4116    pipeline->is_ngg = radv_pipeline_has_ngg(pipeline);
4117    pipeline->has_ngg_culling =
4118       pipeline->is_ngg && pipeline->base.shaders[pipeline->last_vgt_api_stage]->info.has_ngg_culling;
4119    pipeline->force_vrs_per_vertex = pipeline->base.shaders[pipeline->last_vgt_api_stage]->info.force_vrs_per_vertex;
4120    pipeline->rast_prim = vgt_gs_out_prim_type;
4121    pipeline->uses_out_of_order_rast = state.rs->rasterization_order_amd == VK_RASTERIZATION_ORDER_RELAXED_AMD;
4122    pipeline->uses_vrs_attachment = radv_pipeline_uses_vrs_attachment(pipeline, &state);
4123 
4124    pipeline->base.push_constant_size = pipeline_layout.push_constant_size;
4125    pipeline->base.dynamic_offset_count = pipeline_layout.dynamic_offset_count;
4126 
4127    for (unsigned i = 0; i < MESA_VULKAN_SHADER_STAGES; i++) {
4128       if (pipeline->base.shaders[i]) {
4129          pipeline->base.shader_upload_seq =
4130             MAX2(pipeline->base.shader_upload_seq, pipeline->base.shaders[i]->upload_seq);
4131       }
4132    }
4133 
4134    if (pipeline->base.gs_copy_shader) {
4135       pipeline->base.shader_upload_seq =
4136          MAX2(pipeline->base.shader_upload_seq, pipeline->base.gs_copy_shader->upload_seq);
4137    }
4138 
4139    if (extra) {
4140       radv_pipeline_init_extra(pipeline, extra, &blend, &state, &vgt_gs_out_prim_type);
4141    }
4142 
4143    radv_pipeline_emit_pm4(device, pipeline, &blend, vgt_gs_out_prim_type, &state);
4144 
4145    radv_pipeline_layout_finish(device, &pipeline_layout);
4146    return result;
4147 }
4148 
4149 VkResult
radv_graphics_pipeline_create(VkDevice _device,VkPipelineCache _cache,const VkGraphicsPipelineCreateInfo * pCreateInfo,const struct radv_graphics_pipeline_create_info * extra,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipeline)4150 radv_graphics_pipeline_create(VkDevice _device, VkPipelineCache _cache, const VkGraphicsPipelineCreateInfo *pCreateInfo,
4151                               const struct radv_graphics_pipeline_create_info *extra,
4152                               const VkAllocationCallbacks *pAllocator, VkPipeline *pPipeline)
4153 {
4154    RADV_FROM_HANDLE(radv_device, device, _device);
4155    VK_FROM_HANDLE(vk_pipeline_cache, cache, _cache);
4156    struct radv_graphics_pipeline *pipeline;
4157    VkResult result;
4158 
4159    pipeline = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*pipeline), 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4160    if (pipeline == NULL)
4161       return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
4162 
4163    radv_pipeline_init(device, &pipeline->base, RADV_PIPELINE_GRAPHICS);
4164    pipeline->base.create_flags = vk_graphics_pipeline_create_flags(pCreateInfo);
4165    pipeline->base.is_internal = _cache == device->meta_state.cache;
4166 
4167    result = radv_graphics_pipeline_init(pipeline, device, cache, pCreateInfo, extra);
4168    if (result != VK_SUCCESS) {
4169       radv_pipeline_destroy(device, &pipeline->base, pAllocator);
4170       return result;
4171    }
4172 
4173    *pPipeline = radv_pipeline_to_handle(&pipeline->base);
4174    radv_rmv_log_graphics_pipeline_create(device, &pipeline->base, pipeline->base.is_internal);
4175    return VK_SUCCESS;
4176 }
4177 
4178 void
radv_destroy_graphics_pipeline(struct radv_device * device,struct radv_graphics_pipeline * pipeline)4179 radv_destroy_graphics_pipeline(struct radv_device *device, struct radv_graphics_pipeline *pipeline)
4180 {
4181    for (unsigned i = 0; i < MESA_VULKAN_SHADER_STAGES; ++i) {
4182       if (pipeline->base.shaders[i])
4183          radv_shader_unref(device, pipeline->base.shaders[i]);
4184    }
4185 
4186    if (pipeline->base.gs_copy_shader)
4187       radv_shader_unref(device, pipeline->base.gs_copy_shader);
4188 
4189    vk_free(&device->vk.alloc, pipeline->state_data);
4190 }
4191 
4192 static VkResult
radv_graphics_lib_pipeline_init(struct radv_graphics_lib_pipeline * pipeline,struct radv_device * device,struct vk_pipeline_cache * cache,const VkGraphicsPipelineCreateInfo * pCreateInfo)4193 radv_graphics_lib_pipeline_init(struct radv_graphics_lib_pipeline *pipeline, struct radv_device *device,
4194                                 struct vk_pipeline_cache *cache, const VkGraphicsPipelineCreateInfo *pCreateInfo)
4195 {
4196    VkResult result;
4197 
4198    const VkGraphicsPipelineLibraryCreateInfoEXT *lib_info =
4199       vk_find_struct_const(pCreateInfo->pNext, GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT);
4200    VkGraphicsPipelineLibraryFlagBitsEXT needed_lib_flags = lib_info ? lib_info->flags : 0;
4201    const VkPipelineLibraryCreateInfoKHR *libs_info =
4202       vk_find_struct_const(pCreateInfo->pNext, PIPELINE_LIBRARY_CREATE_INFO_KHR);
4203    bool fast_linking_enabled = radv_is_fast_linking_enabled(&pipeline->base, pCreateInfo);
4204 
4205    struct vk_graphics_pipeline_state *state = &pipeline->graphics_state;
4206    struct radv_pipeline_layout *pipeline_layout = &pipeline->layout;
4207 
4208    pipeline->base.last_vgt_api_stage = MESA_SHADER_NONE;
4209    pipeline->base.retain_shaders =
4210       (pipeline->base.base.create_flags & VK_PIPELINE_CREATE_2_RETAIN_LINK_TIME_OPTIMIZATION_INFO_BIT_EXT) != 0;
4211    pipeline->lib_flags = needed_lib_flags;
4212 
4213    radv_pipeline_layout_init(device, pipeline_layout, false);
4214 
4215    /* If we have libraries, import them first. */
4216    if (libs_info) {
4217       const bool link_optimize =
4218          (pipeline->base.base.create_flags & VK_PIPELINE_CREATE_2_LINK_TIME_OPTIMIZATION_BIT_EXT) != 0;
4219 
4220       for (uint32_t i = 0; i < libs_info->libraryCount; i++) {
4221          RADV_FROM_HANDLE(radv_pipeline, pipeline_lib, libs_info->pLibraries[i]);
4222          struct radv_graphics_lib_pipeline *gfx_pipeline_lib = radv_pipeline_to_graphics_lib(pipeline_lib);
4223 
4224          radv_graphics_pipeline_import_lib(device, &pipeline->base, state, pipeline_layout, gfx_pipeline_lib,
4225                                            link_optimize);
4226 
4227          pipeline->lib_flags |= gfx_pipeline_lib->lib_flags;
4228 
4229          needed_lib_flags &= ~gfx_pipeline_lib->lib_flags;
4230       }
4231    }
4232 
4233    result = radv_pipeline_import_graphics_info(device, &pipeline->base, state, pipeline_layout, pCreateInfo,
4234                                                needed_lib_flags);
4235    if (result != VK_SUCCESS)
4236       return result;
4237 
4238    if (radv_should_compute_pipeline_hash(device, &pipeline->base, fast_linking_enabled))
4239       radv_pipeline_layout_hash(pipeline_layout);
4240 
4241    struct radv_graphics_pipeline_key key =
4242       radv_generate_graphics_pipeline_key(device, &pipeline->base, pCreateInfo, state, needed_lib_flags);
4243 
4244    return radv_graphics_pipeline_compile(&pipeline->base, pCreateInfo, pipeline_layout, device, cache, &key,
4245                                          needed_lib_flags, fast_linking_enabled);
4246 }
4247 
4248 static VkResult
radv_graphics_lib_pipeline_create(VkDevice _device,VkPipelineCache _cache,const VkGraphicsPipelineCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipeline)4249 radv_graphics_lib_pipeline_create(VkDevice _device, VkPipelineCache _cache,
4250                                   const VkGraphicsPipelineCreateInfo *pCreateInfo,
4251                                   const VkAllocationCallbacks *pAllocator, VkPipeline *pPipeline)
4252 {
4253    VK_FROM_HANDLE(vk_pipeline_cache, cache, _cache);
4254    RADV_FROM_HANDLE(radv_device, device, _device);
4255    struct radv_graphics_lib_pipeline *pipeline;
4256    VkResult result;
4257 
4258    pipeline = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*pipeline), 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4259    if (pipeline == NULL)
4260       return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
4261 
4262    radv_pipeline_init(device, &pipeline->base.base, RADV_PIPELINE_GRAPHICS_LIB);
4263    pipeline->base.base.create_flags = vk_graphics_pipeline_create_flags(pCreateInfo);
4264 
4265    pipeline->mem_ctx = ralloc_context(NULL);
4266 
4267    result = radv_graphics_lib_pipeline_init(pipeline, device, cache, pCreateInfo);
4268    if (result != VK_SUCCESS) {
4269       radv_pipeline_destroy(device, &pipeline->base.base, pAllocator);
4270       return result;
4271    }
4272 
4273    *pPipeline = radv_pipeline_to_handle(&pipeline->base.base);
4274 
4275    return VK_SUCCESS;
4276 }
4277 
4278 void
radv_destroy_graphics_lib_pipeline(struct radv_device * device,struct radv_graphics_lib_pipeline * pipeline)4279 radv_destroy_graphics_lib_pipeline(struct radv_device *device, struct radv_graphics_lib_pipeline *pipeline)
4280 {
4281    struct radv_retained_shaders *retained_shaders = &pipeline->retained_shaders;
4282 
4283    radv_pipeline_layout_finish(device, &pipeline->layout);
4284 
4285    for (unsigned i = 0; i < MESA_VULKAN_SHADER_STAGES; ++i) {
4286       free(retained_shaders->stages[i].serialized_nir);
4287    }
4288 
4289    ralloc_free(pipeline->mem_ctx);
4290 
4291    radv_destroy_graphics_pipeline(device, &pipeline->base);
4292 }
4293 
4294 VKAPI_ATTR VkResult VKAPI_CALL
radv_CreateGraphicsPipelines(VkDevice _device,VkPipelineCache pipelineCache,uint32_t count,const VkGraphicsPipelineCreateInfo * pCreateInfos,const VkAllocationCallbacks * pAllocator,VkPipeline * pPipelines)4295 radv_CreateGraphicsPipelines(VkDevice _device, VkPipelineCache pipelineCache, uint32_t count,
4296                              const VkGraphicsPipelineCreateInfo *pCreateInfos, const VkAllocationCallbacks *pAllocator,
4297                              VkPipeline *pPipelines)
4298 {
4299    VkResult result = VK_SUCCESS;
4300    unsigned i = 0;
4301 
4302    for (; i < count; i++) {
4303       const VkPipelineCreateFlagBits2KHR create_flags = vk_graphics_pipeline_create_flags(&pCreateInfos[i]);
4304       VkResult r;
4305       if (create_flags & VK_PIPELINE_CREATE_2_LIBRARY_BIT_KHR) {
4306          r = radv_graphics_lib_pipeline_create(_device, pipelineCache, &pCreateInfos[i], pAllocator, &pPipelines[i]);
4307       } else {
4308          r = radv_graphics_pipeline_create(_device, pipelineCache, &pCreateInfos[i], NULL, pAllocator, &pPipelines[i]);
4309       }
4310       if (r != VK_SUCCESS) {
4311          result = r;
4312          pPipelines[i] = VK_NULL_HANDLE;
4313 
4314          if (create_flags & VK_PIPELINE_CREATE_2_EARLY_RETURN_ON_FAILURE_BIT_KHR)
4315             break;
4316       }
4317    }
4318 
4319    for (; i < count; ++i)
4320       pPipelines[i] = VK_NULL_HANDLE;
4321 
4322    return result;
4323 }
4324