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