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