radv_pipeline.c revision 993e1d59
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 "util/mesa-sha1.h"
29#include "util/u_atomic.h"
30#include "radv_debug.h"
31#include "radv_private.h"
32#include "radv_cs.h"
33#include "radv_shader.h"
34#include "nir/nir.h"
35#include "nir/nir_builder.h"
36#include "spirv/nir_spirv.h"
37#include "vk_util.h"
38
39#include <llvm-c/Core.h>
40#include <llvm-c/TargetMachine.h>
41
42#include "sid.h"
43#include "gfx9d.h"
44#include "ac_binary.h"
45#include "ac_llvm_util.h"
46#include "ac_nir_to_llvm.h"
47#include "vk_format.h"
48#include "util/debug.h"
49#include "ac_exp_param.h"
50#include "ac_shader_util.h"
51#include "main/menums.h"
52
53struct radv_blend_state {
54	uint32_t blend_enable_4bit;
55	uint32_t need_src_alpha;
56
57	uint32_t cb_color_control;
58	uint32_t cb_target_mask;
59	uint32_t cb_target_enabled_4bit;
60	uint32_t sx_mrt_blend_opt[8];
61	uint32_t cb_blend_control[8];
62
63	uint32_t spi_shader_col_format;
64	uint32_t cb_shader_mask;
65	uint32_t db_alpha_to_mask;
66
67	uint32_t commutative_4bit;
68
69	bool single_cb_enable;
70	bool mrt0_is_dual_src;
71};
72
73struct radv_dsa_order_invariance {
74	/* Whether the final result in Z/S buffers is guaranteed to be
75	 * invariant under changes to the order in which fragments arrive.
76	 */
77	bool zs;
78
79	/* Whether the set of fragments that pass the combined Z/S test is
80	 * guaranteed to be invariant under changes to the order in which
81	 * fragments arrive.
82	 */
83	bool pass_set;
84};
85
86struct radv_tessellation_state {
87	uint32_t ls_hs_config;
88	unsigned num_patches;
89	unsigned lds_size;
90	uint32_t tf_param;
91};
92
93struct radv_gs_state {
94	uint32_t vgt_gs_onchip_cntl;
95	uint32_t vgt_gs_max_prims_per_subgroup;
96	uint32_t vgt_esgs_ring_itemsize;
97	uint32_t lds_size;
98};
99
100static void
101radv_pipeline_destroy(struct radv_device *device,
102                      struct radv_pipeline *pipeline,
103                      const VkAllocationCallbacks* allocator)
104{
105	for (unsigned i = 0; i < MESA_SHADER_STAGES; ++i)
106		if (pipeline->shaders[i])
107			radv_shader_variant_destroy(device, pipeline->shaders[i]);
108
109	if (pipeline->gs_copy_shader)
110		radv_shader_variant_destroy(device, pipeline->gs_copy_shader);
111
112	if(pipeline->cs.buf)
113		free(pipeline->cs.buf);
114	vk_free2(&device->alloc, allocator, pipeline);
115}
116
117void radv_DestroyPipeline(
118	VkDevice                                    _device,
119	VkPipeline                                  _pipeline,
120	const VkAllocationCallbacks*                pAllocator)
121{
122	RADV_FROM_HANDLE(radv_device, device, _device);
123	RADV_FROM_HANDLE(radv_pipeline, pipeline, _pipeline);
124
125	if (!_pipeline)
126		return;
127
128	radv_pipeline_destroy(device, pipeline, pAllocator);
129}
130
131static uint32_t get_hash_flags(struct radv_device *device)
132{
133	uint32_t hash_flags = 0;
134
135	if (device->instance->debug_flags & RADV_DEBUG_UNSAFE_MATH)
136		hash_flags |= RADV_HASH_SHADER_UNSAFE_MATH;
137	if (device->instance->perftest_flags & RADV_PERFTEST_SISCHED)
138		hash_flags |= RADV_HASH_SHADER_SISCHED;
139	return hash_flags;
140}
141
142static VkResult
143radv_pipeline_scratch_init(struct radv_device *device,
144                           struct radv_pipeline *pipeline)
145{
146	unsigned scratch_bytes_per_wave = 0;
147	unsigned max_waves = 0;
148	unsigned min_waves = 1;
149
150	for (int i = 0; i < MESA_SHADER_STAGES; ++i) {
151		if (pipeline->shaders[i]) {
152			unsigned max_stage_waves = device->scratch_waves;
153
154			scratch_bytes_per_wave = MAX2(scratch_bytes_per_wave,
155			                              pipeline->shaders[i]->config.scratch_bytes_per_wave);
156
157			max_stage_waves = MIN2(max_stage_waves,
158			          4 * device->physical_device->rad_info.num_good_compute_units *
159			          (256 / pipeline->shaders[i]->config.num_vgprs));
160			max_waves = MAX2(max_waves, max_stage_waves);
161		}
162	}
163
164	if (pipeline->shaders[MESA_SHADER_COMPUTE]) {
165		unsigned group_size = pipeline->shaders[MESA_SHADER_COMPUTE]->info.cs.block_size[0] *
166		                      pipeline->shaders[MESA_SHADER_COMPUTE]->info.cs.block_size[1] *
167		                      pipeline->shaders[MESA_SHADER_COMPUTE]->info.cs.block_size[2];
168		min_waves = MAX2(min_waves, round_up_u32(group_size, 64));
169	}
170
171	if (scratch_bytes_per_wave)
172		max_waves = MIN2(max_waves, 0xffffffffu / scratch_bytes_per_wave);
173
174	if (scratch_bytes_per_wave && max_waves < min_waves) {
175		/* Not really true at this moment, but will be true on first
176		 * execution. Avoid having hanging shaders. */
177		return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
178	}
179	pipeline->scratch_bytes_per_wave = scratch_bytes_per_wave;
180	pipeline->max_waves = max_waves;
181	return VK_SUCCESS;
182}
183
184static uint32_t si_translate_blend_logic_op(VkLogicOp op)
185{
186	switch (op) {
187	case VK_LOGIC_OP_CLEAR:
188		return V_028808_ROP3_CLEAR;
189	case VK_LOGIC_OP_AND:
190		return V_028808_ROP3_AND;
191	case VK_LOGIC_OP_AND_REVERSE:
192		return V_028808_ROP3_AND_REVERSE;
193	case VK_LOGIC_OP_COPY:
194		return V_028808_ROP3_COPY;
195	case VK_LOGIC_OP_AND_INVERTED:
196		return V_028808_ROP3_AND_INVERTED;
197	case VK_LOGIC_OP_NO_OP:
198		return V_028808_ROP3_NO_OP;
199	case VK_LOGIC_OP_XOR:
200		return V_028808_ROP3_XOR;
201	case VK_LOGIC_OP_OR:
202		return V_028808_ROP3_OR;
203	case VK_LOGIC_OP_NOR:
204		return V_028808_ROP3_NOR;
205	case VK_LOGIC_OP_EQUIVALENT:
206		return V_028808_ROP3_EQUIVALENT;
207	case VK_LOGIC_OP_INVERT:
208		return V_028808_ROP3_INVERT;
209	case VK_LOGIC_OP_OR_REVERSE:
210		return V_028808_ROP3_OR_REVERSE;
211	case VK_LOGIC_OP_COPY_INVERTED:
212		return V_028808_ROP3_COPY_INVERTED;
213	case VK_LOGIC_OP_OR_INVERTED:
214		return V_028808_ROP3_OR_INVERTED;
215	case VK_LOGIC_OP_NAND:
216		return V_028808_ROP3_NAND;
217	case VK_LOGIC_OP_SET:
218		return V_028808_ROP3_SET;
219	default:
220		unreachable("Unhandled logic op");
221	}
222}
223
224
225static uint32_t si_translate_blend_function(VkBlendOp op)
226{
227	switch (op) {
228	case VK_BLEND_OP_ADD:
229		return V_028780_COMB_DST_PLUS_SRC;
230	case VK_BLEND_OP_SUBTRACT:
231		return V_028780_COMB_SRC_MINUS_DST;
232	case VK_BLEND_OP_REVERSE_SUBTRACT:
233		return V_028780_COMB_DST_MINUS_SRC;
234	case VK_BLEND_OP_MIN:
235		return V_028780_COMB_MIN_DST_SRC;
236	case VK_BLEND_OP_MAX:
237		return V_028780_COMB_MAX_DST_SRC;
238	default:
239		return 0;
240	}
241}
242
243static uint32_t si_translate_blend_factor(VkBlendFactor factor)
244{
245	switch (factor) {
246	case VK_BLEND_FACTOR_ZERO:
247		return V_028780_BLEND_ZERO;
248	case VK_BLEND_FACTOR_ONE:
249		return V_028780_BLEND_ONE;
250	case VK_BLEND_FACTOR_SRC_COLOR:
251		return V_028780_BLEND_SRC_COLOR;
252	case VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR:
253		return V_028780_BLEND_ONE_MINUS_SRC_COLOR;
254	case VK_BLEND_FACTOR_DST_COLOR:
255		return V_028780_BLEND_DST_COLOR;
256	case VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR:
257		return V_028780_BLEND_ONE_MINUS_DST_COLOR;
258	case VK_BLEND_FACTOR_SRC_ALPHA:
259		return V_028780_BLEND_SRC_ALPHA;
260	case VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA:
261		return V_028780_BLEND_ONE_MINUS_SRC_ALPHA;
262	case VK_BLEND_FACTOR_DST_ALPHA:
263		return V_028780_BLEND_DST_ALPHA;
264	case VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA:
265		return V_028780_BLEND_ONE_MINUS_DST_ALPHA;
266	case VK_BLEND_FACTOR_CONSTANT_COLOR:
267		return V_028780_BLEND_CONSTANT_COLOR;
268	case VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR:
269		return V_028780_BLEND_ONE_MINUS_CONSTANT_COLOR;
270	case VK_BLEND_FACTOR_CONSTANT_ALPHA:
271		return V_028780_BLEND_CONSTANT_ALPHA;
272	case VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA:
273		return V_028780_BLEND_ONE_MINUS_CONSTANT_ALPHA;
274	case VK_BLEND_FACTOR_SRC_ALPHA_SATURATE:
275		return V_028780_BLEND_SRC_ALPHA_SATURATE;
276	case VK_BLEND_FACTOR_SRC1_COLOR:
277		return V_028780_BLEND_SRC1_COLOR;
278	case VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR:
279		return V_028780_BLEND_INV_SRC1_COLOR;
280	case VK_BLEND_FACTOR_SRC1_ALPHA:
281		return V_028780_BLEND_SRC1_ALPHA;
282	case VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA:
283		return V_028780_BLEND_INV_SRC1_ALPHA;
284	default:
285		return 0;
286	}
287}
288
289static uint32_t si_translate_blend_opt_function(VkBlendOp op)
290{
291	switch (op) {
292	case VK_BLEND_OP_ADD:
293		return V_028760_OPT_COMB_ADD;
294	case VK_BLEND_OP_SUBTRACT:
295		return V_028760_OPT_COMB_SUBTRACT;
296	case VK_BLEND_OP_REVERSE_SUBTRACT:
297		return V_028760_OPT_COMB_REVSUBTRACT;
298	case VK_BLEND_OP_MIN:
299		return V_028760_OPT_COMB_MIN;
300	case VK_BLEND_OP_MAX:
301		return V_028760_OPT_COMB_MAX;
302	default:
303		return V_028760_OPT_COMB_BLEND_DISABLED;
304	}
305}
306
307static uint32_t si_translate_blend_opt_factor(VkBlendFactor factor, bool is_alpha)
308{
309	switch (factor) {
310	case VK_BLEND_FACTOR_ZERO:
311		return V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_ALL;
312	case VK_BLEND_FACTOR_ONE:
313		return V_028760_BLEND_OPT_PRESERVE_ALL_IGNORE_NONE;
314	case VK_BLEND_FACTOR_SRC_COLOR:
315		return is_alpha ? V_028760_BLEND_OPT_PRESERVE_A1_IGNORE_A0
316				: V_028760_BLEND_OPT_PRESERVE_C1_IGNORE_C0;
317	case VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR:
318		return is_alpha ? V_028760_BLEND_OPT_PRESERVE_A0_IGNORE_A1
319				: V_028760_BLEND_OPT_PRESERVE_C0_IGNORE_C1;
320	case VK_BLEND_FACTOR_SRC_ALPHA:
321		return V_028760_BLEND_OPT_PRESERVE_A1_IGNORE_A0;
322	case VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA:
323		return V_028760_BLEND_OPT_PRESERVE_A0_IGNORE_A1;
324	case VK_BLEND_FACTOR_SRC_ALPHA_SATURATE:
325		return is_alpha ? V_028760_BLEND_OPT_PRESERVE_ALL_IGNORE_NONE
326				: V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_A0;
327	default:
328		return V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_NONE;
329	}
330}
331
332/**
333 * Get rid of DST in the blend factors by commuting the operands:
334 *    func(src * DST, dst * 0) ---> func(src * 0, dst * SRC)
335 */
336static void si_blend_remove_dst(unsigned *func, unsigned *src_factor,
337				unsigned *dst_factor, unsigned expected_dst,
338				unsigned replacement_src)
339{
340	if (*src_factor == expected_dst &&
341	    *dst_factor == VK_BLEND_FACTOR_ZERO) {
342		*src_factor = VK_BLEND_FACTOR_ZERO;
343		*dst_factor = replacement_src;
344
345		/* Commuting the operands requires reversing subtractions. */
346		if (*func == VK_BLEND_OP_SUBTRACT)
347			*func = VK_BLEND_OP_REVERSE_SUBTRACT;
348		else if (*func == VK_BLEND_OP_REVERSE_SUBTRACT)
349			*func = VK_BLEND_OP_SUBTRACT;
350	}
351}
352
353static bool si_blend_factor_uses_dst(unsigned factor)
354{
355	return factor == VK_BLEND_FACTOR_DST_COLOR ||
356		factor == VK_BLEND_FACTOR_DST_ALPHA ||
357		factor == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE ||
358		factor == VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA ||
359		factor == VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR;
360}
361
362static bool is_dual_src(VkBlendFactor factor)
363{
364	switch (factor) {
365	case VK_BLEND_FACTOR_SRC1_COLOR:
366	case VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR:
367	case VK_BLEND_FACTOR_SRC1_ALPHA:
368	case VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA:
369		return true;
370	default:
371		return false;
372	}
373}
374
375static unsigned si_choose_spi_color_format(VkFormat vk_format,
376					    bool blend_enable,
377					    bool blend_need_alpha)
378{
379	const struct vk_format_description *desc = vk_format_description(vk_format);
380	unsigned format, ntype, swap;
381
382	/* Alpha is needed for alpha-to-coverage.
383	 * Blending may be with or without alpha.
384	 */
385	unsigned normal = 0; /* most optimal, may not support blending or export alpha */
386	unsigned alpha = 0; /* exports alpha, but may not support blending */
387	unsigned blend = 0; /* supports blending, but may not export alpha */
388	unsigned blend_alpha = 0; /* least optimal, supports blending and exports alpha */
389
390	format = radv_translate_colorformat(vk_format);
391	ntype = radv_translate_color_numformat(vk_format, desc,
392					       vk_format_get_first_non_void_channel(vk_format));
393	swap = radv_translate_colorswap(vk_format, false);
394
395	/* Choose the SPI color formats. These are required values for Stoney/RB+.
396	 * Other chips have multiple choices, though they are not necessarily better.
397	 */
398	switch (format) {
399	case V_028C70_COLOR_5_6_5:
400	case V_028C70_COLOR_1_5_5_5:
401	case V_028C70_COLOR_5_5_5_1:
402	case V_028C70_COLOR_4_4_4_4:
403	case V_028C70_COLOR_10_11_11:
404	case V_028C70_COLOR_11_11_10:
405	case V_028C70_COLOR_8:
406	case V_028C70_COLOR_8_8:
407	case V_028C70_COLOR_8_8_8_8:
408	case V_028C70_COLOR_10_10_10_2:
409	case V_028C70_COLOR_2_10_10_10:
410		if (ntype == V_028C70_NUMBER_UINT)
411			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_UINT16_ABGR;
412		else if (ntype == V_028C70_NUMBER_SINT)
413			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_SINT16_ABGR;
414		else
415			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_FP16_ABGR;
416		break;
417
418	case V_028C70_COLOR_16:
419	case V_028C70_COLOR_16_16:
420	case V_028C70_COLOR_16_16_16_16:
421		if (ntype == V_028C70_NUMBER_UNORM ||
422		    ntype == V_028C70_NUMBER_SNORM) {
423			/* UNORM16 and SNORM16 don't support blending */
424			if (ntype == V_028C70_NUMBER_UNORM)
425				normal = alpha = V_028714_SPI_SHADER_UNORM16_ABGR;
426			else
427				normal = alpha = V_028714_SPI_SHADER_SNORM16_ABGR;
428
429			/* Use 32 bits per channel for blending. */
430			if (format == V_028C70_COLOR_16) {
431				if (swap == V_028C70_SWAP_STD) { /* R */
432					blend = V_028714_SPI_SHADER_32_R;
433					blend_alpha = V_028714_SPI_SHADER_32_AR;
434				} else if (swap == V_028C70_SWAP_ALT_REV) /* A */
435					blend = blend_alpha = V_028714_SPI_SHADER_32_AR;
436				else
437					assert(0);
438			} else if (format == V_028C70_COLOR_16_16) {
439				if (swap == V_028C70_SWAP_STD) { /* RG */
440					blend = V_028714_SPI_SHADER_32_GR;
441					blend_alpha = V_028714_SPI_SHADER_32_ABGR;
442				} else if (swap == V_028C70_SWAP_ALT) /* RA */
443					blend = blend_alpha = V_028714_SPI_SHADER_32_AR;
444				else
445					assert(0);
446			} else /* 16_16_16_16 */
447				blend = blend_alpha = V_028714_SPI_SHADER_32_ABGR;
448		} else if (ntype == V_028C70_NUMBER_UINT)
449			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_UINT16_ABGR;
450		else if (ntype == V_028C70_NUMBER_SINT)
451			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_SINT16_ABGR;
452		else if (ntype == V_028C70_NUMBER_FLOAT)
453			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_FP16_ABGR;
454		else
455			assert(0);
456		break;
457
458	case V_028C70_COLOR_32:
459		if (swap == V_028C70_SWAP_STD) { /* R */
460			blend = normal = V_028714_SPI_SHADER_32_R;
461			alpha = blend_alpha = V_028714_SPI_SHADER_32_AR;
462		} else if (swap == V_028C70_SWAP_ALT_REV) /* A */
463			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_AR;
464		else
465			assert(0);
466		break;
467
468	case V_028C70_COLOR_32_32:
469		if (swap == V_028C70_SWAP_STD) { /* RG */
470			blend = normal = V_028714_SPI_SHADER_32_GR;
471			alpha = blend_alpha = V_028714_SPI_SHADER_32_ABGR;
472		} else if (swap == V_028C70_SWAP_ALT) /* RA */
473			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_AR;
474		else
475			assert(0);
476		break;
477
478	case V_028C70_COLOR_32_32_32_32:
479	case V_028C70_COLOR_8_24:
480	case V_028C70_COLOR_24_8:
481	case V_028C70_COLOR_X24_8_32_FLOAT:
482		alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_ABGR;
483		break;
484
485	default:
486		unreachable("unhandled blend format");
487	}
488
489	if (blend_enable && blend_need_alpha)
490		return blend_alpha;
491	else if(blend_need_alpha)
492		return alpha;
493	else if(blend_enable)
494		return blend;
495	else
496		return normal;
497}
498
499static void
500radv_pipeline_compute_spi_color_formats(struct radv_pipeline *pipeline,
501					const VkGraphicsPipelineCreateInfo *pCreateInfo,
502					struct radv_blend_state *blend)
503{
504	RADV_FROM_HANDLE(radv_render_pass, pass, pCreateInfo->renderPass);
505	struct radv_subpass *subpass = pass->subpasses + pCreateInfo->subpass;
506	unsigned col_format = 0;
507	unsigned num_targets;
508
509	for (unsigned i = 0; i < (blend->single_cb_enable ? 1 : subpass->color_count); ++i) {
510		unsigned cf;
511
512		if (subpass->color_attachments[i].attachment == VK_ATTACHMENT_UNUSED) {
513			cf = V_028714_SPI_SHADER_ZERO;
514		} else {
515			struct radv_render_pass_attachment *attachment = pass->attachments + subpass->color_attachments[i].attachment;
516			bool blend_enable =
517				blend->blend_enable_4bit & (0xfu << (i * 4));
518
519			cf = si_choose_spi_color_format(attachment->format,
520			                                blend_enable,
521			                                blend->need_src_alpha & (1 << i));
522		}
523
524		col_format |= cf << (4 * i);
525	}
526
527	if (!col_format && blend->need_src_alpha & (1 << 0)) {
528		/* When a subpass doesn't have any color attachments, write the
529		 * alpha channel of MRT0 when alpha coverage is enabled because
530		 * the depth attachment needs it.
531		 */
532		col_format |= V_028714_SPI_SHADER_32_ABGR;
533	}
534
535	/* If the i-th target format is set, all previous target formats must
536	 * be non-zero to avoid hangs.
537	 */
538	num_targets = (util_last_bit(col_format) + 3) / 4;
539	for (unsigned i = 0; i < num_targets; i++) {
540		if (!(col_format & (0xf << (i * 4)))) {
541			col_format |= V_028714_SPI_SHADER_32_R << (i * 4);
542		}
543	}
544
545	blend->cb_shader_mask = ac_get_cb_shader_mask(col_format);
546
547	if (blend->mrt0_is_dual_src)
548		col_format |= (col_format & 0xf) << 4;
549	blend->spi_shader_col_format = col_format;
550}
551
552static bool
553format_is_int8(VkFormat format)
554{
555	const struct vk_format_description *desc = vk_format_description(format);
556	int channel =  vk_format_get_first_non_void_channel(format);
557
558	return channel >= 0 && desc->channel[channel].pure_integer &&
559	       desc->channel[channel].size == 8;
560}
561
562static bool
563format_is_int10(VkFormat format)
564{
565	const struct vk_format_description *desc = vk_format_description(format);
566
567	if (desc->nr_channels != 4)
568		return false;
569	for (unsigned i = 0; i < 4; i++) {
570		if (desc->channel[i].pure_integer && desc->channel[i].size == 10)
571			return true;
572	}
573	return false;
574}
575
576/*
577 * Ordered so that for each i,
578 * radv_format_meta_fs_key(radv_fs_key_format_exemplars[i]) == i.
579 */
580const VkFormat radv_fs_key_format_exemplars[NUM_META_FS_KEYS] = {
581	VK_FORMAT_R32_SFLOAT,
582	VK_FORMAT_R32G32_SFLOAT,
583	VK_FORMAT_R8G8B8A8_UNORM,
584	VK_FORMAT_R16G16B16A16_UNORM,
585	VK_FORMAT_R16G16B16A16_SNORM,
586	VK_FORMAT_R16G16B16A16_UINT,
587	VK_FORMAT_R16G16B16A16_SINT,
588	VK_FORMAT_R32G32B32A32_SFLOAT,
589	VK_FORMAT_R8G8B8A8_UINT,
590	VK_FORMAT_R8G8B8A8_SINT,
591	VK_FORMAT_A2R10G10B10_UINT_PACK32,
592	VK_FORMAT_A2R10G10B10_SINT_PACK32,
593};
594
595unsigned radv_format_meta_fs_key(VkFormat format)
596{
597	unsigned col_format = si_choose_spi_color_format(format, false, false);
598
599	assert(col_format != V_028714_SPI_SHADER_32_AR);
600	if (col_format >= V_028714_SPI_SHADER_32_AR)
601		--col_format; /* Skip V_028714_SPI_SHADER_32_AR  since there is no such VkFormat */
602
603	--col_format; /* Skip V_028714_SPI_SHADER_ZERO */
604	bool is_int8 = format_is_int8(format);
605	bool is_int10 = format_is_int10(format);
606
607	return col_format + (is_int8 ? 3 : is_int10 ? 5 : 0);
608}
609
610static void
611radv_pipeline_compute_get_int_clamp(const VkGraphicsPipelineCreateInfo *pCreateInfo,
612				    unsigned *is_int8, unsigned *is_int10)
613{
614	RADV_FROM_HANDLE(radv_render_pass, pass, pCreateInfo->renderPass);
615	struct radv_subpass *subpass = pass->subpasses + pCreateInfo->subpass;
616	*is_int8 = 0;
617	*is_int10 = 0;
618
619	for (unsigned i = 0; i < subpass->color_count; ++i) {
620		struct radv_render_pass_attachment *attachment;
621
622		if (subpass->color_attachments[i].attachment == VK_ATTACHMENT_UNUSED)
623			continue;
624
625		attachment = pass->attachments + subpass->color_attachments[i].attachment;
626
627		if (format_is_int8(attachment->format))
628			*is_int8 |= 1 << i;
629		if (format_is_int10(attachment->format))
630			*is_int10 |= 1 << i;
631	}
632}
633
634static void
635radv_blend_check_commutativity(struct radv_blend_state *blend,
636			       VkBlendOp op, VkBlendFactor src,
637			       VkBlendFactor dst, unsigned chanmask)
638{
639	/* Src factor is allowed when it does not depend on Dst. */
640	static const uint32_t src_allowed =
641		(1u << VK_BLEND_FACTOR_ONE) |
642		(1u << VK_BLEND_FACTOR_SRC_COLOR) |
643		(1u << VK_BLEND_FACTOR_SRC_ALPHA) |
644		(1u << VK_BLEND_FACTOR_SRC_ALPHA_SATURATE) |
645		(1u << VK_BLEND_FACTOR_CONSTANT_COLOR) |
646		(1u << VK_BLEND_FACTOR_CONSTANT_ALPHA) |
647		(1u << VK_BLEND_FACTOR_SRC1_COLOR) |
648		(1u << VK_BLEND_FACTOR_SRC1_ALPHA) |
649		(1u << VK_BLEND_FACTOR_ZERO) |
650		(1u << VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR) |
651		(1u << VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA) |
652		(1u << VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR) |
653		(1u << VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA) |
654		(1u << VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) |
655		(1u << VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA);
656
657	if (dst == VK_BLEND_FACTOR_ONE &&
658	    (src_allowed & (1u << src))) {
659		/* Addition is commutative, but floating point addition isn't
660		 * associative: subtle changes can be introduced via different
661		 * rounding. Be conservative, only enable for min and max.
662		 */
663		if (op == VK_BLEND_OP_MAX || op == VK_BLEND_OP_MIN)
664			blend->commutative_4bit |= chanmask;
665	}
666}
667
668static struct radv_blend_state
669radv_pipeline_init_blend_state(struct radv_pipeline *pipeline,
670			       const VkGraphicsPipelineCreateInfo *pCreateInfo,
671			       const struct radv_graphics_pipeline_create_info *extra)
672{
673	const VkPipelineColorBlendStateCreateInfo *vkblend = pCreateInfo->pColorBlendState;
674	const VkPipelineMultisampleStateCreateInfo *vkms = pCreateInfo->pMultisampleState;
675	struct radv_blend_state blend = {0};
676	unsigned mode = V_028808_CB_NORMAL;
677	int i;
678
679	if (!vkblend)
680		return blend;
681
682	if (extra && extra->custom_blend_mode) {
683		blend.single_cb_enable = true;
684		mode = extra->custom_blend_mode;
685	}
686	blend.cb_color_control = 0;
687	if (vkblend->logicOpEnable)
688		blend.cb_color_control |= S_028808_ROP3(si_translate_blend_logic_op(vkblend->logicOp));
689	else
690		blend.cb_color_control |= S_028808_ROP3(V_028808_ROP3_COPY);
691
692	blend.db_alpha_to_mask = S_028B70_ALPHA_TO_MASK_OFFSET0(2) |
693		S_028B70_ALPHA_TO_MASK_OFFSET1(2) |
694		S_028B70_ALPHA_TO_MASK_OFFSET2(2) |
695		S_028B70_ALPHA_TO_MASK_OFFSET3(2);
696
697	if (vkms && vkms->alphaToCoverageEnable) {
698		blend.db_alpha_to_mask |= S_028B70_ALPHA_TO_MASK_ENABLE(1);
699		blend.need_src_alpha |= 0x1;
700	}
701
702	blend.cb_target_mask = 0;
703	for (i = 0; i < vkblend->attachmentCount; i++) {
704		const VkPipelineColorBlendAttachmentState *att = &vkblend->pAttachments[i];
705		unsigned blend_cntl = 0;
706		unsigned srcRGB_opt, dstRGB_opt, srcA_opt, dstA_opt;
707		VkBlendOp eqRGB = att->colorBlendOp;
708		VkBlendFactor srcRGB = att->srcColorBlendFactor;
709		VkBlendFactor dstRGB = att->dstColorBlendFactor;
710		VkBlendOp eqA = att->alphaBlendOp;
711		VkBlendFactor srcA = att->srcAlphaBlendFactor;
712		VkBlendFactor dstA = att->dstAlphaBlendFactor;
713
714		blend.sx_mrt_blend_opt[i] = S_028760_COLOR_COMB_FCN(V_028760_OPT_COMB_BLEND_DISABLED) | S_028760_ALPHA_COMB_FCN(V_028760_OPT_COMB_BLEND_DISABLED);
715
716		if (!att->colorWriteMask)
717			continue;
718
719		blend.cb_target_mask |= (unsigned)att->colorWriteMask << (4 * i);
720		blend.cb_target_enabled_4bit |= 0xf << (4 * i);
721		if (!att->blendEnable) {
722			blend.cb_blend_control[i] = blend_cntl;
723			continue;
724		}
725
726		if (is_dual_src(srcRGB) || is_dual_src(dstRGB) || is_dual_src(srcA) || is_dual_src(dstA))
727			if (i == 0)
728				blend.mrt0_is_dual_src = true;
729
730		if (eqRGB == VK_BLEND_OP_MIN || eqRGB == VK_BLEND_OP_MAX) {
731			srcRGB = VK_BLEND_FACTOR_ONE;
732			dstRGB = VK_BLEND_FACTOR_ONE;
733		}
734		if (eqA == VK_BLEND_OP_MIN || eqA == VK_BLEND_OP_MAX) {
735			srcA = VK_BLEND_FACTOR_ONE;
736			dstA = VK_BLEND_FACTOR_ONE;
737		}
738
739		radv_blend_check_commutativity(&blend, eqRGB, srcRGB, dstRGB,
740					       0x7 << (4 * i));
741		radv_blend_check_commutativity(&blend, eqA, srcA, dstA,
742					       0x8 << (4 * i));
743
744		/* Blending optimizations for RB+.
745		 * These transformations don't change the behavior.
746		 *
747		 * First, get rid of DST in the blend factors:
748		 *    func(src * DST, dst * 0) ---> func(src * 0, dst * SRC)
749		 */
750		si_blend_remove_dst(&eqRGB, &srcRGB, &dstRGB,
751				    VK_BLEND_FACTOR_DST_COLOR,
752				    VK_BLEND_FACTOR_SRC_COLOR);
753
754		si_blend_remove_dst(&eqA, &srcA, &dstA,
755				    VK_BLEND_FACTOR_DST_COLOR,
756				    VK_BLEND_FACTOR_SRC_COLOR);
757
758		si_blend_remove_dst(&eqA, &srcA, &dstA,
759				    VK_BLEND_FACTOR_DST_ALPHA,
760				    VK_BLEND_FACTOR_SRC_ALPHA);
761
762		/* Look up the ideal settings from tables. */
763		srcRGB_opt = si_translate_blend_opt_factor(srcRGB, false);
764		dstRGB_opt = si_translate_blend_opt_factor(dstRGB, false);
765		srcA_opt = si_translate_blend_opt_factor(srcA, true);
766		dstA_opt = si_translate_blend_opt_factor(dstA, true);
767
768				/* Handle interdependencies. */
769		if (si_blend_factor_uses_dst(srcRGB))
770			dstRGB_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_NONE;
771		if (si_blend_factor_uses_dst(srcA))
772			dstA_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_NONE;
773
774		if (srcRGB == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE &&
775		    (dstRGB == VK_BLEND_FACTOR_ZERO ||
776		     dstRGB == VK_BLEND_FACTOR_SRC_ALPHA ||
777		     dstRGB == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE))
778			dstRGB_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_A0;
779
780		/* Set the final value. */
781		blend.sx_mrt_blend_opt[i] =
782			S_028760_COLOR_SRC_OPT(srcRGB_opt) |
783			S_028760_COLOR_DST_OPT(dstRGB_opt) |
784			S_028760_COLOR_COMB_FCN(si_translate_blend_opt_function(eqRGB)) |
785			S_028760_ALPHA_SRC_OPT(srcA_opt) |
786			S_028760_ALPHA_DST_OPT(dstA_opt) |
787			S_028760_ALPHA_COMB_FCN(si_translate_blend_opt_function(eqA));
788		blend_cntl |= S_028780_ENABLE(1);
789
790		blend_cntl |= S_028780_COLOR_COMB_FCN(si_translate_blend_function(eqRGB));
791		blend_cntl |= S_028780_COLOR_SRCBLEND(si_translate_blend_factor(srcRGB));
792		blend_cntl |= S_028780_COLOR_DESTBLEND(si_translate_blend_factor(dstRGB));
793		if (srcA != srcRGB || dstA != dstRGB || eqA != eqRGB) {
794			blend_cntl |= S_028780_SEPARATE_ALPHA_BLEND(1);
795			blend_cntl |= S_028780_ALPHA_COMB_FCN(si_translate_blend_function(eqA));
796			blend_cntl |= S_028780_ALPHA_SRCBLEND(si_translate_blend_factor(srcA));
797			blend_cntl |= S_028780_ALPHA_DESTBLEND(si_translate_blend_factor(dstA));
798		}
799		blend.cb_blend_control[i] = blend_cntl;
800
801		blend.blend_enable_4bit |= 0xfu << (i * 4);
802
803		if (srcRGB == VK_BLEND_FACTOR_SRC_ALPHA ||
804		    dstRGB == VK_BLEND_FACTOR_SRC_ALPHA ||
805		    srcRGB == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE ||
806		    dstRGB == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE ||
807		    srcRGB == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA ||
808		    dstRGB == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA)
809			blend.need_src_alpha |= 1 << i;
810	}
811	for (i = vkblend->attachmentCount; i < 8; i++) {
812		blend.cb_blend_control[i] = 0;
813		blend.sx_mrt_blend_opt[i] = S_028760_COLOR_COMB_FCN(V_028760_OPT_COMB_BLEND_DISABLED) | S_028760_ALPHA_COMB_FCN(V_028760_OPT_COMB_BLEND_DISABLED);
814	}
815
816	if (pipeline->device->physical_device->has_rbplus) {
817		/* Disable RB+ blend optimizations for dual source blending. */
818		if (blend.mrt0_is_dual_src) {
819			for (i = 0; i < 8; i++) {
820				blend.sx_mrt_blend_opt[i] =
821					S_028760_COLOR_COMB_FCN(V_028760_OPT_COMB_NONE) |
822					S_028760_ALPHA_COMB_FCN(V_028760_OPT_COMB_NONE);
823			}
824		}
825
826		/* RB+ doesn't work with dual source blending, logic op and
827		 * RESOLVE.
828		 */
829		if (blend.mrt0_is_dual_src || vkblend->logicOpEnable ||
830		    mode == V_028808_CB_RESOLVE)
831			blend.cb_color_control |= S_028808_DISABLE_DUAL_QUAD(1);
832	}
833
834	if (blend.cb_target_mask)
835		blend.cb_color_control |= S_028808_MODE(mode);
836	else
837		blend.cb_color_control |= S_028808_MODE(V_028808_CB_DISABLE);
838
839	radv_pipeline_compute_spi_color_formats(pipeline, pCreateInfo, &blend);
840	return blend;
841}
842
843static uint32_t si_translate_stencil_op(enum VkStencilOp op)
844{
845	switch (op) {
846	case VK_STENCIL_OP_KEEP:
847		return V_02842C_STENCIL_KEEP;
848	case VK_STENCIL_OP_ZERO:
849		return V_02842C_STENCIL_ZERO;
850	case VK_STENCIL_OP_REPLACE:
851		return V_02842C_STENCIL_REPLACE_TEST;
852	case VK_STENCIL_OP_INCREMENT_AND_CLAMP:
853		return V_02842C_STENCIL_ADD_CLAMP;
854	case VK_STENCIL_OP_DECREMENT_AND_CLAMP:
855		return V_02842C_STENCIL_SUB_CLAMP;
856	case VK_STENCIL_OP_INVERT:
857		return V_02842C_STENCIL_INVERT;
858	case VK_STENCIL_OP_INCREMENT_AND_WRAP:
859		return V_02842C_STENCIL_ADD_WRAP;
860	case VK_STENCIL_OP_DECREMENT_AND_WRAP:
861		return V_02842C_STENCIL_SUB_WRAP;
862	default:
863		return 0;
864	}
865}
866
867static uint32_t si_translate_fill(VkPolygonMode func)
868{
869	switch(func) {
870	case VK_POLYGON_MODE_FILL:
871		return V_028814_X_DRAW_TRIANGLES;
872	case VK_POLYGON_MODE_LINE:
873		return V_028814_X_DRAW_LINES;
874	case VK_POLYGON_MODE_POINT:
875		return V_028814_X_DRAW_POINTS;
876	default:
877		assert(0);
878		return V_028814_X_DRAW_POINTS;
879	}
880}
881
882static uint8_t radv_pipeline_get_ps_iter_samples(const VkPipelineMultisampleStateCreateInfo *vkms)
883{
884	uint32_t num_samples = vkms->rasterizationSamples;
885	uint32_t ps_iter_samples = 1;
886
887	if (vkms->sampleShadingEnable) {
888		ps_iter_samples = ceil(vkms->minSampleShading * num_samples);
889		ps_iter_samples = util_next_power_of_two(ps_iter_samples);
890	}
891	return ps_iter_samples;
892}
893
894static bool
895radv_is_depth_write_enabled(const VkPipelineDepthStencilStateCreateInfo *pCreateInfo)
896{
897	return pCreateInfo->depthTestEnable &&
898	       pCreateInfo->depthWriteEnable &&
899	       pCreateInfo->depthCompareOp != VK_COMPARE_OP_NEVER;
900}
901
902static bool
903radv_writes_stencil(const VkStencilOpState *state)
904{
905	return state->writeMask &&
906	       (state->failOp != VK_STENCIL_OP_KEEP ||
907		state->passOp != VK_STENCIL_OP_KEEP ||
908		state->depthFailOp != VK_STENCIL_OP_KEEP);
909}
910
911static bool
912radv_is_stencil_write_enabled(const VkPipelineDepthStencilStateCreateInfo *pCreateInfo)
913{
914	return pCreateInfo->stencilTestEnable &&
915	       (radv_writes_stencil(&pCreateInfo->front) ||
916		radv_writes_stencil(&pCreateInfo->back));
917}
918
919static bool
920radv_is_ds_write_enabled(const VkPipelineDepthStencilStateCreateInfo *pCreateInfo)
921{
922	return radv_is_depth_write_enabled(pCreateInfo) ||
923	       radv_is_stencil_write_enabled(pCreateInfo);
924}
925
926static bool
927radv_order_invariant_stencil_op(VkStencilOp op)
928{
929	/* REPLACE is normally order invariant, except when the stencil
930	 * reference value is written by the fragment shader. Tracking this
931	 * interaction does not seem worth the effort, so be conservative.
932	 */
933	return op != VK_STENCIL_OP_INCREMENT_AND_CLAMP &&
934	       op != VK_STENCIL_OP_DECREMENT_AND_CLAMP &&
935	       op != VK_STENCIL_OP_REPLACE;
936}
937
938static bool
939radv_order_invariant_stencil_state(const VkStencilOpState *state)
940{
941	/* Compute whether, assuming Z writes are disabled, this stencil state
942	 * is order invariant in the sense that the set of passing fragments as
943	 * well as the final stencil buffer result does not depend on the order
944	 * of fragments.
945	 */
946	return !state->writeMask ||
947	       /* The following assumes that Z writes are disabled. */
948	       (state->compareOp == VK_COMPARE_OP_ALWAYS &&
949		radv_order_invariant_stencil_op(state->passOp) &&
950		radv_order_invariant_stencil_op(state->depthFailOp)) ||
951	       (state->compareOp == VK_COMPARE_OP_NEVER &&
952		radv_order_invariant_stencil_op(state->failOp));
953}
954
955static bool
956radv_pipeline_out_of_order_rast(struct radv_pipeline *pipeline,
957				struct radv_blend_state *blend,
958				const VkGraphicsPipelineCreateInfo *pCreateInfo)
959{
960	RADV_FROM_HANDLE(radv_render_pass, pass, pCreateInfo->renderPass);
961	struct radv_subpass *subpass = pass->subpasses + pCreateInfo->subpass;
962	unsigned colormask = blend->cb_target_enabled_4bit;
963
964	if (!pipeline->device->physical_device->out_of_order_rast_allowed)
965		return false;
966
967	/* Be conservative if a logic operation is enabled with color buffers. */
968	if (colormask && pCreateInfo->pColorBlendState->logicOpEnable)
969		return false;
970
971	/* Default depth/stencil invariance when no attachment is bound. */
972	struct radv_dsa_order_invariance dsa_order_invariant = {
973		.zs = true, .pass_set = true
974	};
975
976	if (pCreateInfo->pDepthStencilState &&
977	    subpass->depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED) {
978		const VkPipelineDepthStencilStateCreateInfo *vkds =
979			pCreateInfo->pDepthStencilState;
980		struct radv_render_pass_attachment *attachment =
981			pass->attachments + subpass->depth_stencil_attachment.attachment;
982		bool has_stencil = vk_format_is_stencil(attachment->format);
983		struct radv_dsa_order_invariance order_invariance[2];
984		struct radv_shader_variant *ps =
985			pipeline->shaders[MESA_SHADER_FRAGMENT];
986
987		/* Compute depth/stencil order invariance in order to know if
988		 * it's safe to enable out-of-order.
989		 */
990		bool zfunc_is_ordered =
991			vkds->depthCompareOp == VK_COMPARE_OP_NEVER ||
992			vkds->depthCompareOp == VK_COMPARE_OP_LESS ||
993			vkds->depthCompareOp == VK_COMPARE_OP_LESS_OR_EQUAL ||
994			vkds->depthCompareOp == VK_COMPARE_OP_GREATER ||
995			vkds->depthCompareOp == VK_COMPARE_OP_GREATER_OR_EQUAL;
996
997		bool nozwrite_and_order_invariant_stencil =
998			!radv_is_ds_write_enabled(vkds) ||
999			(!radv_is_depth_write_enabled(vkds) &&
1000			 radv_order_invariant_stencil_state(&vkds->front) &&
1001			 radv_order_invariant_stencil_state(&vkds->back));
1002
1003		order_invariance[1].zs =
1004			nozwrite_and_order_invariant_stencil ||
1005			(!radv_is_stencil_write_enabled(vkds) &&
1006			 zfunc_is_ordered);
1007		order_invariance[0].zs =
1008			!radv_is_depth_write_enabled(vkds) || zfunc_is_ordered;
1009
1010		order_invariance[1].pass_set =
1011			nozwrite_and_order_invariant_stencil ||
1012			(!radv_is_stencil_write_enabled(vkds) &&
1013			 (vkds->depthCompareOp == VK_COMPARE_OP_ALWAYS ||
1014			  vkds->depthCompareOp == VK_COMPARE_OP_NEVER));
1015		order_invariance[0].pass_set =
1016			!radv_is_depth_write_enabled(vkds) ||
1017			(vkds->depthCompareOp == VK_COMPARE_OP_ALWAYS ||
1018			 vkds->depthCompareOp == VK_COMPARE_OP_NEVER);
1019
1020		dsa_order_invariant = order_invariance[has_stencil];
1021		if (!dsa_order_invariant.zs)
1022			return false;
1023
1024		/* The set of PS invocations is always order invariant,
1025		 * except when early Z/S tests are requested.
1026		 */
1027		if (ps &&
1028		    ps->info.info.ps.writes_memory &&
1029		    ps->info.fs.early_fragment_test &&
1030		    !dsa_order_invariant.pass_set)
1031			return false;
1032
1033		/* Determine if out-of-order rasterization should be disabled
1034		 * when occlusion queries are used.
1035		 */
1036		pipeline->graphics.disable_out_of_order_rast_for_occlusion =
1037			!dsa_order_invariant.pass_set;
1038	}
1039
1040	/* No color buffers are enabled for writing. */
1041	if (!colormask)
1042		return true;
1043
1044	unsigned blendmask = colormask & blend->blend_enable_4bit;
1045
1046	if (blendmask) {
1047		/* Only commutative blending. */
1048		if (blendmask & ~blend->commutative_4bit)
1049			return false;
1050
1051		if (!dsa_order_invariant.pass_set)
1052			return false;
1053	}
1054
1055	if (colormask & ~blendmask)
1056		return false;
1057
1058	return true;
1059}
1060
1061static void
1062radv_pipeline_init_multisample_state(struct radv_pipeline *pipeline,
1063				     struct radv_blend_state *blend,
1064				     const VkGraphicsPipelineCreateInfo *pCreateInfo)
1065{
1066	const VkPipelineMultisampleStateCreateInfo *vkms = pCreateInfo->pMultisampleState;
1067	struct radv_multisample_state *ms = &pipeline->graphics.ms;
1068	unsigned num_tile_pipes = pipeline->device->physical_device->rad_info.num_tile_pipes;
1069	bool out_of_order_rast = false;
1070	int ps_iter_samples = 1;
1071	uint32_t mask = 0xffff;
1072
1073	if (vkms)
1074		ms->num_samples = vkms->rasterizationSamples;
1075	else
1076		ms->num_samples = 1;
1077
1078	if (vkms)
1079		ps_iter_samples = radv_pipeline_get_ps_iter_samples(vkms);
1080	if (vkms && !vkms->sampleShadingEnable && pipeline->shaders[MESA_SHADER_FRAGMENT]->info.info.ps.force_persample) {
1081		ps_iter_samples = ms->num_samples;
1082	}
1083
1084	const struct VkPipelineRasterizationStateRasterizationOrderAMD *raster_order =
1085		vk_find_struct_const(pCreateInfo->pRasterizationState->pNext, PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD);
1086	if (raster_order && raster_order->rasterizationOrder == VK_RASTERIZATION_ORDER_RELAXED_AMD) {
1087		/* Out-of-order rasterization is explicitly enabled by the
1088		 * application.
1089		 */
1090		out_of_order_rast = true;
1091	} else {
1092		/* Determine if the driver can enable out-of-order
1093		 * rasterization internally.
1094		 */
1095		out_of_order_rast =
1096			radv_pipeline_out_of_order_rast(pipeline, blend, pCreateInfo);
1097	}
1098
1099	ms->pa_sc_line_cntl = S_028BDC_DX10_DIAMOND_TEST_ENA(1);
1100	ms->pa_sc_aa_config = 0;
1101	ms->db_eqaa = S_028804_HIGH_QUALITY_INTERSECTIONS(1) |
1102		      S_028804_INCOHERENT_EQAA_READS(1) |
1103		      S_028804_INTERPOLATE_COMP_Z(1) |
1104		      S_028804_STATIC_ANCHOR_ASSOCIATIONS(1);
1105	ms->pa_sc_mode_cntl_1 =
1106		S_028A4C_WALK_FENCE_ENABLE(1) | //TODO linear dst fixes
1107		S_028A4C_WALK_FENCE_SIZE(num_tile_pipes == 2 ? 2 : 3) |
1108		S_028A4C_OUT_OF_ORDER_PRIMITIVE_ENABLE(out_of_order_rast) |
1109		S_028A4C_OUT_OF_ORDER_WATER_MARK(0x7) |
1110		/* always 1: */
1111		S_028A4C_WALK_ALIGN8_PRIM_FITS_ST(1) |
1112		S_028A4C_SUPERTILE_WALK_ORDER_ENABLE(1) |
1113		S_028A4C_TILE_WALK_ORDER_ENABLE(1) |
1114		S_028A4C_MULTI_SHADER_ENGINE_PRIM_DISCARD_ENABLE(1) |
1115		S_028A4C_FORCE_EOV_CNTDWN_ENABLE(1) |
1116		S_028A4C_FORCE_EOV_REZ_ENABLE(1);
1117	ms->pa_sc_mode_cntl_0 = S_028A48_ALTERNATE_RBS_PER_TILE(pipeline->device->physical_device->rad_info.chip_class >= GFX9) |
1118	                        S_028A48_VPORT_SCISSOR_ENABLE(1);
1119
1120	if (ms->num_samples > 1) {
1121		unsigned log_samples = util_logbase2(ms->num_samples);
1122		unsigned log_ps_iter_samples = util_logbase2(ps_iter_samples);
1123		ms->pa_sc_mode_cntl_0 |= S_028A48_MSAA_ENABLE(1);
1124		ms->pa_sc_line_cntl |= S_028BDC_EXPAND_LINE_WIDTH(1); /* CM_R_028BDC_PA_SC_LINE_CNTL */
1125		ms->db_eqaa |= S_028804_MAX_ANCHOR_SAMPLES(log_samples) |
1126			S_028804_PS_ITER_SAMPLES(log_ps_iter_samples) |
1127			S_028804_MASK_EXPORT_NUM_SAMPLES(log_samples) |
1128			S_028804_ALPHA_TO_MASK_NUM_SAMPLES(log_samples);
1129		ms->pa_sc_aa_config |= S_028BE0_MSAA_NUM_SAMPLES(log_samples) |
1130			S_028BE0_MAX_SAMPLE_DIST(radv_cayman_get_maxdist(log_samples)) |
1131			S_028BE0_MSAA_EXPOSED_SAMPLES(log_samples); /* CM_R_028BE0_PA_SC_AA_CONFIG */
1132		ms->pa_sc_mode_cntl_1 |= S_028A4C_PS_ITER_SAMPLE(ps_iter_samples > 1);
1133		if (ps_iter_samples > 1)
1134			pipeline->graphics.spi_baryc_cntl |= S_0286E0_POS_FLOAT_LOCATION(2);
1135	}
1136
1137	if (vkms && vkms->pSampleMask) {
1138		mask = vkms->pSampleMask[0] & 0xffff;
1139	}
1140
1141	ms->pa_sc_aa_mask[0] = mask | (mask << 16);
1142	ms->pa_sc_aa_mask[1] = mask | (mask << 16);
1143}
1144
1145static bool
1146radv_prim_can_use_guardband(enum VkPrimitiveTopology topology)
1147{
1148	switch (topology) {
1149	case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
1150	case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
1151	case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
1152	case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
1153	case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
1154		return false;
1155	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
1156	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
1157	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
1158	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
1159	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
1160	case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST:
1161		return true;
1162	default:
1163		unreachable("unhandled primitive type");
1164	}
1165}
1166
1167static uint32_t
1168si_translate_prim(enum VkPrimitiveTopology topology)
1169{
1170	switch (topology) {
1171	case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
1172		return V_008958_DI_PT_POINTLIST;
1173	case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
1174		return V_008958_DI_PT_LINELIST;
1175	case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
1176		return V_008958_DI_PT_LINESTRIP;
1177	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
1178		return V_008958_DI_PT_TRILIST;
1179	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
1180		return V_008958_DI_PT_TRISTRIP;
1181	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
1182		return V_008958_DI_PT_TRIFAN;
1183	case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
1184		return V_008958_DI_PT_LINELIST_ADJ;
1185	case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
1186		return V_008958_DI_PT_LINESTRIP_ADJ;
1187	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
1188		return V_008958_DI_PT_TRILIST_ADJ;
1189	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
1190		return V_008958_DI_PT_TRISTRIP_ADJ;
1191	case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST:
1192		return V_008958_DI_PT_PATCH;
1193	default:
1194		assert(0);
1195		return 0;
1196	}
1197}
1198
1199static uint32_t
1200si_conv_gl_prim_to_gs_out(unsigned gl_prim)
1201{
1202	switch (gl_prim) {
1203	case 0: /* GL_POINTS */
1204		return V_028A6C_OUTPRIM_TYPE_POINTLIST;
1205	case 1: /* GL_LINES */
1206	case 3: /* GL_LINE_STRIP */
1207	case 0xA: /* GL_LINE_STRIP_ADJACENCY_ARB */
1208	case 0x8E7A: /* GL_ISOLINES */
1209		return V_028A6C_OUTPRIM_TYPE_LINESTRIP;
1210
1211	case 4: /* GL_TRIANGLES */
1212	case 0xc: /* GL_TRIANGLES_ADJACENCY_ARB */
1213	case 5: /* GL_TRIANGLE_STRIP */
1214	case 7: /* GL_QUADS */
1215		return V_028A6C_OUTPRIM_TYPE_TRISTRIP;
1216	default:
1217		assert(0);
1218		return 0;
1219	}
1220}
1221
1222static uint32_t
1223si_conv_prim_to_gs_out(enum VkPrimitiveTopology topology)
1224{
1225	switch (topology) {
1226	case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
1227	case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST:
1228		return V_028A6C_OUTPRIM_TYPE_POINTLIST;
1229	case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
1230	case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
1231	case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
1232	case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
1233		return V_028A6C_OUTPRIM_TYPE_LINESTRIP;
1234	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
1235	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
1236	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
1237	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
1238	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
1239		return V_028A6C_OUTPRIM_TYPE_TRISTRIP;
1240	default:
1241		assert(0);
1242		return 0;
1243	}
1244}
1245
1246static unsigned si_map_swizzle(unsigned swizzle)
1247{
1248	switch (swizzle) {
1249	case VK_SWIZZLE_Y:
1250		return V_008F0C_SQ_SEL_Y;
1251	case VK_SWIZZLE_Z:
1252		return V_008F0C_SQ_SEL_Z;
1253	case VK_SWIZZLE_W:
1254		return V_008F0C_SQ_SEL_W;
1255	case VK_SWIZZLE_0:
1256		return V_008F0C_SQ_SEL_0;
1257	case VK_SWIZZLE_1:
1258		return V_008F0C_SQ_SEL_1;
1259	default: /* VK_SWIZZLE_X */
1260		return V_008F0C_SQ_SEL_X;
1261	}
1262}
1263
1264
1265static unsigned radv_dynamic_state_mask(VkDynamicState state)
1266{
1267	switch(state) {
1268	case VK_DYNAMIC_STATE_VIEWPORT:
1269		return RADV_DYNAMIC_VIEWPORT;
1270	case VK_DYNAMIC_STATE_SCISSOR:
1271		return RADV_DYNAMIC_SCISSOR;
1272	case VK_DYNAMIC_STATE_LINE_WIDTH:
1273		return RADV_DYNAMIC_LINE_WIDTH;
1274	case VK_DYNAMIC_STATE_DEPTH_BIAS:
1275		return RADV_DYNAMIC_DEPTH_BIAS;
1276	case VK_DYNAMIC_STATE_BLEND_CONSTANTS:
1277		return RADV_DYNAMIC_BLEND_CONSTANTS;
1278	case VK_DYNAMIC_STATE_DEPTH_BOUNDS:
1279		return RADV_DYNAMIC_DEPTH_BOUNDS;
1280	case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK:
1281		return RADV_DYNAMIC_STENCIL_COMPARE_MASK;
1282	case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK:
1283		return RADV_DYNAMIC_STENCIL_WRITE_MASK;
1284	case VK_DYNAMIC_STATE_STENCIL_REFERENCE:
1285		return RADV_DYNAMIC_STENCIL_REFERENCE;
1286	case VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT:
1287		return RADV_DYNAMIC_DISCARD_RECTANGLE;
1288	default:
1289		unreachable("Unhandled dynamic state");
1290	}
1291}
1292
1293static uint32_t radv_pipeline_needed_dynamic_state(const VkGraphicsPipelineCreateInfo *pCreateInfo)
1294{
1295	uint32_t states = RADV_DYNAMIC_ALL;
1296
1297	/* If rasterization is disabled we do not care about any of the dynamic states,
1298	 * since they are all rasterization related only. */
1299	if (pCreateInfo->pRasterizationState->rasterizerDiscardEnable)
1300		return 0;
1301
1302	if (!pCreateInfo->pRasterizationState->depthBiasEnable)
1303		states &= ~RADV_DYNAMIC_DEPTH_BIAS;
1304
1305	if (!pCreateInfo->pDepthStencilState ||
1306	    !pCreateInfo->pDepthStencilState->depthBoundsTestEnable)
1307		states &= ~RADV_DYNAMIC_DEPTH_BOUNDS;
1308
1309	if (!pCreateInfo->pDepthStencilState ||
1310	    !pCreateInfo->pDepthStencilState->stencilTestEnable)
1311		states &= ~(RADV_DYNAMIC_STENCIL_COMPARE_MASK |
1312		            RADV_DYNAMIC_STENCIL_WRITE_MASK |
1313		            RADV_DYNAMIC_STENCIL_REFERENCE);
1314
1315	if (!vk_find_struct_const(pCreateInfo->pNext, PIPELINE_DISCARD_RECTANGLE_STATE_CREATE_INFO_EXT))
1316		states &= ~RADV_DYNAMIC_DISCARD_RECTANGLE;
1317
1318	/* TODO: blend constants & line width. */
1319
1320	return states;
1321}
1322
1323
1324static void
1325radv_pipeline_init_dynamic_state(struct radv_pipeline *pipeline,
1326				 const VkGraphicsPipelineCreateInfo *pCreateInfo)
1327{
1328	uint32_t needed_states = radv_pipeline_needed_dynamic_state(pCreateInfo);
1329	uint32_t states = needed_states;
1330	RADV_FROM_HANDLE(radv_render_pass, pass, pCreateInfo->renderPass);
1331	struct radv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
1332
1333	pipeline->dynamic_state = default_dynamic_state;
1334	pipeline->graphics.needed_dynamic_state = needed_states;
1335
1336	if (pCreateInfo->pDynamicState) {
1337		/* Remove all of the states that are marked as dynamic */
1338		uint32_t count = pCreateInfo->pDynamicState->dynamicStateCount;
1339		for (uint32_t s = 0; s < count; s++)
1340			states &= ~radv_dynamic_state_mask(pCreateInfo->pDynamicState->pDynamicStates[s]);
1341	}
1342
1343	struct radv_dynamic_state *dynamic = &pipeline->dynamic_state;
1344
1345	if (needed_states & RADV_DYNAMIC_VIEWPORT) {
1346		assert(pCreateInfo->pViewportState);
1347
1348		dynamic->viewport.count = pCreateInfo->pViewportState->viewportCount;
1349		if (states & RADV_DYNAMIC_VIEWPORT) {
1350			typed_memcpy(dynamic->viewport.viewports,
1351			             pCreateInfo->pViewportState->pViewports,
1352			             pCreateInfo->pViewportState->viewportCount);
1353		}
1354	}
1355
1356	if (needed_states & RADV_DYNAMIC_SCISSOR) {
1357		dynamic->scissor.count = pCreateInfo->pViewportState->scissorCount;
1358		if (states & RADV_DYNAMIC_SCISSOR) {
1359			typed_memcpy(dynamic->scissor.scissors,
1360			             pCreateInfo->pViewportState->pScissors,
1361			             pCreateInfo->pViewportState->scissorCount);
1362		}
1363	}
1364
1365	if (states & RADV_DYNAMIC_LINE_WIDTH) {
1366		assert(pCreateInfo->pRasterizationState);
1367		dynamic->line_width = pCreateInfo->pRasterizationState->lineWidth;
1368	}
1369
1370	if (states & RADV_DYNAMIC_DEPTH_BIAS) {
1371		assert(pCreateInfo->pRasterizationState);
1372		dynamic->depth_bias.bias =
1373			pCreateInfo->pRasterizationState->depthBiasConstantFactor;
1374		dynamic->depth_bias.clamp =
1375			pCreateInfo->pRasterizationState->depthBiasClamp;
1376		dynamic->depth_bias.slope =
1377			pCreateInfo->pRasterizationState->depthBiasSlopeFactor;
1378	}
1379
1380	/* Section 9.2 of the Vulkan 1.0.15 spec says:
1381	 *
1382	 *    pColorBlendState is [...] NULL if the pipeline has rasterization
1383	 *    disabled or if the subpass of the render pass the pipeline is
1384	 *    created against does not use any color attachments.
1385	 */
1386	bool uses_color_att = false;
1387	for (unsigned i = 0; i < subpass->color_count; ++i) {
1388		if (subpass->color_attachments[i].attachment != VK_ATTACHMENT_UNUSED) {
1389			uses_color_att = true;
1390			break;
1391		}
1392	}
1393
1394	if (uses_color_att && states & RADV_DYNAMIC_BLEND_CONSTANTS) {
1395		assert(pCreateInfo->pColorBlendState);
1396		typed_memcpy(dynamic->blend_constants,
1397			     pCreateInfo->pColorBlendState->blendConstants, 4);
1398	}
1399
1400	/* If there is no depthstencil attachment, then don't read
1401	 * pDepthStencilState. The Vulkan spec states that pDepthStencilState may
1402	 * be NULL in this case. Even if pDepthStencilState is non-NULL, there is
1403	 * no need to override the depthstencil defaults in
1404	 * radv_pipeline::dynamic_state when there is no depthstencil attachment.
1405	 *
1406	 * Section 9.2 of the Vulkan 1.0.15 spec says:
1407	 *
1408	 *    pDepthStencilState is [...] NULL if the pipeline has rasterization
1409	 *    disabled or if the subpass of the render pass the pipeline is created
1410	 *    against does not use a depth/stencil attachment.
1411	 */
1412	if (needed_states &&
1413	    subpass->depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED) {
1414		assert(pCreateInfo->pDepthStencilState);
1415
1416		if (states & RADV_DYNAMIC_DEPTH_BOUNDS) {
1417			dynamic->depth_bounds.min =
1418				pCreateInfo->pDepthStencilState->minDepthBounds;
1419			dynamic->depth_bounds.max =
1420				pCreateInfo->pDepthStencilState->maxDepthBounds;
1421		}
1422
1423		if (states & RADV_DYNAMIC_STENCIL_COMPARE_MASK) {
1424			dynamic->stencil_compare_mask.front =
1425				pCreateInfo->pDepthStencilState->front.compareMask;
1426			dynamic->stencil_compare_mask.back =
1427				pCreateInfo->pDepthStencilState->back.compareMask;
1428		}
1429
1430		if (states & RADV_DYNAMIC_STENCIL_WRITE_MASK) {
1431			dynamic->stencil_write_mask.front =
1432				pCreateInfo->pDepthStencilState->front.writeMask;
1433			dynamic->stencil_write_mask.back =
1434				pCreateInfo->pDepthStencilState->back.writeMask;
1435		}
1436
1437		if (states & RADV_DYNAMIC_STENCIL_REFERENCE) {
1438			dynamic->stencil_reference.front =
1439				pCreateInfo->pDepthStencilState->front.reference;
1440			dynamic->stencil_reference.back =
1441				pCreateInfo->pDepthStencilState->back.reference;
1442		}
1443	}
1444
1445	const  VkPipelineDiscardRectangleStateCreateInfoEXT *discard_rectangle_info =
1446			vk_find_struct_const(pCreateInfo->pNext, PIPELINE_DISCARD_RECTANGLE_STATE_CREATE_INFO_EXT);
1447	if (states & RADV_DYNAMIC_DISCARD_RECTANGLE) {
1448		dynamic->discard_rectangle.count = discard_rectangle_info->discardRectangleCount;
1449		typed_memcpy(dynamic->discard_rectangle.rectangles,
1450		             discard_rectangle_info->pDiscardRectangles,
1451		             discard_rectangle_info->discardRectangleCount);
1452	}
1453
1454	pipeline->dynamic_state.mask = states;
1455}
1456
1457static struct radv_gs_state
1458calculate_gs_info(const VkGraphicsPipelineCreateInfo *pCreateInfo,
1459                       const struct radv_pipeline *pipeline)
1460{
1461	struct radv_gs_state gs = {0};
1462	struct radv_shader_variant_info *gs_info = &pipeline->shaders[MESA_SHADER_GEOMETRY]->info;
1463	struct radv_es_output_info *es_info;
1464	if (pipeline->device->physical_device->rad_info.chip_class >= GFX9)
1465		es_info = radv_pipeline_has_tess(pipeline) ? &gs_info->tes.es_info : &gs_info->vs.es_info;
1466	else
1467		es_info = radv_pipeline_has_tess(pipeline) ?
1468			&pipeline->shaders[MESA_SHADER_TESS_EVAL]->info.tes.es_info :
1469			&pipeline->shaders[MESA_SHADER_VERTEX]->info.vs.es_info;
1470
1471	unsigned gs_num_invocations = MAX2(gs_info->gs.invocations, 1);
1472	bool uses_adjacency;
1473	switch(pCreateInfo->pInputAssemblyState->topology) {
1474	case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
1475	case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
1476	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
1477	case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
1478		uses_adjacency = true;
1479		break;
1480	default:
1481		uses_adjacency = false;
1482		break;
1483	}
1484
1485	/* All these are in dwords: */
1486	/* We can't allow using the whole LDS, because GS waves compete with
1487	 * other shader stages for LDS space. */
1488	const unsigned max_lds_size = 8 * 1024;
1489	const unsigned esgs_itemsize = es_info->esgs_itemsize / 4;
1490	unsigned esgs_lds_size;
1491
1492	/* All these are per subgroup: */
1493	const unsigned max_out_prims = 32 * 1024;
1494	const unsigned max_es_verts = 255;
1495	const unsigned ideal_gs_prims = 64;
1496	unsigned max_gs_prims, gs_prims;
1497	unsigned min_es_verts, es_verts, worst_case_es_verts;
1498
1499	if (uses_adjacency || gs_num_invocations > 1)
1500		max_gs_prims = 127 / gs_num_invocations;
1501	else
1502		max_gs_prims = 255;
1503
1504	/* MAX_PRIMS_PER_SUBGROUP = gs_prims * max_vert_out * gs_invocations.
1505	 * Make sure we don't go over the maximum value.
1506	 */
1507	if (gs_info->gs.vertices_out > 0) {
1508		max_gs_prims = MIN2(max_gs_prims,
1509				    max_out_prims /
1510				    (gs_info->gs.vertices_out * gs_num_invocations));
1511	}
1512	assert(max_gs_prims > 0);
1513
1514	/* If the primitive has adjacency, halve the number of vertices
1515	 * that will be reused in multiple primitives.
1516	 */
1517	min_es_verts = gs_info->gs.vertices_in / (uses_adjacency ? 2 : 1);
1518
1519	gs_prims = MIN2(ideal_gs_prims, max_gs_prims);
1520	worst_case_es_verts = MIN2(min_es_verts * gs_prims, max_es_verts);
1521
1522	/* Compute ESGS LDS size based on the worst case number of ES vertices
1523	 * needed to create the target number of GS prims per subgroup.
1524	 */
1525	esgs_lds_size = esgs_itemsize * worst_case_es_verts;
1526
1527	/* If total LDS usage is too big, refactor partitions based on ratio
1528	 * of ESGS item sizes.
1529	 */
1530	if (esgs_lds_size > max_lds_size) {
1531		/* Our target GS Prims Per Subgroup was too large. Calculate
1532		 * the maximum number of GS Prims Per Subgroup that will fit
1533		 * into LDS, capped by the maximum that the hardware can support.
1534		 */
1535		gs_prims = MIN2((max_lds_size / (esgs_itemsize * min_es_verts)),
1536				max_gs_prims);
1537		assert(gs_prims > 0);
1538		worst_case_es_verts = MIN2(min_es_verts * gs_prims,
1539					   max_es_verts);
1540
1541		esgs_lds_size = esgs_itemsize * worst_case_es_verts;
1542		assert(esgs_lds_size <= max_lds_size);
1543	}
1544
1545	/* Now calculate remaining ESGS information. */
1546	if (esgs_lds_size)
1547		es_verts = MIN2(esgs_lds_size / esgs_itemsize, max_es_verts);
1548	else
1549		es_verts = max_es_verts;
1550
1551	/* Vertices for adjacency primitives are not always reused, so restore
1552	 * it for ES_VERTS_PER_SUBGRP.
1553	 */
1554	min_es_verts = gs_info->gs.vertices_in;
1555
1556	/* For normal primitives, the VGT only checks if they are past the ES
1557	 * verts per subgroup after allocating a full GS primitive and if they
1558	 * are, kick off a new subgroup.  But if those additional ES verts are
1559	 * unique (e.g. not reused) we need to make sure there is enough LDS
1560	 * space to account for those ES verts beyond ES_VERTS_PER_SUBGRP.
1561	 */
1562	es_verts -= min_es_verts - 1;
1563
1564	uint32_t es_verts_per_subgroup = es_verts;
1565	uint32_t gs_prims_per_subgroup = gs_prims;
1566	uint32_t gs_inst_prims_in_subgroup = gs_prims * gs_num_invocations;
1567	uint32_t max_prims_per_subgroup = gs_inst_prims_in_subgroup * gs_info->gs.vertices_out;
1568	gs.lds_size = align(esgs_lds_size, 128) / 128;
1569	gs.vgt_gs_onchip_cntl = S_028A44_ES_VERTS_PER_SUBGRP(es_verts_per_subgroup) |
1570	                        S_028A44_GS_PRIMS_PER_SUBGRP(gs_prims_per_subgroup) |
1571	                        S_028A44_GS_INST_PRIMS_IN_SUBGRP(gs_inst_prims_in_subgroup);
1572	gs.vgt_gs_max_prims_per_subgroup = S_028A94_MAX_PRIMS_PER_SUBGROUP(max_prims_per_subgroup);
1573	gs.vgt_esgs_ring_itemsize  = esgs_itemsize;
1574	assert(max_prims_per_subgroup <= max_out_prims);
1575
1576	return gs;
1577}
1578
1579static void
1580calculate_gs_ring_sizes(struct radv_pipeline *pipeline, const struct radv_gs_state *gs)
1581{
1582	struct radv_device *device = pipeline->device;
1583	unsigned num_se = device->physical_device->rad_info.max_se;
1584	unsigned wave_size = 64;
1585	unsigned max_gs_waves = 32 * num_se; /* max 32 per SE on GCN */
1586	/* On SI-CI, the value comes from VGT_GS_VERTEX_REUSE = 16.
1587	 * On VI+, the value comes from VGT_VERTEX_REUSE_BLOCK_CNTL = 30 (+2).
1588	 */
1589	unsigned gs_vertex_reuse =
1590		(device->physical_device->rad_info.chip_class >= VI ? 32 : 16) * num_se;
1591	unsigned alignment = 256 * num_se;
1592	/* The maximum size is 63.999 MB per SE. */
1593	unsigned max_size = ((unsigned)(63.999 * 1024 * 1024) & ~255) * num_se;
1594	struct radv_shader_variant_info *gs_info = &pipeline->shaders[MESA_SHADER_GEOMETRY]->info;
1595
1596	/* Calculate the minimum size. */
1597	unsigned min_esgs_ring_size = align(gs->vgt_esgs_ring_itemsize * 4 * gs_vertex_reuse *
1598					    wave_size, alignment);
1599	/* These are recommended sizes, not minimum sizes. */
1600	unsigned esgs_ring_size = max_gs_waves * 2 * wave_size *
1601		gs->vgt_esgs_ring_itemsize * 4 * gs_info->gs.vertices_in;
1602	unsigned gsvs_ring_size = max_gs_waves * 2 * wave_size *
1603		gs_info->gs.max_gsvs_emit_size;
1604
1605	min_esgs_ring_size = align(min_esgs_ring_size, alignment);
1606	esgs_ring_size = align(esgs_ring_size, alignment);
1607	gsvs_ring_size = align(gsvs_ring_size, alignment);
1608
1609	if (pipeline->device->physical_device->rad_info.chip_class <= VI)
1610		pipeline->graphics.esgs_ring_size = CLAMP(esgs_ring_size, min_esgs_ring_size, max_size);
1611
1612	pipeline->graphics.gsvs_ring_size = MIN2(gsvs_ring_size, max_size);
1613}
1614
1615static void si_multiwave_lds_size_workaround(struct radv_device *device,
1616					     unsigned *lds_size)
1617{
1618	/* If tessellation is all offchip and on-chip GS isn't used, this
1619	 * workaround is not needed.
1620	 */
1621	return;
1622
1623	/* SPI barrier management bug:
1624	 *   Make sure we have at least 4k of LDS in use to avoid the bug.
1625	 *   It applies to workgroup sizes of more than one wavefront.
1626	 */
1627	if (device->physical_device->rad_info.family == CHIP_BONAIRE ||
1628	    device->physical_device->rad_info.family == CHIP_KABINI ||
1629	    device->physical_device->rad_info.family == CHIP_MULLINS)
1630		*lds_size = MAX2(*lds_size, 8);
1631}
1632
1633struct radv_shader_variant *
1634radv_get_shader(struct radv_pipeline *pipeline,
1635		gl_shader_stage stage)
1636{
1637	if (stage == MESA_SHADER_VERTEX) {
1638		if (pipeline->shaders[MESA_SHADER_VERTEX])
1639			return pipeline->shaders[MESA_SHADER_VERTEX];
1640		if (pipeline->shaders[MESA_SHADER_TESS_CTRL])
1641			return pipeline->shaders[MESA_SHADER_TESS_CTRL];
1642		if (pipeline->shaders[MESA_SHADER_GEOMETRY])
1643			return pipeline->shaders[MESA_SHADER_GEOMETRY];
1644	} else if (stage == MESA_SHADER_TESS_EVAL) {
1645		if (!radv_pipeline_has_tess(pipeline))
1646			return NULL;
1647		if (pipeline->shaders[MESA_SHADER_TESS_EVAL])
1648			return pipeline->shaders[MESA_SHADER_TESS_EVAL];
1649		if (pipeline->shaders[MESA_SHADER_GEOMETRY])
1650			return pipeline->shaders[MESA_SHADER_GEOMETRY];
1651	}
1652	return pipeline->shaders[stage];
1653}
1654
1655static struct radv_tessellation_state
1656calculate_tess_state(struct radv_pipeline *pipeline,
1657		     const VkGraphicsPipelineCreateInfo *pCreateInfo)
1658{
1659	unsigned num_tcs_input_cp;
1660	unsigned num_tcs_output_cp;
1661	unsigned lds_size;
1662	unsigned num_patches;
1663	struct radv_tessellation_state tess = {0};
1664
1665	num_tcs_input_cp = pCreateInfo->pTessellationState->patchControlPoints;
1666	num_tcs_output_cp = pipeline->shaders[MESA_SHADER_TESS_CTRL]->info.tcs.tcs_vertices_out; //TCS VERTICES OUT
1667	num_patches = pipeline->shaders[MESA_SHADER_TESS_CTRL]->info.tcs.num_patches;
1668
1669	lds_size = pipeline->shaders[MESA_SHADER_TESS_CTRL]->info.tcs.lds_size;
1670
1671	if (pipeline->device->physical_device->rad_info.chip_class >= CIK) {
1672		assert(lds_size <= 65536);
1673		lds_size = align(lds_size, 512) / 512;
1674	} else {
1675		assert(lds_size <= 32768);
1676		lds_size = align(lds_size, 256) / 256;
1677	}
1678	si_multiwave_lds_size_workaround(pipeline->device, &lds_size);
1679
1680	tess.lds_size = lds_size;
1681
1682	tess.ls_hs_config = S_028B58_NUM_PATCHES(num_patches) |
1683		S_028B58_HS_NUM_INPUT_CP(num_tcs_input_cp) |
1684		S_028B58_HS_NUM_OUTPUT_CP(num_tcs_output_cp);
1685	tess.num_patches = num_patches;
1686
1687	struct radv_shader_variant *tes = radv_get_shader(pipeline, MESA_SHADER_TESS_EVAL);
1688	unsigned type = 0, partitioning = 0, topology = 0, distribution_mode = 0;
1689
1690	switch (tes->info.tes.primitive_mode) {
1691	case GL_TRIANGLES:
1692		type = V_028B6C_TESS_TRIANGLE;
1693		break;
1694	case GL_QUADS:
1695		type = V_028B6C_TESS_QUAD;
1696		break;
1697	case GL_ISOLINES:
1698		type = V_028B6C_TESS_ISOLINE;
1699		break;
1700	}
1701
1702	switch (tes->info.tes.spacing) {
1703	case TESS_SPACING_EQUAL:
1704		partitioning = V_028B6C_PART_INTEGER;
1705		break;
1706	case TESS_SPACING_FRACTIONAL_ODD:
1707		partitioning = V_028B6C_PART_FRAC_ODD;
1708		break;
1709	case TESS_SPACING_FRACTIONAL_EVEN:
1710		partitioning = V_028B6C_PART_FRAC_EVEN;
1711		break;
1712	default:
1713		break;
1714	}
1715
1716	bool ccw = tes->info.tes.ccw;
1717	const VkPipelineTessellationDomainOriginStateCreateInfoKHR *domain_origin_state =
1718	              vk_find_struct_const(pCreateInfo->pTessellationState,
1719	                                   PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO_KHR);
1720
1721	if (domain_origin_state && domain_origin_state->domainOrigin != VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT_KHR)
1722		ccw = !ccw;
1723
1724	if (tes->info.tes.point_mode)
1725		topology = V_028B6C_OUTPUT_POINT;
1726	else if (tes->info.tes.primitive_mode == GL_ISOLINES)
1727		topology = V_028B6C_OUTPUT_LINE;
1728	else if (ccw)
1729		topology = V_028B6C_OUTPUT_TRIANGLE_CCW;
1730	else
1731		topology = V_028B6C_OUTPUT_TRIANGLE_CW;
1732
1733	if (pipeline->device->has_distributed_tess) {
1734		if (pipeline->device->physical_device->rad_info.family == CHIP_FIJI ||
1735		    pipeline->device->physical_device->rad_info.family >= CHIP_POLARIS10)
1736			distribution_mode = V_028B6C_DISTRIBUTION_MODE_TRAPEZOIDS;
1737		else
1738			distribution_mode = V_028B6C_DISTRIBUTION_MODE_DONUTS;
1739	} else
1740		distribution_mode = V_028B6C_DISTRIBUTION_MODE_NO_DIST;
1741
1742	tess.tf_param = S_028B6C_TYPE(type) |
1743		S_028B6C_PARTITIONING(partitioning) |
1744		S_028B6C_TOPOLOGY(topology) |
1745		S_028B6C_DISTRIBUTION_MODE(distribution_mode);
1746
1747	return tess;
1748}
1749
1750static const struct radv_prim_vertex_count prim_size_table[] = {
1751	[V_008958_DI_PT_NONE] = {0, 0},
1752	[V_008958_DI_PT_POINTLIST] = {1, 1},
1753	[V_008958_DI_PT_LINELIST] = {2, 2},
1754	[V_008958_DI_PT_LINESTRIP] = {2, 1},
1755	[V_008958_DI_PT_TRILIST] = {3, 3},
1756	[V_008958_DI_PT_TRIFAN] = {3, 1},
1757	[V_008958_DI_PT_TRISTRIP] = {3, 1},
1758	[V_008958_DI_PT_LINELIST_ADJ] = {4, 4},
1759	[V_008958_DI_PT_LINESTRIP_ADJ] = {4, 1},
1760	[V_008958_DI_PT_TRILIST_ADJ] = {6, 6},
1761	[V_008958_DI_PT_TRISTRIP_ADJ] = {6, 2},
1762	[V_008958_DI_PT_RECTLIST] = {3, 3},
1763	[V_008958_DI_PT_LINELOOP] = {2, 1},
1764	[V_008958_DI_PT_POLYGON] = {3, 1},
1765	[V_008958_DI_PT_2D_TRI_STRIP] = {0, 0},
1766};
1767
1768static const struct radv_vs_output_info *get_vs_output_info(const struct radv_pipeline *pipeline)
1769{
1770	if (radv_pipeline_has_gs(pipeline))
1771		return &pipeline->gs_copy_shader->info.vs.outinfo;
1772	else if (radv_pipeline_has_tess(pipeline))
1773		return &pipeline->shaders[MESA_SHADER_TESS_EVAL]->info.tes.outinfo;
1774	else
1775		return &pipeline->shaders[MESA_SHADER_VERTEX]->info.vs.outinfo;
1776}
1777
1778static void
1779radv_link_shaders(struct radv_pipeline *pipeline, nir_shader **shaders)
1780{
1781	nir_shader* ordered_shaders[MESA_SHADER_STAGES];
1782	int shader_count = 0;
1783
1784	if(shaders[MESA_SHADER_FRAGMENT]) {
1785		ordered_shaders[shader_count++] = shaders[MESA_SHADER_FRAGMENT];
1786	}
1787	if(shaders[MESA_SHADER_GEOMETRY]) {
1788		ordered_shaders[shader_count++] = shaders[MESA_SHADER_GEOMETRY];
1789	}
1790	if(shaders[MESA_SHADER_TESS_EVAL]) {
1791		ordered_shaders[shader_count++] = shaders[MESA_SHADER_TESS_EVAL];
1792	}
1793	if(shaders[MESA_SHADER_TESS_CTRL]) {
1794		ordered_shaders[shader_count++] = shaders[MESA_SHADER_TESS_CTRL];
1795	}
1796	if(shaders[MESA_SHADER_VERTEX]) {
1797		ordered_shaders[shader_count++] = shaders[MESA_SHADER_VERTEX];
1798	}
1799
1800	if (shader_count > 1) {
1801		unsigned first = ordered_shaders[shader_count - 1]->info.stage;
1802		unsigned last = ordered_shaders[0]->info.stage;
1803
1804		if (ordered_shaders[0]->info.stage == MESA_SHADER_FRAGMENT &&
1805		    ordered_shaders[1]->info.has_transform_feedback_varyings)
1806			nir_link_xfb_varyings(ordered_shaders[1], ordered_shaders[0]);
1807
1808		for (int i = 0; i < shader_count; ++i)  {
1809			nir_variable_mode mask = 0;
1810
1811			if (ordered_shaders[i]->info.stage != first)
1812				mask = mask | nir_var_shader_in;
1813
1814			if (ordered_shaders[i]->info.stage != last)
1815				mask = mask | nir_var_shader_out;
1816
1817			nir_lower_io_to_scalar_early(ordered_shaders[i], mask);
1818			radv_optimize_nir(ordered_shaders[i], false, false);
1819		}
1820	}
1821
1822	for (int i = 1; i < shader_count; ++i)  {
1823		nir_lower_io_arrays_to_elements(ordered_shaders[i],
1824						ordered_shaders[i - 1]);
1825
1826		nir_remove_dead_variables(ordered_shaders[i],
1827					  nir_var_shader_out);
1828		nir_remove_dead_variables(ordered_shaders[i - 1],
1829					  nir_var_shader_in);
1830
1831		bool progress = nir_remove_unused_varyings(ordered_shaders[i],
1832							   ordered_shaders[i - 1]);
1833
1834		nir_compact_varyings(ordered_shaders[i],
1835				     ordered_shaders[i - 1], true);
1836
1837		if (progress) {
1838			if (nir_lower_global_vars_to_local(ordered_shaders[i])) {
1839				ac_lower_indirect_derefs(ordered_shaders[i],
1840				                         pipeline->device->physical_device->rad_info.chip_class);
1841			}
1842			radv_optimize_nir(ordered_shaders[i], false, false);
1843
1844			if (nir_lower_global_vars_to_local(ordered_shaders[i - 1])) {
1845				ac_lower_indirect_derefs(ordered_shaders[i - 1],
1846				                         pipeline->device->physical_device->rad_info.chip_class);
1847			}
1848			radv_optimize_nir(ordered_shaders[i - 1], false, false);
1849		}
1850	}
1851}
1852
1853
1854static struct radv_pipeline_key
1855radv_generate_graphics_pipeline_key(struct radv_pipeline *pipeline,
1856                                    const VkGraphicsPipelineCreateInfo *pCreateInfo,
1857                                    const struct radv_blend_state *blend,
1858                                    bool has_view_index)
1859{
1860	const VkPipelineVertexInputStateCreateInfo *input_state =
1861	                                         pCreateInfo->pVertexInputState;
1862	const VkPipelineVertexInputDivisorStateCreateInfoEXT *divisor_state =
1863		vk_find_struct_const(input_state->pNext, PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT);
1864
1865	struct radv_pipeline_key key;
1866	memset(&key, 0, sizeof(key));
1867
1868	if (pCreateInfo->flags & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT)
1869		key.optimisations_disabled = 1;
1870
1871	key.has_multiview_view_index = has_view_index;
1872
1873	uint32_t binding_input_rate = 0;
1874	uint32_t instance_rate_divisors[MAX_VERTEX_ATTRIBS];
1875	for (unsigned i = 0; i < input_state->vertexBindingDescriptionCount; ++i) {
1876		if (input_state->pVertexBindingDescriptions[i].inputRate) {
1877			unsigned binding = input_state->pVertexBindingDescriptions[i].binding;
1878			binding_input_rate |= 1u << binding;
1879			instance_rate_divisors[binding] = 1;
1880		}
1881	}
1882	if (divisor_state) {
1883		for (unsigned i = 0; i < divisor_state->vertexBindingDivisorCount; ++i) {
1884			instance_rate_divisors[divisor_state->pVertexBindingDivisors[i].binding] =
1885				divisor_state->pVertexBindingDivisors[i].divisor;
1886		}
1887	}
1888
1889	for (unsigned i = 0; i < input_state->vertexAttributeDescriptionCount; ++i) {
1890		unsigned location = input_state->pVertexAttributeDescriptions[i].location;
1891		unsigned binding = input_state->pVertexAttributeDescriptions[i].binding;
1892		if (binding_input_rate & (1u << binding)) {
1893			key.instance_rate_inputs |= 1u << location;
1894			key.instance_rate_divisors[location] = instance_rate_divisors[binding];
1895		}
1896
1897		if (pipeline->device->physical_device->rad_info.chip_class <= VI &&
1898		    pipeline->device->physical_device->rad_info.family != CHIP_STONEY) {
1899			VkFormat format = input_state->pVertexAttributeDescriptions[i].format;
1900			uint64_t adjust;
1901			switch(format) {
1902			case VK_FORMAT_A2R10G10B10_SNORM_PACK32:
1903			case VK_FORMAT_A2B10G10R10_SNORM_PACK32:
1904				adjust = RADV_ALPHA_ADJUST_SNORM;
1905				break;
1906			case VK_FORMAT_A2R10G10B10_SSCALED_PACK32:
1907			case VK_FORMAT_A2B10G10R10_SSCALED_PACK32:
1908				adjust = RADV_ALPHA_ADJUST_SSCALED;
1909				break;
1910			case VK_FORMAT_A2R10G10B10_SINT_PACK32:
1911			case VK_FORMAT_A2B10G10R10_SINT_PACK32:
1912				adjust = RADV_ALPHA_ADJUST_SINT;
1913				break;
1914			default:
1915				adjust = 0;
1916				break;
1917			}
1918			key.vertex_alpha_adjust |= adjust << (2 * location);
1919		}
1920	}
1921
1922	if (pCreateInfo->pTessellationState)
1923		key.tess_input_vertices = pCreateInfo->pTessellationState->patchControlPoints;
1924
1925
1926	if (pCreateInfo->pMultisampleState &&
1927	    pCreateInfo->pMultisampleState->rasterizationSamples > 1) {
1928		uint32_t num_samples = pCreateInfo->pMultisampleState->rasterizationSamples;
1929		uint32_t ps_iter_samples = radv_pipeline_get_ps_iter_samples(pCreateInfo->pMultisampleState);
1930		key.num_samples = num_samples;
1931		key.log2_ps_iter_samples = util_logbase2(ps_iter_samples);
1932	}
1933
1934	key.col_format = blend->spi_shader_col_format;
1935	if (pipeline->device->physical_device->rad_info.chip_class < VI)
1936		radv_pipeline_compute_get_int_clamp(pCreateInfo, &key.is_int8, &key.is_int10);
1937
1938	return key;
1939}
1940
1941static void
1942radv_fill_shader_keys(struct radv_shader_variant_key *keys,
1943                      const struct radv_pipeline_key *key,
1944                      nir_shader **nir)
1945{
1946	keys[MESA_SHADER_VERTEX].vs.instance_rate_inputs = key->instance_rate_inputs;
1947	keys[MESA_SHADER_VERTEX].vs.alpha_adjust = key->vertex_alpha_adjust;
1948	for (unsigned i = 0; i < MAX_VERTEX_ATTRIBS; ++i)
1949		keys[MESA_SHADER_VERTEX].vs.instance_rate_divisors[i] = key->instance_rate_divisors[i];
1950
1951	if (nir[MESA_SHADER_TESS_CTRL]) {
1952		keys[MESA_SHADER_VERTEX].vs.as_ls = true;
1953		keys[MESA_SHADER_TESS_CTRL].tcs.num_inputs = 0;
1954		keys[MESA_SHADER_TESS_CTRL].tcs.input_vertices = key->tess_input_vertices;
1955		keys[MESA_SHADER_TESS_CTRL].tcs.primitive_mode = nir[MESA_SHADER_TESS_EVAL]->info.tess.primitive_mode;
1956
1957		keys[MESA_SHADER_TESS_CTRL].tcs.tes_reads_tess_factors = !!(nir[MESA_SHADER_TESS_EVAL]->info.inputs_read & (VARYING_BIT_TESS_LEVEL_INNER | VARYING_BIT_TESS_LEVEL_OUTER));
1958	}
1959
1960	if (nir[MESA_SHADER_GEOMETRY]) {
1961		if (nir[MESA_SHADER_TESS_CTRL])
1962			keys[MESA_SHADER_TESS_EVAL].tes.as_es = true;
1963		else
1964			keys[MESA_SHADER_VERTEX].vs.as_es = true;
1965	}
1966
1967	for(int i = 0; i < MESA_SHADER_STAGES; ++i)
1968		keys[i].has_multiview_view_index = key->has_multiview_view_index;
1969
1970	keys[MESA_SHADER_FRAGMENT].fs.col_format = key->col_format;
1971	keys[MESA_SHADER_FRAGMENT].fs.is_int8 = key->is_int8;
1972	keys[MESA_SHADER_FRAGMENT].fs.is_int10 = key->is_int10;
1973	keys[MESA_SHADER_FRAGMENT].fs.log2_ps_iter_samples = key->log2_ps_iter_samples;
1974	keys[MESA_SHADER_FRAGMENT].fs.num_samples = key->num_samples;
1975}
1976
1977static void
1978merge_tess_info(struct shader_info *tes_info,
1979                const struct shader_info *tcs_info)
1980{
1981	/* The Vulkan 1.0.38 spec, section 21.1 Tessellator says:
1982	 *
1983	 *    "PointMode. Controls generation of points rather than triangles
1984	 *     or lines. This functionality defaults to disabled, and is
1985	 *     enabled if either shader stage includes the execution mode.
1986	 *
1987	 * and about Triangles, Quads, IsoLines, VertexOrderCw, VertexOrderCcw,
1988	 * PointMode, SpacingEqual, SpacingFractionalEven, SpacingFractionalOdd,
1989	 * and OutputVertices, it says:
1990	 *
1991	 *    "One mode must be set in at least one of the tessellation
1992	 *     shader stages."
1993	 *
1994	 * So, the fields can be set in either the TCS or TES, but they must
1995	 * agree if set in both.  Our backend looks at TES, so bitwise-or in
1996	 * the values from the TCS.
1997	 */
1998	assert(tcs_info->tess.tcs_vertices_out == 0 ||
1999	       tes_info->tess.tcs_vertices_out == 0 ||
2000	       tcs_info->tess.tcs_vertices_out == tes_info->tess.tcs_vertices_out);
2001	tes_info->tess.tcs_vertices_out |= tcs_info->tess.tcs_vertices_out;
2002
2003	assert(tcs_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
2004	       tes_info->tess.spacing == TESS_SPACING_UNSPECIFIED ||
2005	       tcs_info->tess.spacing == tes_info->tess.spacing);
2006	tes_info->tess.spacing |= tcs_info->tess.spacing;
2007
2008	assert(tcs_info->tess.primitive_mode == 0 ||
2009	       tes_info->tess.primitive_mode == 0 ||
2010	       tcs_info->tess.primitive_mode == tes_info->tess.primitive_mode);
2011	tes_info->tess.primitive_mode |= tcs_info->tess.primitive_mode;
2012	tes_info->tess.ccw |= tcs_info->tess.ccw;
2013	tes_info->tess.point_mode |= tcs_info->tess.point_mode;
2014}
2015
2016static
2017void radv_create_shaders(struct radv_pipeline *pipeline,
2018                         struct radv_device *device,
2019                         struct radv_pipeline_cache *cache,
2020                         const struct radv_pipeline_key *key,
2021                         const VkPipelineShaderStageCreateInfo **pStages,
2022                         const VkPipelineCreateFlags flags)
2023{
2024	struct radv_shader_module fs_m = {0};
2025	struct radv_shader_module *modules[MESA_SHADER_STAGES] = { 0, };
2026	nir_shader *nir[MESA_SHADER_STAGES] = {0};
2027	void *codes[MESA_SHADER_STAGES] = {0};
2028	unsigned code_sizes[MESA_SHADER_STAGES] = {0};
2029	struct radv_shader_variant_key keys[MESA_SHADER_STAGES] = {{{{0}}}};
2030	unsigned char hash[20], gs_copy_hash[20];
2031
2032	for (unsigned i = 0; i < MESA_SHADER_STAGES; ++i) {
2033		if (pStages[i]) {
2034			modules[i] = radv_shader_module_from_handle(pStages[i]->module);
2035			if (modules[i]->nir)
2036				_mesa_sha1_compute(modules[i]->nir->info.name,
2037				                   strlen(modules[i]->nir->info.name),
2038				                   modules[i]->sha1);
2039
2040			pipeline->active_stages |= mesa_to_vk_shader_stage(i);
2041		}
2042	}
2043
2044	radv_hash_shaders(hash, pStages, pipeline->layout, key, get_hash_flags(device));
2045	memcpy(gs_copy_hash, hash, 20);
2046	gs_copy_hash[0] ^= 1;
2047
2048	if (modules[MESA_SHADER_GEOMETRY]) {
2049		struct radv_shader_variant *variants[MESA_SHADER_STAGES] = {0};
2050		radv_create_shader_variants_from_pipeline_cache(device, cache, gs_copy_hash, variants);
2051		pipeline->gs_copy_shader = variants[MESA_SHADER_GEOMETRY];
2052	}
2053
2054	if (radv_create_shader_variants_from_pipeline_cache(device, cache, hash, pipeline->shaders) &&
2055	    (!modules[MESA_SHADER_GEOMETRY] || pipeline->gs_copy_shader)) {
2056		return;
2057	}
2058
2059	if (!modules[MESA_SHADER_FRAGMENT] && !modules[MESA_SHADER_COMPUTE]) {
2060		nir_builder fs_b;
2061		nir_builder_init_simple_shader(&fs_b, NULL, MESA_SHADER_FRAGMENT, NULL);
2062		fs_b.shader->info.name = ralloc_strdup(fs_b.shader, "noop_fs");
2063		fs_m.nir = fs_b.shader;
2064		modules[MESA_SHADER_FRAGMENT] = &fs_m;
2065	}
2066
2067	for (unsigned i = 0; i < MESA_SHADER_STAGES; ++i) {
2068		const VkPipelineShaderStageCreateInfo *stage = pStages[i];
2069
2070		if (!modules[i])
2071			continue;
2072
2073		nir[i] = radv_shader_compile_to_nir(device, modules[i],
2074						    stage ? stage->pName : "main", i,
2075						    stage ? stage->pSpecializationInfo : NULL,
2076						    flags);
2077
2078		/* We don't want to alter meta shaders IR directly so clone it
2079		 * first.
2080		 */
2081		if (nir[i]->info.name) {
2082			nir[i] = nir_shader_clone(NULL, nir[i]);
2083		}
2084	}
2085
2086	if (nir[MESA_SHADER_TESS_CTRL]) {
2087		nir_lower_patch_vertices(nir[MESA_SHADER_TESS_EVAL], nir[MESA_SHADER_TESS_CTRL]->info.tess.tcs_vertices_out, NULL);
2088		merge_tess_info(&nir[MESA_SHADER_TESS_EVAL]->info, &nir[MESA_SHADER_TESS_CTRL]->info);
2089	}
2090
2091	if (!(flags & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT))
2092		radv_link_shaders(pipeline, nir);
2093
2094	for (int i = 0; i < MESA_SHADER_STAGES; ++i) {
2095		if (radv_can_dump_shader(device, modules[i], false))
2096			nir_print_shader(nir[i], stderr);
2097	}
2098
2099	radv_fill_shader_keys(keys, key, nir);
2100
2101	if (nir[MESA_SHADER_FRAGMENT]) {
2102		if (!pipeline->shaders[MESA_SHADER_FRAGMENT]) {
2103			pipeline->shaders[MESA_SHADER_FRAGMENT] =
2104			       radv_shader_variant_create(device, modules[MESA_SHADER_FRAGMENT], &nir[MESA_SHADER_FRAGMENT], 1,
2105			                                  pipeline->layout, keys + MESA_SHADER_FRAGMENT,
2106			                                  &codes[MESA_SHADER_FRAGMENT], &code_sizes[MESA_SHADER_FRAGMENT]);
2107		}
2108
2109		/* TODO: These are no longer used as keys we should refactor this */
2110		keys[MESA_SHADER_VERTEX].vs.export_prim_id =
2111		        pipeline->shaders[MESA_SHADER_FRAGMENT]->info.info.ps.prim_id_input;
2112		keys[MESA_SHADER_VERTEX].vs.export_layer_id =
2113		        pipeline->shaders[MESA_SHADER_FRAGMENT]->info.info.ps.layer_input;
2114		keys[MESA_SHADER_TESS_EVAL].tes.export_prim_id =
2115		        pipeline->shaders[MESA_SHADER_FRAGMENT]->info.info.ps.prim_id_input;
2116		keys[MESA_SHADER_TESS_EVAL].tes.export_layer_id =
2117		        pipeline->shaders[MESA_SHADER_FRAGMENT]->info.info.ps.layer_input;
2118	}
2119
2120	if (device->physical_device->rad_info.chip_class >= GFX9 && modules[MESA_SHADER_TESS_CTRL]) {
2121		if (!pipeline->shaders[MESA_SHADER_TESS_CTRL]) {
2122			struct nir_shader *combined_nir[] = {nir[MESA_SHADER_VERTEX], nir[MESA_SHADER_TESS_CTRL]};
2123			struct radv_shader_variant_key key = keys[MESA_SHADER_TESS_CTRL];
2124			key.tcs.vs_key = keys[MESA_SHADER_VERTEX].vs;
2125			pipeline->shaders[MESA_SHADER_TESS_CTRL] = radv_shader_variant_create(device, modules[MESA_SHADER_TESS_CTRL], combined_nir, 2,
2126			                                                                      pipeline->layout,
2127			                                                                      &key, &codes[MESA_SHADER_TESS_CTRL],
2128			                                                                      &code_sizes[MESA_SHADER_TESS_CTRL]);
2129		}
2130		modules[MESA_SHADER_VERTEX] = NULL;
2131		keys[MESA_SHADER_TESS_EVAL].tes.num_patches = pipeline->shaders[MESA_SHADER_TESS_CTRL]->info.tcs.num_patches;
2132		keys[MESA_SHADER_TESS_EVAL].tes.tcs_num_outputs = util_last_bit64(pipeline->shaders[MESA_SHADER_TESS_CTRL]->info.info.tcs.outputs_written);
2133	}
2134
2135	if (device->physical_device->rad_info.chip_class >= GFX9 && modules[MESA_SHADER_GEOMETRY]) {
2136		gl_shader_stage pre_stage = modules[MESA_SHADER_TESS_EVAL] ? MESA_SHADER_TESS_EVAL : MESA_SHADER_VERTEX;
2137		if (!pipeline->shaders[MESA_SHADER_GEOMETRY]) {
2138			struct nir_shader *combined_nir[] = {nir[pre_stage], nir[MESA_SHADER_GEOMETRY]};
2139			pipeline->shaders[MESA_SHADER_GEOMETRY] = radv_shader_variant_create(device, modules[MESA_SHADER_GEOMETRY], combined_nir, 2,
2140			                                                                     pipeline->layout,
2141			                                                                     &keys[pre_stage] , &codes[MESA_SHADER_GEOMETRY],
2142		                                                                     &code_sizes[MESA_SHADER_GEOMETRY]);
2143		}
2144		modules[pre_stage] = NULL;
2145	}
2146
2147	for (int i = 0; i < MESA_SHADER_STAGES; ++i) {
2148		if(modules[i] && !pipeline->shaders[i]) {
2149			if (i == MESA_SHADER_TESS_CTRL) {
2150				keys[MESA_SHADER_TESS_CTRL].tcs.num_inputs = util_last_bit64(pipeline->shaders[MESA_SHADER_VERTEX]->info.info.vs.ls_outputs_written);
2151			}
2152			if (i == MESA_SHADER_TESS_EVAL) {
2153				keys[MESA_SHADER_TESS_EVAL].tes.num_patches = pipeline->shaders[MESA_SHADER_TESS_CTRL]->info.tcs.num_patches;
2154				keys[MESA_SHADER_TESS_EVAL].tes.tcs_num_outputs = util_last_bit64(pipeline->shaders[MESA_SHADER_TESS_CTRL]->info.info.tcs.outputs_written);
2155			}
2156			pipeline->shaders[i] = radv_shader_variant_create(device, modules[i], &nir[i], 1,
2157									  pipeline->layout,
2158									  keys + i, &codes[i],
2159									  &code_sizes[i]);
2160		}
2161	}
2162
2163	if(modules[MESA_SHADER_GEOMETRY]) {
2164		void *gs_copy_code = NULL;
2165		unsigned gs_copy_code_size = 0;
2166		if (!pipeline->gs_copy_shader) {
2167			pipeline->gs_copy_shader = radv_create_gs_copy_shader(
2168					device, nir[MESA_SHADER_GEOMETRY], &gs_copy_code,
2169					&gs_copy_code_size,
2170					keys[MESA_SHADER_GEOMETRY].has_multiview_view_index);
2171		}
2172
2173		if (pipeline->gs_copy_shader) {
2174			void *code[MESA_SHADER_STAGES] = {0};
2175			unsigned code_size[MESA_SHADER_STAGES] = {0};
2176			struct radv_shader_variant *variants[MESA_SHADER_STAGES] = {0};
2177
2178			code[MESA_SHADER_GEOMETRY] = gs_copy_code;
2179			code_size[MESA_SHADER_GEOMETRY] = gs_copy_code_size;
2180			variants[MESA_SHADER_GEOMETRY] = pipeline->gs_copy_shader;
2181
2182			radv_pipeline_cache_insert_shaders(device, cache,
2183							   gs_copy_hash,
2184							   variants,
2185							   (const void**)code,
2186							   code_size);
2187		}
2188		free(gs_copy_code);
2189	}
2190
2191	radv_pipeline_cache_insert_shaders(device, cache, hash, pipeline->shaders,
2192					   (const void**)codes, code_sizes);
2193
2194	for (int i = 0; i < MESA_SHADER_STAGES; ++i) {
2195		free(codes[i]);
2196		if (nir[i]) {
2197			if (!pipeline->device->keep_shader_info)
2198				ralloc_free(nir[i]);
2199
2200			if (radv_can_dump_shader_stats(device, modules[i]))
2201				radv_shader_dump_stats(device,
2202						       pipeline->shaders[i],
2203						       i, stderr);
2204		}
2205	}
2206
2207	if (fs_m.nir)
2208		ralloc_free(fs_m.nir);
2209}
2210
2211static uint32_t
2212radv_pipeline_stage_to_user_data_0(struct radv_pipeline *pipeline,
2213				   gl_shader_stage stage, enum chip_class chip_class)
2214{
2215	bool has_gs = radv_pipeline_has_gs(pipeline);
2216	bool has_tess = radv_pipeline_has_tess(pipeline);
2217	switch (stage) {
2218	case MESA_SHADER_FRAGMENT:
2219		return R_00B030_SPI_SHADER_USER_DATA_PS_0;
2220	case MESA_SHADER_VERTEX:
2221		if (chip_class >= GFX9) {
2222			return has_tess ? R_00B430_SPI_SHADER_USER_DATA_LS_0 :
2223			       has_gs ? R_00B330_SPI_SHADER_USER_DATA_ES_0 :
2224			       R_00B130_SPI_SHADER_USER_DATA_VS_0;
2225		}
2226		if (has_tess)
2227			return R_00B530_SPI_SHADER_USER_DATA_LS_0;
2228		else
2229			return has_gs ? R_00B330_SPI_SHADER_USER_DATA_ES_0 : R_00B130_SPI_SHADER_USER_DATA_VS_0;
2230	case MESA_SHADER_GEOMETRY:
2231		return chip_class >= GFX9 ? R_00B330_SPI_SHADER_USER_DATA_ES_0 :
2232		                            R_00B230_SPI_SHADER_USER_DATA_GS_0;
2233	case MESA_SHADER_COMPUTE:
2234		return R_00B900_COMPUTE_USER_DATA_0;
2235	case MESA_SHADER_TESS_CTRL:
2236		return chip_class >= GFX9 ? R_00B430_SPI_SHADER_USER_DATA_LS_0 :
2237		                            R_00B430_SPI_SHADER_USER_DATA_HS_0;
2238	case MESA_SHADER_TESS_EVAL:
2239		if (chip_class >= GFX9) {
2240			return has_gs ? R_00B330_SPI_SHADER_USER_DATA_ES_0 :
2241			       R_00B130_SPI_SHADER_USER_DATA_VS_0;
2242		}
2243		if (has_gs)
2244			return R_00B330_SPI_SHADER_USER_DATA_ES_0;
2245		else
2246			return R_00B130_SPI_SHADER_USER_DATA_VS_0;
2247	default:
2248		unreachable("unknown shader");
2249	}
2250}
2251
2252struct radv_bin_size_entry {
2253	unsigned bpp;
2254	VkExtent2D extent;
2255};
2256
2257static VkExtent2D
2258radv_compute_bin_size(struct radv_pipeline *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo)
2259{
2260	static const struct radv_bin_size_entry color_size_table[][3][9] = {
2261		{
2262			/* One RB / SE */
2263			{
2264				/* One shader engine */
2265				{        0, {128,  128}},
2266				{        1, { 64,  128}},
2267				{        2, { 32,  128}},
2268				{        3, { 16,  128}},
2269				{       17, {  0,    0}},
2270				{ UINT_MAX, {  0,    0}},
2271			},
2272			{
2273				/* Two shader engines */
2274				{        0, {128,  128}},
2275				{        2, { 64,  128}},
2276				{        3, { 32,  128}},
2277				{        5, { 16,  128}},
2278				{       17, {  0,    0}},
2279				{ UINT_MAX, {  0,    0}},
2280			},
2281			{
2282				/* Four shader engines */
2283				{        0, {128,  128}},
2284				{        3, { 64,  128}},
2285				{        5, { 16,  128}},
2286				{       17, {  0,    0}},
2287				{ UINT_MAX, {  0,    0}},
2288			},
2289		},
2290		{
2291			/* Two RB / SE */
2292			{
2293				/* One shader engine */
2294				{        0, {128,  128}},
2295				{        2, { 64,  128}},
2296				{        3, { 32,  128}},
2297				{        5, { 16,  128}},
2298				{       33, {  0,    0}},
2299				{ UINT_MAX, {  0,    0}},
2300			},
2301			{
2302				/* Two shader engines */
2303				{        0, {128,  128}},
2304				{        3, { 64,  128}},
2305				{        5, { 32,  128}},
2306				{        9, { 16,  128}},
2307				{       33, {  0,    0}},
2308				{ UINT_MAX, {  0,    0}},
2309			},
2310			{
2311				/* Four shader engines */
2312				{        0, {256,  256}},
2313				{        2, {128,  256}},
2314				{        3, {128,  128}},
2315				{        5, { 64,  128}},
2316				{        9, { 16,  128}},
2317				{       33, {  0,    0}},
2318				{ UINT_MAX, {  0,    0}},
2319			},
2320		},
2321		{
2322			/* Four RB / SE */
2323			{
2324				/* One shader engine */
2325				{        0, {128,  256}},
2326				{        2, {128,  128}},
2327				{        3, { 64,  128}},
2328				{        5, { 32,  128}},
2329				{        9, { 16,  128}},
2330				{       33, {  0,    0}},
2331				{ UINT_MAX, {  0,    0}},
2332			},
2333			{
2334				/* Two shader engines */
2335				{        0, {256,  256}},
2336				{        2, {128,  256}},
2337				{        3, {128,  128}},
2338				{        5, { 64,  128}},
2339				{        9, { 32,  128}},
2340				{       17, { 16,  128}},
2341				{       33, {  0,    0}},
2342				{ UINT_MAX, {  0,    0}},
2343			},
2344			{
2345				/* Four shader engines */
2346				{        0, {256,  512}},
2347				{        2, {256,  256}},
2348				{        3, {128,  256}},
2349				{        5, {128,  128}},
2350				{        9, { 64,  128}},
2351				{       17, { 16,  128}},
2352				{       33, {  0,    0}},
2353				{ UINT_MAX, {  0,    0}},
2354			},
2355		},
2356	};
2357	static const struct radv_bin_size_entry ds_size_table[][3][9] = {
2358		{
2359			// One RB / SE
2360			{
2361				// One shader engine
2362				{        0, {128,  256}},
2363				{        2, {128,  128}},
2364				{        4, { 64,  128}},
2365				{        7, { 32,  128}},
2366				{       13, { 16,  128}},
2367				{       49, {  0,    0}},
2368				{ UINT_MAX, {  0,    0}},
2369			},
2370			{
2371				// Two shader engines
2372				{        0, {256,  256}},
2373				{        2, {128,  256}},
2374				{        4, {128,  128}},
2375				{        7, { 64,  128}},
2376				{       13, { 32,  128}},
2377				{       25, { 16,  128}},
2378				{       49, {  0,    0}},
2379				{ UINT_MAX, {  0,    0}},
2380			},
2381			{
2382				// Four shader engines
2383				{        0, {256,  512}},
2384				{        2, {256,  256}},
2385				{        4, {128,  256}},
2386				{        7, {128,  128}},
2387				{       13, { 64,  128}},
2388				{       25, { 16,  128}},
2389				{       49, {  0,    0}},
2390				{ UINT_MAX, {  0,    0}},
2391			},
2392		},
2393		{
2394			// Two RB / SE
2395			{
2396				// One shader engine
2397				{        0, {256,  256}},
2398				{        2, {128,  256}},
2399				{        4, {128,  128}},
2400				{        7, { 64,  128}},
2401				{       13, { 32,  128}},
2402				{       25, { 16,  128}},
2403				{       97, {  0,    0}},
2404				{ UINT_MAX, {  0,    0}},
2405			},
2406			{
2407				// Two shader engines
2408				{        0, {256,  512}},
2409				{        2, {256,  256}},
2410				{        4, {128,  256}},
2411				{        7, {128,  128}},
2412				{       13, { 64,  128}},
2413				{       25, { 32,  128}},
2414				{       49, { 16,  128}},
2415				{       97, {  0,    0}},
2416				{ UINT_MAX, {  0,    0}},
2417			},
2418			{
2419				// Four shader engines
2420				{        0, {512,  512}},
2421				{        2, {256,  512}},
2422				{        4, {256,  256}},
2423				{        7, {128,  256}},
2424				{       13, {128,  128}},
2425				{       25, { 64,  128}},
2426				{       49, { 16,  128}},
2427				{       97, {  0,    0}},
2428				{ UINT_MAX, {  0,    0}},
2429			},
2430		},
2431		{
2432			// Four RB / SE
2433			{
2434				// One shader engine
2435				{        0, {256,  512}},
2436				{        2, {256,  256}},
2437				{        4, {128,  256}},
2438				{        7, {128,  128}},
2439				{       13, { 64,  128}},
2440				{       25, { 32,  128}},
2441				{       49, { 16,  128}},
2442				{ UINT_MAX, {  0,    0}},
2443			},
2444			{
2445				// Two shader engines
2446				{        0, {512,  512}},
2447				{        2, {256,  512}},
2448				{        4, {256,  256}},
2449				{        7, {128,  256}},
2450				{       13, {128,  128}},
2451				{       25, { 64,  128}},
2452				{       49, { 32,  128}},
2453				{       97, { 16,  128}},
2454				{ UINT_MAX, {  0,    0}},
2455			},
2456			{
2457				// Four shader engines
2458				{        0, {512,  512}},
2459				{        4, {256,  512}},
2460				{        7, {256,  256}},
2461				{       13, {128,  256}},
2462				{       25, {128,  128}},
2463				{       49, { 64,  128}},
2464				{       97, { 16,  128}},
2465				{ UINT_MAX, {  0,    0}},
2466			},
2467		},
2468	};
2469
2470	RADV_FROM_HANDLE(radv_render_pass, pass, pCreateInfo->renderPass);
2471	struct radv_subpass *subpass = pass->subpasses + pCreateInfo->subpass;
2472	VkExtent2D extent = {512, 512};
2473
2474	unsigned log_num_rb_per_se =
2475	    util_logbase2_ceil(pipeline->device->physical_device->rad_info.num_render_backends /
2476	                       pipeline->device->physical_device->rad_info.max_se);
2477	unsigned log_num_se = util_logbase2_ceil(pipeline->device->physical_device->rad_info.max_se);
2478
2479	unsigned total_samples = 1u << G_028BE0_MSAA_NUM_SAMPLES(pipeline->graphics.ms.pa_sc_aa_config);
2480	unsigned ps_iter_samples = 1u << G_028804_PS_ITER_SAMPLES(pipeline->graphics.ms.db_eqaa);
2481	unsigned effective_samples = total_samples;
2482	unsigned color_bytes_per_pixel = 0;
2483
2484	const VkPipelineColorBlendStateCreateInfo *vkblend = pCreateInfo->pColorBlendState;
2485	if (vkblend) {
2486		for (unsigned i = 0; i < subpass->color_count; i++) {
2487			if (!vkblend->pAttachments[i].colorWriteMask)
2488				continue;
2489
2490			if (subpass->color_attachments[i].attachment == VK_ATTACHMENT_UNUSED)
2491				continue;
2492
2493			VkFormat format = pass->attachments[subpass->color_attachments[i].attachment].format;
2494			color_bytes_per_pixel += vk_format_get_blocksize(format);
2495		}
2496
2497		/* MSAA images typically don't use all samples all the time. */
2498		if (effective_samples >= 2 && ps_iter_samples <= 1)
2499			effective_samples = 2;
2500		color_bytes_per_pixel *= effective_samples;
2501	}
2502
2503	const struct radv_bin_size_entry *color_entry = color_size_table[log_num_rb_per_se][log_num_se];
2504	while(color_entry[1].bpp <= color_bytes_per_pixel)
2505		++color_entry;
2506
2507	extent = color_entry->extent;
2508
2509	if (subpass->depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED) {
2510		struct radv_render_pass_attachment *attachment = pass->attachments + subpass->depth_stencil_attachment.attachment;
2511
2512		/* Coefficients taken from AMDVLK */
2513		unsigned depth_coeff = vk_format_is_depth(attachment->format) ? 5 : 0;
2514		unsigned stencil_coeff = vk_format_is_stencil(attachment->format) ? 1 : 0;
2515		unsigned ds_bytes_per_pixel = 4 * (depth_coeff + stencil_coeff) * total_samples;
2516
2517		const struct radv_bin_size_entry *ds_entry = ds_size_table[log_num_rb_per_se][log_num_se];
2518		while(ds_entry[1].bpp <= ds_bytes_per_pixel)
2519			++ds_entry;
2520
2521		extent.width = MIN2(extent.width, ds_entry->extent.width);
2522		extent.height = MIN2(extent.height, ds_entry->extent.height);
2523	}
2524
2525	return extent;
2526}
2527
2528static void
2529radv_pipeline_generate_binning_state(struct radeon_cmdbuf *cs,
2530				     struct radv_pipeline *pipeline,
2531				     const VkGraphicsPipelineCreateInfo *pCreateInfo)
2532{
2533	if (pipeline->device->physical_device->rad_info.chip_class < GFX9)
2534		return;
2535
2536	uint32_t pa_sc_binner_cntl_0 =
2537	                S_028C44_BINNING_MODE(V_028C44_DISABLE_BINNING_USE_LEGACY_SC) |
2538	                S_028C44_DISABLE_START_OF_PRIM(1);
2539	uint32_t db_dfsm_control = S_028060_PUNCHOUT_MODE(V_028060_FORCE_OFF);
2540
2541	VkExtent2D bin_size = radv_compute_bin_size(pipeline, pCreateInfo);
2542
2543	unsigned context_states_per_bin; /* allowed range: [1, 6] */
2544	unsigned persistent_states_per_bin; /* allowed range: [1, 32] */
2545	unsigned fpovs_per_batch; /* allowed range: [0, 255], 0 = unlimited */
2546
2547	switch (pipeline->device->physical_device->rad_info.family) {
2548	case CHIP_VEGA10:
2549	case CHIP_VEGA12:
2550	case CHIP_VEGA20:
2551		context_states_per_bin = 1;
2552		persistent_states_per_bin = 1;
2553		fpovs_per_batch = 63;
2554		break;
2555	case CHIP_RAVEN:
2556	case CHIP_RAVEN2:
2557		context_states_per_bin = 6;
2558		persistent_states_per_bin = 32;
2559		fpovs_per_batch = 63;
2560		break;
2561	default:
2562		unreachable("unhandled family while determining binning state.");
2563	}
2564
2565	if (pipeline->device->pbb_allowed && bin_size.width && bin_size.height) {
2566		pa_sc_binner_cntl_0 =
2567	                S_028C44_BINNING_MODE(V_028C44_BINNING_ALLOWED) |
2568	                S_028C44_BIN_SIZE_X(bin_size.width == 16) |
2569	                S_028C44_BIN_SIZE_Y(bin_size.height == 16) |
2570	                S_028C44_BIN_SIZE_X_EXTEND(util_logbase2(MAX2(bin_size.width, 32)) - 5) |
2571	                S_028C44_BIN_SIZE_Y_EXTEND(util_logbase2(MAX2(bin_size.height, 32)) - 5) |
2572	                S_028C44_CONTEXT_STATES_PER_BIN(context_states_per_bin - 1) |
2573	                S_028C44_PERSISTENT_STATES_PER_BIN(persistent_states_per_bin - 1) |
2574	                S_028C44_DISABLE_START_OF_PRIM(1) |
2575	                S_028C44_FPOVS_PER_BATCH(fpovs_per_batch) |
2576	                S_028C44_OPTIMAL_BIN_SELECTION(1);
2577	}
2578
2579	radeon_set_context_reg(cs, R_028C44_PA_SC_BINNER_CNTL_0,
2580			       pa_sc_binner_cntl_0);
2581	radeon_set_context_reg(cs, R_028060_DB_DFSM_CONTROL,
2582			       db_dfsm_control);
2583}
2584
2585
2586static void
2587radv_pipeline_generate_depth_stencil_state(struct radeon_cmdbuf *cs,
2588                                           struct radv_pipeline *pipeline,
2589                                           const VkGraphicsPipelineCreateInfo *pCreateInfo,
2590                                           const struct radv_graphics_pipeline_create_info *extra)
2591{
2592	const VkPipelineDepthStencilStateCreateInfo *vkds = pCreateInfo->pDepthStencilState;
2593	RADV_FROM_HANDLE(radv_render_pass, pass, pCreateInfo->renderPass);
2594	struct radv_subpass *subpass = pass->subpasses + pCreateInfo->subpass;
2595	struct radv_shader_variant *ps = pipeline->shaders[MESA_SHADER_FRAGMENT];
2596	struct radv_render_pass_attachment *attachment = NULL;
2597	uint32_t db_depth_control = 0, db_stencil_control = 0;
2598	uint32_t db_render_control = 0, db_render_override2 = 0;
2599	uint32_t db_render_override = 0;
2600
2601	if (subpass->depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED)
2602		attachment = pass->attachments + subpass->depth_stencil_attachment.attachment;
2603
2604	bool has_depth_attachment = attachment && vk_format_is_depth(attachment->format);
2605	bool has_stencil_attachment = attachment && vk_format_is_stencil(attachment->format);
2606
2607	if (vkds && has_depth_attachment) {
2608		db_depth_control = S_028800_Z_ENABLE(vkds->depthTestEnable ? 1 : 0) |
2609		                   S_028800_Z_WRITE_ENABLE(vkds->depthWriteEnable ? 1 : 0) |
2610		                   S_028800_ZFUNC(vkds->depthCompareOp) |
2611		                   S_028800_DEPTH_BOUNDS_ENABLE(vkds->depthBoundsTestEnable ? 1 : 0);
2612
2613		/* from amdvlk: For 4xAA and 8xAA need to decompress on flush for better performance */
2614		db_render_override2 |= S_028010_DECOMPRESS_Z_ON_FLUSH(attachment->samples > 2);
2615	}
2616
2617	if (has_stencil_attachment && vkds && vkds->stencilTestEnable) {
2618		db_depth_control |= S_028800_STENCIL_ENABLE(1) | S_028800_BACKFACE_ENABLE(1);
2619		db_depth_control |= S_028800_STENCILFUNC(vkds->front.compareOp);
2620		db_stencil_control |= S_02842C_STENCILFAIL(si_translate_stencil_op(vkds->front.failOp));
2621		db_stencil_control |= S_02842C_STENCILZPASS(si_translate_stencil_op(vkds->front.passOp));
2622		db_stencil_control |= S_02842C_STENCILZFAIL(si_translate_stencil_op(vkds->front.depthFailOp));
2623
2624		db_depth_control |= S_028800_STENCILFUNC_BF(vkds->back.compareOp);
2625		db_stencil_control |= S_02842C_STENCILFAIL_BF(si_translate_stencil_op(vkds->back.failOp));
2626		db_stencil_control |= S_02842C_STENCILZPASS_BF(si_translate_stencil_op(vkds->back.passOp));
2627		db_stencil_control |= S_02842C_STENCILZFAIL_BF(si_translate_stencil_op(vkds->back.depthFailOp));
2628	}
2629
2630	if (attachment && extra) {
2631		db_render_control |= S_028000_DEPTH_CLEAR_ENABLE(extra->db_depth_clear);
2632		db_render_control |= S_028000_STENCIL_CLEAR_ENABLE(extra->db_stencil_clear);
2633
2634		db_render_control |= S_028000_RESUMMARIZE_ENABLE(extra->db_resummarize);
2635		db_render_control |= S_028000_DEPTH_COMPRESS_DISABLE(extra->db_flush_depth_inplace);
2636		db_render_control |= S_028000_STENCIL_COMPRESS_DISABLE(extra->db_flush_stencil_inplace);
2637		db_render_override2 |= S_028010_DISABLE_ZMASK_EXPCLEAR_OPTIMIZATION(extra->db_depth_disable_expclear);
2638		db_render_override2 |= S_028010_DISABLE_SMEM_EXPCLEAR_OPTIMIZATION(extra->db_stencil_disable_expclear);
2639	}
2640
2641	db_render_override |= S_02800C_FORCE_HIS_ENABLE0(V_02800C_FORCE_DISABLE) |
2642			      S_02800C_FORCE_HIS_ENABLE1(V_02800C_FORCE_DISABLE);
2643
2644	if (pipeline->device->enabled_extensions.EXT_depth_range_unrestricted &&
2645	    !pCreateInfo->pRasterizationState->depthClampEnable &&
2646	    ps->info.info.ps.writes_z) {
2647		/* From VK_EXT_depth_range_unrestricted spec:
2648		 *
2649		 * "The behavior described in Primitive Clipping still applies.
2650		 *  If depth clamping is disabled the depth values are still
2651		 *  clipped to 0 ≤ zc ≤ wc before the viewport transform. If
2652		 *  depth clamping is enabled the above equation is ignored and
2653		 *  the depth values are instead clamped to the VkViewport
2654		 *  minDepth and maxDepth values, which in the case of this
2655		 *  extension can be outside of the 0.0 to 1.0 range."
2656		 */
2657		db_render_override |= S_02800C_DISABLE_VIEWPORT_CLAMP(1);
2658	}
2659
2660	radeon_set_context_reg(cs, R_028800_DB_DEPTH_CONTROL, db_depth_control);
2661	radeon_set_context_reg(cs, R_02842C_DB_STENCIL_CONTROL, db_stencil_control);
2662
2663	radeon_set_context_reg(cs, R_028000_DB_RENDER_CONTROL, db_render_control);
2664	radeon_set_context_reg(cs, R_02800C_DB_RENDER_OVERRIDE, db_render_override);
2665	radeon_set_context_reg(cs, R_028010_DB_RENDER_OVERRIDE2, db_render_override2);
2666}
2667
2668static void
2669radv_pipeline_generate_blend_state(struct radeon_cmdbuf *cs,
2670                                   struct radv_pipeline *pipeline,
2671                                   const struct radv_blend_state *blend)
2672{
2673	radeon_set_context_reg_seq(cs, R_028780_CB_BLEND0_CONTROL, 8);
2674	radeon_emit_array(cs, blend->cb_blend_control,
2675			  8);
2676	radeon_set_context_reg(cs, R_028808_CB_COLOR_CONTROL, blend->cb_color_control);
2677	radeon_set_context_reg(cs, R_028B70_DB_ALPHA_TO_MASK, blend->db_alpha_to_mask);
2678
2679	if (pipeline->device->physical_device->has_rbplus) {
2680
2681		radeon_set_context_reg_seq(cs, R_028760_SX_MRT0_BLEND_OPT, 8);
2682		radeon_emit_array(cs, blend->sx_mrt_blend_opt, 8);
2683	}
2684
2685	radeon_set_context_reg(cs, R_028714_SPI_SHADER_COL_FORMAT, blend->spi_shader_col_format);
2686
2687	radeon_set_context_reg(cs, R_028238_CB_TARGET_MASK, blend->cb_target_mask);
2688	radeon_set_context_reg(cs, R_02823C_CB_SHADER_MASK, blend->cb_shader_mask);
2689
2690	pipeline->graphics.col_format = blend->spi_shader_col_format;
2691	pipeline->graphics.cb_target_mask = blend->cb_target_mask;
2692}
2693
2694static const VkConservativeRasterizationModeEXT
2695radv_get_conservative_raster_mode(const VkPipelineRasterizationStateCreateInfo *pCreateInfo)
2696{
2697	const VkPipelineRasterizationConservativeStateCreateInfoEXT *conservative_raster =
2698		vk_find_struct_const(pCreateInfo->pNext, PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT);
2699
2700	if (!conservative_raster)
2701		return VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT;
2702	return conservative_raster->conservativeRasterizationMode;
2703}
2704
2705static void
2706radv_pipeline_generate_raster_state(struct radeon_cmdbuf *cs,
2707				    struct radv_pipeline *pipeline,
2708                                    const VkGraphicsPipelineCreateInfo *pCreateInfo)
2709{
2710	const VkPipelineRasterizationStateCreateInfo *vkraster = pCreateInfo->pRasterizationState;
2711	const VkConservativeRasterizationModeEXT mode =
2712		radv_get_conservative_raster_mode(vkraster);
2713	uint32_t pa_sc_conservative_rast = 0;
2714
2715	radeon_set_context_reg(cs, R_028810_PA_CL_CLIP_CNTL,
2716	                       S_028810_DX_CLIP_SPACE_DEF(1) | // vulkan uses DX conventions.
2717	                       S_028810_ZCLIP_NEAR_DISABLE(vkraster->depthClampEnable ? 1 : 0) |
2718	                       S_028810_ZCLIP_FAR_DISABLE(vkraster->depthClampEnable ? 1 : 0) |
2719	                       S_028810_DX_RASTERIZATION_KILL(vkraster->rasterizerDiscardEnable ? 1 : 0) |
2720	                       S_028810_DX_LINEAR_ATTR_CLIP_ENA(1));
2721
2722	radeon_set_context_reg(cs, R_0286D4_SPI_INTERP_CONTROL_0,
2723	                       S_0286D4_FLAT_SHADE_ENA(1) |
2724	                       S_0286D4_PNT_SPRITE_ENA(1) |
2725	                       S_0286D4_PNT_SPRITE_OVRD_X(V_0286D4_SPI_PNT_SPRITE_SEL_S) |
2726	                       S_0286D4_PNT_SPRITE_OVRD_Y(V_0286D4_SPI_PNT_SPRITE_SEL_T) |
2727	                       S_0286D4_PNT_SPRITE_OVRD_Z(V_0286D4_SPI_PNT_SPRITE_SEL_0) |
2728	                       S_0286D4_PNT_SPRITE_OVRD_W(V_0286D4_SPI_PNT_SPRITE_SEL_1) |
2729	                       S_0286D4_PNT_SPRITE_TOP_1(0)); /* vulkan is top to bottom - 1.0 at bottom */
2730
2731	radeon_set_context_reg(cs, R_028BE4_PA_SU_VTX_CNTL,
2732	                       S_028BE4_PIX_CENTER(1) | // TODO verify
2733	                       S_028BE4_ROUND_MODE(V_028BE4_X_ROUND_TO_EVEN) |
2734	                       S_028BE4_QUANT_MODE(V_028BE4_X_16_8_FIXED_POINT_1_256TH));
2735
2736	radeon_set_context_reg(cs, R_028814_PA_SU_SC_MODE_CNTL,
2737	                       S_028814_FACE(vkraster->frontFace) |
2738	                       S_028814_CULL_FRONT(!!(vkraster->cullMode & VK_CULL_MODE_FRONT_BIT)) |
2739	                       S_028814_CULL_BACK(!!(vkraster->cullMode & VK_CULL_MODE_BACK_BIT)) |
2740	                       S_028814_POLY_MODE(vkraster->polygonMode != VK_POLYGON_MODE_FILL) |
2741	                       S_028814_POLYMODE_FRONT_PTYPE(si_translate_fill(vkraster->polygonMode)) |
2742	                       S_028814_POLYMODE_BACK_PTYPE(si_translate_fill(vkraster->polygonMode)) |
2743	                       S_028814_POLY_OFFSET_FRONT_ENABLE(vkraster->depthBiasEnable ? 1 : 0) |
2744	                       S_028814_POLY_OFFSET_BACK_ENABLE(vkraster->depthBiasEnable ? 1 : 0) |
2745	                       S_028814_POLY_OFFSET_PARA_ENABLE(vkraster->depthBiasEnable ? 1 : 0));
2746
2747	/* Conservative rasterization. */
2748	if (mode != VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT) {
2749		struct radv_multisample_state *ms = &pipeline->graphics.ms;
2750
2751		ms->pa_sc_aa_config |= S_028BE0_AA_MASK_CENTROID_DTMN(1);
2752		ms->db_eqaa |= S_028804_ENABLE_POSTZ_OVERRASTERIZATION(1) |
2753			       S_028804_OVERRASTERIZATION_AMOUNT(4);
2754
2755		pa_sc_conservative_rast = S_028C4C_PREZ_AA_MASK_ENABLE(1) |
2756					  S_028C4C_POSTZ_AA_MASK_ENABLE(1) |
2757					  S_028C4C_CENTROID_SAMPLE_OVERRIDE(1);
2758
2759		if (mode == VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT) {
2760			pa_sc_conservative_rast |=
2761				S_028C4C_OVER_RAST_ENABLE(1) |
2762				S_028C4C_OVER_RAST_SAMPLE_SELECT(0) |
2763				S_028C4C_UNDER_RAST_ENABLE(0) |
2764				S_028C4C_UNDER_RAST_SAMPLE_SELECT(1) |
2765				S_028C4C_PBB_UNCERTAINTY_REGION_ENABLE(1);
2766		} else {
2767			assert(mode == VK_CONSERVATIVE_RASTERIZATION_MODE_UNDERESTIMATE_EXT);
2768			pa_sc_conservative_rast |=
2769				S_028C4C_OVER_RAST_ENABLE(0) |
2770				S_028C4C_OVER_RAST_SAMPLE_SELECT(1) |
2771				S_028C4C_UNDER_RAST_ENABLE(1) |
2772				S_028C4C_UNDER_RAST_SAMPLE_SELECT(0) |
2773				S_028C4C_PBB_UNCERTAINTY_REGION_ENABLE(0);
2774		}
2775	}
2776
2777	radeon_set_context_reg(cs, R_028C4C_PA_SC_CONSERVATIVE_RASTERIZATION_CNTL,
2778				   pa_sc_conservative_rast);
2779}
2780
2781
2782static void
2783radv_pipeline_generate_multisample_state(struct radeon_cmdbuf *cs,
2784                                         struct radv_pipeline *pipeline)
2785{
2786	struct radv_multisample_state *ms = &pipeline->graphics.ms;
2787
2788	radeon_set_context_reg_seq(cs, R_028C38_PA_SC_AA_MASK_X0Y0_X1Y0, 2);
2789	radeon_emit(cs, ms->pa_sc_aa_mask[0]);
2790	radeon_emit(cs, ms->pa_sc_aa_mask[1]);
2791
2792	radeon_set_context_reg(cs, R_028804_DB_EQAA, ms->db_eqaa);
2793	radeon_set_context_reg(cs, R_028A4C_PA_SC_MODE_CNTL_1, ms->pa_sc_mode_cntl_1);
2794
2795	/* The exclusion bits can be set to improve rasterization efficiency
2796	 * if no sample lies on the pixel boundary (-8 sample offset). It's
2797	 * currently always TRUE because the driver doesn't support 16 samples.
2798	 */
2799	bool exclusion = pipeline->device->physical_device->rad_info.chip_class >= CIK;
2800	radeon_set_context_reg(cs, R_02882C_PA_SU_PRIM_FILTER_CNTL,
2801			       S_02882C_XMAX_RIGHT_EXCLUSION(exclusion) |
2802			       S_02882C_YMAX_BOTTOM_EXCLUSION(exclusion));
2803}
2804
2805static void
2806radv_pipeline_generate_vgt_gs_mode(struct radeon_cmdbuf *cs,
2807                                   const struct radv_pipeline *pipeline)
2808{
2809	const struct radv_vs_output_info *outinfo = get_vs_output_info(pipeline);
2810
2811	uint32_t vgt_primitiveid_en = false;
2812	uint32_t vgt_gs_mode = 0;
2813
2814	if (radv_pipeline_has_gs(pipeline)) {
2815		const struct radv_shader_variant *gs =
2816			pipeline->shaders[MESA_SHADER_GEOMETRY];
2817
2818		vgt_gs_mode = ac_vgt_gs_mode(gs->info.gs.vertices_out,
2819		                             pipeline->device->physical_device->rad_info.chip_class);
2820	} else if (outinfo->export_prim_id) {
2821		vgt_gs_mode = S_028A40_MODE(V_028A40_GS_SCENARIO_A);
2822		vgt_primitiveid_en = true;
2823	}
2824
2825	radeon_set_context_reg(cs, R_028A84_VGT_PRIMITIVEID_EN, vgt_primitiveid_en);
2826	radeon_set_context_reg(cs, R_028A40_VGT_GS_MODE, vgt_gs_mode);
2827}
2828
2829static void
2830radv_pipeline_generate_hw_vs(struct radeon_cmdbuf *cs,
2831			     struct radv_pipeline *pipeline,
2832			     struct radv_shader_variant *shader)
2833{
2834	uint64_t va = radv_buffer_get_va(shader->bo) + shader->bo_offset;
2835
2836	radeon_set_sh_reg_seq(cs, R_00B120_SPI_SHADER_PGM_LO_VS, 4);
2837	radeon_emit(cs, va >> 8);
2838	radeon_emit(cs, S_00B124_MEM_BASE(va >> 40));
2839	radeon_emit(cs, shader->rsrc1);
2840	radeon_emit(cs, shader->rsrc2);
2841
2842	const struct radv_vs_output_info *outinfo = get_vs_output_info(pipeline);
2843	unsigned clip_dist_mask, cull_dist_mask, total_mask;
2844	clip_dist_mask = outinfo->clip_dist_mask;
2845	cull_dist_mask = outinfo->cull_dist_mask;
2846	total_mask = clip_dist_mask | cull_dist_mask;
2847	bool misc_vec_ena = outinfo->writes_pointsize ||
2848		outinfo->writes_layer ||
2849		outinfo->writes_viewport_index;
2850
2851	radeon_set_context_reg(cs, R_0286C4_SPI_VS_OUT_CONFIG,
2852	                       S_0286C4_VS_EXPORT_COUNT(MAX2(1, outinfo->param_exports) - 1));
2853
2854	radeon_set_context_reg(cs, R_02870C_SPI_SHADER_POS_FORMAT,
2855	                       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
2856	                       S_02870C_POS1_EXPORT_FORMAT(outinfo->pos_exports > 1 ?
2857	                                                   V_02870C_SPI_SHADER_4COMP :
2858	                                                   V_02870C_SPI_SHADER_NONE) |
2859	                       S_02870C_POS2_EXPORT_FORMAT(outinfo->pos_exports > 2 ?
2860	                                                   V_02870C_SPI_SHADER_4COMP :
2861	                                                   V_02870C_SPI_SHADER_NONE) |
2862	                       S_02870C_POS3_EXPORT_FORMAT(outinfo->pos_exports > 3 ?
2863	                                                   V_02870C_SPI_SHADER_4COMP :
2864	                                                   V_02870C_SPI_SHADER_NONE));
2865
2866	radeon_set_context_reg(cs, R_028818_PA_CL_VTE_CNTL,
2867			       S_028818_VTX_W0_FMT(1) |
2868			       S_028818_VPORT_X_SCALE_ENA(1) | S_028818_VPORT_X_OFFSET_ENA(1) |
2869			       S_028818_VPORT_Y_SCALE_ENA(1) | S_028818_VPORT_Y_OFFSET_ENA(1) |
2870			       S_028818_VPORT_Z_SCALE_ENA(1) | S_028818_VPORT_Z_OFFSET_ENA(1));
2871
2872	radeon_set_context_reg(cs, R_02881C_PA_CL_VS_OUT_CNTL,
2873	                       S_02881C_USE_VTX_POINT_SIZE(outinfo->writes_pointsize) |
2874	                       S_02881C_USE_VTX_RENDER_TARGET_INDX(outinfo->writes_layer) |
2875	                       S_02881C_USE_VTX_VIEWPORT_INDX(outinfo->writes_viewport_index) |
2876	                       S_02881C_VS_OUT_MISC_VEC_ENA(misc_vec_ena) |
2877	                       S_02881C_VS_OUT_MISC_SIDE_BUS_ENA(misc_vec_ena) |
2878	                       S_02881C_VS_OUT_CCDIST0_VEC_ENA((total_mask & 0x0f) != 0) |
2879	                       S_02881C_VS_OUT_CCDIST1_VEC_ENA((total_mask & 0xf0) != 0) |
2880	                       cull_dist_mask << 8 |
2881	                       clip_dist_mask);
2882
2883	if (pipeline->device->physical_device->rad_info.chip_class <= VI)
2884		radeon_set_context_reg(cs, R_028AB4_VGT_REUSE_OFF,
2885		                       outinfo->writes_viewport_index);
2886}
2887
2888static void
2889radv_pipeline_generate_hw_es(struct radeon_cmdbuf *cs,
2890			     struct radv_pipeline *pipeline,
2891			     struct radv_shader_variant *shader)
2892{
2893	uint64_t va = radv_buffer_get_va(shader->bo) + shader->bo_offset;
2894
2895	radeon_set_sh_reg_seq(cs, R_00B320_SPI_SHADER_PGM_LO_ES, 4);
2896	radeon_emit(cs, va >> 8);
2897	radeon_emit(cs, S_00B324_MEM_BASE(va >> 40));
2898	radeon_emit(cs, shader->rsrc1);
2899	radeon_emit(cs, shader->rsrc2);
2900}
2901
2902static void
2903radv_pipeline_generate_hw_ls(struct radeon_cmdbuf *cs,
2904			     struct radv_pipeline *pipeline,
2905			     struct radv_shader_variant *shader,
2906			     const struct radv_tessellation_state *tess)
2907{
2908	uint64_t va = radv_buffer_get_va(shader->bo) + shader->bo_offset;
2909	uint32_t rsrc2 = shader->rsrc2;
2910
2911	radeon_set_sh_reg_seq(cs, R_00B520_SPI_SHADER_PGM_LO_LS, 2);
2912	radeon_emit(cs, va >> 8);
2913	radeon_emit(cs, S_00B524_MEM_BASE(va >> 40));
2914
2915	rsrc2 |= S_00B52C_LDS_SIZE(tess->lds_size);
2916	if (pipeline->device->physical_device->rad_info.chip_class == CIK &&
2917	    pipeline->device->physical_device->rad_info.family != CHIP_HAWAII)
2918		radeon_set_sh_reg(cs, R_00B52C_SPI_SHADER_PGM_RSRC2_LS, rsrc2);
2919
2920	radeon_set_sh_reg_seq(cs, R_00B528_SPI_SHADER_PGM_RSRC1_LS, 2);
2921	radeon_emit(cs, shader->rsrc1);
2922	radeon_emit(cs, rsrc2);
2923}
2924
2925static void
2926radv_pipeline_generate_hw_hs(struct radeon_cmdbuf *cs,
2927			     struct radv_pipeline *pipeline,
2928			     struct radv_shader_variant *shader,
2929			     const struct radv_tessellation_state *tess)
2930{
2931	uint64_t va = radv_buffer_get_va(shader->bo) + shader->bo_offset;
2932
2933	if (pipeline->device->physical_device->rad_info.chip_class >= GFX9) {
2934		radeon_set_sh_reg_seq(cs, R_00B410_SPI_SHADER_PGM_LO_LS, 2);
2935		radeon_emit(cs, va >> 8);
2936		radeon_emit(cs, S_00B414_MEM_BASE(va >> 40));
2937
2938		radeon_set_sh_reg_seq(cs, R_00B428_SPI_SHADER_PGM_RSRC1_HS, 2);
2939		radeon_emit(cs, shader->rsrc1);
2940		radeon_emit(cs, shader->rsrc2 |
2941		                S_00B42C_LDS_SIZE(tess->lds_size));
2942	} else {
2943		radeon_set_sh_reg_seq(cs, R_00B420_SPI_SHADER_PGM_LO_HS, 4);
2944		radeon_emit(cs, va >> 8);
2945		radeon_emit(cs, S_00B424_MEM_BASE(va >> 40));
2946		radeon_emit(cs, shader->rsrc1);
2947		radeon_emit(cs, shader->rsrc2);
2948	}
2949}
2950
2951static void
2952radv_pipeline_generate_vertex_shader(struct radeon_cmdbuf *cs,
2953				     struct radv_pipeline *pipeline,
2954				     const struct radv_tessellation_state *tess)
2955{
2956	struct radv_shader_variant *vs;
2957
2958	/* Skip shaders merged into HS/GS */
2959	vs = pipeline->shaders[MESA_SHADER_VERTEX];
2960	if (!vs)
2961		return;
2962
2963	if (vs->info.vs.as_ls)
2964		radv_pipeline_generate_hw_ls(cs, pipeline, vs, tess);
2965	else if (vs->info.vs.as_es)
2966		radv_pipeline_generate_hw_es(cs, pipeline, vs);
2967	else
2968		radv_pipeline_generate_hw_vs(cs, pipeline, vs);
2969}
2970
2971static void
2972radv_pipeline_generate_tess_shaders(struct radeon_cmdbuf *cs,
2973				    struct radv_pipeline *pipeline,
2974				    const struct radv_tessellation_state *tess)
2975{
2976	if (!radv_pipeline_has_tess(pipeline))
2977		return;
2978
2979	struct radv_shader_variant *tes, *tcs;
2980
2981	tcs = pipeline->shaders[MESA_SHADER_TESS_CTRL];
2982	tes = pipeline->shaders[MESA_SHADER_TESS_EVAL];
2983
2984	if (tes) {
2985		if (tes->info.tes.as_es)
2986			radv_pipeline_generate_hw_es(cs, pipeline, tes);
2987		else
2988			radv_pipeline_generate_hw_vs(cs, pipeline, tes);
2989	}
2990
2991	radv_pipeline_generate_hw_hs(cs, pipeline, tcs, tess);
2992
2993	radeon_set_context_reg(cs, R_028B6C_VGT_TF_PARAM,
2994			       tess->tf_param);
2995
2996	if (pipeline->device->physical_device->rad_info.chip_class >= CIK)
2997		radeon_set_context_reg_idx(cs, R_028B58_VGT_LS_HS_CONFIG, 2,
2998					   tess->ls_hs_config);
2999	else
3000		radeon_set_context_reg(cs, R_028B58_VGT_LS_HS_CONFIG,
3001				       tess->ls_hs_config);
3002}
3003
3004static void
3005radv_pipeline_generate_geometry_shader(struct radeon_cmdbuf *cs,
3006				       struct radv_pipeline *pipeline,
3007				       const struct radv_gs_state *gs_state)
3008{
3009	struct radv_shader_variant *gs;
3010	unsigned gs_max_out_vertices;
3011	uint8_t *num_components;
3012	uint8_t max_stream;
3013	unsigned offset;
3014	uint64_t va;
3015
3016	gs = pipeline->shaders[MESA_SHADER_GEOMETRY];
3017	if (!gs)
3018		return;
3019
3020	gs_max_out_vertices = gs->info.gs.vertices_out;
3021	max_stream = gs->info.info.gs.max_stream;
3022	num_components = gs->info.info.gs.num_stream_output_components;
3023
3024	offset = num_components[0] * gs_max_out_vertices;
3025
3026	radeon_set_context_reg_seq(cs, R_028A60_VGT_GSVS_RING_OFFSET_1, 3);
3027	radeon_emit(cs, offset);
3028	if (max_stream >= 1)
3029		offset += num_components[1] * gs_max_out_vertices;
3030	radeon_emit(cs, offset);
3031	if (max_stream >= 2)
3032		offset += num_components[2] * gs_max_out_vertices;
3033	radeon_emit(cs, offset);
3034	if (max_stream >= 3)
3035		offset += num_components[3] * gs_max_out_vertices;
3036	radeon_set_context_reg(cs, R_028AB0_VGT_GSVS_RING_ITEMSIZE, offset);
3037
3038	radeon_set_context_reg(cs, R_028B38_VGT_GS_MAX_VERT_OUT, gs->info.gs.vertices_out);
3039
3040	radeon_set_context_reg_seq(cs, R_028B5C_VGT_GS_VERT_ITEMSIZE, 4);
3041	radeon_emit(cs, num_components[0]);
3042	radeon_emit(cs, (max_stream >= 1) ? num_components[1] : 0);
3043	radeon_emit(cs, (max_stream >= 2) ? num_components[2] : 0);
3044	radeon_emit(cs, (max_stream >= 3) ? num_components[3] : 0);
3045
3046	uint32_t gs_num_invocations = gs->info.gs.invocations;
3047	radeon_set_context_reg(cs, R_028B90_VGT_GS_INSTANCE_CNT,
3048			       S_028B90_CNT(MIN2(gs_num_invocations, 127)) |
3049			       S_028B90_ENABLE(gs_num_invocations > 0));
3050
3051	radeon_set_context_reg(cs, R_028AAC_VGT_ESGS_RING_ITEMSIZE,
3052			       gs_state->vgt_esgs_ring_itemsize);
3053
3054	va = radv_buffer_get_va(gs->bo) + gs->bo_offset;
3055
3056	if (pipeline->device->physical_device->rad_info.chip_class >= GFX9) {
3057		radeon_set_sh_reg_seq(cs, R_00B210_SPI_SHADER_PGM_LO_ES, 2);
3058		radeon_emit(cs, va >> 8);
3059		radeon_emit(cs, S_00B214_MEM_BASE(va >> 40));
3060
3061		radeon_set_sh_reg_seq(cs, R_00B228_SPI_SHADER_PGM_RSRC1_GS, 2);
3062		radeon_emit(cs, gs->rsrc1);
3063		radeon_emit(cs, gs->rsrc2 | S_00B22C_LDS_SIZE(gs_state->lds_size));
3064
3065		radeon_set_context_reg(cs, R_028A44_VGT_GS_ONCHIP_CNTL, gs_state->vgt_gs_onchip_cntl);
3066		radeon_set_context_reg(cs, R_028A94_VGT_GS_MAX_PRIMS_PER_SUBGROUP, gs_state->vgt_gs_max_prims_per_subgroup);
3067	} else {
3068		radeon_set_sh_reg_seq(cs, R_00B220_SPI_SHADER_PGM_LO_GS, 4);
3069		radeon_emit(cs, va >> 8);
3070		radeon_emit(cs, S_00B224_MEM_BASE(va >> 40));
3071		radeon_emit(cs, gs->rsrc1);
3072		radeon_emit(cs, gs->rsrc2);
3073	}
3074
3075	radv_pipeline_generate_hw_vs(cs, pipeline, pipeline->gs_copy_shader);
3076}
3077
3078static uint32_t offset_to_ps_input(uint32_t offset, bool flat_shade, bool float16)
3079{
3080	uint32_t ps_input_cntl;
3081	if (offset <= AC_EXP_PARAM_OFFSET_31) {
3082		ps_input_cntl = S_028644_OFFSET(offset);
3083		if (flat_shade)
3084			ps_input_cntl |= S_028644_FLAT_SHADE(1);
3085		if (float16) {
3086			ps_input_cntl |= S_028644_FP16_INTERP_MODE(1) |
3087			                 S_028644_ATTR0_VALID(1);
3088		}
3089	} else {
3090		/* The input is a DEFAULT_VAL constant. */
3091		assert(offset >= AC_EXP_PARAM_DEFAULT_VAL_0000 &&
3092		       offset <= AC_EXP_PARAM_DEFAULT_VAL_1111);
3093		offset -= AC_EXP_PARAM_DEFAULT_VAL_0000;
3094		ps_input_cntl = S_028644_OFFSET(0x20) |
3095			S_028644_DEFAULT_VAL(offset);
3096	}
3097	return ps_input_cntl;
3098}
3099
3100static void
3101radv_pipeline_generate_ps_inputs(struct radeon_cmdbuf *cs,
3102                                 struct radv_pipeline *pipeline)
3103{
3104	struct radv_shader_variant *ps = pipeline->shaders[MESA_SHADER_FRAGMENT];
3105	const struct radv_vs_output_info *outinfo = get_vs_output_info(pipeline);
3106	uint32_t ps_input_cntl[32];
3107
3108	unsigned ps_offset = 0;
3109
3110	if (ps->info.info.ps.prim_id_input) {
3111		unsigned vs_offset = outinfo->vs_output_param_offset[VARYING_SLOT_PRIMITIVE_ID];
3112		if (vs_offset != AC_EXP_PARAM_UNDEFINED) {
3113			ps_input_cntl[ps_offset] = offset_to_ps_input(vs_offset, true, false);
3114			++ps_offset;
3115		}
3116	}
3117
3118	if (ps->info.info.ps.layer_input ||
3119	    ps->info.info.ps.uses_input_attachments ||
3120	    ps->info.info.needs_multiview_view_index) {
3121		unsigned vs_offset = outinfo->vs_output_param_offset[VARYING_SLOT_LAYER];
3122		if (vs_offset != AC_EXP_PARAM_UNDEFINED)
3123			ps_input_cntl[ps_offset] = offset_to_ps_input(vs_offset, true, false);
3124		else
3125			ps_input_cntl[ps_offset] = offset_to_ps_input(AC_EXP_PARAM_DEFAULT_VAL_0000, true, false);
3126		++ps_offset;
3127	}
3128
3129	if (ps->info.info.ps.has_pcoord) {
3130		unsigned val;
3131		val = S_028644_PT_SPRITE_TEX(1) | S_028644_OFFSET(0x20);
3132		ps_input_cntl[ps_offset] = val;
3133		ps_offset++;
3134	}
3135
3136	if (ps->info.info.ps.num_input_clips_culls) {
3137		unsigned vs_offset;
3138
3139		vs_offset = outinfo->vs_output_param_offset[VARYING_SLOT_CLIP_DIST0];
3140		if (vs_offset != AC_EXP_PARAM_UNDEFINED) {
3141			ps_input_cntl[ps_offset] = offset_to_ps_input(vs_offset, false, false);
3142			++ps_offset;
3143		}
3144
3145		vs_offset = outinfo->vs_output_param_offset[VARYING_SLOT_CLIP_DIST1];
3146		if (vs_offset != AC_EXP_PARAM_UNDEFINED &&
3147		    ps->info.info.ps.num_input_clips_culls > 4) {
3148			ps_input_cntl[ps_offset] = offset_to_ps_input(vs_offset, false, false);
3149			++ps_offset;
3150		}
3151	}
3152
3153	for (unsigned i = 0; i < 32 && (1u << i) <= ps->info.fs.input_mask; ++i) {
3154		unsigned vs_offset;
3155		bool flat_shade;
3156		bool float16;
3157		if (!(ps->info.fs.input_mask & (1u << i)))
3158			continue;
3159
3160		vs_offset = outinfo->vs_output_param_offset[VARYING_SLOT_VAR0 + i];
3161		if (vs_offset == AC_EXP_PARAM_UNDEFINED) {
3162			ps_input_cntl[ps_offset] = S_028644_OFFSET(0x20);
3163			++ps_offset;
3164			continue;
3165		}
3166
3167		flat_shade = !!(ps->info.fs.flat_shaded_mask & (1u << ps_offset));
3168		float16 = !!(ps->info.fs.float16_shaded_mask & (1u << ps_offset));
3169
3170		ps_input_cntl[ps_offset] = offset_to_ps_input(vs_offset, flat_shade, float16);
3171		++ps_offset;
3172	}
3173
3174	if (ps_offset) {
3175		radeon_set_context_reg_seq(cs, R_028644_SPI_PS_INPUT_CNTL_0, ps_offset);
3176		for (unsigned i = 0; i < ps_offset; i++) {
3177			radeon_emit(cs, ps_input_cntl[i]);
3178		}
3179	}
3180}
3181
3182static uint32_t
3183radv_compute_db_shader_control(const struct radv_device *device,
3184			       const struct radv_pipeline *pipeline,
3185                               const struct radv_shader_variant *ps)
3186{
3187	const struct radv_multisample_state *ms = &pipeline->graphics.ms;
3188	unsigned z_order;
3189	if (ps->info.fs.early_fragment_test || !ps->info.info.ps.writes_memory)
3190		z_order = V_02880C_EARLY_Z_THEN_LATE_Z;
3191	else
3192		z_order = V_02880C_LATE_Z;
3193
3194	bool disable_rbplus = device->physical_device->has_rbplus &&
3195	                      !device->physical_device->rbplus_allowed;
3196
3197	/* It shouldn't be needed to export gl_SampleMask when MSAA is disabled
3198	 * but this appears to break Project Cars (DXVK). See
3199	 * https://bugs.freedesktop.org/show_bug.cgi?id=109401
3200	 */
3201	bool mask_export_enable = ps->info.info.ps.writes_sample_mask;
3202
3203	return  S_02880C_Z_EXPORT_ENABLE(ps->info.info.ps.writes_z) |
3204		S_02880C_STENCIL_TEST_VAL_EXPORT_ENABLE(ps->info.info.ps.writes_stencil) |
3205		S_02880C_KILL_ENABLE(!!ps->info.fs.can_discard) |
3206		S_02880C_MASK_EXPORT_ENABLE(mask_export_enable) |
3207		S_02880C_Z_ORDER(z_order) |
3208		S_02880C_DEPTH_BEFORE_SHADER(ps->info.fs.early_fragment_test) |
3209		S_02880C_EXEC_ON_HIER_FAIL(ps->info.info.ps.writes_memory) |
3210		S_02880C_EXEC_ON_NOOP(ps->info.info.ps.writes_memory) |
3211		S_02880C_DUAL_QUAD_DISABLE(disable_rbplus);
3212}
3213
3214static void
3215radv_pipeline_generate_fragment_shader(struct radeon_cmdbuf *cs,
3216				       struct radv_pipeline *pipeline)
3217{
3218	struct radv_shader_variant *ps;
3219	uint64_t va;
3220	assert (pipeline->shaders[MESA_SHADER_FRAGMENT]);
3221
3222	ps = pipeline->shaders[MESA_SHADER_FRAGMENT];
3223	va = radv_buffer_get_va(ps->bo) + ps->bo_offset;
3224
3225	radeon_set_sh_reg_seq(cs, R_00B020_SPI_SHADER_PGM_LO_PS, 4);
3226	radeon_emit(cs, va >> 8);
3227	radeon_emit(cs, S_00B024_MEM_BASE(va >> 40));
3228	radeon_emit(cs, ps->rsrc1);
3229	radeon_emit(cs, ps->rsrc2);
3230
3231	radeon_set_context_reg(cs, R_02880C_DB_SHADER_CONTROL,
3232	                       radv_compute_db_shader_control(pipeline->device,
3233							      pipeline, ps));
3234
3235	radeon_set_context_reg(cs, R_0286CC_SPI_PS_INPUT_ENA,
3236			       ps->config.spi_ps_input_ena);
3237
3238	radeon_set_context_reg(cs, R_0286D0_SPI_PS_INPUT_ADDR,
3239			       ps->config.spi_ps_input_addr);
3240
3241	radeon_set_context_reg(cs, R_0286D8_SPI_PS_IN_CONTROL,
3242			       S_0286D8_NUM_INTERP(ps->info.fs.num_interp));
3243
3244	radeon_set_context_reg(cs, R_0286E0_SPI_BARYC_CNTL, pipeline->graphics.spi_baryc_cntl);
3245
3246	radeon_set_context_reg(cs, R_028710_SPI_SHADER_Z_FORMAT,
3247	                       ac_get_spi_shader_z_format(ps->info.info.ps.writes_z,
3248	                                                  ps->info.info.ps.writes_stencil,
3249	                                                  ps->info.info.ps.writes_sample_mask));
3250
3251	if (pipeline->device->dfsm_allowed) {
3252		/* optimise this? */
3253		radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3254		radeon_emit(cs, EVENT_TYPE(V_028A90_FLUSH_DFSM) | EVENT_INDEX(0));
3255	}
3256}
3257
3258static void
3259radv_pipeline_generate_vgt_vertex_reuse(struct radeon_cmdbuf *cs,
3260					struct radv_pipeline *pipeline)
3261{
3262	if (pipeline->device->physical_device->rad_info.family < CHIP_POLARIS10)
3263		return;
3264
3265	unsigned vtx_reuse_depth = 30;
3266	if (radv_pipeline_has_tess(pipeline) &&
3267	    radv_get_shader(pipeline, MESA_SHADER_TESS_EVAL)->info.tes.spacing == TESS_SPACING_FRACTIONAL_ODD) {
3268		vtx_reuse_depth = 14;
3269	}
3270	radeon_set_context_reg(cs, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL,
3271	                       S_028C58_VTX_REUSE_DEPTH(vtx_reuse_depth));
3272}
3273
3274static uint32_t
3275radv_compute_vgt_shader_stages_en(const struct radv_pipeline *pipeline)
3276{
3277	uint32_t stages = 0;
3278	if (radv_pipeline_has_tess(pipeline)) {
3279		stages |= S_028B54_LS_EN(V_028B54_LS_STAGE_ON) |
3280			S_028B54_HS_EN(1) | S_028B54_DYNAMIC_HS(1);
3281
3282		if (radv_pipeline_has_gs(pipeline))
3283			stages |=  S_028B54_ES_EN(V_028B54_ES_STAGE_DS) |
3284				S_028B54_GS_EN(1) |
3285				S_028B54_VS_EN(V_028B54_VS_STAGE_COPY_SHADER);
3286		else
3287			stages |= S_028B54_VS_EN(V_028B54_VS_STAGE_DS);
3288
3289	} else if (radv_pipeline_has_gs(pipeline))
3290		stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_REAL) |
3291			S_028B54_GS_EN(1) |
3292			S_028B54_VS_EN(V_028B54_VS_STAGE_COPY_SHADER);
3293
3294	if (pipeline->device->physical_device->rad_info.chip_class >= GFX9)
3295		stages |= S_028B54_MAX_PRIMGRP_IN_WAVE(2);
3296
3297	return stages;
3298}
3299
3300static uint32_t
3301radv_compute_cliprect_rule(const VkGraphicsPipelineCreateInfo *pCreateInfo)
3302{
3303	const  VkPipelineDiscardRectangleStateCreateInfoEXT *discard_rectangle_info =
3304			vk_find_struct_const(pCreateInfo->pNext, PIPELINE_DISCARD_RECTANGLE_STATE_CREATE_INFO_EXT);
3305
3306	if (!discard_rectangle_info)
3307		return 0xffff;
3308
3309	unsigned mask = 0;
3310
3311	for (unsigned i = 0; i < (1u << MAX_DISCARD_RECTANGLES); ++i) {
3312		/* Interpret i as a bitmask, and then set the bit in the mask if
3313		 * that combination of rectangles in which the pixel is contained
3314		 * should pass the cliprect test. */
3315		unsigned relevant_subset = i & ((1u << discard_rectangle_info->discardRectangleCount) - 1);
3316
3317		if (discard_rectangle_info->discardRectangleMode == VK_DISCARD_RECTANGLE_MODE_INCLUSIVE_EXT &&
3318		    !relevant_subset)
3319			continue;
3320
3321		if (discard_rectangle_info->discardRectangleMode == VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT &&
3322		    relevant_subset)
3323			continue;
3324
3325		mask |= 1u << i;
3326	}
3327
3328	return mask;
3329}
3330
3331static void
3332radv_pipeline_generate_pm4(struct radv_pipeline *pipeline,
3333                           const VkGraphicsPipelineCreateInfo *pCreateInfo,
3334                           const struct radv_graphics_pipeline_create_info *extra,
3335                           const struct radv_blend_state *blend,
3336                           const struct radv_tessellation_state *tess,
3337                           const struct radv_gs_state *gs,
3338                           unsigned prim, unsigned gs_out)
3339{
3340	pipeline->cs.buf = malloc(4 * 256);
3341	pipeline->cs.max_dw = 256;
3342
3343	radv_pipeline_generate_depth_stencil_state(&pipeline->cs, pipeline, pCreateInfo, extra);
3344	radv_pipeline_generate_blend_state(&pipeline->cs, pipeline, blend);
3345	radv_pipeline_generate_raster_state(&pipeline->cs, pipeline, pCreateInfo);
3346	radv_pipeline_generate_multisample_state(&pipeline->cs, pipeline);
3347	radv_pipeline_generate_vgt_gs_mode(&pipeline->cs, pipeline);
3348	radv_pipeline_generate_vertex_shader(&pipeline->cs, pipeline, tess);
3349	radv_pipeline_generate_tess_shaders(&pipeline->cs, pipeline, tess);
3350	radv_pipeline_generate_geometry_shader(&pipeline->cs, pipeline, gs);
3351	radv_pipeline_generate_fragment_shader(&pipeline->cs, pipeline);
3352	radv_pipeline_generate_ps_inputs(&pipeline->cs, pipeline);
3353	radv_pipeline_generate_vgt_vertex_reuse(&pipeline->cs, pipeline);
3354	radv_pipeline_generate_binning_state(&pipeline->cs, pipeline, pCreateInfo);
3355
3356	radeon_set_context_reg(&pipeline->cs, R_0286E8_SPI_TMPRING_SIZE,
3357			       S_0286E8_WAVES(pipeline->max_waves) |
3358			       S_0286E8_WAVESIZE(pipeline->scratch_bytes_per_wave >> 10));
3359
3360	radeon_set_context_reg(&pipeline->cs, R_028B54_VGT_SHADER_STAGES_EN, radv_compute_vgt_shader_stages_en(pipeline));
3361
3362	if (pipeline->device->physical_device->rad_info.chip_class >= CIK) {
3363		radeon_set_uconfig_reg_idx(&pipeline->cs, R_030908_VGT_PRIMITIVE_TYPE, 1, prim);
3364	} else {
3365		radeon_set_config_reg(&pipeline->cs, R_008958_VGT_PRIMITIVE_TYPE, prim);
3366	}
3367	radeon_set_context_reg(&pipeline->cs, R_028A6C_VGT_GS_OUT_PRIM_TYPE, gs_out);
3368
3369	radeon_set_context_reg(&pipeline->cs, R_02820C_PA_SC_CLIPRECT_RULE, radv_compute_cliprect_rule(pCreateInfo));
3370
3371	assert(pipeline->cs.cdw <= pipeline->cs.max_dw);
3372}
3373
3374static struct radv_ia_multi_vgt_param_helpers
3375radv_compute_ia_multi_vgt_param_helpers(struct radv_pipeline *pipeline,
3376                                        const struct radv_tessellation_state *tess,
3377                                        uint32_t prim)
3378{
3379	struct radv_ia_multi_vgt_param_helpers ia_multi_vgt_param = {0};
3380	const struct radv_device *device = pipeline->device;
3381
3382	if (radv_pipeline_has_tess(pipeline))
3383		ia_multi_vgt_param.primgroup_size = tess->num_patches;
3384	else if (radv_pipeline_has_gs(pipeline))
3385		ia_multi_vgt_param.primgroup_size = 64;
3386	else
3387		ia_multi_vgt_param.primgroup_size = 128; /* recommended without a GS */
3388
3389	/* GS requirement. */
3390	ia_multi_vgt_param.partial_es_wave = false;
3391	if (radv_pipeline_has_gs(pipeline) && device->physical_device->rad_info.chip_class <= VI)
3392		if (SI_GS_PER_ES / ia_multi_vgt_param.primgroup_size >= pipeline->device->gs_table_depth - 3)
3393			ia_multi_vgt_param.partial_es_wave = true;
3394
3395	ia_multi_vgt_param.wd_switch_on_eop = false;
3396	if (device->physical_device->rad_info.chip_class >= CIK) {
3397		/* WD_SWITCH_ON_EOP has no effect on GPUs with less than
3398		 * 4 shader engines. Set 1 to pass the assertion below.
3399		 * The other cases are hardware requirements. */
3400		if (device->physical_device->rad_info.max_se < 4 ||
3401		    prim == V_008958_DI_PT_POLYGON ||
3402		    prim == V_008958_DI_PT_LINELOOP ||
3403		    prim == V_008958_DI_PT_TRIFAN ||
3404		    prim == V_008958_DI_PT_TRISTRIP_ADJ ||
3405		    (pipeline->graphics.prim_restart_enable &&
3406		     (device->physical_device->rad_info.family < CHIP_POLARIS10 ||
3407		      (prim != V_008958_DI_PT_POINTLIST &&
3408		       prim != V_008958_DI_PT_LINESTRIP))))
3409			ia_multi_vgt_param.wd_switch_on_eop = true;
3410	}
3411
3412	ia_multi_vgt_param.ia_switch_on_eoi = false;
3413	if (pipeline->shaders[MESA_SHADER_FRAGMENT]->info.info.ps.prim_id_input)
3414		ia_multi_vgt_param.ia_switch_on_eoi = true;
3415	if (radv_pipeline_has_gs(pipeline) &&
3416	    pipeline->shaders[MESA_SHADER_GEOMETRY]->info.info.uses_prim_id)
3417		ia_multi_vgt_param.ia_switch_on_eoi = true;
3418	if (radv_pipeline_has_tess(pipeline)) {
3419		/* SWITCH_ON_EOI must be set if PrimID is used. */
3420		if (pipeline->shaders[MESA_SHADER_TESS_CTRL]->info.info.uses_prim_id ||
3421		    radv_get_shader(pipeline, MESA_SHADER_TESS_EVAL)->info.info.uses_prim_id)
3422			ia_multi_vgt_param.ia_switch_on_eoi = true;
3423	}
3424
3425	ia_multi_vgt_param.partial_vs_wave = false;
3426	if (radv_pipeline_has_tess(pipeline)) {
3427		/* Bug with tessellation and GS on Bonaire and older 2 SE chips. */
3428		if ((device->physical_device->rad_info.family == CHIP_TAHITI ||
3429		     device->physical_device->rad_info.family == CHIP_PITCAIRN ||
3430		     device->physical_device->rad_info.family == CHIP_BONAIRE) &&
3431		    radv_pipeline_has_gs(pipeline))
3432			ia_multi_vgt_param.partial_vs_wave = true;
3433		/* Needed for 028B6C_DISTRIBUTION_MODE != 0 */
3434		if (device->has_distributed_tess) {
3435			if (radv_pipeline_has_gs(pipeline)) {
3436				if (device->physical_device->rad_info.chip_class <= VI)
3437					ia_multi_vgt_param.partial_es_wave = true;
3438			} else {
3439				ia_multi_vgt_param.partial_vs_wave = true;
3440			}
3441		}
3442	}
3443
3444	/* Workaround for a VGT hang when strip primitive types are used with
3445	 * primitive restart.
3446	 */
3447	if (pipeline->graphics.prim_restart_enable &&
3448	    (prim == V_008958_DI_PT_LINESTRIP ||
3449	     prim == V_008958_DI_PT_TRISTRIP ||
3450	     prim == V_008958_DI_PT_LINESTRIP_ADJ ||
3451	     prim == V_008958_DI_PT_TRISTRIP_ADJ)) {
3452		ia_multi_vgt_param.partial_vs_wave = true;
3453	}
3454
3455	if (radv_pipeline_has_gs(pipeline)) {
3456		/* On these chips there is the possibility of a hang if the
3457		 * pipeline uses a GS and partial_vs_wave is not set.
3458		 *
3459		 * This mostly does not hit 4-SE chips, as those typically set
3460		 * ia_switch_on_eoi and then partial_vs_wave is set for pipelines
3461		 * with GS due to another workaround.
3462		 *
3463		 * Reproducer: https://bugs.freedesktop.org/show_bug.cgi?id=109242
3464		 */
3465		if (device->physical_device->rad_info.family == CHIP_TONGA ||
3466		    device->physical_device->rad_info.family == CHIP_FIJI ||
3467		    device->physical_device->rad_info.family == CHIP_POLARIS10 ||
3468		    device->physical_device->rad_info.family == CHIP_POLARIS11 ||
3469		    device->physical_device->rad_info.family == CHIP_POLARIS12 ||
3470	            device->physical_device->rad_info.family == CHIP_VEGAM) {
3471			ia_multi_vgt_param.partial_vs_wave = true;
3472		}
3473	}
3474
3475	ia_multi_vgt_param.base =
3476		S_028AA8_PRIMGROUP_SIZE(ia_multi_vgt_param.primgroup_size - 1) |
3477		/* The following field was moved to VGT_SHADER_STAGES_EN in GFX9. */
3478		S_028AA8_MAX_PRIMGRP_IN_WAVE(device->physical_device->rad_info.chip_class == VI ? 2 : 0) |
3479		S_030960_EN_INST_OPT_BASIC(device->physical_device->rad_info.chip_class >= GFX9) |
3480		S_030960_EN_INST_OPT_ADV(device->physical_device->rad_info.chip_class >= GFX9);
3481
3482	return ia_multi_vgt_param;
3483}
3484
3485
3486static void
3487radv_compute_vertex_input_state(struct radv_pipeline *pipeline,
3488                                const VkGraphicsPipelineCreateInfo *pCreateInfo)
3489{
3490	const VkPipelineVertexInputStateCreateInfo *vi_info =
3491		pCreateInfo->pVertexInputState;
3492	struct radv_vertex_elements_info *velems = &pipeline->vertex_elements;
3493
3494	for (uint32_t i = 0; i < vi_info->vertexAttributeDescriptionCount; i++) {
3495		const VkVertexInputAttributeDescription *desc =
3496			&vi_info->pVertexAttributeDescriptions[i];
3497		unsigned loc = desc->location;
3498		const struct vk_format_description *format_desc;
3499		int first_non_void;
3500		uint32_t num_format, data_format;
3501		format_desc = vk_format_description(desc->format);
3502		first_non_void = vk_format_get_first_non_void_channel(desc->format);
3503
3504		num_format = radv_translate_buffer_numformat(format_desc, first_non_void);
3505		data_format = radv_translate_buffer_dataformat(format_desc, first_non_void);
3506
3507		velems->rsrc_word3[loc] = S_008F0C_DST_SEL_X(si_map_swizzle(format_desc->swizzle[0])) |
3508			S_008F0C_DST_SEL_Y(si_map_swizzle(format_desc->swizzle[1])) |
3509			S_008F0C_DST_SEL_Z(si_map_swizzle(format_desc->swizzle[2])) |
3510			S_008F0C_DST_SEL_W(si_map_swizzle(format_desc->swizzle[3])) |
3511			S_008F0C_NUM_FORMAT(num_format) |
3512			S_008F0C_DATA_FORMAT(data_format);
3513		velems->format_size[loc] = format_desc->block.bits / 8;
3514		velems->offset[loc] = desc->offset;
3515		velems->binding[loc] = desc->binding;
3516		velems->count = MAX2(velems->count, loc + 1);
3517	}
3518
3519	for (uint32_t i = 0; i < vi_info->vertexBindingDescriptionCount; i++) {
3520		const VkVertexInputBindingDescription *desc =
3521			&vi_info->pVertexBindingDescriptions[i];
3522
3523		pipeline->binding_stride[desc->binding] = desc->stride;
3524	}
3525}
3526
3527static struct radv_shader_variant *
3528radv_pipeline_get_streamout_shader(struct radv_pipeline *pipeline)
3529{
3530	int i;
3531
3532	for (i = MESA_SHADER_GEOMETRY; i >= MESA_SHADER_VERTEX; i--) {
3533		struct radv_shader_variant *shader =
3534			radv_get_shader(pipeline, i);
3535
3536		if (shader && shader->info.info.so.num_outputs > 0)
3537			return shader;
3538	}
3539
3540	return NULL;
3541}
3542
3543static VkResult
3544radv_pipeline_init(struct radv_pipeline *pipeline,
3545		   struct radv_device *device,
3546		   struct radv_pipeline_cache *cache,
3547		   const VkGraphicsPipelineCreateInfo *pCreateInfo,
3548		   const struct radv_graphics_pipeline_create_info *extra,
3549		   const VkAllocationCallbacks *alloc)
3550{
3551	VkResult result;
3552	bool has_view_index = false;
3553
3554	RADV_FROM_HANDLE(radv_render_pass, pass, pCreateInfo->renderPass);
3555	struct radv_subpass *subpass = pass->subpasses + pCreateInfo->subpass;
3556	if (subpass->view_mask)
3557		has_view_index = true;
3558	if (alloc == NULL)
3559		alloc = &device->alloc;
3560
3561	pipeline->device = device;
3562	pipeline->layout = radv_pipeline_layout_from_handle(pCreateInfo->layout);
3563	assert(pipeline->layout);
3564
3565	struct radv_blend_state blend = radv_pipeline_init_blend_state(pipeline, pCreateInfo, extra);
3566
3567	const VkPipelineShaderStageCreateInfo *pStages[MESA_SHADER_STAGES] = { 0, };
3568	for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
3569		gl_shader_stage stage = ffs(pCreateInfo->pStages[i].stage) - 1;
3570		pStages[stage] = &pCreateInfo->pStages[i];
3571	}
3572
3573	struct radv_pipeline_key key = radv_generate_graphics_pipeline_key(pipeline, pCreateInfo, &blend, has_view_index);
3574	radv_create_shaders(pipeline, device, cache, &key, pStages, pCreateInfo->flags);
3575
3576	pipeline->graphics.spi_baryc_cntl = S_0286E0_FRONT_FACE_ALL_BITS(1);
3577	radv_pipeline_init_multisample_state(pipeline, &blend, pCreateInfo);
3578	uint32_t gs_out;
3579	uint32_t prim = si_translate_prim(pCreateInfo->pInputAssemblyState->topology);
3580
3581	pipeline->graphics.can_use_guardband = radv_prim_can_use_guardband(pCreateInfo->pInputAssemblyState->topology);
3582
3583	if (radv_pipeline_has_gs(pipeline)) {
3584		gs_out = si_conv_gl_prim_to_gs_out(pipeline->shaders[MESA_SHADER_GEOMETRY]->info.gs.output_prim);
3585		pipeline->graphics.can_use_guardband = gs_out == V_028A6C_OUTPRIM_TYPE_TRISTRIP;
3586	} else {
3587		gs_out = si_conv_prim_to_gs_out(pCreateInfo->pInputAssemblyState->topology);
3588	}
3589	if (extra && extra->use_rectlist) {
3590		prim = V_008958_DI_PT_RECTLIST;
3591		gs_out = V_028A6C_OUTPRIM_TYPE_TRISTRIP;
3592		pipeline->graphics.can_use_guardband = true;
3593	}
3594	pipeline->graphics.prim_restart_enable = !!pCreateInfo->pInputAssemblyState->primitiveRestartEnable;
3595	/* prim vertex count will need TESS changes */
3596	pipeline->graphics.prim_vertex_count = prim_size_table[prim];
3597
3598	radv_pipeline_init_dynamic_state(pipeline, pCreateInfo);
3599
3600	/* Ensure that some export memory is always allocated, for two reasons:
3601	 *
3602	 * 1) Correctness: The hardware ignores the EXEC mask if no export
3603	 *    memory is allocated, so KILL and alpha test do not work correctly
3604	 *    without this.
3605	 * 2) Performance: Every shader needs at least a NULL export, even when
3606	 *    it writes no color/depth output. The NULL export instruction
3607	 *    stalls without this setting.
3608	 *
3609	 * Don't add this to CB_SHADER_MASK.
3610	 */
3611	struct radv_shader_variant *ps = pipeline->shaders[MESA_SHADER_FRAGMENT];
3612	if (!blend.spi_shader_col_format) {
3613		if (!ps->info.info.ps.writes_z &&
3614		    !ps->info.info.ps.writes_stencil &&
3615		    !ps->info.info.ps.writes_sample_mask)
3616			blend.spi_shader_col_format = V_028714_SPI_SHADER_32_R;
3617	}
3618
3619	for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
3620		if (pipeline->shaders[i]) {
3621			pipeline->need_indirect_descriptor_sets |= pipeline->shaders[i]->info.need_indirect_descriptor_sets;
3622		}
3623	}
3624
3625	struct radv_gs_state gs = {0};
3626	if (radv_pipeline_has_gs(pipeline)) {
3627		gs = calculate_gs_info(pCreateInfo, pipeline);
3628		calculate_gs_ring_sizes(pipeline, &gs);
3629	}
3630
3631	struct radv_tessellation_state tess = {0};
3632	if (radv_pipeline_has_tess(pipeline)) {
3633		if (prim == V_008958_DI_PT_PATCH) {
3634			pipeline->graphics.prim_vertex_count.min = pCreateInfo->pTessellationState->patchControlPoints;
3635			pipeline->graphics.prim_vertex_count.incr = 1;
3636		}
3637		tess = calculate_tess_state(pipeline, pCreateInfo);
3638	}
3639
3640	pipeline->graphics.ia_multi_vgt_param = radv_compute_ia_multi_vgt_param_helpers(pipeline, &tess, prim);
3641
3642	radv_compute_vertex_input_state(pipeline, pCreateInfo);
3643
3644	for (uint32_t i = 0; i < MESA_SHADER_STAGES; i++)
3645		pipeline->user_data_0[i] = radv_pipeline_stage_to_user_data_0(pipeline, i, device->physical_device->rad_info.chip_class);
3646
3647	struct radv_userdata_info *loc = radv_lookup_user_sgpr(pipeline, MESA_SHADER_VERTEX,
3648							     AC_UD_VS_BASE_VERTEX_START_INSTANCE);
3649	if (loc->sgpr_idx != -1) {
3650		pipeline->graphics.vtx_base_sgpr = pipeline->user_data_0[MESA_SHADER_VERTEX];
3651		pipeline->graphics.vtx_base_sgpr += loc->sgpr_idx * 4;
3652		if (radv_get_shader(pipeline, MESA_SHADER_VERTEX)->info.info.vs.needs_draw_id)
3653			pipeline->graphics.vtx_emit_num = 3;
3654		else
3655			pipeline->graphics.vtx_emit_num = 2;
3656	}
3657
3658	/* Find the last vertex shader stage that eventually uses streamout. */
3659	pipeline->streamout_shader = radv_pipeline_get_streamout_shader(pipeline);
3660
3661	result = radv_pipeline_scratch_init(device, pipeline);
3662	radv_pipeline_generate_pm4(pipeline, pCreateInfo, extra, &blend, &tess, &gs, prim, gs_out);
3663
3664	return result;
3665}
3666
3667VkResult
3668radv_graphics_pipeline_create(
3669	VkDevice _device,
3670	VkPipelineCache _cache,
3671	const VkGraphicsPipelineCreateInfo *pCreateInfo,
3672	const struct radv_graphics_pipeline_create_info *extra,
3673	const VkAllocationCallbacks *pAllocator,
3674	VkPipeline *pPipeline)
3675{
3676	RADV_FROM_HANDLE(radv_device, device, _device);
3677	RADV_FROM_HANDLE(radv_pipeline_cache, cache, _cache);
3678	struct radv_pipeline *pipeline;
3679	VkResult result;
3680
3681	pipeline = vk_zalloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
3682			      VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3683	if (pipeline == NULL)
3684		return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3685
3686	result = radv_pipeline_init(pipeline, device, cache,
3687				    pCreateInfo, extra, pAllocator);
3688	if (result != VK_SUCCESS) {
3689		radv_pipeline_destroy(device, pipeline, pAllocator);
3690		return result;
3691	}
3692
3693	*pPipeline = radv_pipeline_to_handle(pipeline);
3694
3695	return VK_SUCCESS;
3696}
3697
3698VkResult radv_CreateGraphicsPipelines(
3699	VkDevice                                    _device,
3700	VkPipelineCache                             pipelineCache,
3701	uint32_t                                    count,
3702	const VkGraphicsPipelineCreateInfo*         pCreateInfos,
3703	const VkAllocationCallbacks*                pAllocator,
3704	VkPipeline*                                 pPipelines)
3705{
3706	VkResult result = VK_SUCCESS;
3707	unsigned i = 0;
3708
3709	for (; i < count; i++) {
3710		VkResult r;
3711		r = radv_graphics_pipeline_create(_device,
3712						  pipelineCache,
3713						  &pCreateInfos[i],
3714						  NULL, pAllocator, &pPipelines[i]);
3715		if (r != VK_SUCCESS) {
3716			result = r;
3717			pPipelines[i] = VK_NULL_HANDLE;
3718		}
3719	}
3720
3721	return result;
3722}
3723
3724
3725static void
3726radv_compute_generate_pm4(struct radv_pipeline *pipeline)
3727{
3728	struct radv_shader_variant *compute_shader;
3729	struct radv_device *device = pipeline->device;
3730	unsigned compute_resource_limits;
3731	unsigned waves_per_threadgroup;
3732	uint64_t va;
3733
3734	pipeline->cs.buf = malloc(20 * 4);
3735	pipeline->cs.max_dw = 20;
3736
3737	compute_shader = pipeline->shaders[MESA_SHADER_COMPUTE];
3738	va = radv_buffer_get_va(compute_shader->bo) + compute_shader->bo_offset;
3739
3740	radeon_set_sh_reg_seq(&pipeline->cs, R_00B830_COMPUTE_PGM_LO, 2);
3741	radeon_emit(&pipeline->cs, va >> 8);
3742	radeon_emit(&pipeline->cs, S_00B834_DATA(va >> 40));
3743
3744	radeon_set_sh_reg_seq(&pipeline->cs, R_00B848_COMPUTE_PGM_RSRC1, 2);
3745	radeon_emit(&pipeline->cs, compute_shader->rsrc1);
3746	radeon_emit(&pipeline->cs, compute_shader->rsrc2);
3747
3748	radeon_set_sh_reg(&pipeline->cs, R_00B860_COMPUTE_TMPRING_SIZE,
3749			  S_00B860_WAVES(pipeline->max_waves) |
3750			  S_00B860_WAVESIZE(pipeline->scratch_bytes_per_wave >> 10));
3751
3752	/* Calculate best compute resource limits. */
3753	waves_per_threadgroup =
3754		DIV_ROUND_UP(compute_shader->info.cs.block_size[0] *
3755			     compute_shader->info.cs.block_size[1] *
3756			     compute_shader->info.cs.block_size[2], 64);
3757	compute_resource_limits =
3758		S_00B854_SIMD_DEST_CNTL(waves_per_threadgroup % 4 == 0);
3759
3760	if (device->physical_device->rad_info.chip_class >= CIK) {
3761		unsigned num_cu_per_se =
3762			device->physical_device->rad_info.num_good_compute_units /
3763			device->physical_device->rad_info.max_se;
3764
3765		/* Force even distribution on all SIMDs in CU if the workgroup
3766		 * size is 64. This has shown some good improvements if # of
3767		 * CUs per SE is not a multiple of 4.
3768		 */
3769		if (num_cu_per_se % 4 && waves_per_threadgroup == 1)
3770			compute_resource_limits |= S_00B854_FORCE_SIMD_DIST(1);
3771	}
3772
3773	radeon_set_sh_reg(&pipeline->cs, R_00B854_COMPUTE_RESOURCE_LIMITS,
3774			  compute_resource_limits);
3775
3776	radeon_set_sh_reg_seq(&pipeline->cs, R_00B81C_COMPUTE_NUM_THREAD_X, 3);
3777	radeon_emit(&pipeline->cs,
3778		    S_00B81C_NUM_THREAD_FULL(compute_shader->info.cs.block_size[0]));
3779	radeon_emit(&pipeline->cs,
3780		    S_00B81C_NUM_THREAD_FULL(compute_shader->info.cs.block_size[1]));
3781	radeon_emit(&pipeline->cs,
3782		    S_00B81C_NUM_THREAD_FULL(compute_shader->info.cs.block_size[2]));
3783
3784	assert(pipeline->cs.cdw <= pipeline->cs.max_dw);
3785}
3786
3787static VkResult radv_compute_pipeline_create(
3788	VkDevice                                    _device,
3789	VkPipelineCache                             _cache,
3790	const VkComputePipelineCreateInfo*          pCreateInfo,
3791	const VkAllocationCallbacks*                pAllocator,
3792	VkPipeline*                                 pPipeline)
3793{
3794	RADV_FROM_HANDLE(radv_device, device, _device);
3795	RADV_FROM_HANDLE(radv_pipeline_cache, cache, _cache);
3796	const VkPipelineShaderStageCreateInfo *pStages[MESA_SHADER_STAGES] = { 0, };
3797	struct radv_pipeline *pipeline;
3798	VkResult result;
3799
3800	pipeline = vk_zalloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
3801			      VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3802	if (pipeline == NULL)
3803		return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3804
3805	pipeline->device = device;
3806	pipeline->layout = radv_pipeline_layout_from_handle(pCreateInfo->layout);
3807	assert(pipeline->layout);
3808
3809	pStages[MESA_SHADER_COMPUTE] = &pCreateInfo->stage;
3810	radv_create_shaders(pipeline, device, cache, &(struct radv_pipeline_key) {0}, pStages, pCreateInfo->flags);
3811
3812	pipeline->user_data_0[MESA_SHADER_COMPUTE] = radv_pipeline_stage_to_user_data_0(pipeline, MESA_SHADER_COMPUTE, device->physical_device->rad_info.chip_class);
3813	pipeline->need_indirect_descriptor_sets |= pipeline->shaders[MESA_SHADER_COMPUTE]->info.need_indirect_descriptor_sets;
3814	result = radv_pipeline_scratch_init(device, pipeline);
3815	if (result != VK_SUCCESS) {
3816		radv_pipeline_destroy(device, pipeline, pAllocator);
3817		return result;
3818	}
3819
3820	radv_compute_generate_pm4(pipeline);
3821
3822	*pPipeline = radv_pipeline_to_handle(pipeline);
3823
3824	return VK_SUCCESS;
3825}
3826
3827VkResult radv_CreateComputePipelines(
3828	VkDevice                                    _device,
3829	VkPipelineCache                             pipelineCache,
3830	uint32_t                                    count,
3831	const VkComputePipelineCreateInfo*          pCreateInfos,
3832	const VkAllocationCallbacks*                pAllocator,
3833	VkPipeline*                                 pPipelines)
3834{
3835	VkResult result = VK_SUCCESS;
3836
3837	unsigned i = 0;
3838	for (; i < count; i++) {
3839		VkResult r;
3840		r = radv_compute_pipeline_create(_device, pipelineCache,
3841						 &pCreateInfos[i],
3842						 pAllocator, &pPipelines[i]);
3843		if (r != VK_SUCCESS) {
3844			result = r;
3845			pPipelines[i] = VK_NULL_HANDLE;
3846		}
3847	}
3848
3849	return result;
3850}
3851