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