d4b93688da13ccfbf99f40a6619744a688e1e319
[mesa.git] / src / intel / vulkan / genX_pipeline.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include "anv_private.h"
25
26 #include "genxml/gen_macros.h"
27 #include "genxml/genX_pack.h"
28
29 #include "common/gen_l3_config.h"
30 #include "common/gen_sample_positions.h"
31 #include "nir/nir_xfb_info.h"
32 #include "vk_util.h"
33 #include "vk_format_info.h"
34
35 static uint32_t
36 vertex_element_comp_control(enum isl_format format, unsigned comp)
37 {
38 uint8_t bits;
39 switch (comp) {
40 case 0: bits = isl_format_layouts[format].channels.r.bits; break;
41 case 1: bits = isl_format_layouts[format].channels.g.bits; break;
42 case 2: bits = isl_format_layouts[format].channels.b.bits; break;
43 case 3: bits = isl_format_layouts[format].channels.a.bits; break;
44 default: unreachable("Invalid component");
45 }
46
47 /*
48 * Take in account hardware restrictions when dealing with 64-bit floats.
49 *
50 * From Broadwell spec, command reference structures, page 586:
51 * "When SourceElementFormat is set to one of the *64*_PASSTHRU formats,
52 * 64-bit components are stored * in the URB without any conversion. In
53 * this case, vertex elements must be written as 128 or 256 bits, with
54 * VFCOMP_STORE_0 being used to pad the output as required. E.g., if
55 * R64_PASSTHRU is used to copy a 64-bit Red component into the URB,
56 * Component 1 must be specified as VFCOMP_STORE_0 (with Components 2,3
57 * set to VFCOMP_NOSTORE) in order to output a 128-bit vertex element, or
58 * Components 1-3 must be specified as VFCOMP_STORE_0 in order to output
59 * a 256-bit vertex element. Likewise, use of R64G64B64_PASSTHRU requires
60 * Component 3 to be specified as VFCOMP_STORE_0 in order to output a
61 * 256-bit vertex element."
62 */
63 if (bits) {
64 return VFCOMP_STORE_SRC;
65 } else if (comp >= 2 &&
66 !isl_format_layouts[format].channels.b.bits &&
67 isl_format_layouts[format].channels.r.type == ISL_RAW) {
68 /* When emitting 64-bit attributes, we need to write either 128 or 256
69 * bit chunks, using VFCOMP_NOSTORE when not writing the chunk, and
70 * VFCOMP_STORE_0 to pad the written chunk */
71 return VFCOMP_NOSTORE;
72 } else if (comp < 3 ||
73 isl_format_layouts[format].channels.r.type == ISL_RAW) {
74 /* Note we need to pad with value 0, not 1, due hardware restrictions
75 * (see comment above) */
76 return VFCOMP_STORE_0;
77 } else if (isl_format_layouts[format].channels.r.type == ISL_UINT ||
78 isl_format_layouts[format].channels.r.type == ISL_SINT) {
79 assert(comp == 3);
80 return VFCOMP_STORE_1_INT;
81 } else {
82 assert(comp == 3);
83 return VFCOMP_STORE_1_FP;
84 }
85 }
86
87 static void
88 emit_vertex_input(struct anv_graphics_pipeline *pipeline,
89 const VkPipelineVertexInputStateCreateInfo *info)
90 {
91 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
92
93 /* Pull inputs_read out of the VS prog data */
94 const uint64_t inputs_read = vs_prog_data->inputs_read;
95 const uint64_t double_inputs_read =
96 vs_prog_data->double_inputs_read & inputs_read;
97 assert((inputs_read & ((1 << VERT_ATTRIB_GENERIC0) - 1)) == 0);
98 const uint32_t elements = inputs_read >> VERT_ATTRIB_GENERIC0;
99 const uint32_t elements_double = double_inputs_read >> VERT_ATTRIB_GENERIC0;
100 const bool needs_svgs_elem = vs_prog_data->uses_vertexid ||
101 vs_prog_data->uses_instanceid ||
102 vs_prog_data->uses_firstvertex ||
103 vs_prog_data->uses_baseinstance;
104
105 uint32_t elem_count = __builtin_popcount(elements) -
106 __builtin_popcount(elements_double) / 2;
107
108 const uint32_t total_elems =
109 MAX2(1, elem_count + needs_svgs_elem + vs_prog_data->uses_drawid);
110
111 uint32_t *p;
112
113 const uint32_t num_dwords = 1 + total_elems * 2;
114 p = anv_batch_emitn(&pipeline->base.batch, num_dwords,
115 GENX(3DSTATE_VERTEX_ELEMENTS));
116 if (!p)
117 return;
118
119 for (uint32_t i = 0; i < total_elems; i++) {
120 /* The SKL docs for VERTEX_ELEMENT_STATE say:
121 *
122 * "All elements must be valid from Element[0] to the last valid
123 * element. (I.e. if Element[2] is valid then Element[1] and
124 * Element[0] must also be valid)."
125 *
126 * The SKL docs for 3D_Vertex_Component_Control say:
127 *
128 * "Don't store this component. (Not valid for Component 0, but can
129 * be used for Component 1-3)."
130 *
131 * So we can't just leave a vertex element blank and hope for the best.
132 * We have to tell the VF hardware to put something in it; so we just
133 * store a bunch of zero.
134 *
135 * TODO: Compact vertex elements so we never end up with holes.
136 */
137 struct GENX(VERTEX_ELEMENT_STATE) element = {
138 .Valid = true,
139 .Component0Control = VFCOMP_STORE_0,
140 .Component1Control = VFCOMP_STORE_0,
141 .Component2Control = VFCOMP_STORE_0,
142 .Component3Control = VFCOMP_STORE_0,
143 };
144 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + i * 2], &element);
145 }
146
147 for (uint32_t i = 0; i < info->vertexAttributeDescriptionCount; i++) {
148 const VkVertexInputAttributeDescription *desc =
149 &info->pVertexAttributeDescriptions[i];
150 enum isl_format format = anv_get_isl_format(&pipeline->base.device->info,
151 desc->format,
152 VK_IMAGE_ASPECT_COLOR_BIT,
153 VK_IMAGE_TILING_LINEAR);
154
155 assert(desc->binding < MAX_VBS);
156
157 if ((elements & (1 << desc->location)) == 0)
158 continue; /* Binding unused */
159
160 uint32_t slot =
161 __builtin_popcount(elements & ((1 << desc->location) - 1)) -
162 DIV_ROUND_UP(__builtin_popcount(elements_double &
163 ((1 << desc->location) -1)), 2);
164
165 struct GENX(VERTEX_ELEMENT_STATE) element = {
166 .VertexBufferIndex = desc->binding,
167 .Valid = true,
168 .SourceElementFormat = format,
169 .EdgeFlagEnable = false,
170 .SourceElementOffset = desc->offset,
171 .Component0Control = vertex_element_comp_control(format, 0),
172 .Component1Control = vertex_element_comp_control(format, 1),
173 .Component2Control = vertex_element_comp_control(format, 2),
174 .Component3Control = vertex_element_comp_control(format, 3),
175 };
176 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + slot * 2], &element);
177
178 #if GEN_GEN >= 8
179 /* On Broadwell and later, we have a separate VF_INSTANCING packet
180 * that controls instancing. On Haswell and prior, that's part of
181 * VERTEX_BUFFER_STATE which we emit later.
182 */
183 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
184 vfi.InstancingEnable = pipeline->vb[desc->binding].instanced;
185 vfi.VertexElementIndex = slot;
186 vfi.InstanceDataStepRate =
187 pipeline->vb[desc->binding].instance_divisor;
188 }
189 #endif
190 }
191
192 const uint32_t id_slot = elem_count;
193 if (needs_svgs_elem) {
194 /* From the Broadwell PRM for the 3D_Vertex_Component_Control enum:
195 * "Within a VERTEX_ELEMENT_STATE structure, if a Component
196 * Control field is set to something other than VFCOMP_STORE_SRC,
197 * no higher-numbered Component Control fields may be set to
198 * VFCOMP_STORE_SRC"
199 *
200 * This means, that if we have BaseInstance, we need BaseVertex as
201 * well. Just do all or nothing.
202 */
203 uint32_t base_ctrl = (vs_prog_data->uses_firstvertex ||
204 vs_prog_data->uses_baseinstance) ?
205 VFCOMP_STORE_SRC : VFCOMP_STORE_0;
206
207 struct GENX(VERTEX_ELEMENT_STATE) element = {
208 .VertexBufferIndex = ANV_SVGS_VB_INDEX,
209 .Valid = true,
210 .SourceElementFormat = ISL_FORMAT_R32G32_UINT,
211 .Component0Control = base_ctrl,
212 .Component1Control = base_ctrl,
213 #if GEN_GEN >= 8
214 .Component2Control = VFCOMP_STORE_0,
215 .Component3Control = VFCOMP_STORE_0,
216 #else
217 .Component2Control = VFCOMP_STORE_VID,
218 .Component3Control = VFCOMP_STORE_IID,
219 #endif
220 };
221 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + id_slot * 2], &element);
222
223 #if GEN_GEN >= 8
224 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
225 vfi.VertexElementIndex = id_slot;
226 }
227 #endif
228 }
229
230 #if GEN_GEN >= 8
231 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_SGVS), sgvs) {
232 sgvs.VertexIDEnable = vs_prog_data->uses_vertexid;
233 sgvs.VertexIDComponentNumber = 2;
234 sgvs.VertexIDElementOffset = id_slot;
235 sgvs.InstanceIDEnable = vs_prog_data->uses_instanceid;
236 sgvs.InstanceIDComponentNumber = 3;
237 sgvs.InstanceIDElementOffset = id_slot;
238 }
239 #endif
240
241 const uint32_t drawid_slot = elem_count + needs_svgs_elem;
242 if (vs_prog_data->uses_drawid) {
243 struct GENX(VERTEX_ELEMENT_STATE) element = {
244 .VertexBufferIndex = ANV_DRAWID_VB_INDEX,
245 .Valid = true,
246 .SourceElementFormat = ISL_FORMAT_R32_UINT,
247 .Component0Control = VFCOMP_STORE_SRC,
248 .Component1Control = VFCOMP_STORE_0,
249 .Component2Control = VFCOMP_STORE_0,
250 .Component3Control = VFCOMP_STORE_0,
251 };
252 GENX(VERTEX_ELEMENT_STATE_pack)(NULL,
253 &p[1 + drawid_slot * 2],
254 &element);
255
256 #if GEN_GEN >= 8
257 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
258 vfi.VertexElementIndex = drawid_slot;
259 }
260 #endif
261 }
262 }
263
264 void
265 genX(emit_urb_setup)(struct anv_device *device, struct anv_batch *batch,
266 const struct gen_l3_config *l3_config,
267 VkShaderStageFlags active_stages,
268 const unsigned entry_size[4],
269 enum gen_urb_deref_block_size *deref_block_size)
270 {
271 const struct gen_device_info *devinfo = &device->info;
272
273 unsigned entries[4];
274 unsigned start[4];
275 gen_get_urb_config(devinfo, l3_config,
276 active_stages &
277 VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
278 active_stages & VK_SHADER_STAGE_GEOMETRY_BIT,
279 entry_size, entries, start, deref_block_size);
280
281 #if GEN_GEN == 7 && !GEN_IS_HASWELL
282 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
283 *
284 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth stall
285 * needs to be sent just prior to any 3DSTATE_VS, 3DSTATE_URB_VS,
286 * 3DSTATE_CONSTANT_VS, 3DSTATE_BINDING_TABLE_POINTER_VS,
287 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one PIPE_CONTROL
288 * needs to be sent before any combination of VS associated 3DSTATE."
289 */
290 anv_batch_emit(batch, GEN7_PIPE_CONTROL, pc) {
291 pc.DepthStallEnable = true;
292 pc.PostSyncOperation = WriteImmediateData;
293 pc.Address = device->workaround_address;
294 }
295 #endif
296
297 for (int i = 0; i <= MESA_SHADER_GEOMETRY; i++) {
298 anv_batch_emit(batch, GENX(3DSTATE_URB_VS), urb) {
299 urb._3DCommandSubOpcode += i;
300 urb.VSURBStartingAddress = start[i];
301 urb.VSURBEntryAllocationSize = entry_size[i] - 1;
302 urb.VSNumberofURBEntries = entries[i];
303 }
304 }
305 }
306
307 static void
308 emit_urb_setup(struct anv_graphics_pipeline *pipeline,
309 enum gen_urb_deref_block_size *deref_block_size)
310 {
311 unsigned entry_size[4];
312 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
313 const struct brw_vue_prog_data *prog_data =
314 !anv_pipeline_has_stage(pipeline, i) ? NULL :
315 (const struct brw_vue_prog_data *) pipeline->shaders[i]->prog_data;
316
317 entry_size[i] = prog_data ? prog_data->urb_entry_size : 1;
318 }
319
320 genX(emit_urb_setup)(pipeline->base.device, &pipeline->base.batch,
321 pipeline->base.l3_config,
322 pipeline->active_stages, entry_size,
323 deref_block_size);
324 }
325
326 static void
327 emit_3dstate_sbe(struct anv_graphics_pipeline *pipeline)
328 {
329 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
330
331 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
332 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_SBE), sbe);
333 #if GEN_GEN >= 8
334 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_SBE_SWIZ), sbe);
335 #endif
336 return;
337 }
338
339 const struct brw_vue_map *fs_input_map =
340 &anv_pipeline_get_last_vue_prog_data(pipeline)->vue_map;
341
342 struct GENX(3DSTATE_SBE) sbe = {
343 GENX(3DSTATE_SBE_header),
344 .AttributeSwizzleEnable = true,
345 .PointSpriteTextureCoordinateOrigin = UPPERLEFT,
346 .NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs,
347 .ConstantInterpolationEnable = wm_prog_data->flat_inputs,
348 };
349
350 #if GEN_GEN >= 9
351 for (unsigned i = 0; i < 32; i++)
352 sbe.AttributeActiveComponentFormat[i] = ACF_XYZW;
353 #endif
354
355 #if GEN_GEN >= 8
356 /* On Broadwell, they broke 3DSTATE_SBE into two packets */
357 struct GENX(3DSTATE_SBE_SWIZ) swiz = {
358 GENX(3DSTATE_SBE_SWIZ_header),
359 };
360 #else
361 # define swiz sbe
362 #endif
363
364 int first_slot = brw_compute_first_urb_slot_required(wm_prog_data->inputs,
365 fs_input_map);
366 assert(first_slot % 2 == 0);
367 unsigned urb_entry_read_offset = first_slot / 2;
368 int max_source_attr = 0;
369 for (uint8_t idx = 0; idx < wm_prog_data->urb_setup_attribs_count; idx++) {
370 uint8_t attr = wm_prog_data->urb_setup_attribs[idx];
371 int input_index = wm_prog_data->urb_setup[attr];
372
373 assert(0 <= input_index);
374
375 /* gl_Viewport and gl_Layer are stored in the VUE header */
376 if (attr == VARYING_SLOT_VIEWPORT || attr == VARYING_SLOT_LAYER) {
377 continue;
378 }
379
380 if (attr == VARYING_SLOT_PNTC) {
381 sbe.PointSpriteTextureCoordinateEnable = 1 << input_index;
382 continue;
383 }
384
385 const int slot = fs_input_map->varying_to_slot[attr];
386
387 if (slot == -1) {
388 /* This attribute does not exist in the VUE--that means that the
389 * vertex shader did not write to it. It could be that it's a
390 * regular varying read by the fragment shader but not written by
391 * the vertex shader or it's gl_PrimitiveID. In the first case the
392 * value is undefined, in the second it needs to be
393 * gl_PrimitiveID.
394 */
395 swiz.Attribute[input_index].ConstantSource = PRIM_ID;
396 swiz.Attribute[input_index].ComponentOverrideX = true;
397 swiz.Attribute[input_index].ComponentOverrideY = true;
398 swiz.Attribute[input_index].ComponentOverrideZ = true;
399 swiz.Attribute[input_index].ComponentOverrideW = true;
400 continue;
401 }
402
403 /* We have to subtract two slots to accout for the URB entry output
404 * read offset in the VS and GS stages.
405 */
406 const int source_attr = slot - 2 * urb_entry_read_offset;
407 assert(source_attr >= 0 && source_attr < 32);
408 max_source_attr = MAX2(max_source_attr, source_attr);
409 /* The hardware can only do overrides on 16 overrides at a time, and the
410 * other up to 16 have to be lined up so that the input index = the
411 * output index. We'll need to do some tweaking to make sure that's the
412 * case.
413 */
414 if (input_index < 16)
415 swiz.Attribute[input_index].SourceAttribute = source_attr;
416 else
417 assert(source_attr == input_index);
418 }
419
420 sbe.VertexURBEntryReadOffset = urb_entry_read_offset;
421 sbe.VertexURBEntryReadLength = DIV_ROUND_UP(max_source_attr + 1, 2);
422 #if GEN_GEN >= 8
423 sbe.ForceVertexURBEntryReadOffset = true;
424 sbe.ForceVertexURBEntryReadLength = true;
425 #endif
426
427 uint32_t *dw = anv_batch_emit_dwords(&pipeline->base.batch,
428 GENX(3DSTATE_SBE_length));
429 if (!dw)
430 return;
431 GENX(3DSTATE_SBE_pack)(&pipeline->base.batch, dw, &sbe);
432
433 #if GEN_GEN >= 8
434 dw = anv_batch_emit_dwords(&pipeline->base.batch, GENX(3DSTATE_SBE_SWIZ_length));
435 if (!dw)
436 return;
437 GENX(3DSTATE_SBE_SWIZ_pack)(&pipeline->base.batch, dw, &swiz);
438 #endif
439 }
440
441 static VkLineRasterizationModeEXT
442 vk_line_rasterization_mode(const VkPipelineRasterizationLineStateCreateInfoEXT *line_info,
443 const VkPipelineMultisampleStateCreateInfo *ms_info)
444 {
445 VkLineRasterizationModeEXT line_mode =
446 line_info ? line_info->lineRasterizationMode :
447 VK_LINE_RASTERIZATION_MODE_DEFAULT_EXT;
448
449 if (line_mode == VK_LINE_RASTERIZATION_MODE_DEFAULT_EXT) {
450 if (ms_info && ms_info->rasterizationSamples > 1) {
451 return VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT;
452 } else {
453 return VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT;
454 }
455 }
456
457 return line_mode;
458 }
459
460 /** Returns the final polygon mode for rasterization
461 *
462 * This function takes into account polygon mode, primitive topology and the
463 * different shader stages which might generate their own type of primitives.
464 */
465 static VkPolygonMode
466 anv_raster_polygon_mode(struct anv_graphics_pipeline *pipeline,
467 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
468 const VkPipelineRasterizationStateCreateInfo *rs_info)
469 {
470 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
471 switch (get_gs_prog_data(pipeline)->output_topology) {
472 case _3DPRIM_POINTLIST:
473 return VK_POLYGON_MODE_POINT;
474
475 case _3DPRIM_LINELIST:
476 case _3DPRIM_LINESTRIP:
477 case _3DPRIM_LINELOOP:
478 return VK_POLYGON_MODE_LINE;
479
480 case _3DPRIM_TRILIST:
481 case _3DPRIM_TRIFAN:
482 case _3DPRIM_TRISTRIP:
483 case _3DPRIM_RECTLIST:
484 case _3DPRIM_QUADLIST:
485 case _3DPRIM_QUADSTRIP:
486 case _3DPRIM_POLYGON:
487 return rs_info->polygonMode;
488 }
489 unreachable("Unsupported GS output topology");
490 } else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
491 switch (get_tes_prog_data(pipeline)->output_topology) {
492 case BRW_TESS_OUTPUT_TOPOLOGY_POINT:
493 return VK_POLYGON_MODE_POINT;
494
495 case BRW_TESS_OUTPUT_TOPOLOGY_LINE:
496 return VK_POLYGON_MODE_LINE;
497
498 case BRW_TESS_OUTPUT_TOPOLOGY_TRI_CW:
499 case BRW_TESS_OUTPUT_TOPOLOGY_TRI_CCW:
500 return rs_info->polygonMode;
501 }
502 unreachable("Unsupported TCS output topology");
503 } else {
504 switch (ia_info->topology) {
505 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
506 return VK_POLYGON_MODE_POINT;
507
508 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
509 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
510 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
511 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
512 return VK_POLYGON_MODE_LINE;
513
514 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
515 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
516 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
517 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
518 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
519 return rs_info->polygonMode;
520
521 default:
522 unreachable("Unsupported primitive topology");
523 }
524 }
525 }
526
527 #if GEN_GEN <= 7
528 static uint32_t
529 gen7_ms_rast_mode(struct anv_graphics_pipeline *pipeline,
530 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
531 const VkPipelineRasterizationStateCreateInfo *rs_info,
532 const VkPipelineMultisampleStateCreateInfo *ms_info)
533 {
534 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info =
535 vk_find_struct_const(rs_info->pNext,
536 PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
537
538 VkPolygonMode raster_mode =
539 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
540 if (raster_mode == VK_POLYGON_MODE_LINE) {
541 switch (vk_line_rasterization_mode(line_info, ms_info)) {
542 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT:
543 return MSRASTMODE_ON_PATTERN;
544
545 case VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT:
546 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT:
547 return MSRASTMODE_OFF_PIXEL;
548
549 default:
550 unreachable("Unsupported line rasterization mode");
551 }
552 } else {
553 return (ms_info && ms_info->rasterizationSamples > 1) ?
554 MSRASTMODE_ON_PATTERN : MSRASTMODE_OFF_PIXEL;
555 }
556 }
557 #endif
558
559 const uint32_t genX(vk_to_gen_cullmode)[] = {
560 [VK_CULL_MODE_NONE] = CULLMODE_NONE,
561 [VK_CULL_MODE_FRONT_BIT] = CULLMODE_FRONT,
562 [VK_CULL_MODE_BACK_BIT] = CULLMODE_BACK,
563 [VK_CULL_MODE_FRONT_AND_BACK] = CULLMODE_BOTH
564 };
565
566 const uint32_t genX(vk_to_gen_fillmode)[] = {
567 [VK_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
568 [VK_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
569 [VK_POLYGON_MODE_POINT] = FILL_MODE_POINT,
570 };
571
572 const uint32_t genX(vk_to_gen_front_face)[] = {
573 [VK_FRONT_FACE_COUNTER_CLOCKWISE] = 1,
574 [VK_FRONT_FACE_CLOCKWISE] = 0
575 };
576
577 static void
578 emit_rs_state(struct anv_graphics_pipeline *pipeline,
579 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
580 const VkPipelineRasterizationStateCreateInfo *rs_info,
581 const VkPipelineMultisampleStateCreateInfo *ms_info,
582 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info,
583 const uint32_t dynamic_states,
584 const struct anv_render_pass *pass,
585 const struct anv_subpass *subpass,
586 enum gen_urb_deref_block_size urb_deref_block_size)
587 {
588 struct GENX(3DSTATE_SF) sf = {
589 GENX(3DSTATE_SF_header),
590 };
591
592 sf.ViewportTransformEnable = true;
593 sf.StatisticsEnable = true;
594 sf.TriangleStripListProvokingVertexSelect = 0;
595 sf.LineStripListProvokingVertexSelect = 0;
596 sf.TriangleFanProvokingVertexSelect = 1;
597 sf.VertexSubPixelPrecisionSelect = _8Bit;
598 sf.AALineDistanceMode = true;
599
600 #if GEN_IS_HASWELL
601 sf.LineStippleEnable = line_info && line_info->stippledLineEnable;
602 #endif
603
604 #if GEN_GEN >= 12
605 sf.DerefBlockSize = urb_deref_block_size;
606 #endif
607
608 const struct brw_vue_prog_data *last_vue_prog_data =
609 anv_pipeline_get_last_vue_prog_data(pipeline);
610
611 if (last_vue_prog_data->vue_map.slots_valid & VARYING_BIT_PSIZ) {
612 sf.PointWidthSource = Vertex;
613 } else {
614 sf.PointWidthSource = State;
615 sf.PointWidth = 1.0;
616 }
617
618 #if GEN_GEN >= 8
619 struct GENX(3DSTATE_RASTER) raster = {
620 GENX(3DSTATE_RASTER_header),
621 };
622 #else
623 # define raster sf
624 #endif
625
626 VkPolygonMode raster_mode =
627 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
628 VkLineRasterizationModeEXT line_mode =
629 vk_line_rasterization_mode(line_info, ms_info);
630
631 /* For details on 3DSTATE_RASTER multisample state, see the BSpec table
632 * "Multisample Modes State".
633 */
634 #if GEN_GEN >= 8
635 if (raster_mode == VK_POLYGON_MODE_LINE) {
636 /* Unfortunately, configuring our line rasterization hardware on gen8
637 * and later is rather painful. Instead of giving us bits to tell the
638 * hardware what line mode to use like we had on gen7, we now have an
639 * arcane combination of API Mode and MSAA enable bits which do things
640 * in a table which are expected to magically put the hardware into the
641 * right mode for your API. Sadly, Vulkan isn't any of the APIs the
642 * hardware people thought of so nothing works the way you want it to.
643 *
644 * Look at the table titled "Multisample Rasterization Modes" in Vol 7
645 * of the Skylake PRM for more details.
646 */
647 switch (line_mode) {
648 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT:
649 raster.APIMode = DX100;
650 raster.DXMultisampleRasterizationEnable = true;
651 break;
652
653 case VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT:
654 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT:
655 raster.APIMode = DX9OGL;
656 raster.DXMultisampleRasterizationEnable = false;
657 break;
658
659 default:
660 unreachable("Unsupported line rasterization mode");
661 }
662 } else {
663 raster.APIMode = DX100;
664 raster.DXMultisampleRasterizationEnable = true;
665 }
666
667 /* NOTE: 3DSTATE_RASTER::ForcedSampleCount affects the BDW and SKL PMA fix
668 * computations. If we ever set this bit to a different value, they will
669 * need to be updated accordingly.
670 */
671 raster.ForcedSampleCount = FSC_NUMRASTSAMPLES_0;
672 raster.ForceMultisampling = false;
673 #else
674 raster.MultisampleRasterizationMode =
675 gen7_ms_rast_mode(pipeline, ia_info, rs_info, ms_info);
676 #endif
677
678 if (raster_mode == VK_POLYGON_MODE_LINE &&
679 line_mode == VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT)
680 raster.AntialiasingEnable = true;
681
682 raster.FrontWinding =
683 dynamic_states & ANV_CMD_DIRTY_DYNAMIC_FRONT_FACE ?
684 0 : genX(vk_to_gen_front_face)[rs_info->frontFace];
685 raster.CullMode =
686 dynamic_states & ANV_CMD_DIRTY_DYNAMIC_CULL_MODE ?
687 0 : genX(vk_to_gen_cullmode)[rs_info->cullMode];
688
689 raster.FrontFaceFillMode = genX(vk_to_gen_fillmode)[rs_info->polygonMode];
690 raster.BackFaceFillMode = genX(vk_to_gen_fillmode)[rs_info->polygonMode];
691 raster.ScissorRectangleEnable = true;
692
693 #if GEN_GEN >= 9
694 /* GEN9+ splits ViewportZClipTestEnable into near and far enable bits */
695 raster.ViewportZFarClipTestEnable = pipeline->depth_clip_enable;
696 raster.ViewportZNearClipTestEnable = pipeline->depth_clip_enable;
697 #elif GEN_GEN >= 8
698 raster.ViewportZClipTestEnable = pipeline->depth_clip_enable;
699 #endif
700
701 raster.GlobalDepthOffsetEnableSolid = rs_info->depthBiasEnable;
702 raster.GlobalDepthOffsetEnableWireframe = rs_info->depthBiasEnable;
703 raster.GlobalDepthOffsetEnablePoint = rs_info->depthBiasEnable;
704
705 #if GEN_GEN == 7
706 /* Gen7 requires that we provide the depth format in 3DSTATE_SF so that it
707 * can get the depth offsets correct.
708 */
709 if (subpass->depth_stencil_attachment) {
710 VkFormat vk_format =
711 pass->attachments[subpass->depth_stencil_attachment->attachment].format;
712 assert(vk_format_is_depth_or_stencil(vk_format));
713 if (vk_format_aspects(vk_format) & VK_IMAGE_ASPECT_DEPTH_BIT) {
714 enum isl_format isl_format =
715 anv_get_isl_format(&pipeline->base.device->info, vk_format,
716 VK_IMAGE_ASPECT_DEPTH_BIT,
717 VK_IMAGE_TILING_OPTIMAL);
718 sf.DepthBufferSurfaceFormat =
719 isl_format_get_depth_format(isl_format, false);
720 }
721 }
722 #endif
723
724 #if GEN_GEN >= 8
725 GENX(3DSTATE_SF_pack)(NULL, pipeline->gen8.sf, &sf);
726 GENX(3DSTATE_RASTER_pack)(NULL, pipeline->gen8.raster, &raster);
727 #else
728 # undef raster
729 GENX(3DSTATE_SF_pack)(NULL, &pipeline->gen7.sf, &sf);
730 #endif
731 }
732
733 static void
734 emit_ms_state(struct anv_graphics_pipeline *pipeline,
735 const VkPipelineMultisampleStateCreateInfo *info)
736 {
737 uint32_t samples = 1;
738 uint32_t log2_samples = 0;
739
740 /* From the Vulkan 1.0 spec:
741 * If pSampleMask is NULL, it is treated as if the mask has all bits
742 * enabled, i.e. no coverage is removed from fragments.
743 *
744 * 3DSTATE_SAMPLE_MASK.SampleMask is 16 bits.
745 */
746 #if GEN_GEN >= 8
747 uint32_t sample_mask = 0xffff;
748 #else
749 uint32_t sample_mask = 0xff;
750 #endif
751
752 if (info) {
753 samples = info->rasterizationSamples;
754 log2_samples = __builtin_ffs(samples) - 1;
755 }
756
757 if (info && info->pSampleMask)
758 sample_mask &= info->pSampleMask[0];
759
760 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_MULTISAMPLE), ms) {
761 ms.NumberofMultisamples = log2_samples;
762
763 ms.PixelLocation = CENTER;
764 #if GEN_GEN >= 8
765 /* The PRM says that this bit is valid only for DX9:
766 *
767 * SW can choose to set this bit only for DX9 API. DX10/OGL API's
768 * should not have any effect by setting or not setting this bit.
769 */
770 ms.PixelPositionOffsetEnable = false;
771 #else
772
773 switch (samples) {
774 case 1:
775 GEN_SAMPLE_POS_1X(ms.Sample);
776 break;
777 case 2:
778 GEN_SAMPLE_POS_2X(ms.Sample);
779 break;
780 case 4:
781 GEN_SAMPLE_POS_4X(ms.Sample);
782 break;
783 case 8:
784 GEN_SAMPLE_POS_8X(ms.Sample);
785 break;
786 default:
787 break;
788 }
789 #endif
790 }
791
792 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_SAMPLE_MASK), sm) {
793 sm.SampleMask = sample_mask;
794 }
795 }
796
797 static const uint32_t vk_to_gen_logic_op[] = {
798 [VK_LOGIC_OP_COPY] = LOGICOP_COPY,
799 [VK_LOGIC_OP_CLEAR] = LOGICOP_CLEAR,
800 [VK_LOGIC_OP_AND] = LOGICOP_AND,
801 [VK_LOGIC_OP_AND_REVERSE] = LOGICOP_AND_REVERSE,
802 [VK_LOGIC_OP_AND_INVERTED] = LOGICOP_AND_INVERTED,
803 [VK_LOGIC_OP_NO_OP] = LOGICOP_NOOP,
804 [VK_LOGIC_OP_XOR] = LOGICOP_XOR,
805 [VK_LOGIC_OP_OR] = LOGICOP_OR,
806 [VK_LOGIC_OP_NOR] = LOGICOP_NOR,
807 [VK_LOGIC_OP_EQUIVALENT] = LOGICOP_EQUIV,
808 [VK_LOGIC_OP_INVERT] = LOGICOP_INVERT,
809 [VK_LOGIC_OP_OR_REVERSE] = LOGICOP_OR_REVERSE,
810 [VK_LOGIC_OP_COPY_INVERTED] = LOGICOP_COPY_INVERTED,
811 [VK_LOGIC_OP_OR_INVERTED] = LOGICOP_OR_INVERTED,
812 [VK_LOGIC_OP_NAND] = LOGICOP_NAND,
813 [VK_LOGIC_OP_SET] = LOGICOP_SET,
814 };
815
816 static const uint32_t vk_to_gen_blend[] = {
817 [VK_BLEND_FACTOR_ZERO] = BLENDFACTOR_ZERO,
818 [VK_BLEND_FACTOR_ONE] = BLENDFACTOR_ONE,
819 [VK_BLEND_FACTOR_SRC_COLOR] = BLENDFACTOR_SRC_COLOR,
820 [VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR] = BLENDFACTOR_INV_SRC_COLOR,
821 [VK_BLEND_FACTOR_DST_COLOR] = BLENDFACTOR_DST_COLOR,
822 [VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR] = BLENDFACTOR_INV_DST_COLOR,
823 [VK_BLEND_FACTOR_SRC_ALPHA] = BLENDFACTOR_SRC_ALPHA,
824 [VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA] = BLENDFACTOR_INV_SRC_ALPHA,
825 [VK_BLEND_FACTOR_DST_ALPHA] = BLENDFACTOR_DST_ALPHA,
826 [VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA] = BLENDFACTOR_INV_DST_ALPHA,
827 [VK_BLEND_FACTOR_CONSTANT_COLOR] = BLENDFACTOR_CONST_COLOR,
828 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR]= BLENDFACTOR_INV_CONST_COLOR,
829 [VK_BLEND_FACTOR_CONSTANT_ALPHA] = BLENDFACTOR_CONST_ALPHA,
830 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA]= BLENDFACTOR_INV_CONST_ALPHA,
831 [VK_BLEND_FACTOR_SRC_ALPHA_SATURATE] = BLENDFACTOR_SRC_ALPHA_SATURATE,
832 [VK_BLEND_FACTOR_SRC1_COLOR] = BLENDFACTOR_SRC1_COLOR,
833 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR] = BLENDFACTOR_INV_SRC1_COLOR,
834 [VK_BLEND_FACTOR_SRC1_ALPHA] = BLENDFACTOR_SRC1_ALPHA,
835 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA] = BLENDFACTOR_INV_SRC1_ALPHA,
836 };
837
838 static const uint32_t vk_to_gen_blend_op[] = {
839 [VK_BLEND_OP_ADD] = BLENDFUNCTION_ADD,
840 [VK_BLEND_OP_SUBTRACT] = BLENDFUNCTION_SUBTRACT,
841 [VK_BLEND_OP_REVERSE_SUBTRACT] = BLENDFUNCTION_REVERSE_SUBTRACT,
842 [VK_BLEND_OP_MIN] = BLENDFUNCTION_MIN,
843 [VK_BLEND_OP_MAX] = BLENDFUNCTION_MAX,
844 };
845
846 const uint32_t genX(vk_to_gen_compare_op)[] = {
847 [VK_COMPARE_OP_NEVER] = PREFILTEROPNEVER,
848 [VK_COMPARE_OP_LESS] = PREFILTEROPLESS,
849 [VK_COMPARE_OP_EQUAL] = PREFILTEROPEQUAL,
850 [VK_COMPARE_OP_LESS_OR_EQUAL] = PREFILTEROPLEQUAL,
851 [VK_COMPARE_OP_GREATER] = PREFILTEROPGREATER,
852 [VK_COMPARE_OP_NOT_EQUAL] = PREFILTEROPNOTEQUAL,
853 [VK_COMPARE_OP_GREATER_OR_EQUAL] = PREFILTEROPGEQUAL,
854 [VK_COMPARE_OP_ALWAYS] = PREFILTEROPALWAYS,
855 };
856
857 const uint32_t genX(vk_to_gen_stencil_op)[] = {
858 [VK_STENCIL_OP_KEEP] = STENCILOP_KEEP,
859 [VK_STENCIL_OP_ZERO] = STENCILOP_ZERO,
860 [VK_STENCIL_OP_REPLACE] = STENCILOP_REPLACE,
861 [VK_STENCIL_OP_INCREMENT_AND_CLAMP] = STENCILOP_INCRSAT,
862 [VK_STENCIL_OP_DECREMENT_AND_CLAMP] = STENCILOP_DECRSAT,
863 [VK_STENCIL_OP_INVERT] = STENCILOP_INVERT,
864 [VK_STENCIL_OP_INCREMENT_AND_WRAP] = STENCILOP_INCR,
865 [VK_STENCIL_OP_DECREMENT_AND_WRAP] = STENCILOP_DECR,
866 };
867
868 const uint32_t genX(vk_to_gen_primitive_type)[] = {
869 [VK_PRIMITIVE_TOPOLOGY_POINT_LIST] = _3DPRIM_POINTLIST,
870 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST] = _3DPRIM_LINELIST,
871 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP] = _3DPRIM_LINESTRIP,
872 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST] = _3DPRIM_TRILIST,
873 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
874 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
875 [VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
876 [VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
877 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
878 [VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
879 };
880
881 /* This function sanitizes the VkStencilOpState by looking at the compare ops
882 * and trying to determine whether or not a given stencil op can ever actually
883 * occur. Stencil ops which can never occur are set to VK_STENCIL_OP_KEEP.
884 * This function returns true if, after sanitation, any of the stencil ops are
885 * set to something other than VK_STENCIL_OP_KEEP.
886 */
887 static bool
888 sanitize_stencil_face(VkStencilOpState *face,
889 VkCompareOp depthCompareOp)
890 {
891 /* If compareOp is ALWAYS then the stencil test will never fail and failOp
892 * will never happen. Set failOp to KEEP in this case.
893 */
894 if (face->compareOp == VK_COMPARE_OP_ALWAYS)
895 face->failOp = VK_STENCIL_OP_KEEP;
896
897 /* If compareOp is NEVER or depthCompareOp is NEVER then one of the depth
898 * or stencil tests will fail and passOp will never happen.
899 */
900 if (face->compareOp == VK_COMPARE_OP_NEVER ||
901 depthCompareOp == VK_COMPARE_OP_NEVER)
902 face->passOp = VK_STENCIL_OP_KEEP;
903
904 /* If compareOp is NEVER or depthCompareOp is ALWAYS then either the
905 * stencil test will fail or the depth test will pass. In either case,
906 * depthFailOp will never happen.
907 */
908 if (face->compareOp == VK_COMPARE_OP_NEVER ||
909 depthCompareOp == VK_COMPARE_OP_ALWAYS)
910 face->depthFailOp = VK_STENCIL_OP_KEEP;
911
912 return face->failOp != VK_STENCIL_OP_KEEP ||
913 face->depthFailOp != VK_STENCIL_OP_KEEP ||
914 face->passOp != VK_STENCIL_OP_KEEP;
915 }
916
917 /* Intel hardware is fairly sensitive to whether or not depth/stencil writes
918 * are enabled. In the presence of discards, it's fairly easy to get into the
919 * non-promoted case which means a fairly big performance hit. From the Iron
920 * Lake PRM, Vol 2, pt. 1, section 8.4.3.2, "Early Depth Test Cases":
921 *
922 * "Non-promoted depth (N) is active whenever the depth test can be done
923 * early but it cannot determine whether or not to write source depth to
924 * the depth buffer, therefore the depth write must be performed post pixel
925 * shader. This includes cases where the pixel shader can kill pixels,
926 * including via sampler chroma key, as well as cases where the alpha test
927 * function is enabled, which kills pixels based on a programmable alpha
928 * test. In this case, even if the depth test fails, the pixel cannot be
929 * killed if a stencil write is indicated. Whether or not the stencil write
930 * happens depends on whether or not the pixel is killed later. In these
931 * cases if stencil test fails and stencil writes are off, the pixels can
932 * also be killed early. If stencil writes are enabled, the pixels must be
933 * treated as Computed depth (described above)."
934 *
935 * The same thing as mentioned in the stencil case can happen in the depth
936 * case as well if it thinks it writes depth but, thanks to the depth test
937 * being GL_EQUAL, the write doesn't actually matter. A little extra work
938 * up-front to try and disable depth and stencil writes can make a big
939 * difference.
940 *
941 * Unfortunately, the way depth and stencil testing is specified, there are
942 * many case where, regardless of depth/stencil writes being enabled, nothing
943 * actually gets written due to some other bit of state being set. This
944 * function attempts to "sanitize" the depth stencil state and disable writes
945 * and sometimes even testing whenever possible.
946 */
947 static void
948 sanitize_ds_state(VkPipelineDepthStencilStateCreateInfo *state,
949 bool *stencilWriteEnable,
950 VkImageAspectFlags ds_aspects)
951 {
952 *stencilWriteEnable = state->stencilTestEnable;
953
954 /* If the depth test is disabled, we won't be writing anything. Make sure we
955 * treat the test as always passing later on as well.
956 *
957 * Also, the Vulkan spec requires that if either depth or stencil is not
958 * present, the pipeline is to act as if the test silently passes. In that
959 * case we won't write either.
960 */
961 if (!state->depthTestEnable || !(ds_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
962 state->depthWriteEnable = false;
963 state->depthCompareOp = VK_COMPARE_OP_ALWAYS;
964 }
965
966 if (!(ds_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
967 *stencilWriteEnable = false;
968 state->front.compareOp = VK_COMPARE_OP_ALWAYS;
969 state->back.compareOp = VK_COMPARE_OP_ALWAYS;
970 }
971
972 /* If the stencil test is enabled and always fails, then we will never get
973 * to the depth test so we can just disable the depth test entirely.
974 */
975 if (state->stencilTestEnable &&
976 state->front.compareOp == VK_COMPARE_OP_NEVER &&
977 state->back.compareOp == VK_COMPARE_OP_NEVER) {
978 state->depthTestEnable = false;
979 state->depthWriteEnable = false;
980 }
981
982 /* If depthCompareOp is EQUAL then the value we would be writing to the
983 * depth buffer is the same as the value that's already there so there's no
984 * point in writing it.
985 */
986 if (state->depthCompareOp == VK_COMPARE_OP_EQUAL)
987 state->depthWriteEnable = false;
988
989 /* If the stencil ops are such that we don't actually ever modify the
990 * stencil buffer, we should disable writes.
991 */
992 if (!sanitize_stencil_face(&state->front, state->depthCompareOp) &&
993 !sanitize_stencil_face(&state->back, state->depthCompareOp))
994 *stencilWriteEnable = false;
995
996 /* If the depth test always passes and we never write out depth, that's the
997 * same as if the depth test is disabled entirely.
998 */
999 if (state->depthCompareOp == VK_COMPARE_OP_ALWAYS &&
1000 !state->depthWriteEnable)
1001 state->depthTestEnable = false;
1002
1003 /* If the stencil test always passes and we never write out stencil, that's
1004 * the same as if the stencil test is disabled entirely.
1005 */
1006 if (state->front.compareOp == VK_COMPARE_OP_ALWAYS &&
1007 state->back.compareOp == VK_COMPARE_OP_ALWAYS &&
1008 !*stencilWriteEnable)
1009 state->stencilTestEnable = false;
1010 }
1011
1012 static void
1013 emit_ds_state(struct anv_graphics_pipeline *pipeline,
1014 const VkPipelineDepthStencilStateCreateInfo *pCreateInfo,
1015 const uint32_t dynamic_states,
1016 const struct anv_render_pass *pass,
1017 const struct anv_subpass *subpass)
1018 {
1019 #if GEN_GEN == 7
1020 # define depth_stencil_dw pipeline->gen7.depth_stencil_state
1021 #elif GEN_GEN == 8
1022 # define depth_stencil_dw pipeline->gen8.wm_depth_stencil
1023 #else
1024 # define depth_stencil_dw pipeline->gen9.wm_depth_stencil
1025 #endif
1026
1027 if (pCreateInfo == NULL) {
1028 /* We're going to OR this together with the dynamic state. We need
1029 * to make sure it's initialized to something useful.
1030 */
1031 pipeline->writes_stencil = false;
1032 pipeline->stencil_test_enable = false;
1033 pipeline->writes_depth = false;
1034 pipeline->depth_test_enable = false;
1035 pipeline->depth_bounds_test_enable = false;
1036 memset(depth_stencil_dw, 0, sizeof(depth_stencil_dw));
1037 return;
1038 }
1039
1040 VkImageAspectFlags ds_aspects = 0;
1041 if (subpass->depth_stencil_attachment) {
1042 VkFormat depth_stencil_format =
1043 pass->attachments[subpass->depth_stencil_attachment->attachment].format;
1044 ds_aspects = vk_format_aspects(depth_stencil_format);
1045 }
1046
1047 VkPipelineDepthStencilStateCreateInfo info = *pCreateInfo;
1048 sanitize_ds_state(&info, &pipeline->writes_stencil, ds_aspects);
1049 pipeline->stencil_test_enable = info.stencilTestEnable;
1050 pipeline->writes_depth = info.depthWriteEnable;
1051 pipeline->depth_test_enable = info.depthTestEnable;
1052 pipeline->depth_bounds_test_enable = info.depthBoundsTestEnable;
1053
1054 bool dynamic_stencil_op =
1055 dynamic_states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_OP;
1056
1057 #if GEN_GEN <= 7
1058 struct GENX(DEPTH_STENCIL_STATE) depth_stencil = {
1059 #else
1060 struct GENX(3DSTATE_WM_DEPTH_STENCIL) depth_stencil = {
1061 #endif
1062 .DepthTestEnable =
1063 dynamic_states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_TEST_ENABLE ?
1064 0 : info.depthTestEnable,
1065
1066 .DepthBufferWriteEnable =
1067 dynamic_states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_WRITE_ENABLE ?
1068 0 : info.depthWriteEnable,
1069
1070 .DepthTestFunction =
1071 dynamic_states & ANV_CMD_DIRTY_DYNAMIC_DEPTH_COMPARE_OP ?
1072 0 : genX(vk_to_gen_compare_op)[info.depthCompareOp],
1073
1074 .DoubleSidedStencilEnable = true,
1075
1076 .StencilTestEnable =
1077 dynamic_states & ANV_CMD_DIRTY_DYNAMIC_STENCIL_TEST_ENABLE ?
1078 0 : info.stencilTestEnable,
1079
1080 .StencilFailOp = genX(vk_to_gen_stencil_op)[info.front.failOp],
1081 .StencilPassDepthPassOp = genX(vk_to_gen_stencil_op)[info.front.passOp],
1082 .StencilPassDepthFailOp = genX(vk_to_gen_stencil_op)[info.front.depthFailOp],
1083 .StencilTestFunction = genX(vk_to_gen_compare_op)[info.front.compareOp],
1084 .BackfaceStencilFailOp = genX(vk_to_gen_stencil_op)[info.back.failOp],
1085 .BackfaceStencilPassDepthPassOp = genX(vk_to_gen_stencil_op)[info.back.passOp],
1086 .BackfaceStencilPassDepthFailOp = genX(vk_to_gen_stencil_op)[info.back.depthFailOp],
1087 .BackfaceStencilTestFunction = genX(vk_to_gen_compare_op)[info.back.compareOp],
1088 };
1089
1090 if (dynamic_stencil_op) {
1091 depth_stencil.StencilFailOp = 0;
1092 depth_stencil.StencilPassDepthPassOp = 0;
1093 depth_stencil.StencilPassDepthFailOp = 0;
1094 depth_stencil.StencilTestFunction = 0;
1095 depth_stencil.BackfaceStencilFailOp = 0;
1096 depth_stencil.BackfaceStencilPassDepthPassOp = 0;
1097 depth_stencil.BackfaceStencilPassDepthFailOp = 0;
1098 depth_stencil.BackfaceStencilTestFunction = 0;
1099 }
1100
1101 #if GEN_GEN <= 7
1102 GENX(DEPTH_STENCIL_STATE_pack)(NULL, depth_stencil_dw, &depth_stencil);
1103 #else
1104 GENX(3DSTATE_WM_DEPTH_STENCIL_pack)(NULL, depth_stencil_dw, &depth_stencil);
1105 #endif
1106 }
1107
1108 static bool
1109 is_dual_src_blend_factor(VkBlendFactor factor)
1110 {
1111 return factor == VK_BLEND_FACTOR_SRC1_COLOR ||
1112 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR ||
1113 factor == VK_BLEND_FACTOR_SRC1_ALPHA ||
1114 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
1115 }
1116
1117 static void
1118 emit_cb_state(struct anv_graphics_pipeline *pipeline,
1119 const VkPipelineColorBlendStateCreateInfo *info,
1120 const VkPipelineMultisampleStateCreateInfo *ms_info)
1121 {
1122 struct anv_device *device = pipeline->base.device;
1123 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1124
1125 struct GENX(BLEND_STATE) blend_state = {
1126 #if GEN_GEN >= 8
1127 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
1128 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
1129 #endif
1130 };
1131
1132 uint32_t surface_count = 0;
1133 struct anv_pipeline_bind_map *map;
1134 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1135 map = &pipeline->shaders[MESA_SHADER_FRAGMENT]->bind_map;
1136 surface_count = map->surface_count;
1137 }
1138
1139 const uint32_t num_dwords = GENX(BLEND_STATE_length) +
1140 GENX(BLEND_STATE_ENTRY_length) * surface_count;
1141 pipeline->blend_state =
1142 anv_state_pool_alloc(&device->dynamic_state_pool, num_dwords * 4, 64);
1143
1144 bool has_writeable_rt = false;
1145 uint32_t *state_pos = pipeline->blend_state.map;
1146 state_pos += GENX(BLEND_STATE_length);
1147 #if GEN_GEN >= 8
1148 struct GENX(BLEND_STATE_ENTRY) bs0 = { 0 };
1149 #endif
1150 for (unsigned i = 0; i < surface_count; i++) {
1151 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[i];
1152
1153 /* All color attachments are at the beginning of the binding table */
1154 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
1155 break;
1156
1157 /* We can have at most 8 attachments */
1158 assert(i < 8);
1159
1160 if (info == NULL || binding->index >= info->attachmentCount) {
1161 /* Default everything to disabled */
1162 struct GENX(BLEND_STATE_ENTRY) entry = {
1163 .WriteDisableAlpha = true,
1164 .WriteDisableRed = true,
1165 .WriteDisableGreen = true,
1166 .WriteDisableBlue = true,
1167 };
1168 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
1169 state_pos += GENX(BLEND_STATE_ENTRY_length);
1170 continue;
1171 }
1172
1173 const VkPipelineColorBlendAttachmentState *a =
1174 &info->pAttachments[binding->index];
1175
1176 struct GENX(BLEND_STATE_ENTRY) entry = {
1177 #if GEN_GEN < 8
1178 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
1179 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
1180 #endif
1181 .LogicOpEnable = info->logicOpEnable,
1182 .LogicOpFunction = vk_to_gen_logic_op[info->logicOp],
1183 .ColorBufferBlendEnable = a->blendEnable,
1184 .ColorClampRange = COLORCLAMP_RTFORMAT,
1185 .PreBlendColorClampEnable = true,
1186 .PostBlendColorClampEnable = true,
1187 .SourceBlendFactor = vk_to_gen_blend[a->srcColorBlendFactor],
1188 .DestinationBlendFactor = vk_to_gen_blend[a->dstColorBlendFactor],
1189 .ColorBlendFunction = vk_to_gen_blend_op[a->colorBlendOp],
1190 .SourceAlphaBlendFactor = vk_to_gen_blend[a->srcAlphaBlendFactor],
1191 .DestinationAlphaBlendFactor = vk_to_gen_blend[a->dstAlphaBlendFactor],
1192 .AlphaBlendFunction = vk_to_gen_blend_op[a->alphaBlendOp],
1193 .WriteDisableAlpha = !(a->colorWriteMask & VK_COLOR_COMPONENT_A_BIT),
1194 .WriteDisableRed = !(a->colorWriteMask & VK_COLOR_COMPONENT_R_BIT),
1195 .WriteDisableGreen = !(a->colorWriteMask & VK_COLOR_COMPONENT_G_BIT),
1196 .WriteDisableBlue = !(a->colorWriteMask & VK_COLOR_COMPONENT_B_BIT),
1197 };
1198
1199 if (a->srcColorBlendFactor != a->srcAlphaBlendFactor ||
1200 a->dstColorBlendFactor != a->dstAlphaBlendFactor ||
1201 a->colorBlendOp != a->alphaBlendOp) {
1202 #if GEN_GEN >= 8
1203 blend_state.IndependentAlphaBlendEnable = true;
1204 #else
1205 entry.IndependentAlphaBlendEnable = true;
1206 #endif
1207 }
1208
1209 /* The Dual Source Blending documentation says:
1210 *
1211 * "If SRC1 is included in a src/dst blend factor and
1212 * a DualSource RT Write message is not used, results
1213 * are UNDEFINED. (This reflects the same restriction in DX APIs,
1214 * where undefined results are produced if “o1” is not written
1215 * by a PS – there are no default values defined)."
1216 *
1217 * There is no way to gracefully fix this undefined situation
1218 * so we just disable the blending to prevent possible issues.
1219 */
1220 if (!wm_prog_data->dual_src_blend &&
1221 (is_dual_src_blend_factor(a->srcColorBlendFactor) ||
1222 is_dual_src_blend_factor(a->dstColorBlendFactor) ||
1223 is_dual_src_blend_factor(a->srcAlphaBlendFactor) ||
1224 is_dual_src_blend_factor(a->dstAlphaBlendFactor))) {
1225 vk_debug_report(&device->physical->instance->debug_report_callbacks,
1226 VK_DEBUG_REPORT_WARNING_BIT_EXT,
1227 VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
1228 (uint64_t)(uintptr_t)device,
1229 0, 0, "anv",
1230 "Enabled dual-src blend factors without writing both targets "
1231 "in the shader. Disabling blending to avoid GPU hangs.");
1232 entry.ColorBufferBlendEnable = false;
1233 }
1234
1235 if (a->colorWriteMask != 0)
1236 has_writeable_rt = true;
1237
1238 /* Our hardware applies the blend factor prior to the blend function
1239 * regardless of what function is used. Technically, this means the
1240 * hardware can do MORE than GL or Vulkan specify. However, it also
1241 * means that, for MIN and MAX, we have to stomp the blend factor to
1242 * ONE to make it a no-op.
1243 */
1244 if (a->colorBlendOp == VK_BLEND_OP_MIN ||
1245 a->colorBlendOp == VK_BLEND_OP_MAX) {
1246 entry.SourceBlendFactor = BLENDFACTOR_ONE;
1247 entry.DestinationBlendFactor = BLENDFACTOR_ONE;
1248 }
1249 if (a->alphaBlendOp == VK_BLEND_OP_MIN ||
1250 a->alphaBlendOp == VK_BLEND_OP_MAX) {
1251 entry.SourceAlphaBlendFactor = BLENDFACTOR_ONE;
1252 entry.DestinationAlphaBlendFactor = BLENDFACTOR_ONE;
1253 }
1254 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
1255 state_pos += GENX(BLEND_STATE_ENTRY_length);
1256 #if GEN_GEN >= 8
1257 if (i == 0)
1258 bs0 = entry;
1259 #endif
1260 }
1261
1262 #if GEN_GEN >= 8
1263 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS_BLEND), blend) {
1264 blend.AlphaToCoverageEnable = blend_state.AlphaToCoverageEnable;
1265 blend.HasWriteableRT = has_writeable_rt;
1266 blend.ColorBufferBlendEnable = bs0.ColorBufferBlendEnable;
1267 blend.SourceAlphaBlendFactor = bs0.SourceAlphaBlendFactor;
1268 blend.DestinationAlphaBlendFactor = bs0.DestinationAlphaBlendFactor;
1269 blend.SourceBlendFactor = bs0.SourceBlendFactor;
1270 blend.DestinationBlendFactor = bs0.DestinationBlendFactor;
1271 blend.AlphaTestEnable = false;
1272 blend.IndependentAlphaBlendEnable =
1273 blend_state.IndependentAlphaBlendEnable;
1274 }
1275 #else
1276 (void)has_writeable_rt;
1277 #endif
1278
1279 GENX(BLEND_STATE_pack)(NULL, pipeline->blend_state.map, &blend_state);
1280
1281 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_BLEND_STATE_POINTERS), bsp) {
1282 bsp.BlendStatePointer = pipeline->blend_state.offset;
1283 #if GEN_GEN >= 8
1284 bsp.BlendStatePointerValid = true;
1285 #endif
1286 }
1287 }
1288
1289 static void
1290 emit_3dstate_clip(struct anv_graphics_pipeline *pipeline,
1291 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
1292 const VkPipelineViewportStateCreateInfo *vp_info,
1293 const VkPipelineRasterizationStateCreateInfo *rs_info,
1294 const uint32_t dynamic_states)
1295 {
1296 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1297 (void) wm_prog_data;
1298
1299 struct GENX(3DSTATE_CLIP) clip = {
1300 GENX(3DSTATE_CLIP_header),
1301 };
1302
1303 clip.ClipEnable = true;
1304 clip.StatisticsEnable = true;
1305 clip.EarlyCullEnable = true;
1306 clip.APIMode = APIMODE_D3D;
1307 clip.GuardbandClipTestEnable = true;
1308
1309 /* Only enable the XY clip test when the final polygon rasterization
1310 * mode is VK_POLYGON_MODE_FILL. We want to leave it disabled for
1311 * points and lines so we get "pop-free" clipping.
1312 */
1313 VkPolygonMode raster_mode =
1314 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
1315 clip.ViewportXYClipTestEnable = (raster_mode == VK_POLYGON_MODE_FILL);
1316
1317 #if GEN_GEN >= 8
1318 clip.VertexSubPixelPrecisionSelect = _8Bit;
1319 #endif
1320 clip.ClipMode = CLIPMODE_NORMAL;
1321
1322 clip.TriangleStripListProvokingVertexSelect = 0;
1323 clip.LineStripListProvokingVertexSelect = 0;
1324 clip.TriangleFanProvokingVertexSelect = 1;
1325
1326 clip.MinimumPointWidth = 0.125;
1327 clip.MaximumPointWidth = 255.875;
1328
1329 const struct brw_vue_prog_data *last =
1330 anv_pipeline_get_last_vue_prog_data(pipeline);
1331
1332 /* From the Vulkan 1.0.45 spec:
1333 *
1334 * "If the last active vertex processing stage shader entry point's
1335 * interface does not include a variable decorated with
1336 * ViewportIndex, then the first viewport is used."
1337 */
1338 if (vp_info && (last->vue_map.slots_valid & VARYING_BIT_VIEWPORT)) {
1339 clip.MaximumVPIndex = vp_info->viewportCount > 0 ?
1340 vp_info->viewportCount - 1 : 0;
1341 } else {
1342 clip.MaximumVPIndex = 0;
1343 }
1344
1345 /* From the Vulkan 1.0.45 spec:
1346 *
1347 * "If the last active vertex processing stage shader entry point's
1348 * interface does not include a variable decorated with Layer, then
1349 * the first layer is used."
1350 */
1351 clip.ForceZeroRTAIndexEnable =
1352 !(last->vue_map.slots_valid & VARYING_BIT_LAYER);
1353
1354 #if GEN_GEN == 7
1355 clip.FrontWinding = genX(vk_to_gen_front_face)[rs_info->frontFace];
1356 clip.CullMode = genX(vk_to_gen_cullmode)[rs_info->cullMode];
1357 clip.ViewportZClipTestEnable = pipeline->depth_clip_enable;
1358 clip.UserClipDistanceClipTestEnableBitmask = last->clip_distance_mask;
1359 clip.UserClipDistanceCullTestEnableBitmask = last->cull_distance_mask;
1360 #else
1361 clip.NonPerspectiveBarycentricEnable = wm_prog_data ?
1362 (wm_prog_data->barycentric_interp_modes &
1363 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS) != 0 : 0;
1364 #endif
1365
1366 GENX(3DSTATE_CLIP_pack)(NULL, pipeline->gen7.clip, &clip);
1367 }
1368
1369 static void
1370 emit_3dstate_streamout(struct anv_graphics_pipeline *pipeline,
1371 const VkPipelineRasterizationStateCreateInfo *rs_info)
1372 {
1373 #if GEN_GEN >= 8
1374 const struct brw_vue_prog_data *prog_data =
1375 anv_pipeline_get_last_vue_prog_data(pipeline);
1376 const struct brw_vue_map *vue_map = &prog_data->vue_map;
1377
1378 nir_xfb_info *xfb_info;
1379 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY))
1380 xfb_info = pipeline->shaders[MESA_SHADER_GEOMETRY]->xfb_info;
1381 else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
1382 xfb_info = pipeline->shaders[MESA_SHADER_TESS_EVAL]->xfb_info;
1383 else
1384 xfb_info = pipeline->shaders[MESA_SHADER_VERTEX]->xfb_info;
1385 #endif
1386
1387 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_STREAMOUT), so) {
1388 so.RenderingDisable = rs_info->rasterizerDiscardEnable;
1389
1390 #if GEN_GEN >= 8
1391 if (xfb_info) {
1392 so.SOFunctionEnable = true;
1393 so.SOStatisticsEnable = true;
1394
1395 const VkPipelineRasterizationStateStreamCreateInfoEXT *stream_info =
1396 vk_find_struct_const(rs_info, PIPELINE_RASTERIZATION_STATE_STREAM_CREATE_INFO_EXT);
1397 so.RenderStreamSelect = stream_info ?
1398 stream_info->rasterizationStream : 0;
1399
1400 so.Buffer0SurfacePitch = xfb_info->buffers[0].stride;
1401 so.Buffer1SurfacePitch = xfb_info->buffers[1].stride;
1402 so.Buffer2SurfacePitch = xfb_info->buffers[2].stride;
1403 so.Buffer3SurfacePitch = xfb_info->buffers[3].stride;
1404
1405 int urb_entry_read_offset = 0;
1406 int urb_entry_read_length =
1407 (prog_data->vue_map.num_slots + 1) / 2 - urb_entry_read_offset;
1408
1409 /* We always read the whole vertex. This could be reduced at some
1410 * point by reading less and offsetting the register index in the
1411 * SO_DECLs.
1412 */
1413 so.Stream0VertexReadOffset = urb_entry_read_offset;
1414 so.Stream0VertexReadLength = urb_entry_read_length - 1;
1415 so.Stream1VertexReadOffset = urb_entry_read_offset;
1416 so.Stream1VertexReadLength = urb_entry_read_length - 1;
1417 so.Stream2VertexReadOffset = urb_entry_read_offset;
1418 so.Stream2VertexReadLength = urb_entry_read_length - 1;
1419 so.Stream3VertexReadOffset = urb_entry_read_offset;
1420 so.Stream3VertexReadLength = urb_entry_read_length - 1;
1421 }
1422 #endif /* GEN_GEN >= 8 */
1423 }
1424
1425 #if GEN_GEN >= 8
1426 if (xfb_info) {
1427 struct GENX(SO_DECL) so_decl[MAX_XFB_STREAMS][128];
1428 int next_offset[MAX_XFB_BUFFERS] = {0, 0, 0, 0};
1429 int decls[MAX_XFB_STREAMS] = {0, 0, 0, 0};
1430
1431 memset(so_decl, 0, sizeof(so_decl));
1432
1433 for (unsigned i = 0; i < xfb_info->output_count; i++) {
1434 const nir_xfb_output_info *output = &xfb_info->outputs[i];
1435 unsigned buffer = output->buffer;
1436 unsigned stream = xfb_info->buffer_to_stream[buffer];
1437
1438 /* Our hardware is unusual in that it requires us to program SO_DECLs
1439 * for fake "hole" components, rather than simply taking the offset
1440 * for each real varying. Each hole can have size 1, 2, 3, or 4; we
1441 * program as many size = 4 holes as we can, then a final hole to
1442 * accommodate the final 1, 2, or 3 remaining.
1443 */
1444 int hole_dwords = (output->offset - next_offset[buffer]) / 4;
1445 while (hole_dwords > 0) {
1446 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1447 .HoleFlag = 1,
1448 .OutputBufferSlot = buffer,
1449 .ComponentMask = (1 << MIN2(hole_dwords, 4)) - 1,
1450 };
1451 hole_dwords -= 4;
1452 }
1453
1454 int varying = output->location;
1455 uint8_t component_mask = output->component_mask;
1456 /* VARYING_SLOT_PSIZ contains three scalar fields packed together:
1457 * - VARYING_SLOT_LAYER in VARYING_SLOT_PSIZ.y
1458 * - VARYING_SLOT_VIEWPORT in VARYING_SLOT_PSIZ.z
1459 * - VARYING_SLOT_PSIZ in VARYING_SLOT_PSIZ.w
1460 */
1461 if (varying == VARYING_SLOT_LAYER) {
1462 varying = VARYING_SLOT_PSIZ;
1463 component_mask = 1 << 1; // SO_DECL_COMPMASK_Y
1464 } else if (varying == VARYING_SLOT_VIEWPORT) {
1465 varying = VARYING_SLOT_PSIZ;
1466 component_mask = 1 << 2; // SO_DECL_COMPMASK_Z
1467 } else if (varying == VARYING_SLOT_PSIZ) {
1468 component_mask = 1 << 3; // SO_DECL_COMPMASK_W
1469 }
1470
1471 next_offset[buffer] = output->offset +
1472 __builtin_popcount(component_mask) * 4;
1473
1474 const int slot = vue_map->varying_to_slot[varying];
1475 if (slot < 0) {
1476 /* This can happen if the shader never writes to the varying.
1477 * Insert a hole instead of actual varying data.
1478 */
1479 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1480 .HoleFlag = true,
1481 .OutputBufferSlot = buffer,
1482 .ComponentMask = component_mask,
1483 };
1484 } else {
1485 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1486 .OutputBufferSlot = buffer,
1487 .RegisterIndex = slot,
1488 .ComponentMask = component_mask,
1489 };
1490 }
1491 }
1492
1493 int max_decls = 0;
1494 for (unsigned s = 0; s < MAX_XFB_STREAMS; s++)
1495 max_decls = MAX2(max_decls, decls[s]);
1496
1497 uint8_t sbs[MAX_XFB_STREAMS] = { };
1498 for (unsigned b = 0; b < MAX_XFB_BUFFERS; b++) {
1499 if (xfb_info->buffers_written & (1 << b))
1500 sbs[xfb_info->buffer_to_stream[b]] |= 1 << b;
1501 }
1502
1503 uint32_t *dw = anv_batch_emitn(&pipeline->base.batch, 3 + 2 * max_decls,
1504 GENX(3DSTATE_SO_DECL_LIST),
1505 .StreamtoBufferSelects0 = sbs[0],
1506 .StreamtoBufferSelects1 = sbs[1],
1507 .StreamtoBufferSelects2 = sbs[2],
1508 .StreamtoBufferSelects3 = sbs[3],
1509 .NumEntries0 = decls[0],
1510 .NumEntries1 = decls[1],
1511 .NumEntries2 = decls[2],
1512 .NumEntries3 = decls[3]);
1513
1514 for (int i = 0; i < max_decls; i++) {
1515 GENX(SO_DECL_ENTRY_pack)(NULL, dw + 3 + i * 2,
1516 &(struct GENX(SO_DECL_ENTRY)) {
1517 .Stream0Decl = so_decl[0][i],
1518 .Stream1Decl = so_decl[1][i],
1519 .Stream2Decl = so_decl[2][i],
1520 .Stream3Decl = so_decl[3][i],
1521 });
1522 }
1523 }
1524 #endif /* GEN_GEN >= 8 */
1525 }
1526
1527 static uint32_t
1528 get_sampler_count(const struct anv_shader_bin *bin)
1529 {
1530 uint32_t count_by_4 = DIV_ROUND_UP(bin->bind_map.sampler_count, 4);
1531
1532 /* We can potentially have way more than 32 samplers and that's ok.
1533 * However, the 3DSTATE_XS packets only have 3 bits to specify how
1534 * many to pre-fetch and all values above 4 are marked reserved.
1535 */
1536 return MIN2(count_by_4, 4);
1537 }
1538
1539 static uint32_t
1540 get_binding_table_entry_count(const struct anv_shader_bin *bin)
1541 {
1542 return DIV_ROUND_UP(bin->bind_map.surface_count, 32);
1543 }
1544
1545 static struct anv_address
1546 get_scratch_address(struct anv_pipeline *pipeline,
1547 gl_shader_stage stage,
1548 const struct anv_shader_bin *bin)
1549 {
1550 return (struct anv_address) {
1551 .bo = anv_scratch_pool_alloc(pipeline->device,
1552 &pipeline->device->scratch_pool,
1553 stage, bin->prog_data->total_scratch),
1554 .offset = 0,
1555 };
1556 }
1557
1558 static uint32_t
1559 get_scratch_space(const struct anv_shader_bin *bin)
1560 {
1561 return ffs(bin->prog_data->total_scratch / 2048);
1562 }
1563
1564 static void
1565 emit_3dstate_vs(struct anv_graphics_pipeline *pipeline)
1566 {
1567 const struct gen_device_info *devinfo = &pipeline->base.device->info;
1568 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
1569 const struct anv_shader_bin *vs_bin =
1570 pipeline->shaders[MESA_SHADER_VERTEX];
1571
1572 assert(anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX));
1573
1574 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VS), vs) {
1575 vs.Enable = true;
1576 vs.StatisticsEnable = true;
1577 vs.KernelStartPointer = vs_bin->kernel.offset;
1578 #if GEN_GEN >= 8
1579 vs.SIMD8DispatchEnable =
1580 vs_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8;
1581 #endif
1582
1583 assert(!vs_prog_data->base.base.use_alt_mode);
1584 #if GEN_GEN < 11
1585 vs.SingleVertexDispatch = false;
1586 #endif
1587 vs.VectorMaskEnable = false;
1588 /* WA_1606682166:
1589 * Incorrect TDL's SSP address shift in SARB for 16:6 & 18:8 modes.
1590 * Disable the Sampler state prefetch functionality in the SARB by
1591 * programming 0xB000[30] to '1'.
1592 */
1593 vs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(vs_bin);
1594 vs.BindingTableEntryCount = get_binding_table_entry_count(vs_bin);
1595 vs.FloatingPointMode = IEEE754;
1596 vs.IllegalOpcodeExceptionEnable = false;
1597 vs.SoftwareExceptionEnable = false;
1598 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
1599
1600 if (GEN_GEN == 9 && devinfo->gt == 4 &&
1601 anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
1602 /* On Sky Lake GT4, we have experienced some hangs related to the VS
1603 * cache and tessellation. It is unknown exactly what is happening
1604 * but the Haswell docs for the "VS Reference Count Full Force Miss
1605 * Enable" field of the "Thread Mode" register refer to a HSW bug in
1606 * which the VUE handle reference count would overflow resulting in
1607 * internal reference counting bugs. My (Jason's) best guess is that
1608 * this bug cropped back up on SKL GT4 when we suddenly had more
1609 * threads in play than any previous gen9 hardware.
1610 *
1611 * What we do know for sure is that setting this bit when
1612 * tessellation shaders are in use fixes a GPU hang in Batman: Arkham
1613 * City when playing with DXVK (https://bugs.freedesktop.org/107280).
1614 * Disabling the vertex cache with tessellation shaders should only
1615 * have a minor performance impact as the tessellation shaders are
1616 * likely generating and processing far more geometry than the vertex
1617 * stage.
1618 */
1619 vs.VertexCacheDisable = true;
1620 }
1621
1622 vs.VertexURBEntryReadLength = vs_prog_data->base.urb_read_length;
1623 vs.VertexURBEntryReadOffset = 0;
1624 vs.DispatchGRFStartRegisterForURBData =
1625 vs_prog_data->base.base.dispatch_grf_start_reg;
1626
1627 #if GEN_GEN >= 8
1628 vs.UserClipDistanceClipTestEnableBitmask =
1629 vs_prog_data->base.clip_distance_mask;
1630 vs.UserClipDistanceCullTestEnableBitmask =
1631 vs_prog_data->base.cull_distance_mask;
1632 #endif
1633
1634 vs.PerThreadScratchSpace = get_scratch_space(vs_bin);
1635 vs.ScratchSpaceBasePointer =
1636 get_scratch_address(&pipeline->base, MESA_SHADER_VERTEX, vs_bin);
1637 }
1638 }
1639
1640 static void
1641 emit_3dstate_hs_te_ds(struct anv_graphics_pipeline *pipeline,
1642 const VkPipelineTessellationStateCreateInfo *tess_info)
1643 {
1644 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
1645 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_HS), hs);
1646 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_TE), te);
1647 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_DS), ds);
1648 return;
1649 }
1650
1651 const struct gen_device_info *devinfo = &pipeline->base.device->info;
1652 const struct anv_shader_bin *tcs_bin =
1653 pipeline->shaders[MESA_SHADER_TESS_CTRL];
1654 const struct anv_shader_bin *tes_bin =
1655 pipeline->shaders[MESA_SHADER_TESS_EVAL];
1656
1657 const struct brw_tcs_prog_data *tcs_prog_data = get_tcs_prog_data(pipeline);
1658 const struct brw_tes_prog_data *tes_prog_data = get_tes_prog_data(pipeline);
1659
1660 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_HS), hs) {
1661 hs.Enable = true;
1662 hs.StatisticsEnable = true;
1663 hs.KernelStartPointer = tcs_bin->kernel.offset;
1664 /* WA_1606682166 */
1665 hs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(tcs_bin);
1666 hs.BindingTableEntryCount = get_binding_table_entry_count(tcs_bin);
1667
1668 #if GEN_GEN >= 12
1669 /* GEN:BUG:1604578095:
1670 *
1671 * Hang occurs when the number of max threads is less than 2 times
1672 * the number of instance count. The number of max threads must be
1673 * more than 2 times the number of instance count.
1674 */
1675 assert((devinfo->max_tcs_threads / 2) > tcs_prog_data->instances);
1676 #endif
1677
1678 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
1679 hs.IncludeVertexHandles = true;
1680 hs.InstanceCount = tcs_prog_data->instances - 1;
1681
1682 hs.VertexURBEntryReadLength = 0;
1683 hs.VertexURBEntryReadOffset = 0;
1684 hs.DispatchGRFStartRegisterForURBData =
1685 tcs_prog_data->base.base.dispatch_grf_start_reg & 0x1f;
1686 #if GEN_GEN >= 12
1687 hs.DispatchGRFStartRegisterForURBData5 =
1688 tcs_prog_data->base.base.dispatch_grf_start_reg >> 5;
1689 #endif
1690
1691
1692 hs.PerThreadScratchSpace = get_scratch_space(tcs_bin);
1693 hs.ScratchSpaceBasePointer =
1694 get_scratch_address(&pipeline->base, MESA_SHADER_TESS_CTRL, tcs_bin);
1695
1696 #if GEN_GEN == 12
1697 /* Patch Count threshold specifies the maximum number of patches that
1698 * will be accumulated before a thread dispatch is forced.
1699 */
1700 hs.PatchCountThreshold = tcs_prog_data->patch_count_threshold;
1701 #endif
1702
1703 #if GEN_GEN >= 9
1704 hs.DispatchMode = tcs_prog_data->base.dispatch_mode;
1705 hs.IncludePrimitiveID = tcs_prog_data->include_primitive_id;
1706 #endif
1707 }
1708
1709 const VkPipelineTessellationDomainOriginStateCreateInfo *domain_origin_state =
1710 tess_info ? vk_find_struct_const(tess_info, PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO) : NULL;
1711
1712 VkTessellationDomainOrigin uv_origin =
1713 domain_origin_state ? domain_origin_state->domainOrigin :
1714 VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT;
1715
1716 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_TE), te) {
1717 te.Partitioning = tes_prog_data->partitioning;
1718
1719 if (uv_origin == VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT) {
1720 te.OutputTopology = tes_prog_data->output_topology;
1721 } else {
1722 /* When the origin is upper-left, we have to flip the winding order */
1723 if (tes_prog_data->output_topology == OUTPUT_TRI_CCW) {
1724 te.OutputTopology = OUTPUT_TRI_CW;
1725 } else if (tes_prog_data->output_topology == OUTPUT_TRI_CW) {
1726 te.OutputTopology = OUTPUT_TRI_CCW;
1727 } else {
1728 te.OutputTopology = tes_prog_data->output_topology;
1729 }
1730 }
1731
1732 te.TEDomain = tes_prog_data->domain;
1733 te.TEEnable = true;
1734 te.MaximumTessellationFactorOdd = 63.0;
1735 te.MaximumTessellationFactorNotOdd = 64.0;
1736 }
1737
1738 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_DS), ds) {
1739 ds.Enable = true;
1740 ds.StatisticsEnable = true;
1741 ds.KernelStartPointer = tes_bin->kernel.offset;
1742 /* WA_1606682166 */
1743 ds.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(tes_bin);
1744 ds.BindingTableEntryCount = get_binding_table_entry_count(tes_bin);
1745 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
1746
1747 ds.ComputeWCoordinateEnable =
1748 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
1749
1750 ds.PatchURBEntryReadLength = tes_prog_data->base.urb_read_length;
1751 ds.PatchURBEntryReadOffset = 0;
1752 ds.DispatchGRFStartRegisterForURBData =
1753 tes_prog_data->base.base.dispatch_grf_start_reg;
1754
1755 #if GEN_GEN >= 8
1756 #if GEN_GEN < 11
1757 ds.DispatchMode =
1758 tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8 ?
1759 DISPATCH_MODE_SIMD8_SINGLE_PATCH :
1760 DISPATCH_MODE_SIMD4X2;
1761 #else
1762 assert(tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8);
1763 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
1764 #endif
1765
1766 ds.UserClipDistanceClipTestEnableBitmask =
1767 tes_prog_data->base.clip_distance_mask;
1768 ds.UserClipDistanceCullTestEnableBitmask =
1769 tes_prog_data->base.cull_distance_mask;
1770 #endif
1771
1772 ds.PerThreadScratchSpace = get_scratch_space(tes_bin);
1773 ds.ScratchSpaceBasePointer =
1774 get_scratch_address(&pipeline->base, MESA_SHADER_TESS_EVAL, tes_bin);
1775 }
1776 }
1777
1778 static void
1779 emit_3dstate_gs(struct anv_graphics_pipeline *pipeline)
1780 {
1781 const struct gen_device_info *devinfo = &pipeline->base.device->info;
1782 const struct anv_shader_bin *gs_bin =
1783 pipeline->shaders[MESA_SHADER_GEOMETRY];
1784
1785 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
1786 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_GS), gs);
1787 return;
1788 }
1789
1790 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
1791
1792 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_GS), gs) {
1793 gs.Enable = true;
1794 gs.StatisticsEnable = true;
1795 gs.KernelStartPointer = gs_bin->kernel.offset;
1796 gs.DispatchMode = gs_prog_data->base.dispatch_mode;
1797
1798 gs.SingleProgramFlow = false;
1799 gs.VectorMaskEnable = false;
1800 /* WA_1606682166 */
1801 gs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(gs_bin);
1802 gs.BindingTableEntryCount = get_binding_table_entry_count(gs_bin);
1803 gs.IncludeVertexHandles = gs_prog_data->base.include_vue_handles;
1804 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
1805
1806 if (GEN_GEN == 8) {
1807 /* Broadwell is weird. It needs us to divide by 2. */
1808 gs.MaximumNumberofThreads = devinfo->max_gs_threads / 2 - 1;
1809 } else {
1810 gs.MaximumNumberofThreads = devinfo->max_gs_threads - 1;
1811 }
1812
1813 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
1814 gs.OutputTopology = gs_prog_data->output_topology;
1815 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1816 gs.ControlDataFormat = gs_prog_data->control_data_format;
1817 gs.ControlDataHeaderSize = gs_prog_data->control_data_header_size_hwords;
1818 gs.InstanceControl = MAX2(gs_prog_data->invocations, 1) - 1;
1819 gs.ReorderMode = TRAILING;
1820
1821 #if GEN_GEN >= 8
1822 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
1823 gs.StaticOutput = gs_prog_data->static_vertex_count >= 0;
1824 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count >= 0 ?
1825 gs_prog_data->static_vertex_count : 0;
1826 #endif
1827
1828 gs.VertexURBEntryReadOffset = 0;
1829 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1830 gs.DispatchGRFStartRegisterForURBData =
1831 gs_prog_data->base.base.dispatch_grf_start_reg;
1832
1833 #if GEN_GEN >= 8
1834 gs.UserClipDistanceClipTestEnableBitmask =
1835 gs_prog_data->base.clip_distance_mask;
1836 gs.UserClipDistanceCullTestEnableBitmask =
1837 gs_prog_data->base.cull_distance_mask;
1838 #endif
1839
1840 gs.PerThreadScratchSpace = get_scratch_space(gs_bin);
1841 gs.ScratchSpaceBasePointer =
1842 get_scratch_address(&pipeline->base, MESA_SHADER_GEOMETRY, gs_bin);
1843 }
1844 }
1845
1846 static bool
1847 has_color_buffer_write_enabled(const struct anv_graphics_pipeline *pipeline,
1848 const VkPipelineColorBlendStateCreateInfo *blend)
1849 {
1850 const struct anv_shader_bin *shader_bin =
1851 pipeline->shaders[MESA_SHADER_FRAGMENT];
1852 if (!shader_bin)
1853 return false;
1854
1855 const struct anv_pipeline_bind_map *bind_map = &shader_bin->bind_map;
1856 for (int i = 0; i < bind_map->surface_count; i++) {
1857 struct anv_pipeline_binding *binding = &bind_map->surface_to_descriptor[i];
1858
1859 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
1860 continue;
1861
1862 if (binding->index == UINT32_MAX)
1863 continue;
1864
1865 if (blend && blend->pAttachments[binding->index].colorWriteMask != 0)
1866 return true;
1867 }
1868
1869 return false;
1870 }
1871
1872 static void
1873 emit_3dstate_wm(struct anv_graphics_pipeline *pipeline, struct anv_subpass *subpass,
1874 const VkPipelineInputAssemblyStateCreateInfo *ia,
1875 const VkPipelineRasterizationStateCreateInfo *raster,
1876 const VkPipelineColorBlendStateCreateInfo *blend,
1877 const VkPipelineMultisampleStateCreateInfo *multisample,
1878 const VkPipelineRasterizationLineStateCreateInfoEXT *line)
1879 {
1880 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1881
1882 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_WM), wm) {
1883 wm.StatisticsEnable = true;
1884 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1885 wm.LineAntialiasingRegionWidth = _10pixels;
1886 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1887
1888 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1889 if (wm_prog_data->early_fragment_tests) {
1890 wm.EarlyDepthStencilControl = EDSC_PREPS;
1891 } else if (wm_prog_data->has_side_effects) {
1892 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
1893 } else {
1894 wm.EarlyDepthStencilControl = EDSC_NORMAL;
1895 }
1896
1897 #if GEN_GEN >= 8
1898 /* Gen8 hardware tries to compute ThreadDispatchEnable for us but
1899 * doesn't take into account KillPixels when no depth or stencil
1900 * writes are enabled. In order for occlusion queries to work
1901 * correctly with no attachments, we need to force-enable PS thread
1902 * dispatch.
1903 *
1904 * The BDW docs are pretty clear that that this bit isn't validated
1905 * and probably shouldn't be used in production:
1906 *
1907 * "This must always be set to Normal. This field should not be
1908 * tested for functional validation."
1909 *
1910 * Unfortunately, however, the other mechanism we have for doing this
1911 * is 3DSTATE_PS_EXTRA::PixelShaderHasUAV which causes hangs on BDW.
1912 * Given two bad options, we choose the one which works.
1913 */
1914 if ((wm_prog_data->has_side_effects || wm_prog_data->uses_kill) &&
1915 !has_color_buffer_write_enabled(pipeline, blend))
1916 wm.ForceThreadDispatchEnable = ForceON;
1917 #endif
1918
1919 wm.BarycentricInterpolationMode =
1920 wm_prog_data->barycentric_interp_modes;
1921
1922 #if GEN_GEN < 8
1923 wm.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1924 wm.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1925 wm.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1926 wm.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1927
1928 /* If the subpass has a depth or stencil self-dependency, then we
1929 * need to force the hardware to do the depth/stencil write *after*
1930 * fragment shader execution. Otherwise, the writes may hit memory
1931 * before we get around to fetching from the input attachment and we
1932 * may get the depth or stencil value from the current draw rather
1933 * than the previous one.
1934 */
1935 wm.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1936 wm_prog_data->uses_kill;
1937
1938 if (wm.PixelShaderComputedDepthMode != PSCDEPTH_OFF ||
1939 wm_prog_data->has_side_effects ||
1940 wm.PixelShaderKillsPixel ||
1941 has_color_buffer_write_enabled(pipeline, blend))
1942 wm.ThreadDispatchEnable = true;
1943
1944 if (multisample && multisample->rasterizationSamples > 1) {
1945 if (wm_prog_data->persample_dispatch) {
1946 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1947 } else {
1948 wm.MultisampleDispatchMode = MSDISPMODE_PERPIXEL;
1949 }
1950 } else {
1951 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1952 }
1953 wm.MultisampleRasterizationMode =
1954 gen7_ms_rast_mode(pipeline, ia, raster, multisample);
1955 #endif
1956
1957 wm.LineStippleEnable = line && line->stippledLineEnable;
1958 }
1959 }
1960 }
1961
1962 static void
1963 emit_3dstate_ps(struct anv_graphics_pipeline *pipeline,
1964 const VkPipelineColorBlendStateCreateInfo *blend,
1965 const VkPipelineMultisampleStateCreateInfo *multisample)
1966 {
1967 UNUSED const struct gen_device_info *devinfo = &pipeline->base.device->info;
1968 const struct anv_shader_bin *fs_bin =
1969 pipeline->shaders[MESA_SHADER_FRAGMENT];
1970
1971 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1972 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS), ps) {
1973 #if GEN_GEN == 7
1974 /* Even if no fragments are ever dispatched, gen7 hardware hangs if
1975 * we don't at least set the maximum number of threads.
1976 */
1977 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1978 #endif
1979 }
1980 return;
1981 }
1982
1983 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1984
1985 #if GEN_GEN < 8
1986 /* The hardware wedges if you have this bit set but don't turn on any dual
1987 * source blend factors.
1988 */
1989 bool dual_src_blend = false;
1990 if (wm_prog_data->dual_src_blend && blend) {
1991 for (uint32_t i = 0; i < blend->attachmentCount; i++) {
1992 const VkPipelineColorBlendAttachmentState *bstate =
1993 &blend->pAttachments[i];
1994
1995 if (bstate->blendEnable &&
1996 (is_dual_src_blend_factor(bstate->srcColorBlendFactor) ||
1997 is_dual_src_blend_factor(bstate->dstColorBlendFactor) ||
1998 is_dual_src_blend_factor(bstate->srcAlphaBlendFactor) ||
1999 is_dual_src_blend_factor(bstate->dstAlphaBlendFactor))) {
2000 dual_src_blend = true;
2001 break;
2002 }
2003 }
2004 }
2005 #endif
2006
2007 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS), ps) {
2008 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
2009 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
2010 ps._32PixelDispatchEnable = wm_prog_data->dispatch_32;
2011
2012 /* From the Sky Lake PRM 3DSTATE_PS::32 Pixel Dispatch Enable:
2013 *
2014 * "When NUM_MULTISAMPLES = 16 or FORCE_SAMPLE_COUNT = 16, SIMD32
2015 * Dispatch must not be enabled for PER_PIXEL dispatch mode."
2016 *
2017 * Since 16x MSAA is first introduced on SKL, we don't need to apply
2018 * the workaround on any older hardware.
2019 */
2020 if (GEN_GEN >= 9 && !wm_prog_data->persample_dispatch &&
2021 multisample && multisample->rasterizationSamples == 16) {
2022 assert(ps._8PixelDispatchEnable || ps._16PixelDispatchEnable);
2023 ps._32PixelDispatchEnable = false;
2024 }
2025
2026 ps.KernelStartPointer0 = fs_bin->kernel.offset +
2027 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
2028 ps.KernelStartPointer1 = fs_bin->kernel.offset +
2029 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
2030 ps.KernelStartPointer2 = fs_bin->kernel.offset +
2031 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
2032
2033 ps.SingleProgramFlow = false;
2034 ps.VectorMaskEnable = GEN_GEN >= 8;
2035 /* WA_1606682166 */
2036 ps.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(fs_bin);
2037 ps.BindingTableEntryCount = get_binding_table_entry_count(fs_bin);
2038 ps.PushConstantEnable = wm_prog_data->base.nr_params > 0 ||
2039 wm_prog_data->base.ubo_ranges[0].length;
2040 ps.PositionXYOffsetSelect = wm_prog_data->uses_pos_offset ?
2041 POSOFFSET_SAMPLE: POSOFFSET_NONE;
2042 #if GEN_GEN < 8
2043 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
2044 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
2045 ps.DualSourceBlendEnable = dual_src_blend;
2046 #endif
2047
2048 #if GEN_IS_HASWELL
2049 /* Haswell requires the sample mask to be set in this packet as well
2050 * as in 3DSTATE_SAMPLE_MASK; the values should match.
2051 */
2052 ps.SampleMask = 0xff;
2053 #endif
2054
2055 #if GEN_GEN >= 9
2056 ps.MaximumNumberofThreadsPerPSD = 64 - 1;
2057 #elif GEN_GEN >= 8
2058 ps.MaximumNumberofThreadsPerPSD = 64 - 2;
2059 #else
2060 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
2061 #endif
2062
2063 ps.DispatchGRFStartRegisterForConstantSetupData0 =
2064 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
2065 ps.DispatchGRFStartRegisterForConstantSetupData1 =
2066 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
2067 ps.DispatchGRFStartRegisterForConstantSetupData2 =
2068 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
2069
2070 ps.PerThreadScratchSpace = get_scratch_space(fs_bin);
2071 ps.ScratchSpaceBasePointer =
2072 get_scratch_address(&pipeline->base, MESA_SHADER_FRAGMENT, fs_bin);
2073 }
2074 }
2075
2076 #if GEN_GEN >= 8
2077 static void
2078 emit_3dstate_ps_extra(struct anv_graphics_pipeline *pipeline,
2079 struct anv_subpass *subpass)
2080 {
2081 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
2082
2083 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
2084 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS_EXTRA), ps);
2085 return;
2086 }
2087
2088 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS_EXTRA), ps) {
2089 ps.PixelShaderValid = true;
2090 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
2091 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
2092 ps.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
2093 ps.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
2094 ps.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
2095 ps.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
2096
2097 /* If the subpass has a depth or stencil self-dependency, then we need
2098 * to force the hardware to do the depth/stencil write *after* fragment
2099 * shader execution. Otherwise, the writes may hit memory before we get
2100 * around to fetching from the input attachment and we may get the depth
2101 * or stencil value from the current draw rather than the previous one.
2102 */
2103 ps.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
2104 wm_prog_data->uses_kill;
2105
2106 #if GEN_GEN >= 9
2107 ps.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
2108 ps.PixelShaderPullsBary = wm_prog_data->pulls_bary;
2109
2110 ps.InputCoverageMaskState = ICMS_NONE;
2111 if (wm_prog_data->uses_sample_mask) {
2112 if (wm_prog_data->post_depth_coverage)
2113 ps.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
2114 else
2115 ps.InputCoverageMaskState = ICMS_INNER_CONSERVATIVE;
2116 }
2117 #else
2118 ps.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
2119 #endif
2120 }
2121 }
2122
2123 static void
2124 emit_3dstate_vf_topology(struct anv_graphics_pipeline *pipeline)
2125 {
2126 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_TOPOLOGY), vft) {
2127 vft.PrimitiveTopologyType = pipeline->topology;
2128 }
2129 }
2130 #endif
2131
2132 static void
2133 emit_3dstate_vf_statistics(struct anv_graphics_pipeline *pipeline)
2134 {
2135 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_STATISTICS), vfs) {
2136 vfs.StatisticsEnable = true;
2137 }
2138 }
2139
2140 static void
2141 compute_kill_pixel(struct anv_graphics_pipeline *pipeline,
2142 const VkPipelineMultisampleStateCreateInfo *ms_info,
2143 const struct anv_subpass *subpass)
2144 {
2145 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
2146 pipeline->kill_pixel = false;
2147 return;
2148 }
2149
2150 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
2151
2152 /* This computes the KillPixel portion of the computation for whether or
2153 * not we want to enable the PMA fix on gen8 or gen9. It's given by this
2154 * chunk of the giant formula:
2155 *
2156 * (3DSTATE_PS_EXTRA::PixelShaderKillsPixels ||
2157 * 3DSTATE_PS_EXTRA::oMask Present to RenderTarget ||
2158 * 3DSTATE_PS_BLEND::AlphaToCoverageEnable ||
2159 * 3DSTATE_PS_BLEND::AlphaTestEnable ||
2160 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable)
2161 *
2162 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable is always false and so is
2163 * 3DSTATE_PS_BLEND::AlphaTestEnable since Vulkan doesn't have a concept
2164 * of an alpha test.
2165 */
2166 pipeline->kill_pixel =
2167 subpass->has_ds_self_dep || wm_prog_data->uses_kill ||
2168 wm_prog_data->uses_omask ||
2169 (ms_info && ms_info->alphaToCoverageEnable);
2170 }
2171
2172 #if GEN_GEN == 12
2173 static void
2174 emit_3dstate_primitive_replication(struct anv_graphics_pipeline *pipeline)
2175 {
2176 if (!pipeline->use_primitive_replication) {
2177 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PRIMITIVE_REPLICATION), pr);
2178 return;
2179 }
2180
2181 uint32_t view_mask = pipeline->subpass->view_mask;
2182 int view_count = util_bitcount(view_mask);
2183 assert(view_count > 1 && view_count <= MAX_VIEWS_FOR_PRIMITIVE_REPLICATION);
2184
2185 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PRIMITIVE_REPLICATION), pr) {
2186 pr.ReplicaMask = (1 << view_count) - 1;
2187 pr.ReplicationCount = view_count - 1;
2188
2189 int i = 0, view_index;
2190 for_each_bit(view_index, view_mask) {
2191 pr.RTAIOffset[i] = view_index;
2192 i++;
2193 }
2194 }
2195 }
2196 #endif
2197
2198 static VkResult
2199 genX(graphics_pipeline_create)(
2200 VkDevice _device,
2201 struct anv_pipeline_cache * cache,
2202 const VkGraphicsPipelineCreateInfo* pCreateInfo,
2203 const VkAllocationCallbacks* pAllocator,
2204 VkPipeline* pPipeline)
2205 {
2206 ANV_FROM_HANDLE(anv_device, device, _device);
2207 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
2208 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
2209 struct anv_graphics_pipeline *pipeline;
2210 VkResult result;
2211
2212 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
2213
2214 /* Use the default pipeline cache if none is specified */
2215 if (cache == NULL && device->physical->instance->pipeline_cache_enabled)
2216 cache = &device->default_pipeline_cache;
2217
2218 pipeline = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*pipeline), 8,
2219 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2220 if (pipeline == NULL)
2221 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2222
2223 result = anv_graphics_pipeline_init(pipeline, device, cache,
2224 pCreateInfo, pAllocator);
2225 if (result != VK_SUCCESS) {
2226 vk_free2(&device->vk.alloc, pAllocator, pipeline);
2227 if (result == VK_PIPELINE_COMPILE_REQUIRED_EXT)
2228 *pPipeline = VK_NULL_HANDLE;
2229 return result;
2230 }
2231
2232 /* If rasterization is not enabled, various CreateInfo structs must be
2233 * ignored.
2234 */
2235 const bool raster_enabled =
2236 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable;
2237
2238 const VkPipelineViewportStateCreateInfo *vp_info =
2239 raster_enabled ? pCreateInfo->pViewportState : NULL;
2240
2241 const VkPipelineMultisampleStateCreateInfo *ms_info =
2242 raster_enabled ? pCreateInfo->pMultisampleState : NULL;
2243
2244 const VkPipelineDepthStencilStateCreateInfo *ds_info =
2245 raster_enabled ? pCreateInfo->pDepthStencilState : NULL;
2246
2247 const VkPipelineColorBlendStateCreateInfo *cb_info =
2248 raster_enabled ? pCreateInfo->pColorBlendState : NULL;
2249
2250 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info =
2251 vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
2252 PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
2253
2254 /* Information on which states are considered dynamic. */
2255 const VkPipelineDynamicStateCreateInfo *dyn_info =
2256 pCreateInfo->pDynamicState;
2257 uint32_t dynamic_states = 0;
2258 if (dyn_info) {
2259 for (unsigned i = 0; i < dyn_info->dynamicStateCount; i++)
2260 dynamic_states |=
2261 anv_cmd_dirty_bit_for_vk_dynamic_state(dyn_info->pDynamicStates[i]);
2262 }
2263
2264 enum gen_urb_deref_block_size urb_deref_block_size;
2265 emit_urb_setup(pipeline, &urb_deref_block_size);
2266
2267 assert(pCreateInfo->pVertexInputState);
2268 emit_vertex_input(pipeline, pCreateInfo->pVertexInputState);
2269 assert(pCreateInfo->pRasterizationState);
2270 emit_rs_state(pipeline, pCreateInfo->pInputAssemblyState,
2271 pCreateInfo->pRasterizationState,
2272 ms_info, line_info, dynamic_states, pass, subpass,
2273 urb_deref_block_size);
2274 emit_ms_state(pipeline, ms_info);
2275 emit_ds_state(pipeline, ds_info, dynamic_states, pass, subpass);
2276 emit_cb_state(pipeline, cb_info, ms_info);
2277 compute_kill_pixel(pipeline, ms_info, subpass);
2278
2279 emit_3dstate_clip(pipeline,
2280 pCreateInfo->pInputAssemblyState,
2281 vp_info,
2282 pCreateInfo->pRasterizationState,
2283 dynamic_states);
2284 emit_3dstate_streamout(pipeline, pCreateInfo->pRasterizationState);
2285
2286 #if GEN_GEN == 12
2287 emit_3dstate_primitive_replication(pipeline);
2288 #endif
2289
2290 #if 0
2291 /* From gen7_vs_state.c */
2292
2293 /**
2294 * From Graphics BSpec: 3D-Media-GPGPU Engine > 3D Pipeline Stages >
2295 * Geometry > Geometry Shader > State:
2296 *
2297 * "Note: Because of corruption in IVB:GT2, software needs to flush the
2298 * whole fixed function pipeline when the GS enable changes value in
2299 * the 3DSTATE_GS."
2300 *
2301 * The hardware architects have clarified that in this context "flush the
2302 * whole fixed function pipeline" means to emit a PIPE_CONTROL with the "CS
2303 * Stall" bit set.
2304 */
2305 if (!device->info.is_haswell && !device->info.is_baytrail)
2306 gen7_emit_vs_workaround_flush(brw);
2307 #endif
2308
2309 emit_3dstate_vs(pipeline);
2310 emit_3dstate_hs_te_ds(pipeline, pCreateInfo->pTessellationState);
2311 emit_3dstate_gs(pipeline);
2312 emit_3dstate_sbe(pipeline);
2313 emit_3dstate_wm(pipeline, subpass,
2314 pCreateInfo->pInputAssemblyState,
2315 pCreateInfo->pRasterizationState,
2316 cb_info, ms_info, line_info);
2317 emit_3dstate_ps(pipeline, cb_info, ms_info);
2318 #if GEN_GEN >= 8
2319 emit_3dstate_ps_extra(pipeline, subpass);
2320
2321 if (!(dynamic_states & ANV_CMD_DIRTY_DYNAMIC_PRIMITIVE_TOPOLOGY))
2322 emit_3dstate_vf_topology(pipeline);
2323 #endif
2324 emit_3dstate_vf_statistics(pipeline);
2325
2326 *pPipeline = anv_pipeline_to_handle(&pipeline->base);
2327
2328 return pipeline->base.batch.status;
2329 }
2330
2331 static void
2332 emit_media_cs_state(struct anv_compute_pipeline *pipeline,
2333 const struct anv_device *device)
2334 {
2335 const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
2336
2337 anv_pipeline_setup_l3_config(&pipeline->base, cs_prog_data->base.total_shared > 0);
2338
2339 const struct anv_cs_parameters cs_params = anv_cs_parameters(pipeline);
2340
2341 pipeline->cs_right_mask = brw_cs_right_mask(cs_params.group_size, cs_params.simd_size);
2342
2343 const uint32_t vfe_curbe_allocation =
2344 ALIGN(cs_prog_data->push.per_thread.regs * cs_params.threads +
2345 cs_prog_data->push.cross_thread.regs, 2);
2346
2347 const uint32_t subslices = MAX2(device->physical->subslice_total, 1);
2348
2349 const struct anv_shader_bin *cs_bin = pipeline->cs;
2350 const struct gen_device_info *devinfo = &device->info;
2351
2352 anv_batch_emit(&pipeline->base.batch, GENX(MEDIA_VFE_STATE), vfe) {
2353 #if GEN_GEN > 7
2354 vfe.StackSize = 0;
2355 #else
2356 vfe.GPGPUMode = true;
2357 #endif
2358 vfe.MaximumNumberofThreads =
2359 devinfo->max_cs_threads * subslices - 1;
2360 vfe.NumberofURBEntries = GEN_GEN <= 7 ? 0 : 2;
2361 #if GEN_GEN < 11
2362 vfe.ResetGatewayTimer = true;
2363 #endif
2364 #if GEN_GEN <= 8
2365 vfe.BypassGatewayControl = true;
2366 #endif
2367 vfe.URBEntryAllocationSize = GEN_GEN <= 7 ? 0 : 2;
2368 vfe.CURBEAllocationSize = vfe_curbe_allocation;
2369
2370 if (cs_bin->prog_data->total_scratch) {
2371 if (GEN_GEN >= 8) {
2372 /* Broadwell's Per Thread Scratch Space is in the range [0, 11]
2373 * where 0 = 1k, 1 = 2k, 2 = 4k, ..., 11 = 2M.
2374 */
2375 vfe.PerThreadScratchSpace =
2376 ffs(cs_bin->prog_data->total_scratch) - 11;
2377 } else if (GEN_IS_HASWELL) {
2378 /* Haswell's Per Thread Scratch Space is in the range [0, 10]
2379 * where 0 = 2k, 1 = 4k, 2 = 8k, ..., 10 = 2M.
2380 */
2381 vfe.PerThreadScratchSpace =
2382 ffs(cs_bin->prog_data->total_scratch) - 12;
2383 } else {
2384 /* IVB and BYT use the range [0, 11] to mean [1kB, 12kB]
2385 * where 0 = 1kB, 1 = 2kB, 2 = 3kB, ..., 11 = 12kB.
2386 */
2387 vfe.PerThreadScratchSpace =
2388 cs_bin->prog_data->total_scratch / 1024 - 1;
2389 }
2390 vfe.ScratchSpaceBasePointer =
2391 get_scratch_address(&pipeline->base, MESA_SHADER_COMPUTE, cs_bin);
2392 }
2393 }
2394
2395 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
2396 .KernelStartPointer =
2397 cs_bin->kernel.offset +
2398 brw_cs_prog_data_prog_offset(cs_prog_data, cs_params.simd_size),
2399
2400 /* WA_1606682166 */
2401 .SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(cs_bin),
2402 /* We add 1 because the CS indirect parameters buffer isn't accounted
2403 * for in bind_map.surface_count.
2404 */
2405 .BindingTableEntryCount = 1 + MIN2(cs_bin->bind_map.surface_count, 30),
2406 .BarrierEnable = cs_prog_data->uses_barrier,
2407 .SharedLocalMemorySize =
2408 encode_slm_size(GEN_GEN, cs_prog_data->base.total_shared),
2409
2410 #if !GEN_IS_HASWELL
2411 .ConstantURBEntryReadOffset = 0,
2412 #endif
2413 .ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs,
2414 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2415 .CrossThreadConstantDataReadLength =
2416 cs_prog_data->push.cross_thread.regs,
2417 #endif
2418 #if GEN_GEN >= 12
2419 /* TODO: Check if we are missing workarounds and enable mid-thread
2420 * preemption.
2421 *
2422 * We still have issues with mid-thread preemption (it was already
2423 * disabled by the kernel on gen11, due to missing workarounds). It's
2424 * possible that we are just missing some workarounds, and could enable
2425 * it later, but for now let's disable it to fix a GPU in compute in Car
2426 * Chase (and possibly more).
2427 */
2428 .ThreadPreemptionDisable = true,
2429 #endif
2430
2431 .NumberofThreadsinGPGPUThreadGroup = cs_params.threads,
2432 };
2433 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL,
2434 pipeline->interface_descriptor_data,
2435 &desc);
2436 }
2437
2438 static VkResult
2439 compute_pipeline_create(
2440 VkDevice _device,
2441 struct anv_pipeline_cache * cache,
2442 const VkComputePipelineCreateInfo* pCreateInfo,
2443 const VkAllocationCallbacks* pAllocator,
2444 VkPipeline* pPipeline)
2445 {
2446 ANV_FROM_HANDLE(anv_device, device, _device);
2447 struct anv_compute_pipeline *pipeline;
2448 VkResult result;
2449
2450 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO);
2451
2452 /* Use the default pipeline cache if none is specified */
2453 if (cache == NULL && device->physical->instance->pipeline_cache_enabled)
2454 cache = &device->default_pipeline_cache;
2455
2456 pipeline = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*pipeline), 8,
2457 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2458 if (pipeline == NULL)
2459 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2460
2461 result = anv_pipeline_init(&pipeline->base, device,
2462 ANV_PIPELINE_COMPUTE, pCreateInfo->flags,
2463 pAllocator);
2464 if (result != VK_SUCCESS) {
2465 vk_free2(&device->vk.alloc, pAllocator, pipeline);
2466 return result;
2467 }
2468
2469 anv_batch_set_storage(&pipeline->base.batch, ANV_NULL_ADDRESS,
2470 pipeline->batch_data, sizeof(pipeline->batch_data));
2471
2472 pipeline->cs = NULL;
2473
2474 assert(pCreateInfo->stage.stage == VK_SHADER_STAGE_COMPUTE_BIT);
2475 ANV_FROM_HANDLE(anv_shader_module, module, pCreateInfo->stage.module);
2476 result = anv_pipeline_compile_cs(pipeline, cache, pCreateInfo, module,
2477 pCreateInfo->stage.pName,
2478 pCreateInfo->stage.pSpecializationInfo);
2479 if (result != VK_SUCCESS) {
2480 anv_pipeline_finish(&pipeline->base, device, pAllocator);
2481 vk_free2(&device->vk.alloc, pAllocator, pipeline);
2482 if (result == VK_PIPELINE_COMPILE_REQUIRED_EXT)
2483 *pPipeline = VK_NULL_HANDLE;
2484 return result;
2485 }
2486
2487 emit_media_cs_state(pipeline, device);
2488
2489 *pPipeline = anv_pipeline_to_handle(&pipeline->base);
2490
2491 return pipeline->base.batch.status;
2492 }
2493
2494 VkResult genX(CreateGraphicsPipelines)(
2495 VkDevice _device,
2496 VkPipelineCache pipelineCache,
2497 uint32_t count,
2498 const VkGraphicsPipelineCreateInfo* pCreateInfos,
2499 const VkAllocationCallbacks* pAllocator,
2500 VkPipeline* pPipelines)
2501 {
2502 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
2503
2504 VkResult result = VK_SUCCESS;
2505
2506 unsigned i;
2507 for (i = 0; i < count; i++) {
2508 VkResult res = genX(graphics_pipeline_create)(_device,
2509 pipeline_cache,
2510 &pCreateInfos[i],
2511 pAllocator, &pPipelines[i]);
2512
2513 if (res == VK_SUCCESS)
2514 continue;
2515
2516 /* Bail out on the first error != VK_PIPELINE_COMPILE_REQUIRED_EX as it
2517 * is not obvious what error should be report upon 2 different failures.
2518 * */
2519 result = res;
2520 if (res != VK_PIPELINE_COMPILE_REQUIRED_EXT)
2521 break;
2522
2523 if (pCreateInfos[i].flags & VK_PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT)
2524 break;
2525 }
2526
2527 for (; i < count; i++)
2528 pPipelines[i] = VK_NULL_HANDLE;
2529
2530 return result;
2531 }
2532
2533 VkResult genX(CreateComputePipelines)(
2534 VkDevice _device,
2535 VkPipelineCache pipelineCache,
2536 uint32_t count,
2537 const VkComputePipelineCreateInfo* pCreateInfos,
2538 const VkAllocationCallbacks* pAllocator,
2539 VkPipeline* pPipelines)
2540 {
2541 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
2542
2543 VkResult result = VK_SUCCESS;
2544
2545 unsigned i;
2546 for (i = 0; i < count; i++) {
2547 VkResult res = compute_pipeline_create(_device, pipeline_cache,
2548 &pCreateInfos[i],
2549 pAllocator, &pPipelines[i]);
2550
2551 if (res == VK_SUCCESS)
2552 continue;
2553
2554 /* Bail out on the first error != VK_PIPELINE_COMPILE_REQUIRED_EX as it
2555 * is not obvious what error should be report upon 2 different failures.
2556 * */
2557 result = res;
2558 if (res != VK_PIPELINE_COMPILE_REQUIRED_EXT)
2559 break;
2560
2561 if (pCreateInfos[i].flags & VK_PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT)
2562 break;
2563 }
2564
2565 for (; i < count; i++)
2566 pPipelines[i] = VK_NULL_HANDLE;
2567
2568 return result;
2569 }