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