anv/icl: Disable binding table prefetching
[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 "vk_util.h"
32 #include "vk_format_info.h"
33
34 static uint32_t
35 vertex_element_comp_control(enum isl_format format, unsigned comp)
36 {
37 uint8_t bits;
38 switch (comp) {
39 case 0: bits = isl_format_layouts[format].channels.r.bits; break;
40 case 1: bits = isl_format_layouts[format].channels.g.bits; break;
41 case 2: bits = isl_format_layouts[format].channels.b.bits; break;
42 case 3: bits = isl_format_layouts[format].channels.a.bits; break;
43 default: unreachable("Invalid component");
44 }
45
46 /*
47 * Take in account hardware restrictions when dealing with 64-bit floats.
48 *
49 * From Broadwell spec, command reference structures, page 586:
50 * "When SourceElementFormat is set to one of the *64*_PASSTHRU formats,
51 * 64-bit components are stored * in the URB without any conversion. In
52 * this case, vertex elements must be written as 128 or 256 bits, with
53 * VFCOMP_STORE_0 being used to pad the output as required. E.g., if
54 * R64_PASSTHRU is used to copy a 64-bit Red component into the URB,
55 * Component 1 must be specified as VFCOMP_STORE_0 (with Components 2,3
56 * set to VFCOMP_NOSTORE) in order to output a 128-bit vertex element, or
57 * Components 1-3 must be specified as VFCOMP_STORE_0 in order to output
58 * a 256-bit vertex element. Likewise, use of R64G64B64_PASSTHRU requires
59 * Component 3 to be specified as VFCOMP_STORE_0 in order to output a
60 * 256-bit vertex element."
61 */
62 if (bits) {
63 return VFCOMP_STORE_SRC;
64 } else if (comp >= 2 &&
65 !isl_format_layouts[format].channels.b.bits &&
66 isl_format_layouts[format].channels.r.type == ISL_RAW) {
67 /* When emitting 64-bit attributes, we need to write either 128 or 256
68 * bit chunks, using VFCOMP_NOSTORE when not writing the chunk, and
69 * VFCOMP_STORE_0 to pad the written chunk */
70 return VFCOMP_NOSTORE;
71 } else if (comp < 3 ||
72 isl_format_layouts[format].channels.r.type == ISL_RAW) {
73 /* Note we need to pad with value 0, not 1, due hardware restrictions
74 * (see comment above) */
75 return VFCOMP_STORE_0;
76 } else if (isl_format_layouts[format].channels.r.type == ISL_UINT ||
77 isl_format_layouts[format].channels.r.type == ISL_SINT) {
78 assert(comp == 3);
79 return VFCOMP_STORE_1_INT;
80 } else {
81 assert(comp == 3);
82 return VFCOMP_STORE_1_FP;
83 }
84 }
85
86 static void
87 emit_vertex_input(struct anv_pipeline *pipeline,
88 const VkPipelineVertexInputStateCreateInfo *info)
89 {
90 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
91
92 /* Pull inputs_read out of the VS prog data */
93 const uint64_t inputs_read = vs_prog_data->inputs_read;
94 const uint64_t double_inputs_read = vs_prog_data->double_inputs_read;
95 assert((inputs_read & ((1 << VERT_ATTRIB_GENERIC0) - 1)) == 0);
96 const uint32_t elements = inputs_read >> VERT_ATTRIB_GENERIC0;
97 const uint32_t elements_double = double_inputs_read >> VERT_ATTRIB_GENERIC0;
98 const bool needs_svgs_elem = vs_prog_data->uses_vertexid ||
99 vs_prog_data->uses_instanceid ||
100 vs_prog_data->uses_firstvertex ||
101 vs_prog_data->uses_baseinstance;
102
103 uint32_t elem_count = __builtin_popcount(elements) -
104 __builtin_popcount(elements_double) / 2;
105
106 const uint32_t total_elems =
107 elem_count + needs_svgs_elem + vs_prog_data->uses_drawid;
108 if (total_elems == 0)
109 return;
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 memset(p + 1, 0, (num_dwords - 1) * 4);
119
120 for (uint32_t i = 0; i < info->vertexAttributeDescriptionCount; i++) {
121 const VkVertexInputAttributeDescription *desc =
122 &info->pVertexAttributeDescriptions[i];
123 enum isl_format format = anv_get_isl_format(&pipeline->device->info,
124 desc->format,
125 VK_IMAGE_ASPECT_COLOR_BIT,
126 VK_IMAGE_TILING_LINEAR);
127
128 assert(desc->binding < MAX_VBS);
129
130 if ((elements & (1 << desc->location)) == 0)
131 continue; /* Binding unused */
132
133 uint32_t slot =
134 __builtin_popcount(elements & ((1 << desc->location) - 1)) -
135 DIV_ROUND_UP(__builtin_popcount(elements_double &
136 ((1 << desc->location) -1)), 2);
137
138 struct GENX(VERTEX_ELEMENT_STATE) element = {
139 .VertexBufferIndex = desc->binding,
140 .Valid = true,
141 .SourceElementFormat = format,
142 .EdgeFlagEnable = false,
143 .SourceElementOffset = desc->offset,
144 .Component0Control = vertex_element_comp_control(format, 0),
145 .Component1Control = vertex_element_comp_control(format, 1),
146 .Component2Control = vertex_element_comp_control(format, 2),
147 .Component3Control = vertex_element_comp_control(format, 3),
148 };
149 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + slot * 2], &element);
150
151 #if GEN_GEN >= 8
152 /* On Broadwell and later, we have a separate VF_INSTANCING packet
153 * that controls instancing. On Haswell and prior, that's part of
154 * VERTEX_BUFFER_STATE which we emit later.
155 */
156 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
157 vfi.InstancingEnable = pipeline->vb[desc->binding].instanced;
158 vfi.VertexElementIndex = slot;
159 vfi.InstanceDataStepRate =
160 pipeline->vb[desc->binding].instance_divisor;
161 }
162 #endif
163 }
164
165 const uint32_t id_slot = elem_count;
166 if (needs_svgs_elem) {
167 /* From the Broadwell PRM for the 3D_Vertex_Component_Control enum:
168 * "Within a VERTEX_ELEMENT_STATE structure, if a Component
169 * Control field is set to something other than VFCOMP_STORE_SRC,
170 * no higher-numbered Component Control fields may be set to
171 * VFCOMP_STORE_SRC"
172 *
173 * This means, that if we have BaseInstance, we need BaseVertex as
174 * well. Just do all or nothing.
175 */
176 uint32_t base_ctrl = (vs_prog_data->uses_firstvertex ||
177 vs_prog_data->uses_baseinstance) ?
178 VFCOMP_STORE_SRC : VFCOMP_STORE_0;
179
180 struct GENX(VERTEX_ELEMENT_STATE) element = {
181 .VertexBufferIndex = ANV_SVGS_VB_INDEX,
182 .Valid = true,
183 .SourceElementFormat = ISL_FORMAT_R32G32_UINT,
184 .Component0Control = base_ctrl,
185 .Component1Control = base_ctrl,
186 #if GEN_GEN >= 8
187 .Component2Control = VFCOMP_STORE_0,
188 .Component3Control = VFCOMP_STORE_0,
189 #else
190 .Component2Control = VFCOMP_STORE_VID,
191 .Component3Control = VFCOMP_STORE_IID,
192 #endif
193 };
194 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + id_slot * 2], &element);
195 }
196
197 #if GEN_GEN >= 8
198 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_SGVS), sgvs) {
199 sgvs.VertexIDEnable = vs_prog_data->uses_vertexid;
200 sgvs.VertexIDComponentNumber = 2;
201 sgvs.VertexIDElementOffset = id_slot;
202 sgvs.InstanceIDEnable = vs_prog_data->uses_instanceid;
203 sgvs.InstanceIDComponentNumber = 3;
204 sgvs.InstanceIDElementOffset = id_slot;
205 }
206 #endif
207
208 const uint32_t drawid_slot = elem_count + needs_svgs_elem;
209 if (vs_prog_data->uses_drawid) {
210 struct GENX(VERTEX_ELEMENT_STATE) element = {
211 .VertexBufferIndex = ANV_DRAWID_VB_INDEX,
212 .Valid = true,
213 .SourceElementFormat = ISL_FORMAT_R32_UINT,
214 .Component0Control = VFCOMP_STORE_SRC,
215 .Component1Control = VFCOMP_STORE_0,
216 .Component2Control = VFCOMP_STORE_0,
217 .Component3Control = VFCOMP_STORE_0,
218 };
219 GENX(VERTEX_ELEMENT_STATE_pack)(NULL,
220 &p[1 + drawid_slot * 2],
221 &element);
222
223 #if GEN_GEN >= 8
224 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
225 vfi.VertexElementIndex = drawid_slot;
226 }
227 #endif
228 }
229 }
230
231 void
232 genX(emit_urb_setup)(struct anv_device *device, struct anv_batch *batch,
233 const struct gen_l3_config *l3_config,
234 VkShaderStageFlags active_stages,
235 const unsigned entry_size[4])
236 {
237 const struct gen_device_info *devinfo = &device->info;
238 #if GEN_IS_HASWELL
239 const unsigned push_constant_kb = devinfo->gt == 3 ? 32 : 16;
240 #else
241 const unsigned push_constant_kb = GEN_GEN >= 8 ? 32 : 16;
242 #endif
243
244 const unsigned urb_size_kb = gen_get_l3_config_urb_size(devinfo, l3_config);
245
246 unsigned entries[4];
247 unsigned start[4];
248 gen_get_urb_config(devinfo,
249 1024 * push_constant_kb, 1024 * urb_size_kb,
250 active_stages &
251 VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
252 active_stages & VK_SHADER_STAGE_GEOMETRY_BIT,
253 entry_size, entries, start);
254
255 #if GEN_GEN == 7 && !GEN_IS_HASWELL
256 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
257 *
258 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth stall
259 * needs to be sent just prior to any 3DSTATE_VS, 3DSTATE_URB_VS,
260 * 3DSTATE_CONSTANT_VS, 3DSTATE_BINDING_TABLE_POINTER_VS,
261 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one PIPE_CONTROL
262 * needs to be sent before any combination of VS associated 3DSTATE."
263 */
264 anv_batch_emit(batch, GEN7_PIPE_CONTROL, pc) {
265 pc.DepthStallEnable = true;
266 pc.PostSyncOperation = WriteImmediateData;
267 pc.Address = (struct anv_address) { &device->workaround_bo, 0 };
268 }
269 #endif
270
271 for (int i = 0; i <= MESA_SHADER_GEOMETRY; i++) {
272 anv_batch_emit(batch, GENX(3DSTATE_URB_VS), urb) {
273 urb._3DCommandSubOpcode += i;
274 urb.VSURBStartingAddress = start[i];
275 urb.VSURBEntryAllocationSize = entry_size[i] - 1;
276 urb.VSNumberofURBEntries = entries[i];
277 }
278 }
279 }
280
281 static void
282 emit_urb_setup(struct anv_pipeline *pipeline)
283 {
284 unsigned entry_size[4];
285 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
286 const struct brw_vue_prog_data *prog_data =
287 !anv_pipeline_has_stage(pipeline, i) ? NULL :
288 (const struct brw_vue_prog_data *) pipeline->shaders[i]->prog_data;
289
290 entry_size[i] = prog_data ? prog_data->urb_entry_size : 1;
291 }
292
293 genX(emit_urb_setup)(pipeline->device, &pipeline->batch,
294 pipeline->urb.l3_config,
295 pipeline->active_stages, entry_size);
296 }
297
298 static void
299 emit_3dstate_sbe(struct anv_pipeline *pipeline)
300 {
301 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
302
303 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
304 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE), sbe);
305 #if GEN_GEN >= 8
306 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ), sbe);
307 #endif
308 return;
309 }
310
311 const struct brw_vue_map *fs_input_map =
312 &anv_pipeline_get_last_vue_prog_data(pipeline)->vue_map;
313
314 struct GENX(3DSTATE_SBE) sbe = {
315 GENX(3DSTATE_SBE_header),
316 .AttributeSwizzleEnable = true,
317 .PointSpriteTextureCoordinateOrigin = UPPERLEFT,
318 .NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs,
319 .ConstantInterpolationEnable = wm_prog_data->flat_inputs,
320 };
321
322 #if GEN_GEN >= 9
323 for (unsigned i = 0; i < 32; i++)
324 sbe.AttributeActiveComponentFormat[i] = ACF_XYZW;
325 #endif
326
327 #if GEN_GEN >= 8
328 /* On Broadwell, they broke 3DSTATE_SBE into two packets */
329 struct GENX(3DSTATE_SBE_SWIZ) swiz = {
330 GENX(3DSTATE_SBE_SWIZ_header),
331 };
332 #else
333 # define swiz sbe
334 #endif
335
336 /* Skip the VUE header and position slots by default */
337 unsigned urb_entry_read_offset = 1;
338 int max_source_attr = 0;
339 for (int attr = 0; attr < VARYING_SLOT_MAX; attr++) {
340 int input_index = wm_prog_data->urb_setup[attr];
341
342 if (input_index < 0)
343 continue;
344
345 /* gl_Layer is stored in the VUE header */
346 if (attr == VARYING_SLOT_LAYER) {
347 urb_entry_read_offset = 0;
348 continue;
349 }
350
351 if (attr == VARYING_SLOT_PNTC) {
352 sbe.PointSpriteTextureCoordinateEnable = 1 << input_index;
353 continue;
354 }
355
356 const int slot = fs_input_map->varying_to_slot[attr];
357
358 if (input_index >= 16)
359 continue;
360
361 if (slot == -1) {
362 /* This attribute does not exist in the VUE--that means that the
363 * vertex shader did not write to it. It could be that it's a
364 * regular varying read by the fragment shader but not written by
365 * the vertex shader or it's gl_PrimitiveID. In the first case the
366 * value is undefined, in the second it needs to be
367 * gl_PrimitiveID.
368 */
369 swiz.Attribute[input_index].ConstantSource = PRIM_ID;
370 swiz.Attribute[input_index].ComponentOverrideX = true;
371 swiz.Attribute[input_index].ComponentOverrideY = true;
372 swiz.Attribute[input_index].ComponentOverrideZ = true;
373 swiz.Attribute[input_index].ComponentOverrideW = true;
374 } else {
375 /* We have to subtract two slots to accout for the URB entry output
376 * read offset in the VS and GS stages.
377 */
378 const int source_attr = slot - 2 * urb_entry_read_offset;
379 assert(source_attr >= 0 && source_attr < 32);
380 max_source_attr = MAX2(max_source_attr, source_attr);
381 swiz.Attribute[input_index].SourceAttribute = source_attr;
382 }
383 }
384
385 sbe.VertexURBEntryReadOffset = urb_entry_read_offset;
386 sbe.VertexURBEntryReadLength = DIV_ROUND_UP(max_source_attr + 1, 2);
387 #if GEN_GEN >= 8
388 sbe.ForceVertexURBEntryReadOffset = true;
389 sbe.ForceVertexURBEntryReadLength = true;
390 #endif
391
392 uint32_t *dw = anv_batch_emit_dwords(&pipeline->batch,
393 GENX(3DSTATE_SBE_length));
394 if (!dw)
395 return;
396 GENX(3DSTATE_SBE_pack)(&pipeline->batch, dw, &sbe);
397
398 #if GEN_GEN >= 8
399 dw = anv_batch_emit_dwords(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ_length));
400 if (!dw)
401 return;
402 GENX(3DSTATE_SBE_SWIZ_pack)(&pipeline->batch, dw, &swiz);
403 #endif
404 }
405
406 static const uint32_t vk_to_gen_cullmode[] = {
407 [VK_CULL_MODE_NONE] = CULLMODE_NONE,
408 [VK_CULL_MODE_FRONT_BIT] = CULLMODE_FRONT,
409 [VK_CULL_MODE_BACK_BIT] = CULLMODE_BACK,
410 [VK_CULL_MODE_FRONT_AND_BACK] = CULLMODE_BOTH
411 };
412
413 static const uint32_t vk_to_gen_fillmode[] = {
414 [VK_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
415 [VK_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
416 [VK_POLYGON_MODE_POINT] = FILL_MODE_POINT,
417 };
418
419 static const uint32_t vk_to_gen_front_face[] = {
420 [VK_FRONT_FACE_COUNTER_CLOCKWISE] = 1,
421 [VK_FRONT_FACE_CLOCKWISE] = 0
422 };
423
424 static void
425 emit_rs_state(struct anv_pipeline *pipeline,
426 const VkPipelineRasterizationStateCreateInfo *rs_info,
427 const VkPipelineMultisampleStateCreateInfo *ms_info,
428 const struct anv_render_pass *pass,
429 const struct anv_subpass *subpass)
430 {
431 struct GENX(3DSTATE_SF) sf = {
432 GENX(3DSTATE_SF_header),
433 };
434
435 sf.ViewportTransformEnable = true;
436 sf.StatisticsEnable = true;
437 sf.TriangleStripListProvokingVertexSelect = 0;
438 sf.LineStripListProvokingVertexSelect = 0;
439 sf.TriangleFanProvokingVertexSelect = 1;
440
441 const struct brw_vue_prog_data *last_vue_prog_data =
442 anv_pipeline_get_last_vue_prog_data(pipeline);
443
444 if (last_vue_prog_data->vue_map.slots_valid & VARYING_BIT_PSIZ) {
445 sf.PointWidthSource = Vertex;
446 } else {
447 sf.PointWidthSource = State;
448 sf.PointWidth = 1.0;
449 }
450
451 #if GEN_GEN >= 8
452 struct GENX(3DSTATE_RASTER) raster = {
453 GENX(3DSTATE_RASTER_header),
454 };
455 #else
456 # define raster sf
457 #endif
458
459 /* For details on 3DSTATE_RASTER multisample state, see the BSpec table
460 * "Multisample Modes State".
461 */
462 #if GEN_GEN >= 8
463 raster.DXMultisampleRasterizationEnable = true;
464 /* NOTE: 3DSTATE_RASTER::ForcedSampleCount affects the BDW and SKL PMA fix
465 * computations. If we ever set this bit to a different value, they will
466 * need to be updated accordingly.
467 */
468 raster.ForcedSampleCount = FSC_NUMRASTSAMPLES_0;
469 raster.ForceMultisampling = false;
470 #else
471 raster.MultisampleRasterizationMode =
472 (ms_info && ms_info->rasterizationSamples > 1) ?
473 MSRASTMODE_ON_PATTERN : MSRASTMODE_OFF_PIXEL;
474 #endif
475
476 raster.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
477 raster.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
478 raster.FrontFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
479 raster.BackFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
480 raster.ScissorRectangleEnable = true;
481
482 #if GEN_GEN >= 9
483 /* GEN9+ splits ViewportZClipTestEnable into near and far enable bits */
484 raster.ViewportZFarClipTestEnable = !pipeline->depth_clamp_enable;
485 raster.ViewportZNearClipTestEnable = !pipeline->depth_clamp_enable;
486 #elif GEN_GEN >= 8
487 raster.ViewportZClipTestEnable = !pipeline->depth_clamp_enable;
488 #endif
489
490 raster.GlobalDepthOffsetEnableSolid = rs_info->depthBiasEnable;
491 raster.GlobalDepthOffsetEnableWireframe = rs_info->depthBiasEnable;
492 raster.GlobalDepthOffsetEnablePoint = rs_info->depthBiasEnable;
493
494 #if GEN_GEN == 7
495 /* Gen7 requires that we provide the depth format in 3DSTATE_SF so that it
496 * can get the depth offsets correct.
497 */
498 if (subpass->depth_stencil_attachment) {
499 VkFormat vk_format =
500 pass->attachments[subpass->depth_stencil_attachment->attachment].format;
501 assert(vk_format_is_depth_or_stencil(vk_format));
502 if (vk_format_aspects(vk_format) & VK_IMAGE_ASPECT_DEPTH_BIT) {
503 enum isl_format isl_format =
504 anv_get_isl_format(&pipeline->device->info, vk_format,
505 VK_IMAGE_ASPECT_DEPTH_BIT,
506 VK_IMAGE_TILING_OPTIMAL);
507 sf.DepthBufferSurfaceFormat =
508 isl_format_get_depth_format(isl_format, false);
509 }
510 }
511 #endif
512
513 #if GEN_GEN >= 8
514 GENX(3DSTATE_SF_pack)(NULL, pipeline->gen8.sf, &sf);
515 GENX(3DSTATE_RASTER_pack)(NULL, pipeline->gen8.raster, &raster);
516 #else
517 # undef raster
518 GENX(3DSTATE_SF_pack)(NULL, &pipeline->gen7.sf, &sf);
519 #endif
520 }
521
522 static void
523 emit_ms_state(struct anv_pipeline *pipeline,
524 const VkPipelineMultisampleStateCreateInfo *info)
525 {
526 uint32_t samples = 1;
527 uint32_t log2_samples = 0;
528
529 /* From the Vulkan 1.0 spec:
530 * If pSampleMask is NULL, it is treated as if the mask has all bits
531 * enabled, i.e. no coverage is removed from fragments.
532 *
533 * 3DSTATE_SAMPLE_MASK.SampleMask is 16 bits.
534 */
535 #if GEN_GEN >= 8
536 uint32_t sample_mask = 0xffff;
537 #else
538 uint32_t sample_mask = 0xff;
539 #endif
540
541 if (info) {
542 samples = info->rasterizationSamples;
543 log2_samples = __builtin_ffs(samples) - 1;
544 }
545
546 if (info && info->pSampleMask)
547 sample_mask &= info->pSampleMask[0];
548
549 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_MULTISAMPLE), ms) {
550 ms.NumberofMultisamples = log2_samples;
551
552 ms.PixelLocation = CENTER;
553 #if GEN_GEN >= 8
554 /* The PRM says that this bit is valid only for DX9:
555 *
556 * SW can choose to set this bit only for DX9 API. DX10/OGL API's
557 * should not have any effect by setting or not setting this bit.
558 */
559 ms.PixelPositionOffsetEnable = false;
560 #else
561
562 switch (samples) {
563 case 1:
564 GEN_SAMPLE_POS_1X(ms.Sample);
565 break;
566 case 2:
567 GEN_SAMPLE_POS_2X(ms.Sample);
568 break;
569 case 4:
570 GEN_SAMPLE_POS_4X(ms.Sample);
571 break;
572 case 8:
573 GEN_SAMPLE_POS_8X(ms.Sample);
574 break;
575 default:
576 break;
577 }
578 #endif
579 }
580
581 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SAMPLE_MASK), sm) {
582 sm.SampleMask = sample_mask;
583 }
584 }
585
586 static const uint32_t vk_to_gen_logic_op[] = {
587 [VK_LOGIC_OP_COPY] = LOGICOP_COPY,
588 [VK_LOGIC_OP_CLEAR] = LOGICOP_CLEAR,
589 [VK_LOGIC_OP_AND] = LOGICOP_AND,
590 [VK_LOGIC_OP_AND_REVERSE] = LOGICOP_AND_REVERSE,
591 [VK_LOGIC_OP_AND_INVERTED] = LOGICOP_AND_INVERTED,
592 [VK_LOGIC_OP_NO_OP] = LOGICOP_NOOP,
593 [VK_LOGIC_OP_XOR] = LOGICOP_XOR,
594 [VK_LOGIC_OP_OR] = LOGICOP_OR,
595 [VK_LOGIC_OP_NOR] = LOGICOP_NOR,
596 [VK_LOGIC_OP_EQUIVALENT] = LOGICOP_EQUIV,
597 [VK_LOGIC_OP_INVERT] = LOGICOP_INVERT,
598 [VK_LOGIC_OP_OR_REVERSE] = LOGICOP_OR_REVERSE,
599 [VK_LOGIC_OP_COPY_INVERTED] = LOGICOP_COPY_INVERTED,
600 [VK_LOGIC_OP_OR_INVERTED] = LOGICOP_OR_INVERTED,
601 [VK_LOGIC_OP_NAND] = LOGICOP_NAND,
602 [VK_LOGIC_OP_SET] = LOGICOP_SET,
603 };
604
605 static const uint32_t vk_to_gen_blend[] = {
606 [VK_BLEND_FACTOR_ZERO] = BLENDFACTOR_ZERO,
607 [VK_BLEND_FACTOR_ONE] = BLENDFACTOR_ONE,
608 [VK_BLEND_FACTOR_SRC_COLOR] = BLENDFACTOR_SRC_COLOR,
609 [VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR] = BLENDFACTOR_INV_SRC_COLOR,
610 [VK_BLEND_FACTOR_DST_COLOR] = BLENDFACTOR_DST_COLOR,
611 [VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR] = BLENDFACTOR_INV_DST_COLOR,
612 [VK_BLEND_FACTOR_SRC_ALPHA] = BLENDFACTOR_SRC_ALPHA,
613 [VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA] = BLENDFACTOR_INV_SRC_ALPHA,
614 [VK_BLEND_FACTOR_DST_ALPHA] = BLENDFACTOR_DST_ALPHA,
615 [VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA] = BLENDFACTOR_INV_DST_ALPHA,
616 [VK_BLEND_FACTOR_CONSTANT_COLOR] = BLENDFACTOR_CONST_COLOR,
617 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR]= BLENDFACTOR_INV_CONST_COLOR,
618 [VK_BLEND_FACTOR_CONSTANT_ALPHA] = BLENDFACTOR_CONST_ALPHA,
619 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA]= BLENDFACTOR_INV_CONST_ALPHA,
620 [VK_BLEND_FACTOR_SRC_ALPHA_SATURATE] = BLENDFACTOR_SRC_ALPHA_SATURATE,
621 [VK_BLEND_FACTOR_SRC1_COLOR] = BLENDFACTOR_SRC1_COLOR,
622 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR] = BLENDFACTOR_INV_SRC1_COLOR,
623 [VK_BLEND_FACTOR_SRC1_ALPHA] = BLENDFACTOR_SRC1_ALPHA,
624 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA] = BLENDFACTOR_INV_SRC1_ALPHA,
625 };
626
627 static const uint32_t vk_to_gen_blend_op[] = {
628 [VK_BLEND_OP_ADD] = BLENDFUNCTION_ADD,
629 [VK_BLEND_OP_SUBTRACT] = BLENDFUNCTION_SUBTRACT,
630 [VK_BLEND_OP_REVERSE_SUBTRACT] = BLENDFUNCTION_REVERSE_SUBTRACT,
631 [VK_BLEND_OP_MIN] = BLENDFUNCTION_MIN,
632 [VK_BLEND_OP_MAX] = BLENDFUNCTION_MAX,
633 };
634
635 static const uint32_t vk_to_gen_compare_op[] = {
636 [VK_COMPARE_OP_NEVER] = PREFILTEROPNEVER,
637 [VK_COMPARE_OP_LESS] = PREFILTEROPLESS,
638 [VK_COMPARE_OP_EQUAL] = PREFILTEROPEQUAL,
639 [VK_COMPARE_OP_LESS_OR_EQUAL] = PREFILTEROPLEQUAL,
640 [VK_COMPARE_OP_GREATER] = PREFILTEROPGREATER,
641 [VK_COMPARE_OP_NOT_EQUAL] = PREFILTEROPNOTEQUAL,
642 [VK_COMPARE_OP_GREATER_OR_EQUAL] = PREFILTEROPGEQUAL,
643 [VK_COMPARE_OP_ALWAYS] = PREFILTEROPALWAYS,
644 };
645
646 static const uint32_t vk_to_gen_stencil_op[] = {
647 [VK_STENCIL_OP_KEEP] = STENCILOP_KEEP,
648 [VK_STENCIL_OP_ZERO] = STENCILOP_ZERO,
649 [VK_STENCIL_OP_REPLACE] = STENCILOP_REPLACE,
650 [VK_STENCIL_OP_INCREMENT_AND_CLAMP] = STENCILOP_INCRSAT,
651 [VK_STENCIL_OP_DECREMENT_AND_CLAMP] = STENCILOP_DECRSAT,
652 [VK_STENCIL_OP_INVERT] = STENCILOP_INVERT,
653 [VK_STENCIL_OP_INCREMENT_AND_WRAP] = STENCILOP_INCR,
654 [VK_STENCIL_OP_DECREMENT_AND_WRAP] = STENCILOP_DECR,
655 };
656
657 /* This function sanitizes the VkStencilOpState by looking at the compare ops
658 * and trying to determine whether or not a given stencil op can ever actually
659 * occur. Stencil ops which can never occur are set to VK_STENCIL_OP_KEEP.
660 * This function returns true if, after sanitation, any of the stencil ops are
661 * set to something other than VK_STENCIL_OP_KEEP.
662 */
663 static bool
664 sanitize_stencil_face(VkStencilOpState *face,
665 VkCompareOp depthCompareOp)
666 {
667 /* If compareOp is ALWAYS then the stencil test will never fail and failOp
668 * will never happen. Set failOp to KEEP in this case.
669 */
670 if (face->compareOp == VK_COMPARE_OP_ALWAYS)
671 face->failOp = VK_STENCIL_OP_KEEP;
672
673 /* If compareOp is NEVER or depthCompareOp is NEVER then one of the depth
674 * or stencil tests will fail and passOp will never happen.
675 */
676 if (face->compareOp == VK_COMPARE_OP_NEVER ||
677 depthCompareOp == VK_COMPARE_OP_NEVER)
678 face->passOp = VK_STENCIL_OP_KEEP;
679
680 /* If compareOp is NEVER or depthCompareOp is ALWAYS then either the
681 * stencil test will fail or the depth test will pass. In either case,
682 * depthFailOp will never happen.
683 */
684 if (face->compareOp == VK_COMPARE_OP_NEVER ||
685 depthCompareOp == VK_COMPARE_OP_ALWAYS)
686 face->depthFailOp = VK_STENCIL_OP_KEEP;
687
688 return face->failOp != VK_STENCIL_OP_KEEP ||
689 face->depthFailOp != VK_STENCIL_OP_KEEP ||
690 face->passOp != VK_STENCIL_OP_KEEP;
691 }
692
693 /* Intel hardware is fairly sensitive to whether or not depth/stencil writes
694 * are enabled. In the presence of discards, it's fairly easy to get into the
695 * non-promoted case which means a fairly big performance hit. From the Iron
696 * Lake PRM, Vol 2, pt. 1, section 8.4.3.2, "Early Depth Test Cases":
697 *
698 * "Non-promoted depth (N) is active whenever the depth test can be done
699 * early but it cannot determine whether or not to write source depth to
700 * the depth buffer, therefore the depth write must be performed post pixel
701 * shader. This includes cases where the pixel shader can kill pixels,
702 * including via sampler chroma key, as well as cases where the alpha test
703 * function is enabled, which kills pixels based on a programmable alpha
704 * test. In this case, even if the depth test fails, the pixel cannot be
705 * killed if a stencil write is indicated. Whether or not the stencil write
706 * happens depends on whether or not the pixel is killed later. In these
707 * cases if stencil test fails and stencil writes are off, the pixels can
708 * also be killed early. If stencil writes are enabled, the pixels must be
709 * treated as Computed depth (described above)."
710 *
711 * The same thing as mentioned in the stencil case can happen in the depth
712 * case as well if it thinks it writes depth but, thanks to the depth test
713 * being GL_EQUAL, the write doesn't actually matter. A little extra work
714 * up-front to try and disable depth and stencil writes can make a big
715 * difference.
716 *
717 * Unfortunately, the way depth and stencil testing is specified, there are
718 * many case where, regardless of depth/stencil writes being enabled, nothing
719 * actually gets written due to some other bit of state being set. This
720 * function attempts to "sanitize" the depth stencil state and disable writes
721 * and sometimes even testing whenever possible.
722 */
723 static void
724 sanitize_ds_state(VkPipelineDepthStencilStateCreateInfo *state,
725 bool *stencilWriteEnable,
726 VkImageAspectFlags ds_aspects)
727 {
728 *stencilWriteEnable = state->stencilTestEnable;
729
730 /* If the depth test is disabled, we won't be writing anything. */
731 if (!state->depthTestEnable)
732 state->depthWriteEnable = false;
733
734 /* The Vulkan spec requires that if either depth or stencil is not present,
735 * the pipeline is to act as if the test silently passes.
736 */
737 if (!(ds_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
738 state->depthWriteEnable = false;
739 state->depthCompareOp = VK_COMPARE_OP_ALWAYS;
740 }
741
742 if (!(ds_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
743 *stencilWriteEnable = false;
744 state->front.compareOp = VK_COMPARE_OP_ALWAYS;
745 state->back.compareOp = VK_COMPARE_OP_ALWAYS;
746 }
747
748 /* If the stencil test is enabled and always fails, then we will never get
749 * to the depth test so we can just disable the depth test entirely.
750 */
751 if (state->stencilTestEnable &&
752 state->front.compareOp == VK_COMPARE_OP_NEVER &&
753 state->back.compareOp == VK_COMPARE_OP_NEVER) {
754 state->depthTestEnable = false;
755 state->depthWriteEnable = false;
756 }
757
758 /* If depthCompareOp is EQUAL then the value we would be writing to the
759 * depth buffer is the same as the value that's already there so there's no
760 * point in writing it.
761 */
762 if (state->depthCompareOp == VK_COMPARE_OP_EQUAL)
763 state->depthWriteEnable = false;
764
765 /* If the stencil ops are such that we don't actually ever modify the
766 * stencil buffer, we should disable writes.
767 */
768 if (!sanitize_stencil_face(&state->front, state->depthCompareOp) &&
769 !sanitize_stencil_face(&state->back, state->depthCompareOp))
770 *stencilWriteEnable = false;
771
772 /* If the depth test always passes and we never write out depth, that's the
773 * same as if the depth test is disabled entirely.
774 */
775 if (state->depthCompareOp == VK_COMPARE_OP_ALWAYS &&
776 !state->depthWriteEnable)
777 state->depthTestEnable = false;
778
779 /* If the stencil test always passes and we never write out stencil, that's
780 * the same as if the stencil test is disabled entirely.
781 */
782 if (state->front.compareOp == VK_COMPARE_OP_ALWAYS &&
783 state->back.compareOp == VK_COMPARE_OP_ALWAYS &&
784 !*stencilWriteEnable)
785 state->stencilTestEnable = false;
786 }
787
788 static void
789 emit_ds_state(struct anv_pipeline *pipeline,
790 const VkPipelineDepthStencilStateCreateInfo *pCreateInfo,
791 const struct anv_render_pass *pass,
792 const struct anv_subpass *subpass)
793 {
794 #if GEN_GEN == 7
795 # define depth_stencil_dw pipeline->gen7.depth_stencil_state
796 #elif GEN_GEN == 8
797 # define depth_stencil_dw pipeline->gen8.wm_depth_stencil
798 #else
799 # define depth_stencil_dw pipeline->gen9.wm_depth_stencil
800 #endif
801
802 if (pCreateInfo == NULL) {
803 /* We're going to OR this together with the dynamic state. We need
804 * to make sure it's initialized to something useful.
805 */
806 pipeline->writes_stencil = false;
807 pipeline->stencil_test_enable = false;
808 pipeline->writes_depth = false;
809 pipeline->depth_test_enable = false;
810 memset(depth_stencil_dw, 0, sizeof(depth_stencil_dw));
811 return;
812 }
813
814 VkImageAspectFlags ds_aspects = 0;
815 if (subpass->depth_stencil_attachment) {
816 VkFormat depth_stencil_format =
817 pass->attachments[subpass->depth_stencil_attachment->attachment].format;
818 ds_aspects = vk_format_aspects(depth_stencil_format);
819 }
820
821 VkPipelineDepthStencilStateCreateInfo info = *pCreateInfo;
822 sanitize_ds_state(&info, &pipeline->writes_stencil, ds_aspects);
823 pipeline->stencil_test_enable = info.stencilTestEnable;
824 pipeline->writes_depth = info.depthWriteEnable;
825 pipeline->depth_test_enable = info.depthTestEnable;
826
827 /* VkBool32 depthBoundsTestEnable; // optional (depth_bounds_test) */
828
829 #if GEN_GEN <= 7
830 struct GENX(DEPTH_STENCIL_STATE) depth_stencil = {
831 #else
832 struct GENX(3DSTATE_WM_DEPTH_STENCIL) depth_stencil = {
833 #endif
834 .DepthTestEnable = info.depthTestEnable,
835 .DepthBufferWriteEnable = info.depthWriteEnable,
836 .DepthTestFunction = vk_to_gen_compare_op[info.depthCompareOp],
837 .DoubleSidedStencilEnable = true,
838
839 .StencilTestEnable = info.stencilTestEnable,
840 .StencilFailOp = vk_to_gen_stencil_op[info.front.failOp],
841 .StencilPassDepthPassOp = vk_to_gen_stencil_op[info.front.passOp],
842 .StencilPassDepthFailOp = vk_to_gen_stencil_op[info.front.depthFailOp],
843 .StencilTestFunction = vk_to_gen_compare_op[info.front.compareOp],
844 .BackfaceStencilFailOp = vk_to_gen_stencil_op[info.back.failOp],
845 .BackfaceStencilPassDepthPassOp = vk_to_gen_stencil_op[info.back.passOp],
846 .BackfaceStencilPassDepthFailOp =vk_to_gen_stencil_op[info.back.depthFailOp],
847 .BackfaceStencilTestFunction = vk_to_gen_compare_op[info.back.compareOp],
848 };
849
850 #if GEN_GEN <= 7
851 GENX(DEPTH_STENCIL_STATE_pack)(NULL, depth_stencil_dw, &depth_stencil);
852 #else
853 GENX(3DSTATE_WM_DEPTH_STENCIL_pack)(NULL, depth_stencil_dw, &depth_stencil);
854 #endif
855 }
856
857 static void
858 emit_cb_state(struct anv_pipeline *pipeline,
859 const VkPipelineColorBlendStateCreateInfo *info,
860 const VkPipelineMultisampleStateCreateInfo *ms_info)
861 {
862 struct anv_device *device = pipeline->device;
863
864
865 struct GENX(BLEND_STATE) blend_state = {
866 #if GEN_GEN >= 8
867 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
868 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
869 #endif
870 };
871
872 uint32_t surface_count = 0;
873 struct anv_pipeline_bind_map *map;
874 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
875 map = &pipeline->shaders[MESA_SHADER_FRAGMENT]->bind_map;
876 surface_count = map->surface_count;
877 }
878
879 const uint32_t num_dwords = GENX(BLEND_STATE_length) +
880 GENX(BLEND_STATE_ENTRY_length) * surface_count;
881 pipeline->blend_state =
882 anv_state_pool_alloc(&device->dynamic_state_pool, num_dwords * 4, 64);
883
884 bool has_writeable_rt = false;
885 uint32_t *state_pos = pipeline->blend_state.map;
886 state_pos += GENX(BLEND_STATE_length);
887 #if GEN_GEN >= 8
888 struct GENX(BLEND_STATE_ENTRY) bs0 = { 0 };
889 #endif
890 for (unsigned i = 0; i < surface_count; i++) {
891 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[i];
892
893 /* All color attachments are at the beginning of the binding table */
894 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
895 break;
896
897 /* We can have at most 8 attachments */
898 assert(i < 8);
899
900 if (info == NULL || binding->index >= info->attachmentCount) {
901 /* Default everything to disabled */
902 struct GENX(BLEND_STATE_ENTRY) entry = {
903 .WriteDisableAlpha = true,
904 .WriteDisableRed = true,
905 .WriteDisableGreen = true,
906 .WriteDisableBlue = true,
907 };
908 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
909 state_pos += GENX(BLEND_STATE_ENTRY_length);
910 continue;
911 }
912
913 assert(binding->binding == 0);
914 const VkPipelineColorBlendAttachmentState *a =
915 &info->pAttachments[binding->index];
916
917 struct GENX(BLEND_STATE_ENTRY) entry = {
918 #if GEN_GEN < 8
919 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
920 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
921 #endif
922 .LogicOpEnable = info->logicOpEnable,
923 .LogicOpFunction = vk_to_gen_logic_op[info->logicOp],
924 .ColorBufferBlendEnable = a->blendEnable,
925 .ColorClampRange = COLORCLAMP_RTFORMAT,
926 .PreBlendColorClampEnable = true,
927 .PostBlendColorClampEnable = true,
928 .SourceBlendFactor = vk_to_gen_blend[a->srcColorBlendFactor],
929 .DestinationBlendFactor = vk_to_gen_blend[a->dstColorBlendFactor],
930 .ColorBlendFunction = vk_to_gen_blend_op[a->colorBlendOp],
931 .SourceAlphaBlendFactor = vk_to_gen_blend[a->srcAlphaBlendFactor],
932 .DestinationAlphaBlendFactor = vk_to_gen_blend[a->dstAlphaBlendFactor],
933 .AlphaBlendFunction = vk_to_gen_blend_op[a->alphaBlendOp],
934 .WriteDisableAlpha = !(a->colorWriteMask & VK_COLOR_COMPONENT_A_BIT),
935 .WriteDisableRed = !(a->colorWriteMask & VK_COLOR_COMPONENT_R_BIT),
936 .WriteDisableGreen = !(a->colorWriteMask & VK_COLOR_COMPONENT_G_BIT),
937 .WriteDisableBlue = !(a->colorWriteMask & VK_COLOR_COMPONENT_B_BIT),
938 };
939
940 if (a->srcColorBlendFactor != a->srcAlphaBlendFactor ||
941 a->dstColorBlendFactor != a->dstAlphaBlendFactor ||
942 a->colorBlendOp != a->alphaBlendOp) {
943 #if GEN_GEN >= 8
944 blend_state.IndependentAlphaBlendEnable = true;
945 #else
946 entry.IndependentAlphaBlendEnable = true;
947 #endif
948 }
949
950 if (a->colorWriteMask != 0)
951 has_writeable_rt = true;
952
953 /* Our hardware applies the blend factor prior to the blend function
954 * regardless of what function is used. Technically, this means the
955 * hardware can do MORE than GL or Vulkan specify. However, it also
956 * means that, for MIN and MAX, we have to stomp the blend factor to
957 * ONE to make it a no-op.
958 */
959 if (a->colorBlendOp == VK_BLEND_OP_MIN ||
960 a->colorBlendOp == VK_BLEND_OP_MAX) {
961 entry.SourceBlendFactor = BLENDFACTOR_ONE;
962 entry.DestinationBlendFactor = BLENDFACTOR_ONE;
963 }
964 if (a->alphaBlendOp == VK_BLEND_OP_MIN ||
965 a->alphaBlendOp == VK_BLEND_OP_MAX) {
966 entry.SourceAlphaBlendFactor = BLENDFACTOR_ONE;
967 entry.DestinationAlphaBlendFactor = BLENDFACTOR_ONE;
968 }
969 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
970 state_pos += GENX(BLEND_STATE_ENTRY_length);
971 #if GEN_GEN >= 8
972 if (i == 0)
973 bs0 = entry;
974 #endif
975 }
976
977 #if GEN_GEN >= 8
978 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_BLEND), blend) {
979 blend.AlphaToCoverageEnable = blend_state.AlphaToCoverageEnable;
980 blend.HasWriteableRT = has_writeable_rt;
981 blend.ColorBufferBlendEnable = bs0.ColorBufferBlendEnable;
982 blend.SourceAlphaBlendFactor = bs0.SourceAlphaBlendFactor;
983 blend.DestinationAlphaBlendFactor = bs0.DestinationAlphaBlendFactor;
984 blend.SourceBlendFactor = bs0.SourceBlendFactor;
985 blend.DestinationBlendFactor = bs0.DestinationBlendFactor;
986 blend.AlphaTestEnable = false;
987 blend.IndependentAlphaBlendEnable =
988 blend_state.IndependentAlphaBlendEnable;
989 }
990 #else
991 (void)has_writeable_rt;
992 #endif
993
994 GENX(BLEND_STATE_pack)(NULL, pipeline->blend_state.map, &blend_state);
995 anv_state_flush(device, pipeline->blend_state);
996
997 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_BLEND_STATE_POINTERS), bsp) {
998 bsp.BlendStatePointer = pipeline->blend_state.offset;
999 #if GEN_GEN >= 8
1000 bsp.BlendStatePointerValid = true;
1001 #endif
1002 }
1003 }
1004
1005 static void
1006 emit_3dstate_clip(struct anv_pipeline *pipeline,
1007 const VkPipelineViewportStateCreateInfo *vp_info,
1008 const VkPipelineRasterizationStateCreateInfo *rs_info)
1009 {
1010 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1011 (void) wm_prog_data;
1012 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_CLIP), clip) {
1013 clip.ClipEnable = true;
1014 clip.StatisticsEnable = true;
1015 clip.EarlyCullEnable = true;
1016 clip.APIMode = APIMODE_D3D,
1017 clip.ViewportXYClipTestEnable = true;
1018
1019 clip.ClipMode = CLIPMODE_NORMAL;
1020
1021 clip.TriangleStripListProvokingVertexSelect = 0;
1022 clip.LineStripListProvokingVertexSelect = 0;
1023 clip.TriangleFanProvokingVertexSelect = 1;
1024
1025 clip.MinimumPointWidth = 0.125;
1026 clip.MaximumPointWidth = 255.875;
1027
1028 const struct brw_vue_prog_data *last =
1029 anv_pipeline_get_last_vue_prog_data(pipeline);
1030
1031 /* From the Vulkan 1.0.45 spec:
1032 *
1033 * "If the last active vertex processing stage shader entry point's
1034 * interface does not include a variable decorated with
1035 * ViewportIndex, then the first viewport is used."
1036 */
1037 if (vp_info && (last->vue_map.slots_valid & VARYING_BIT_VIEWPORT)) {
1038 clip.MaximumVPIndex = vp_info->viewportCount - 1;
1039 } else {
1040 clip.MaximumVPIndex = 0;
1041 }
1042
1043 /* From the Vulkan 1.0.45 spec:
1044 *
1045 * "If the last active vertex processing stage shader entry point's
1046 * interface does not include a variable decorated with Layer, then
1047 * the first layer is used."
1048 */
1049 clip.ForceZeroRTAIndexEnable =
1050 !(last->vue_map.slots_valid & VARYING_BIT_LAYER);
1051
1052 #if GEN_GEN == 7
1053 clip.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
1054 clip.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
1055 clip.ViewportZClipTestEnable = !pipeline->depth_clamp_enable;
1056 if (last) {
1057 clip.UserClipDistanceClipTestEnableBitmask = last->clip_distance_mask;
1058 clip.UserClipDistanceCullTestEnableBitmask = last->cull_distance_mask;
1059 }
1060 #else
1061 clip.NonPerspectiveBarycentricEnable = wm_prog_data ?
1062 (wm_prog_data->barycentric_interp_modes &
1063 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS) != 0 : 0;
1064 #endif
1065 }
1066 }
1067
1068 static void
1069 emit_3dstate_streamout(struct anv_pipeline *pipeline,
1070 const VkPipelineRasterizationStateCreateInfo *rs_info)
1071 {
1072 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_STREAMOUT), so) {
1073 so.RenderingDisable = rs_info->rasterizerDiscardEnable;
1074 }
1075 }
1076
1077 static uint32_t
1078 get_sampler_count(const struct anv_shader_bin *bin)
1079 {
1080 uint32_t count_by_4 = DIV_ROUND_UP(bin->bind_map.sampler_count, 4);
1081
1082 /* We can potentially have way more than 32 samplers and that's ok.
1083 * However, the 3DSTATE_XS packets only have 3 bits to specify how
1084 * many to pre-fetch and all values above 4 are marked reserved.
1085 */
1086 return MIN2(count_by_4, 4);
1087 }
1088
1089 static uint32_t
1090 get_binding_table_entry_count(const struct anv_shader_bin *bin)
1091 {
1092 return DIV_ROUND_UP(bin->bind_map.surface_count, 32);
1093 }
1094
1095 static struct anv_address
1096 get_scratch_address(struct anv_pipeline *pipeline,
1097 gl_shader_stage stage,
1098 const struct anv_shader_bin *bin)
1099 {
1100 return (struct anv_address) {
1101 .bo = anv_scratch_pool_alloc(pipeline->device,
1102 &pipeline->device->scratch_pool,
1103 stage, bin->prog_data->total_scratch),
1104 .offset = 0,
1105 };
1106 }
1107
1108 static uint32_t
1109 get_scratch_space(const struct anv_shader_bin *bin)
1110 {
1111 return ffs(bin->prog_data->total_scratch / 2048);
1112 }
1113
1114 static void
1115 emit_3dstate_vs(struct anv_pipeline *pipeline)
1116 {
1117 const struct gen_device_info *devinfo = &pipeline->device->info;
1118 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
1119 const struct anv_shader_bin *vs_bin =
1120 pipeline->shaders[MESA_SHADER_VERTEX];
1121
1122 assert(anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX));
1123
1124 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VS), vs) {
1125 vs.Enable = true;
1126 vs.StatisticsEnable = true;
1127 vs.KernelStartPointer = vs_bin->kernel.offset;
1128 #if GEN_GEN >= 8
1129 vs.SIMD8DispatchEnable =
1130 vs_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8;
1131 #endif
1132
1133 assert(!vs_prog_data->base.base.use_alt_mode);
1134 #if GEN_GEN < 11
1135 vs.SingleVertexDispatch = false;
1136 #endif
1137 vs.VectorMaskEnable = false;
1138 vs.SamplerCount = get_sampler_count(vs_bin);
1139 /* Gen 11 workarounds table #2056 WABTPPrefetchDisable suggests to
1140 * disable prefetching of binding tables on A0 and B0 steppings.
1141 * TODO: Revisit this WA on newer steppings.
1142 */
1143 vs.BindingTableEntryCount = GEN_GEN == 11 ? 0 : get_binding_table_entry_count(vs_bin);
1144 vs.FloatingPointMode = IEEE754;
1145 vs.IllegalOpcodeExceptionEnable = false;
1146 vs.SoftwareExceptionEnable = false;
1147 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
1148 vs.VertexCacheDisable = false;
1149
1150 vs.VertexURBEntryReadLength = vs_prog_data->base.urb_read_length;
1151 vs.VertexURBEntryReadOffset = 0;
1152 vs.DispatchGRFStartRegisterForURBData =
1153 vs_prog_data->base.base.dispatch_grf_start_reg;
1154
1155 #if GEN_GEN >= 8
1156 vs.UserClipDistanceClipTestEnableBitmask =
1157 vs_prog_data->base.clip_distance_mask;
1158 vs.UserClipDistanceCullTestEnableBitmask =
1159 vs_prog_data->base.cull_distance_mask;
1160 #endif
1161
1162 vs.PerThreadScratchSpace = get_scratch_space(vs_bin);
1163 vs.ScratchSpaceBasePointer =
1164 get_scratch_address(pipeline, MESA_SHADER_VERTEX, vs_bin);
1165 }
1166 }
1167
1168 static void
1169 emit_3dstate_hs_te_ds(struct anv_pipeline *pipeline,
1170 const VkPipelineTessellationStateCreateInfo *tess_info)
1171 {
1172 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
1173 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_HS), hs);
1174 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_TE), te);
1175 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_DS), ds);
1176 return;
1177 }
1178
1179 const struct gen_device_info *devinfo = &pipeline->device->info;
1180 const struct anv_shader_bin *tcs_bin =
1181 pipeline->shaders[MESA_SHADER_TESS_CTRL];
1182 const struct anv_shader_bin *tes_bin =
1183 pipeline->shaders[MESA_SHADER_TESS_EVAL];
1184
1185 const struct brw_tcs_prog_data *tcs_prog_data = get_tcs_prog_data(pipeline);
1186 const struct brw_tes_prog_data *tes_prog_data = get_tes_prog_data(pipeline);
1187
1188 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_HS), hs) {
1189 hs.Enable = true;
1190 hs.StatisticsEnable = true;
1191 hs.KernelStartPointer = tcs_bin->kernel.offset;
1192
1193 hs.SamplerCount = get_sampler_count(tcs_bin);
1194 /* Gen 11 workarounds table #2056 WABTPPrefetchDisable */
1195 hs.BindingTableEntryCount = GEN_GEN == 11 ? 0 : get_binding_table_entry_count(tcs_bin);
1196 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
1197 hs.IncludeVertexHandles = true;
1198 hs.InstanceCount = tcs_prog_data->instances - 1;
1199
1200 hs.VertexURBEntryReadLength = 0;
1201 hs.VertexURBEntryReadOffset = 0;
1202 hs.DispatchGRFStartRegisterForURBData =
1203 tcs_prog_data->base.base.dispatch_grf_start_reg;
1204
1205 hs.PerThreadScratchSpace = get_scratch_space(tcs_bin);
1206 hs.ScratchSpaceBasePointer =
1207 get_scratch_address(pipeline, MESA_SHADER_TESS_CTRL, tcs_bin);
1208 }
1209
1210 const VkPipelineTessellationDomainOriginStateCreateInfoKHR *domain_origin_state =
1211 tess_info ? vk_find_struct_const(tess_info, PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO_KHR) : NULL;
1212
1213 VkTessellationDomainOriginKHR uv_origin =
1214 domain_origin_state ? domain_origin_state->domainOrigin :
1215 VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT_KHR;
1216
1217 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_TE), te) {
1218 te.Partitioning = tes_prog_data->partitioning;
1219
1220 if (uv_origin == VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT_KHR) {
1221 te.OutputTopology = tes_prog_data->output_topology;
1222 } else {
1223 /* When the origin is upper-left, we have to flip the winding order */
1224 if (tes_prog_data->output_topology == OUTPUT_TRI_CCW) {
1225 te.OutputTopology = OUTPUT_TRI_CW;
1226 } else if (tes_prog_data->output_topology == OUTPUT_TRI_CW) {
1227 te.OutputTopology = OUTPUT_TRI_CCW;
1228 } else {
1229 te.OutputTopology = tes_prog_data->output_topology;
1230 }
1231 }
1232
1233 te.TEDomain = tes_prog_data->domain;
1234 te.TEEnable = true;
1235 te.MaximumTessellationFactorOdd = 63.0;
1236 te.MaximumTessellationFactorNotOdd = 64.0;
1237 }
1238
1239 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_DS), ds) {
1240 ds.Enable = true;
1241 ds.StatisticsEnable = true;
1242 ds.KernelStartPointer = tes_bin->kernel.offset;
1243
1244 ds.SamplerCount = get_sampler_count(tes_bin);
1245 /* Gen 11 workarounds table #2056 WABTPPrefetchDisable */
1246 ds.BindingTableEntryCount = GEN_GEN == 11 ? 0 : get_binding_table_entry_count(tes_bin);
1247 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
1248
1249 ds.ComputeWCoordinateEnable =
1250 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
1251
1252 ds.PatchURBEntryReadLength = tes_prog_data->base.urb_read_length;
1253 ds.PatchURBEntryReadOffset = 0;
1254 ds.DispatchGRFStartRegisterForURBData =
1255 tes_prog_data->base.base.dispatch_grf_start_reg;
1256
1257 #if GEN_GEN >= 8
1258 #if GEN_GEN < 11
1259 ds.DispatchMode =
1260 tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8 ?
1261 DISPATCH_MODE_SIMD8_SINGLE_PATCH :
1262 DISPATCH_MODE_SIMD4X2;
1263 #else
1264 assert(tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8);
1265 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
1266 #endif
1267
1268 ds.UserClipDistanceClipTestEnableBitmask =
1269 tes_prog_data->base.clip_distance_mask;
1270 ds.UserClipDistanceCullTestEnableBitmask =
1271 tes_prog_data->base.cull_distance_mask;
1272 #endif
1273
1274 ds.PerThreadScratchSpace = get_scratch_space(tes_bin);
1275 ds.ScratchSpaceBasePointer =
1276 get_scratch_address(pipeline, MESA_SHADER_TESS_EVAL, tes_bin);
1277 }
1278 }
1279
1280 static void
1281 emit_3dstate_gs(struct anv_pipeline *pipeline)
1282 {
1283 const struct gen_device_info *devinfo = &pipeline->device->info;
1284 const struct anv_shader_bin *gs_bin =
1285 pipeline->shaders[MESA_SHADER_GEOMETRY];
1286
1287 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
1288 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs);
1289 return;
1290 }
1291
1292 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
1293
1294 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs) {
1295 gs.Enable = true;
1296 gs.StatisticsEnable = true;
1297 gs.KernelStartPointer = gs_bin->kernel.offset;
1298 gs.DispatchMode = gs_prog_data->base.dispatch_mode;
1299
1300 gs.SingleProgramFlow = false;
1301 gs.VectorMaskEnable = false;
1302 gs.SamplerCount = get_sampler_count(gs_bin);
1303 /* Gen 11 workarounds table #2056 WABTPPrefetchDisable */
1304 gs.BindingTableEntryCount = GEN_GEN == 11 ? 0 : get_binding_table_entry_count(gs_bin);
1305 gs.IncludeVertexHandles = gs_prog_data->base.include_vue_handles;
1306 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
1307
1308 if (GEN_GEN == 8) {
1309 /* Broadwell is weird. It needs us to divide by 2. */
1310 gs.MaximumNumberofThreads = devinfo->max_gs_threads / 2 - 1;
1311 } else {
1312 gs.MaximumNumberofThreads = devinfo->max_gs_threads - 1;
1313 }
1314
1315 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
1316 gs.OutputTopology = gs_prog_data->output_topology;
1317 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1318 gs.ControlDataFormat = gs_prog_data->control_data_format;
1319 gs.ControlDataHeaderSize = gs_prog_data->control_data_header_size_hwords;
1320 gs.InstanceControl = MAX2(gs_prog_data->invocations, 1) - 1;
1321 gs.ReorderMode = TRAILING;
1322
1323 #if GEN_GEN >= 8
1324 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
1325 gs.StaticOutput = gs_prog_data->static_vertex_count >= 0;
1326 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count >= 0 ?
1327 gs_prog_data->static_vertex_count : 0;
1328 #endif
1329
1330 gs.VertexURBEntryReadOffset = 0;
1331 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1332 gs.DispatchGRFStartRegisterForURBData =
1333 gs_prog_data->base.base.dispatch_grf_start_reg;
1334
1335 #if GEN_GEN >= 8
1336 gs.UserClipDistanceClipTestEnableBitmask =
1337 gs_prog_data->base.clip_distance_mask;
1338 gs.UserClipDistanceCullTestEnableBitmask =
1339 gs_prog_data->base.cull_distance_mask;
1340 #endif
1341
1342 gs.PerThreadScratchSpace = get_scratch_space(gs_bin);
1343 gs.ScratchSpaceBasePointer =
1344 get_scratch_address(pipeline, MESA_SHADER_GEOMETRY, gs_bin);
1345 }
1346 }
1347
1348 static bool
1349 has_color_buffer_write_enabled(const struct anv_pipeline *pipeline,
1350 const VkPipelineColorBlendStateCreateInfo *blend)
1351 {
1352 const struct anv_shader_bin *shader_bin =
1353 pipeline->shaders[MESA_SHADER_FRAGMENT];
1354 if (!shader_bin)
1355 return false;
1356
1357 const struct anv_pipeline_bind_map *bind_map = &shader_bin->bind_map;
1358 for (int i = 0; i < bind_map->surface_count; i++) {
1359 struct anv_pipeline_binding *binding = &bind_map->surface_to_descriptor[i];
1360
1361 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
1362 continue;
1363
1364 if (binding->index == UINT32_MAX)
1365 continue;
1366
1367 if (blend && blend->pAttachments[binding->index].colorWriteMask != 0)
1368 return true;
1369 }
1370
1371 return false;
1372 }
1373
1374 static void
1375 emit_3dstate_wm(struct anv_pipeline *pipeline, struct anv_subpass *subpass,
1376 const VkPipelineColorBlendStateCreateInfo *blend,
1377 const VkPipelineMultisampleStateCreateInfo *multisample)
1378 {
1379 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1380
1381 MAYBE_UNUSED uint32_t samples =
1382 multisample ? multisample->rasterizationSamples : 1;
1383
1384 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_WM), wm) {
1385 wm.StatisticsEnable = true;
1386 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1387 wm.LineAntialiasingRegionWidth = _10pixels;
1388 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1389
1390 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1391 if (wm_prog_data->early_fragment_tests) {
1392 wm.EarlyDepthStencilControl = EDSC_PREPS;
1393 } else if (wm_prog_data->has_side_effects) {
1394 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
1395 } else {
1396 wm.EarlyDepthStencilControl = EDSC_NORMAL;
1397 }
1398
1399 #if GEN_GEN >= 8
1400 /* Gen8 hardware tries to compute ThreadDispatchEnable for us but
1401 * doesn't take into account KillPixels when no depth or stencil
1402 * writes are enabled. In order for occlusion queries to work
1403 * correctly with no attachments, we need to force-enable PS thread
1404 * dispatch.
1405 *
1406 * The BDW docs are pretty clear that that this bit isn't validated
1407 * and probably shouldn't be used in production:
1408 *
1409 * "This must always be set to Normal. This field should not be
1410 * tested for functional validation."
1411 *
1412 * Unfortunately, however, the other mechanism we have for doing this
1413 * is 3DSTATE_PS_EXTRA::PixelShaderHasUAV which causes hangs on BDW.
1414 * Given two bad options, we choose the one which works.
1415 */
1416 if ((wm_prog_data->has_side_effects || wm_prog_data->uses_kill) &&
1417 !has_color_buffer_write_enabled(pipeline, blend))
1418 wm.ForceThreadDispatchEnable = ForceON;
1419 #endif
1420
1421 wm.BarycentricInterpolationMode =
1422 wm_prog_data->barycentric_interp_modes;
1423
1424 #if GEN_GEN < 8
1425 wm.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1426 wm.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1427 wm.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1428 wm.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1429
1430 /* If the subpass has a depth or stencil self-dependency, then we
1431 * need to force the hardware to do the depth/stencil write *after*
1432 * fragment shader execution. Otherwise, the writes may hit memory
1433 * before we get around to fetching from the input attachment and we
1434 * may get the depth or stencil value from the current draw rather
1435 * than the previous one.
1436 */
1437 wm.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1438 wm_prog_data->uses_kill;
1439
1440 if (wm.PixelShaderComputedDepthMode != PSCDEPTH_OFF ||
1441 wm_prog_data->has_side_effects ||
1442 wm.PixelShaderKillsPixel ||
1443 has_color_buffer_write_enabled(pipeline, blend))
1444 wm.ThreadDispatchEnable = true;
1445
1446 if (samples > 1) {
1447 wm.MultisampleRasterizationMode = MSRASTMODE_ON_PATTERN;
1448 if (wm_prog_data->persample_dispatch) {
1449 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1450 } else {
1451 wm.MultisampleDispatchMode = MSDISPMODE_PERPIXEL;
1452 }
1453 } else {
1454 wm.MultisampleRasterizationMode = MSRASTMODE_OFF_PIXEL;
1455 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1456 }
1457 #endif
1458 }
1459 }
1460 }
1461
1462 UNUSED static bool
1463 is_dual_src_blend_factor(VkBlendFactor factor)
1464 {
1465 return factor == VK_BLEND_FACTOR_SRC1_COLOR ||
1466 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR ||
1467 factor == VK_BLEND_FACTOR_SRC1_ALPHA ||
1468 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
1469 }
1470
1471 static void
1472 emit_3dstate_ps(struct anv_pipeline *pipeline,
1473 const VkPipelineColorBlendStateCreateInfo *blend,
1474 const VkPipelineMultisampleStateCreateInfo *multisample)
1475 {
1476 MAYBE_UNUSED const struct gen_device_info *devinfo = &pipeline->device->info;
1477 const struct anv_shader_bin *fs_bin =
1478 pipeline->shaders[MESA_SHADER_FRAGMENT];
1479
1480 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1481 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1482 #if GEN_GEN == 7
1483 /* Even if no fragments are ever dispatched, gen7 hardware hangs if
1484 * we don't at least set the maximum number of threads.
1485 */
1486 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1487 #endif
1488 }
1489 return;
1490 }
1491
1492 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1493
1494 #if GEN_GEN < 8
1495 /* The hardware wedges if you have this bit set but don't turn on any dual
1496 * source blend factors.
1497 */
1498 bool dual_src_blend = false;
1499 if (wm_prog_data->dual_src_blend && blend) {
1500 for (uint32_t i = 0; i < blend->attachmentCount; i++) {
1501 const VkPipelineColorBlendAttachmentState *bstate =
1502 &blend->pAttachments[i];
1503
1504 if (bstate->blendEnable &&
1505 (is_dual_src_blend_factor(bstate->srcColorBlendFactor) ||
1506 is_dual_src_blend_factor(bstate->dstColorBlendFactor) ||
1507 is_dual_src_blend_factor(bstate->srcAlphaBlendFactor) ||
1508 is_dual_src_blend_factor(bstate->dstAlphaBlendFactor))) {
1509 dual_src_blend = true;
1510 break;
1511 }
1512 }
1513 }
1514 #endif
1515
1516 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1517 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
1518 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
1519 ps._32PixelDispatchEnable = wm_prog_data->dispatch_32;
1520
1521 /* From the Sky Lake PRM 3DSTATE_PS::32 Pixel Dispatch Enable:
1522 *
1523 * "When NUM_MULTISAMPLES = 16 or FORCE_SAMPLE_COUNT = 16, SIMD32
1524 * Dispatch must not be enabled for PER_PIXEL dispatch mode."
1525 *
1526 * Since 16x MSAA is first introduced on SKL, we don't need to apply
1527 * the workaround on any older hardware.
1528 */
1529 if (GEN_GEN >= 9 && !wm_prog_data->persample_dispatch &&
1530 multisample && multisample->rasterizationSamples == 16) {
1531 assert(ps._8PixelDispatchEnable || ps._16PixelDispatchEnable);
1532 ps._32PixelDispatchEnable = false;
1533 }
1534
1535 ps.KernelStartPointer0 = fs_bin->kernel.offset +
1536 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
1537 ps.KernelStartPointer1 = fs_bin->kernel.offset +
1538 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
1539 ps.KernelStartPointer2 = fs_bin->kernel.offset +
1540 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
1541
1542 ps.SingleProgramFlow = false;
1543 ps.VectorMaskEnable = true;
1544 ps.SamplerCount = get_sampler_count(fs_bin);
1545 /* Gen 11 workarounds table #2056 WABTPPrefetchDisable */
1546 ps.BindingTableEntryCount = GEN_GEN == 11 ? 0 : get_binding_table_entry_count(fs_bin);
1547 ps.PushConstantEnable = wm_prog_data->base.nr_params > 0 ||
1548 wm_prog_data->base.ubo_ranges[0].length;
1549 ps.PositionXYOffsetSelect = wm_prog_data->uses_pos_offset ?
1550 POSOFFSET_SAMPLE: POSOFFSET_NONE;
1551 #if GEN_GEN < 8
1552 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1553 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1554 ps.DualSourceBlendEnable = dual_src_blend;
1555 #endif
1556
1557 #if GEN_IS_HASWELL
1558 /* Haswell requires the sample mask to be set in this packet as well
1559 * as in 3DSTATE_SAMPLE_MASK; the values should match.
1560 */
1561 ps.SampleMask = 0xff;
1562 #endif
1563
1564 #if GEN_GEN >= 9
1565 ps.MaximumNumberofThreadsPerPSD = 64 - 1;
1566 #elif GEN_GEN >= 8
1567 ps.MaximumNumberofThreadsPerPSD = 64 - 2;
1568 #else
1569 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1570 #endif
1571
1572 ps.DispatchGRFStartRegisterForConstantSetupData0 =
1573 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
1574 ps.DispatchGRFStartRegisterForConstantSetupData1 =
1575 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
1576 ps.DispatchGRFStartRegisterForConstantSetupData2 =
1577 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
1578
1579 ps.PerThreadScratchSpace = get_scratch_space(fs_bin);
1580 ps.ScratchSpaceBasePointer =
1581 get_scratch_address(pipeline, MESA_SHADER_FRAGMENT, fs_bin);
1582 }
1583 }
1584
1585 #if GEN_GEN >= 8
1586 static void
1587 emit_3dstate_ps_extra(struct anv_pipeline *pipeline,
1588 struct anv_subpass *subpass,
1589 const VkPipelineColorBlendStateCreateInfo *blend)
1590 {
1591 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1592
1593 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1594 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps);
1595 return;
1596 }
1597
1598 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps) {
1599 ps.PixelShaderValid = true;
1600 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1601 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1602 ps.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
1603 ps.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1604 ps.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1605 ps.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1606
1607 /* If the subpass has a depth or stencil self-dependency, then we need
1608 * to force the hardware to do the depth/stencil write *after* fragment
1609 * shader execution. Otherwise, the writes may hit memory before we get
1610 * around to fetching from the input attachment and we may get the depth
1611 * or stencil value from the current draw rather than the previous one.
1612 */
1613 ps.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1614 wm_prog_data->uses_kill;
1615
1616 #if GEN_GEN >= 9
1617 ps.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
1618 ps.PixelShaderPullsBary = wm_prog_data->pulls_bary;
1619
1620 ps.InputCoverageMaskState = ICMS_NONE;
1621 if (wm_prog_data->uses_sample_mask) {
1622 if (wm_prog_data->post_depth_coverage)
1623 ps.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
1624 else
1625 ps.InputCoverageMaskState = ICMS_INNER_CONSERVATIVE;
1626 }
1627 #else
1628 ps.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1629 #endif
1630 }
1631 }
1632
1633 static void
1634 emit_3dstate_vf_topology(struct anv_pipeline *pipeline)
1635 {
1636 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_TOPOLOGY), vft) {
1637 vft.PrimitiveTopologyType = pipeline->topology;
1638 }
1639 }
1640 #endif
1641
1642 static void
1643 emit_3dstate_vf_statistics(struct anv_pipeline *pipeline)
1644 {
1645 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_STATISTICS), vfs) {
1646 vfs.StatisticsEnable = true;
1647 }
1648 }
1649
1650 static void
1651 compute_kill_pixel(struct anv_pipeline *pipeline,
1652 const VkPipelineMultisampleStateCreateInfo *ms_info,
1653 const struct anv_subpass *subpass)
1654 {
1655 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1656 pipeline->kill_pixel = false;
1657 return;
1658 }
1659
1660 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1661
1662 /* This computes the KillPixel portion of the computation for whether or
1663 * not we want to enable the PMA fix on gen8 or gen9. It's given by this
1664 * chunk of the giant formula:
1665 *
1666 * (3DSTATE_PS_EXTRA::PixelShaderKillsPixels ||
1667 * 3DSTATE_PS_EXTRA::oMask Present to RenderTarget ||
1668 * 3DSTATE_PS_BLEND::AlphaToCoverageEnable ||
1669 * 3DSTATE_PS_BLEND::AlphaTestEnable ||
1670 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable)
1671 *
1672 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable is always false and so is
1673 * 3DSTATE_PS_BLEND::AlphaTestEnable since Vulkan doesn't have a concept
1674 * of an alpha test.
1675 */
1676 pipeline->kill_pixel =
1677 subpass->has_ds_self_dep || wm_prog_data->uses_kill ||
1678 wm_prog_data->uses_omask ||
1679 (ms_info && ms_info->alphaToCoverageEnable);
1680 }
1681
1682 static VkResult
1683 genX(graphics_pipeline_create)(
1684 VkDevice _device,
1685 struct anv_pipeline_cache * cache,
1686 const VkGraphicsPipelineCreateInfo* pCreateInfo,
1687 const VkAllocationCallbacks* pAllocator,
1688 VkPipeline* pPipeline)
1689 {
1690 ANV_FROM_HANDLE(anv_device, device, _device);
1691 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
1692 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
1693 struct anv_pipeline *pipeline;
1694 VkResult result;
1695
1696 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
1697
1698 /* Use the default pipeline cache if none is specified */
1699 if (cache == NULL && device->instance->pipeline_cache_enabled)
1700 cache = &device->default_pipeline_cache;
1701
1702 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
1703 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1704 if (pipeline == NULL)
1705 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1706
1707 result = anv_pipeline_init(pipeline, device, cache,
1708 pCreateInfo, pAllocator);
1709 if (result != VK_SUCCESS) {
1710 vk_free2(&device->alloc, pAllocator, pipeline);
1711 return result;
1712 }
1713
1714 assert(pCreateInfo->pVertexInputState);
1715 emit_vertex_input(pipeline, pCreateInfo->pVertexInputState);
1716 assert(pCreateInfo->pRasterizationState);
1717 emit_rs_state(pipeline, pCreateInfo->pRasterizationState,
1718 pCreateInfo->pMultisampleState, pass, subpass);
1719 emit_ms_state(pipeline, pCreateInfo->pMultisampleState);
1720 emit_ds_state(pipeline, pCreateInfo->pDepthStencilState, pass, subpass);
1721 emit_cb_state(pipeline, pCreateInfo->pColorBlendState,
1722 pCreateInfo->pMultisampleState);
1723 compute_kill_pixel(pipeline, pCreateInfo->pMultisampleState, subpass);
1724
1725 emit_urb_setup(pipeline);
1726
1727 emit_3dstate_clip(pipeline, pCreateInfo->pViewportState,
1728 pCreateInfo->pRasterizationState);
1729 emit_3dstate_streamout(pipeline, pCreateInfo->pRasterizationState);
1730
1731 #if 0
1732 /* From gen7_vs_state.c */
1733
1734 /**
1735 * From Graphics BSpec: 3D-Media-GPGPU Engine > 3D Pipeline Stages >
1736 * Geometry > Geometry Shader > State:
1737 *
1738 * "Note: Because of corruption in IVB:GT2, software needs to flush the
1739 * whole fixed function pipeline when the GS enable changes value in
1740 * the 3DSTATE_GS."
1741 *
1742 * The hardware architects have clarified that in this context "flush the
1743 * whole fixed function pipeline" means to emit a PIPE_CONTROL with the "CS
1744 * Stall" bit set.
1745 */
1746 if (!device->info.is_haswell && !device->info.is_baytrail)
1747 gen7_emit_vs_workaround_flush(brw);
1748 #endif
1749
1750 emit_3dstate_vs(pipeline);
1751 emit_3dstate_hs_te_ds(pipeline, pCreateInfo->pTessellationState);
1752 emit_3dstate_gs(pipeline);
1753 emit_3dstate_sbe(pipeline);
1754 emit_3dstate_wm(pipeline, subpass, pCreateInfo->pColorBlendState,
1755 pCreateInfo->pMultisampleState);
1756 emit_3dstate_ps(pipeline, pCreateInfo->pColorBlendState,
1757 pCreateInfo->pMultisampleState);
1758 #if GEN_GEN >= 8
1759 emit_3dstate_ps_extra(pipeline, subpass, pCreateInfo->pColorBlendState);
1760 emit_3dstate_vf_topology(pipeline);
1761 #endif
1762 emit_3dstate_vf_statistics(pipeline);
1763
1764 *pPipeline = anv_pipeline_to_handle(pipeline);
1765
1766 return pipeline->batch.status;
1767 }
1768
1769 static VkResult
1770 compute_pipeline_create(
1771 VkDevice _device,
1772 struct anv_pipeline_cache * cache,
1773 const VkComputePipelineCreateInfo* pCreateInfo,
1774 const VkAllocationCallbacks* pAllocator,
1775 VkPipeline* pPipeline)
1776 {
1777 ANV_FROM_HANDLE(anv_device, device, _device);
1778 const struct anv_physical_device *physical_device =
1779 &device->instance->physicalDevice;
1780 const struct gen_device_info *devinfo = &physical_device->info;
1781 struct anv_pipeline *pipeline;
1782 VkResult result;
1783
1784 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO);
1785
1786 /* Use the default pipeline cache if none is specified */
1787 if (cache == NULL && device->instance->pipeline_cache_enabled)
1788 cache = &device->default_pipeline_cache;
1789
1790 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
1791 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1792 if (pipeline == NULL)
1793 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1794
1795 pipeline->device = device;
1796
1797 pipeline->blend_state.map = NULL;
1798
1799 result = anv_reloc_list_init(&pipeline->batch_relocs,
1800 pAllocator ? pAllocator : &device->alloc);
1801 if (result != VK_SUCCESS) {
1802 vk_free2(&device->alloc, pAllocator, pipeline);
1803 return result;
1804 }
1805 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
1806 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
1807 pipeline->batch.relocs = &pipeline->batch_relocs;
1808 pipeline->batch.status = VK_SUCCESS;
1809
1810 /* When we free the pipeline, we detect stages based on the NULL status
1811 * of various prog_data pointers. Make them NULL by default.
1812 */
1813 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
1814
1815 pipeline->needs_data_cache = false;
1816
1817 assert(pCreateInfo->stage.stage == VK_SHADER_STAGE_COMPUTE_BIT);
1818 pipeline->active_stages |= VK_SHADER_STAGE_COMPUTE_BIT;
1819 ANV_FROM_HANDLE(anv_shader_module, module, pCreateInfo->stage.module);
1820 result = anv_pipeline_compile_cs(pipeline, cache, pCreateInfo, module,
1821 pCreateInfo->stage.pName,
1822 pCreateInfo->stage.pSpecializationInfo);
1823 if (result != VK_SUCCESS) {
1824 vk_free2(&device->alloc, pAllocator, pipeline);
1825 return result;
1826 }
1827
1828 const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
1829
1830 anv_pipeline_setup_l3_config(pipeline, cs_prog_data->base.total_shared > 0);
1831
1832 uint32_t group_size = cs_prog_data->local_size[0] *
1833 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
1834 uint32_t remainder = group_size & (cs_prog_data->simd_size - 1);
1835
1836 if (remainder > 0)
1837 pipeline->cs_right_mask = ~0u >> (32 - remainder);
1838 else
1839 pipeline->cs_right_mask = ~0u >> (32 - cs_prog_data->simd_size);
1840
1841 const uint32_t vfe_curbe_allocation =
1842 ALIGN(cs_prog_data->push.per_thread.regs * cs_prog_data->threads +
1843 cs_prog_data->push.cross_thread.regs, 2);
1844
1845 const uint32_t subslices = MAX2(physical_device->subslice_total, 1);
1846
1847 const struct anv_shader_bin *cs_bin =
1848 pipeline->shaders[MESA_SHADER_COMPUTE];
1849
1850 anv_batch_emit(&pipeline->batch, GENX(MEDIA_VFE_STATE), vfe) {
1851 #if GEN_GEN > 7
1852 vfe.StackSize = 0;
1853 #else
1854 vfe.GPGPUMode = true;
1855 #endif
1856 vfe.MaximumNumberofThreads =
1857 devinfo->max_cs_threads * subslices - 1;
1858 vfe.NumberofURBEntries = GEN_GEN <= 7 ? 0 : 2;
1859 #if GEN_GEN < 11
1860 vfe.ResetGatewayTimer = true;
1861 #endif
1862 #if GEN_GEN <= 8
1863 vfe.BypassGatewayControl = true;
1864 #endif
1865 vfe.URBEntryAllocationSize = GEN_GEN <= 7 ? 0 : 2;
1866 vfe.CURBEAllocationSize = vfe_curbe_allocation;
1867
1868 vfe.PerThreadScratchSpace = get_scratch_space(cs_bin);
1869 vfe.ScratchSpaceBasePointer =
1870 get_scratch_address(pipeline, MESA_SHADER_COMPUTE, cs_bin);
1871 }
1872
1873 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
1874 .KernelStartPointer = cs_bin->kernel.offset,
1875
1876 .SamplerCount = get_sampler_count(cs_bin),
1877 /* Gen 11 workarounds table #2056 WABTPPrefetchDisable */
1878 .BindingTableEntryCount = GEN_GEN == 11 ? 0 : get_binding_table_entry_count(cs_bin),
1879 .BarrierEnable = cs_prog_data->uses_barrier,
1880 .SharedLocalMemorySize =
1881 encode_slm_size(GEN_GEN, cs_prog_data->base.total_shared),
1882
1883 #if !GEN_IS_HASWELL
1884 .ConstantURBEntryReadOffset = 0,
1885 #endif
1886 .ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs,
1887 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1888 .CrossThreadConstantDataReadLength =
1889 cs_prog_data->push.cross_thread.regs,
1890 #endif
1891
1892 .NumberofThreadsinGPGPUThreadGroup = cs_prog_data->threads,
1893 };
1894 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL,
1895 pipeline->interface_descriptor_data,
1896 &desc);
1897
1898 *pPipeline = anv_pipeline_to_handle(pipeline);
1899
1900 return pipeline->batch.status;
1901 }
1902
1903 VkResult genX(CreateGraphicsPipelines)(
1904 VkDevice _device,
1905 VkPipelineCache pipelineCache,
1906 uint32_t count,
1907 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1908 const VkAllocationCallbacks* pAllocator,
1909 VkPipeline* pPipelines)
1910 {
1911 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
1912
1913 VkResult result = VK_SUCCESS;
1914
1915 unsigned i;
1916 for (i = 0; i < count; i++) {
1917 result = genX(graphics_pipeline_create)(_device,
1918 pipeline_cache,
1919 &pCreateInfos[i],
1920 pAllocator, &pPipelines[i]);
1921
1922 /* Bail out on the first error as it is not obvious what error should be
1923 * report upon 2 different failures. */
1924 if (result != VK_SUCCESS)
1925 break;
1926 }
1927
1928 for (; i < count; i++)
1929 pPipelines[i] = VK_NULL_HANDLE;
1930
1931 return result;
1932 }
1933
1934 VkResult genX(CreateComputePipelines)(
1935 VkDevice _device,
1936 VkPipelineCache pipelineCache,
1937 uint32_t count,
1938 const VkComputePipelineCreateInfo* pCreateInfos,
1939 const VkAllocationCallbacks* pAllocator,
1940 VkPipeline* pPipelines)
1941 {
1942 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
1943
1944 VkResult result = VK_SUCCESS;
1945
1946 unsigned i;
1947 for (i = 0; i < count; i++) {
1948 result = compute_pipeline_create(_device, pipeline_cache,
1949 &pCreateInfos[i],
1950 pAllocator, &pPipelines[i]);
1951
1952 /* Bail out on the first error as it is not obvious what error should be
1953 * report upon 2 different failures. */
1954 if (result != VK_SUCCESS)
1955 break;
1956 }
1957
1958 for (; i < count; i++)
1959 pPipelines[i] = VK_NULL_HANDLE;
1960
1961 return result;
1962 }