anv/pipeline: Make the temp blend attachment state pointer const
[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 if (bits) {
46 return VFCOMP_STORE_SRC;
47 } else if (comp < 3) {
48 return VFCOMP_STORE_0;
49 } else if (isl_format_layouts[format].channels.r.type == ISL_UINT ||
50 isl_format_layouts[format].channels.r.type == ISL_SINT) {
51 assert(comp == 3);
52 return VFCOMP_STORE_1_INT;
53 } else {
54 assert(comp == 3);
55 return VFCOMP_STORE_1_FP;
56 }
57 }
58
59 static void
60 emit_vertex_input(struct anv_pipeline *pipeline,
61 const VkPipelineVertexInputStateCreateInfo *info)
62 {
63 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
64
65 /* Pull inputs_read out of the VS prog data */
66 const uint64_t inputs_read = vs_prog_data->inputs_read;
67 assert((inputs_read & ((1 << VERT_ATTRIB_GENERIC0) - 1)) == 0);
68 const uint32_t elements = inputs_read >> VERT_ATTRIB_GENERIC0;
69
70 #if GEN_GEN >= 8
71 /* On BDW+, we only need to allocate space for base ids. Setting up
72 * the actual vertex and instance id is a separate packet.
73 */
74 const bool needs_svgs_elem = vs_prog_data->uses_basevertex ||
75 vs_prog_data->uses_baseinstance;
76 #else
77 /* On Haswell and prior, vertex and instance id are created by using the
78 * ComponentControl fields, so we need an element for any of them.
79 */
80 const bool needs_svgs_elem = vs_prog_data->uses_vertexid ||
81 vs_prog_data->uses_instanceid ||
82 vs_prog_data->uses_basevertex ||
83 vs_prog_data->uses_baseinstance;
84 #endif
85
86 uint32_t elem_count = __builtin_popcount(elements) + needs_svgs_elem;
87 if (elem_count == 0)
88 return;
89
90 uint32_t *p;
91
92 const uint32_t num_dwords = 1 + elem_count * 2;
93 p = anv_batch_emitn(&pipeline->batch, num_dwords,
94 GENX(3DSTATE_VERTEX_ELEMENTS));
95 memset(p + 1, 0, (num_dwords - 1) * 4);
96
97 for (uint32_t i = 0; i < info->vertexAttributeDescriptionCount; i++) {
98 const VkVertexInputAttributeDescription *desc =
99 &info->pVertexAttributeDescriptions[i];
100 enum isl_format format = anv_get_isl_format(&pipeline->device->info,
101 desc->format,
102 VK_IMAGE_ASPECT_COLOR_BIT,
103 VK_IMAGE_TILING_LINEAR);
104
105 assert(desc->binding < 32);
106
107 if ((elements & (1 << desc->location)) == 0)
108 continue; /* Binding unused */
109
110 uint32_t slot = __builtin_popcount(elements & ((1 << desc->location) - 1));
111
112 struct GENX(VERTEX_ELEMENT_STATE) element = {
113 .VertexBufferIndex = desc->binding,
114 .Valid = true,
115 .SourceElementFormat = format,
116 .EdgeFlagEnable = false,
117 .SourceElementOffset = desc->offset,
118 .Component0Control = vertex_element_comp_control(format, 0),
119 .Component1Control = vertex_element_comp_control(format, 1),
120 .Component2Control = vertex_element_comp_control(format, 2),
121 .Component3Control = vertex_element_comp_control(format, 3),
122 };
123 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + slot * 2], &element);
124
125 #if GEN_GEN >= 8
126 /* On Broadwell and later, we have a separate VF_INSTANCING packet
127 * that controls instancing. On Haswell and prior, that's part of
128 * VERTEX_BUFFER_STATE which we emit later.
129 */
130 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
131 vfi.InstancingEnable = pipeline->instancing_enable[desc->binding];
132 vfi.VertexElementIndex = slot;
133 /* Vulkan so far doesn't have an instance divisor, so
134 * this is always 1 (ignored if not instancing). */
135 vfi.InstanceDataStepRate = 1;
136 }
137 #endif
138 }
139
140 const uint32_t id_slot = __builtin_popcount(elements);
141 if (needs_svgs_elem) {
142 /* From the Broadwell PRM for the 3D_Vertex_Component_Control enum:
143 * "Within a VERTEX_ELEMENT_STATE structure, if a Component
144 * Control field is set to something other than VFCOMP_STORE_SRC,
145 * no higher-numbered Component Control fields may be set to
146 * VFCOMP_STORE_SRC"
147 *
148 * This means, that if we have BaseInstance, we need BaseVertex as
149 * well. Just do all or nothing.
150 */
151 uint32_t base_ctrl = (vs_prog_data->uses_basevertex ||
152 vs_prog_data->uses_baseinstance) ?
153 VFCOMP_STORE_SRC : VFCOMP_STORE_0;
154
155 struct GENX(VERTEX_ELEMENT_STATE) element = {
156 .VertexBufferIndex = 32, /* Reserved for this */
157 .Valid = true,
158 .SourceElementFormat = ISL_FORMAT_R32G32_UINT,
159 .Component0Control = base_ctrl,
160 .Component1Control = base_ctrl,
161 #if GEN_GEN >= 8
162 .Component2Control = VFCOMP_STORE_0,
163 .Component3Control = VFCOMP_STORE_0,
164 #else
165 .Component2Control = VFCOMP_STORE_VID,
166 .Component3Control = VFCOMP_STORE_IID,
167 #endif
168 };
169 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + id_slot * 2], &element);
170 }
171
172 #if GEN_GEN >= 8
173 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_SGVS), sgvs) {
174 sgvs.VertexIDEnable = vs_prog_data->uses_vertexid;
175 sgvs.VertexIDComponentNumber = 2;
176 sgvs.VertexIDElementOffset = id_slot;
177 sgvs.InstanceIDEnable = vs_prog_data->uses_instanceid;
178 sgvs.InstanceIDComponentNumber = 3;
179 sgvs.InstanceIDElementOffset = id_slot;
180 }
181 #endif
182 }
183
184 void
185 genX(emit_urb_setup)(struct anv_device *device, struct anv_batch *batch,
186 const struct gen_l3_config *l3_config,
187 VkShaderStageFlags active_stages,
188 const unsigned entry_size[4])
189 {
190 const struct gen_device_info *devinfo = &device->info;
191 #if GEN_IS_HASWELL
192 const unsigned push_constant_kb = devinfo->gt == 3 ? 32 : 16;
193 #else
194 const unsigned push_constant_kb = GEN_GEN >= 8 ? 32 : 16;
195 #endif
196
197 const unsigned urb_size_kb = gen_get_l3_config_urb_size(devinfo, l3_config);
198
199 unsigned entries[4];
200 unsigned start[4];
201 gen_get_urb_config(devinfo,
202 1024 * push_constant_kb, 1024 * urb_size_kb,
203 active_stages &
204 VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
205 active_stages & VK_SHADER_STAGE_GEOMETRY_BIT,
206 entry_size, entries, start);
207
208 #if GEN_GEN == 7 && !GEN_IS_HASWELL
209 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
210 *
211 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth stall
212 * needs to be sent just prior to any 3DSTATE_VS, 3DSTATE_URB_VS,
213 * 3DSTATE_CONSTANT_VS, 3DSTATE_BINDING_TABLE_POINTER_VS,
214 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one PIPE_CONTROL
215 * needs to be sent before any combination of VS associated 3DSTATE."
216 */
217 anv_batch_emit(batch, GEN7_PIPE_CONTROL, pc) {
218 pc.DepthStallEnable = true;
219 pc.PostSyncOperation = WriteImmediateData;
220 pc.Address = (struct anv_address) { &device->workaround_bo, 0 };
221 }
222 #endif
223
224 for (int i = 0; i <= MESA_SHADER_GEOMETRY; i++) {
225 anv_batch_emit(batch, GENX(3DSTATE_URB_VS), urb) {
226 urb._3DCommandSubOpcode += i;
227 urb.VSURBStartingAddress = start[i];
228 urb.VSURBEntryAllocationSize = entry_size[i] - 1;
229 urb.VSNumberofURBEntries = entries[i];
230 }
231 }
232 }
233
234 static inline void
235 emit_urb_setup(struct anv_pipeline *pipeline)
236 {
237 unsigned entry_size[4];
238 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
239 const struct brw_vue_prog_data *prog_data =
240 !anv_pipeline_has_stage(pipeline, i) ? NULL :
241 (const struct brw_vue_prog_data *) pipeline->shaders[i]->prog_data;
242
243 entry_size[i] = prog_data ? prog_data->urb_entry_size : 1;
244 }
245
246 genX(emit_urb_setup)(pipeline->device, &pipeline->batch,
247 pipeline->urb.l3_config,
248 pipeline->active_stages, entry_size);
249 }
250
251 static void
252 emit_3dstate_sbe(struct anv_pipeline *pipeline)
253 {
254 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
255 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
256 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
257 const struct brw_vue_map *fs_input_map;
258
259 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
260 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE), sbe);
261 #if GEN_GEN >= 8
262 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ), sbe);
263 #endif
264 return;
265 }
266
267 if (gs_prog_data)
268 fs_input_map = &gs_prog_data->base.vue_map;
269 else
270 fs_input_map = &vs_prog_data->base.vue_map;
271
272 struct GENX(3DSTATE_SBE) sbe = {
273 GENX(3DSTATE_SBE_header),
274 .AttributeSwizzleEnable = true,
275 .PointSpriteTextureCoordinateOrigin = UPPERLEFT,
276 .NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs,
277 .ConstantInterpolationEnable = wm_prog_data->flat_inputs,
278 };
279
280 #if GEN_GEN >= 9
281 for (unsigned i = 0; i < 32; i++)
282 sbe.AttributeActiveComponentFormat[i] = ACF_XYZW;
283 #endif
284
285 #if GEN_GEN >= 8
286 /* On Broadwell, they broke 3DSTATE_SBE into two packets */
287 struct GENX(3DSTATE_SBE_SWIZ) swiz = {
288 GENX(3DSTATE_SBE_SWIZ_header),
289 };
290 #else
291 # define swiz sbe
292 #endif
293
294 int max_source_attr = 0;
295 for (int attr = 0; attr < VARYING_SLOT_MAX; attr++) {
296 int input_index = wm_prog_data->urb_setup[attr];
297
298 if (input_index < 0)
299 continue;
300
301 if (attr == VARYING_SLOT_PNTC) {
302 sbe.PointSpriteTextureCoordinateEnable = 1 << input_index;
303 continue;
304 }
305
306 const int slot = fs_input_map->varying_to_slot[attr];
307
308 if (input_index >= 16)
309 continue;
310
311 if (slot == -1) {
312 /* This attribute does not exist in the VUE--that means that the
313 * vertex shader did not write to it. It could be that it's a
314 * regular varying read by the fragment shader but not written by
315 * the vertex shader or it's gl_PrimitiveID. In the first case the
316 * value is undefined, in the second it needs to be
317 * gl_PrimitiveID.
318 */
319 swiz.Attribute[input_index].ConstantSource = PRIM_ID;
320 swiz.Attribute[input_index].ComponentOverrideX = true;
321 swiz.Attribute[input_index].ComponentOverrideY = true;
322 swiz.Attribute[input_index].ComponentOverrideZ = true;
323 swiz.Attribute[input_index].ComponentOverrideW = true;
324 } else {
325 assert(slot >= 2);
326 const int source_attr = slot - 2;
327 max_source_attr = MAX2(max_source_attr, source_attr);
328 /* We have to subtract two slots to accout for the URB entry output
329 * read offset in the VS and GS stages.
330 */
331 swiz.Attribute[input_index].SourceAttribute = source_attr;
332 }
333 }
334
335 sbe.VertexURBEntryReadOffset = 1; /* Skip the VUE header and position slots */
336 sbe.VertexURBEntryReadLength = DIV_ROUND_UP(max_source_attr + 1, 2);
337
338 uint32_t *dw = anv_batch_emit_dwords(&pipeline->batch,
339 GENX(3DSTATE_SBE_length));
340 GENX(3DSTATE_SBE_pack)(&pipeline->batch, dw, &sbe);
341
342 #if GEN_GEN >= 8
343 dw = anv_batch_emit_dwords(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ_length));
344 GENX(3DSTATE_SBE_SWIZ_pack)(&pipeline->batch, dw, &swiz);
345 #endif
346 }
347
348 static const uint32_t vk_to_gen_cullmode[] = {
349 [VK_CULL_MODE_NONE] = CULLMODE_NONE,
350 [VK_CULL_MODE_FRONT_BIT] = CULLMODE_FRONT,
351 [VK_CULL_MODE_BACK_BIT] = CULLMODE_BACK,
352 [VK_CULL_MODE_FRONT_AND_BACK] = CULLMODE_BOTH
353 };
354
355 static const uint32_t vk_to_gen_fillmode[] = {
356 [VK_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
357 [VK_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
358 [VK_POLYGON_MODE_POINT] = FILL_MODE_POINT,
359 };
360
361 static const uint32_t vk_to_gen_front_face[] = {
362 [VK_FRONT_FACE_COUNTER_CLOCKWISE] = 1,
363 [VK_FRONT_FACE_CLOCKWISE] = 0
364 };
365
366 static void
367 emit_rs_state(struct anv_pipeline *pipeline,
368 const VkPipelineRasterizationStateCreateInfo *rs_info,
369 const VkPipelineMultisampleStateCreateInfo *ms_info,
370 const struct anv_render_pass *pass,
371 const struct anv_subpass *subpass)
372 {
373 struct GENX(3DSTATE_SF) sf = {
374 GENX(3DSTATE_SF_header),
375 };
376
377 sf.ViewportTransformEnable = true;
378 sf.StatisticsEnable = true;
379 sf.TriangleStripListProvokingVertexSelect = 0;
380 sf.LineStripListProvokingVertexSelect = 0;
381 sf.TriangleFanProvokingVertexSelect = 1;
382 sf.PointWidthSource = Vertex;
383 sf.PointWidth = 1.0;
384
385 #if GEN_GEN >= 8
386 struct GENX(3DSTATE_RASTER) raster = {
387 GENX(3DSTATE_RASTER_header),
388 };
389 #else
390 # define raster sf
391 #endif
392
393 /* For details on 3DSTATE_RASTER multisample state, see the BSpec table
394 * "Multisample Modes State".
395 */
396 #if GEN_GEN >= 8
397 raster.DXMultisampleRasterizationEnable = true;
398 raster.ForcedSampleCount = FSC_NUMRASTSAMPLES_0;
399 raster.ForceMultisampling = false;
400 #else
401 raster.MultisampleRasterizationMode =
402 (ms_info && ms_info->rasterizationSamples > 1) ?
403 MSRASTMODE_ON_PATTERN : MSRASTMODE_OFF_PIXEL;
404 #endif
405
406 raster.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
407 raster.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
408 raster.FrontFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
409 raster.BackFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
410 raster.ScissorRectangleEnable = true;
411
412 #if GEN_GEN >= 9
413 /* GEN9+ splits ViewportZClipTestEnable into near and far enable bits */
414 raster.ViewportZFarClipTestEnable = !pipeline->depth_clamp_enable;
415 raster.ViewportZNearClipTestEnable = !pipeline->depth_clamp_enable;
416 #elif GEN_GEN >= 8
417 raster.ViewportZClipTestEnable = !pipeline->depth_clamp_enable;
418 #endif
419
420 raster.GlobalDepthOffsetEnableSolid = rs_info->depthBiasEnable;
421 raster.GlobalDepthOffsetEnableWireframe = rs_info->depthBiasEnable;
422 raster.GlobalDepthOffsetEnablePoint = rs_info->depthBiasEnable;
423
424 #if GEN_GEN == 7
425 /* Gen7 requires that we provide the depth format in 3DSTATE_SF so that it
426 * can get the depth offsets correct.
427 */
428 if (subpass->depth_stencil_attachment < pass->attachment_count) {
429 VkFormat vk_format =
430 pass->attachments[subpass->depth_stencil_attachment].format;
431 assert(vk_format_is_depth_or_stencil(vk_format));
432 if (vk_format_aspects(vk_format) & VK_IMAGE_ASPECT_DEPTH_BIT) {
433 enum isl_format isl_format =
434 anv_get_isl_format(&pipeline->device->info, vk_format,
435 VK_IMAGE_ASPECT_DEPTH_BIT,
436 VK_IMAGE_TILING_OPTIMAL);
437 sf.DepthBufferSurfaceFormat =
438 isl_format_get_depth_format(isl_format, false);
439 }
440 }
441 #endif
442
443 #if GEN_GEN >= 8
444 GENX(3DSTATE_SF_pack)(NULL, pipeline->gen8.sf, &sf);
445 GENX(3DSTATE_RASTER_pack)(NULL, pipeline->gen8.raster, &raster);
446 #else
447 # undef raster
448 GENX(3DSTATE_SF_pack)(NULL, &pipeline->gen7.sf, &sf);
449 #endif
450 }
451
452 static void
453 emit_ms_state(struct anv_pipeline *pipeline,
454 const VkPipelineMultisampleStateCreateInfo *info)
455 {
456 uint32_t samples = 1;
457 uint32_t log2_samples = 0;
458
459 /* From the Vulkan 1.0 spec:
460 * If pSampleMask is NULL, it is treated as if the mask has all bits
461 * enabled, i.e. no coverage is removed from fragments.
462 *
463 * 3DSTATE_SAMPLE_MASK.SampleMask is 16 bits.
464 */
465 #if GEN_GEN >= 8
466 uint32_t sample_mask = 0xffff;
467 #else
468 uint32_t sample_mask = 0xff;
469 #endif
470
471 if (info) {
472 samples = info->rasterizationSamples;
473 log2_samples = __builtin_ffs(samples) - 1;
474 }
475
476 if (info && info->pSampleMask)
477 sample_mask &= info->pSampleMask[0];
478
479 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_MULTISAMPLE), ms) {
480 ms.NumberofMultisamples = log2_samples;
481
482 #if GEN_GEN >= 8
483 /* The PRM says that this bit is valid only for DX9:
484 *
485 * SW can choose to set this bit only for DX9 API. DX10/OGL API's
486 * should not have any effect by setting or not setting this bit.
487 */
488 ms.PixelPositionOffsetEnable = false;
489 ms.PixelLocation = CENTER;
490 #else
491 ms.PixelLocation = PIXLOC_CENTER;
492
493 switch (samples) {
494 case 1:
495 GEN_SAMPLE_POS_1X(ms.Sample);
496 break;
497 case 2:
498 GEN_SAMPLE_POS_2X(ms.Sample);
499 break;
500 case 4:
501 GEN_SAMPLE_POS_4X(ms.Sample);
502 break;
503 case 8:
504 GEN_SAMPLE_POS_8X(ms.Sample);
505 break;
506 default:
507 break;
508 }
509 #endif
510 }
511
512 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SAMPLE_MASK), sm) {
513 sm.SampleMask = sample_mask;
514 }
515 }
516
517 static const uint32_t vk_to_gen_logic_op[] = {
518 [VK_LOGIC_OP_COPY] = LOGICOP_COPY,
519 [VK_LOGIC_OP_CLEAR] = LOGICOP_CLEAR,
520 [VK_LOGIC_OP_AND] = LOGICOP_AND,
521 [VK_LOGIC_OP_AND_REVERSE] = LOGICOP_AND_REVERSE,
522 [VK_LOGIC_OP_AND_INVERTED] = LOGICOP_AND_INVERTED,
523 [VK_LOGIC_OP_NO_OP] = LOGICOP_NOOP,
524 [VK_LOGIC_OP_XOR] = LOGICOP_XOR,
525 [VK_LOGIC_OP_OR] = LOGICOP_OR,
526 [VK_LOGIC_OP_NOR] = LOGICOP_NOR,
527 [VK_LOGIC_OP_EQUIVALENT] = LOGICOP_EQUIV,
528 [VK_LOGIC_OP_INVERT] = LOGICOP_INVERT,
529 [VK_LOGIC_OP_OR_REVERSE] = LOGICOP_OR_REVERSE,
530 [VK_LOGIC_OP_COPY_INVERTED] = LOGICOP_COPY_INVERTED,
531 [VK_LOGIC_OP_OR_INVERTED] = LOGICOP_OR_INVERTED,
532 [VK_LOGIC_OP_NAND] = LOGICOP_NAND,
533 [VK_LOGIC_OP_SET] = LOGICOP_SET,
534 };
535
536 static const uint32_t vk_to_gen_blend[] = {
537 [VK_BLEND_FACTOR_ZERO] = BLENDFACTOR_ZERO,
538 [VK_BLEND_FACTOR_ONE] = BLENDFACTOR_ONE,
539 [VK_BLEND_FACTOR_SRC_COLOR] = BLENDFACTOR_SRC_COLOR,
540 [VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR] = BLENDFACTOR_INV_SRC_COLOR,
541 [VK_BLEND_FACTOR_DST_COLOR] = BLENDFACTOR_DST_COLOR,
542 [VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR] = BLENDFACTOR_INV_DST_COLOR,
543 [VK_BLEND_FACTOR_SRC_ALPHA] = BLENDFACTOR_SRC_ALPHA,
544 [VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA] = BLENDFACTOR_INV_SRC_ALPHA,
545 [VK_BLEND_FACTOR_DST_ALPHA] = BLENDFACTOR_DST_ALPHA,
546 [VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA] = BLENDFACTOR_INV_DST_ALPHA,
547 [VK_BLEND_FACTOR_CONSTANT_COLOR] = BLENDFACTOR_CONST_COLOR,
548 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR]= BLENDFACTOR_INV_CONST_COLOR,
549 [VK_BLEND_FACTOR_CONSTANT_ALPHA] = BLENDFACTOR_CONST_ALPHA,
550 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA]= BLENDFACTOR_INV_CONST_ALPHA,
551 [VK_BLEND_FACTOR_SRC_ALPHA_SATURATE] = BLENDFACTOR_SRC_ALPHA_SATURATE,
552 [VK_BLEND_FACTOR_SRC1_COLOR] = BLENDFACTOR_SRC1_COLOR,
553 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR] = BLENDFACTOR_INV_SRC1_COLOR,
554 [VK_BLEND_FACTOR_SRC1_ALPHA] = BLENDFACTOR_SRC1_ALPHA,
555 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA] = BLENDFACTOR_INV_SRC1_ALPHA,
556 };
557
558 static const uint32_t vk_to_gen_blend_op[] = {
559 [VK_BLEND_OP_ADD] = BLENDFUNCTION_ADD,
560 [VK_BLEND_OP_SUBTRACT] = BLENDFUNCTION_SUBTRACT,
561 [VK_BLEND_OP_REVERSE_SUBTRACT] = BLENDFUNCTION_REVERSE_SUBTRACT,
562 [VK_BLEND_OP_MIN] = BLENDFUNCTION_MIN,
563 [VK_BLEND_OP_MAX] = BLENDFUNCTION_MAX,
564 };
565
566 static const uint32_t vk_to_gen_compare_op[] = {
567 [VK_COMPARE_OP_NEVER] = PREFILTEROPNEVER,
568 [VK_COMPARE_OP_LESS] = PREFILTEROPLESS,
569 [VK_COMPARE_OP_EQUAL] = PREFILTEROPEQUAL,
570 [VK_COMPARE_OP_LESS_OR_EQUAL] = PREFILTEROPLEQUAL,
571 [VK_COMPARE_OP_GREATER] = PREFILTEROPGREATER,
572 [VK_COMPARE_OP_NOT_EQUAL] = PREFILTEROPNOTEQUAL,
573 [VK_COMPARE_OP_GREATER_OR_EQUAL] = PREFILTEROPGEQUAL,
574 [VK_COMPARE_OP_ALWAYS] = PREFILTEROPALWAYS,
575 };
576
577 static const uint32_t vk_to_gen_stencil_op[] = {
578 [VK_STENCIL_OP_KEEP] = STENCILOP_KEEP,
579 [VK_STENCIL_OP_ZERO] = STENCILOP_ZERO,
580 [VK_STENCIL_OP_REPLACE] = STENCILOP_REPLACE,
581 [VK_STENCIL_OP_INCREMENT_AND_CLAMP] = STENCILOP_INCRSAT,
582 [VK_STENCIL_OP_DECREMENT_AND_CLAMP] = STENCILOP_DECRSAT,
583 [VK_STENCIL_OP_INVERT] = STENCILOP_INVERT,
584 [VK_STENCIL_OP_INCREMENT_AND_WRAP] = STENCILOP_INCR,
585 [VK_STENCIL_OP_DECREMENT_AND_WRAP] = STENCILOP_DECR,
586 };
587
588 static void
589 emit_ds_state(struct anv_pipeline *pipeline,
590 const VkPipelineDepthStencilStateCreateInfo *info,
591 const struct anv_render_pass *pass,
592 const struct anv_subpass *subpass)
593 {
594 #if GEN_GEN == 7
595 # define depth_stencil_dw pipeline->gen7.depth_stencil_state
596 #elif GEN_GEN == 8
597 # define depth_stencil_dw pipeline->gen8.wm_depth_stencil
598 #else
599 # define depth_stencil_dw pipeline->gen9.wm_depth_stencil
600 #endif
601
602 if (info == NULL) {
603 /* We're going to OR this together with the dynamic state. We need
604 * to make sure it's initialized to something useful.
605 */
606 memset(depth_stencil_dw, 0, sizeof(depth_stencil_dw));
607 return;
608 }
609
610 /* VkBool32 depthBoundsTestEnable; // optional (depth_bounds_test) */
611
612 #if GEN_GEN <= 7
613 struct GENX(DEPTH_STENCIL_STATE) depth_stencil = {
614 #else
615 struct GENX(3DSTATE_WM_DEPTH_STENCIL) depth_stencil = {
616 #endif
617 .DepthTestEnable = info->depthTestEnable,
618 .DepthBufferWriteEnable = info->depthWriteEnable,
619 .DepthTestFunction = vk_to_gen_compare_op[info->depthCompareOp],
620 .DoubleSidedStencilEnable = true,
621
622 .StencilTestEnable = info->stencilTestEnable,
623 .StencilBufferWriteEnable = info->stencilTestEnable,
624 .StencilFailOp = vk_to_gen_stencil_op[info->front.failOp],
625 .StencilPassDepthPassOp = vk_to_gen_stencil_op[info->front.passOp],
626 .StencilPassDepthFailOp = vk_to_gen_stencil_op[info->front.depthFailOp],
627 .StencilTestFunction = vk_to_gen_compare_op[info->front.compareOp],
628 .BackfaceStencilFailOp = vk_to_gen_stencil_op[info->back.failOp],
629 .BackfaceStencilPassDepthPassOp = vk_to_gen_stencil_op[info->back.passOp],
630 .BackfaceStencilPassDepthFailOp =vk_to_gen_stencil_op[info->back.depthFailOp],
631 .BackfaceStencilTestFunction = vk_to_gen_compare_op[info->back.compareOp],
632 };
633
634 VkImageAspectFlags aspects = 0;
635 if (subpass->depth_stencil_attachment != VK_ATTACHMENT_UNUSED) {
636 VkFormat depth_stencil_format =
637 pass->attachments[subpass->depth_stencil_attachment].format;
638 aspects = vk_format_aspects(depth_stencil_format);
639 }
640
641 /* The Vulkan spec requires that if either depth or stencil is not present,
642 * the pipeline is to act as if the test silently passes.
643 */
644 if (!(aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
645 depth_stencil.DepthBufferWriteEnable = false;
646 depth_stencil.DepthTestFunction = PREFILTEROPALWAYS;
647 }
648
649 if (!(aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
650 depth_stencil.StencilBufferWriteEnable = false;
651 depth_stencil.StencilTestFunction = PREFILTEROPALWAYS;
652 depth_stencil.BackfaceStencilTestFunction = PREFILTEROPALWAYS;
653 }
654
655 /* From the Broadwell PRM:
656 *
657 * "If Depth_Test_Enable = 1 AND Depth_Test_func = EQUAL, the
658 * Depth_Write_Enable must be set to 0."
659 */
660 if (info->depthTestEnable && info->depthCompareOp == VK_COMPARE_OP_EQUAL)
661 depth_stencil.DepthBufferWriteEnable = false;
662
663 #if GEN_GEN <= 7
664 GENX(DEPTH_STENCIL_STATE_pack)(NULL, depth_stencil_dw, &depth_stencil);
665 #else
666 GENX(3DSTATE_WM_DEPTH_STENCIL_pack)(NULL, depth_stencil_dw, &depth_stencil);
667 #endif
668 }
669
670 static void
671 emit_cb_state(struct anv_pipeline *pipeline,
672 const VkPipelineColorBlendStateCreateInfo *info,
673 const VkPipelineMultisampleStateCreateInfo *ms_info)
674 {
675 struct anv_device *device = pipeline->device;
676
677 const uint32_t num_dwords = GENX(BLEND_STATE_length);
678 pipeline->blend_state =
679 anv_state_pool_alloc(&device->dynamic_state_pool, num_dwords * 4, 64);
680
681 struct GENX(BLEND_STATE) blend_state = {
682 #if GEN_GEN >= 8
683 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
684 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
685 #else
686 /* Make sure it gets zeroed */
687 .Entry = { { 0, }, },
688 #endif
689 };
690
691 /* Default everything to disabled */
692 for (uint32_t i = 0; i < 8; i++) {
693 blend_state.Entry[i].WriteDisableAlpha = true;
694 blend_state.Entry[i].WriteDisableRed = true;
695 blend_state.Entry[i].WriteDisableGreen = true;
696 blend_state.Entry[i].WriteDisableBlue = true;
697 }
698
699 uint32_t surface_count = 0;
700 struct anv_pipeline_bind_map *map;
701 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
702 map = &pipeline->shaders[MESA_SHADER_FRAGMENT]->bind_map;
703 surface_count = map->surface_count;
704 }
705
706 bool has_writeable_rt = false;
707 for (unsigned i = 0; i < surface_count; i++) {
708 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[i];
709
710 /* All color attachments are at the beginning of the binding table */
711 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
712 break;
713
714 /* We can have at most 8 attachments */
715 assert(i < 8);
716
717 if (binding->index >= info->attachmentCount)
718 continue;
719
720 assert(binding->binding == 0);
721 const VkPipelineColorBlendAttachmentState *a =
722 &info->pAttachments[binding->index];
723
724 blend_state.Entry[i] = (struct GENX(BLEND_STATE_ENTRY)) {
725 #if GEN_GEN < 8
726 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
727 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
728 #endif
729 .LogicOpEnable = info->logicOpEnable,
730 .LogicOpFunction = vk_to_gen_logic_op[info->logicOp],
731 .ColorBufferBlendEnable = a->blendEnable,
732 .ColorClampRange = COLORCLAMP_RTFORMAT,
733 .PreBlendColorClampEnable = true,
734 .PostBlendColorClampEnable = true,
735 .SourceBlendFactor = vk_to_gen_blend[a->srcColorBlendFactor],
736 .DestinationBlendFactor = vk_to_gen_blend[a->dstColorBlendFactor],
737 .ColorBlendFunction = vk_to_gen_blend_op[a->colorBlendOp],
738 .SourceAlphaBlendFactor = vk_to_gen_blend[a->srcAlphaBlendFactor],
739 .DestinationAlphaBlendFactor = vk_to_gen_blend[a->dstAlphaBlendFactor],
740 .AlphaBlendFunction = vk_to_gen_blend_op[a->alphaBlendOp],
741 .WriteDisableAlpha = !(a->colorWriteMask & VK_COLOR_COMPONENT_A_BIT),
742 .WriteDisableRed = !(a->colorWriteMask & VK_COLOR_COMPONENT_R_BIT),
743 .WriteDisableGreen = !(a->colorWriteMask & VK_COLOR_COMPONENT_G_BIT),
744 .WriteDisableBlue = !(a->colorWriteMask & VK_COLOR_COMPONENT_B_BIT),
745 };
746
747 if (a->srcColorBlendFactor != a->srcAlphaBlendFactor ||
748 a->dstColorBlendFactor != a->dstAlphaBlendFactor ||
749 a->colorBlendOp != a->alphaBlendOp) {
750 #if GEN_GEN >= 8
751 blend_state.IndependentAlphaBlendEnable = true;
752 #else
753 blend_state.Entry[i].IndependentAlphaBlendEnable = true;
754 #endif
755 }
756
757 if (a->colorWriteMask != 0)
758 has_writeable_rt = true;
759
760 /* Our hardware applies the blend factor prior to the blend function
761 * regardless of what function is used. Technically, this means the
762 * hardware can do MORE than GL or Vulkan specify. However, it also
763 * means that, for MIN and MAX, we have to stomp the blend factor to
764 * ONE to make it a no-op.
765 */
766 if (a->colorBlendOp == VK_BLEND_OP_MIN ||
767 a->colorBlendOp == VK_BLEND_OP_MAX) {
768 blend_state.Entry[i].SourceBlendFactor = BLENDFACTOR_ONE;
769 blend_state.Entry[i].DestinationBlendFactor = BLENDFACTOR_ONE;
770 }
771 if (a->alphaBlendOp == VK_BLEND_OP_MIN ||
772 a->alphaBlendOp == VK_BLEND_OP_MAX) {
773 blend_state.Entry[i].SourceAlphaBlendFactor = BLENDFACTOR_ONE;
774 blend_state.Entry[i].DestinationAlphaBlendFactor = BLENDFACTOR_ONE;
775 }
776 }
777
778 #if GEN_GEN >= 8
779 struct GENX(BLEND_STATE_ENTRY) *bs0 = &blend_state.Entry[0];
780 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_BLEND), blend) {
781 blend.AlphaToCoverageEnable = blend_state.AlphaToCoverageEnable;
782 blend.HasWriteableRT = has_writeable_rt;
783 blend.ColorBufferBlendEnable = bs0->ColorBufferBlendEnable;
784 blend.SourceAlphaBlendFactor = bs0->SourceAlphaBlendFactor;
785 blend.DestinationAlphaBlendFactor = bs0->DestinationAlphaBlendFactor;
786 blend.SourceBlendFactor = bs0->SourceBlendFactor;
787 blend.DestinationBlendFactor = bs0->DestinationBlendFactor;
788 blend.AlphaTestEnable = false;
789 blend.IndependentAlphaBlendEnable =
790 blend_state.IndependentAlphaBlendEnable;
791 }
792 #else
793 (void)has_writeable_rt;
794 #endif
795
796 GENX(BLEND_STATE_pack)(NULL, pipeline->blend_state.map, &blend_state);
797 if (!device->info.has_llc)
798 anv_state_clflush(pipeline->blend_state);
799
800 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_BLEND_STATE_POINTERS), bsp) {
801 bsp.BlendStatePointer = pipeline->blend_state.offset;
802 #if GEN_GEN >= 8
803 bsp.BlendStatePointerValid = true;
804 #endif
805 }
806 }
807
808 /**
809 * Get the brw_vue_prog_data for the last stage which outputs VUEs.
810 */
811 static inline struct brw_vue_prog_data *
812 get_last_vue_prog_data(struct anv_pipeline *pipeline)
813 {
814 for (int s = MESA_SHADER_GEOMETRY; s >= 0; s--) {
815 if (pipeline->shaders[s])
816 return (struct brw_vue_prog_data *) pipeline->shaders[s]->prog_data;
817 }
818 return NULL;
819 }
820
821 static void
822 emit_3dstate_clip(struct anv_pipeline *pipeline,
823 const VkPipelineViewportStateCreateInfo *vp_info,
824 const VkPipelineRasterizationStateCreateInfo *rs_info)
825 {
826 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
827 (void) wm_prog_data;
828 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_CLIP), clip) {
829 clip.ClipEnable = true;
830 clip.EarlyCullEnable = true;
831 clip.APIMode = APIMODE_D3D,
832 clip.ViewportXYClipTestEnable = true;
833
834 clip.ClipMode = CLIPMODE_NORMAL;
835
836 clip.TriangleStripListProvokingVertexSelect = 0;
837 clip.LineStripListProvokingVertexSelect = 0;
838 clip.TriangleFanProvokingVertexSelect = 1;
839
840 clip.MinimumPointWidth = 0.125;
841 clip.MaximumPointWidth = 255.875;
842 clip.MaximumVPIndex = (vp_info ? vp_info->viewportCount : 1) - 1;
843
844 #if GEN_GEN == 7
845 clip.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
846 clip.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
847 clip.ViewportZClipTestEnable = !pipeline->depth_clamp_enable;
848 const struct brw_vue_prog_data *last = get_last_vue_prog_data(pipeline);
849 if (last) {
850 clip.UserClipDistanceClipTestEnableBitmask = last->clip_distance_mask;
851 clip.UserClipDistanceCullTestEnableBitmask = last->cull_distance_mask;
852 }
853 #else
854 clip.NonPerspectiveBarycentricEnable = wm_prog_data ?
855 (wm_prog_data->barycentric_interp_modes & 0x38) != 0 : 0;
856 #endif
857 }
858 }
859
860 static void
861 emit_3dstate_streamout(struct anv_pipeline *pipeline,
862 const VkPipelineRasterizationStateCreateInfo *rs_info)
863 {
864 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_STREAMOUT), so) {
865 so.RenderingDisable = rs_info->rasterizerDiscardEnable;
866 }
867 }
868
869 static inline uint32_t
870 get_sampler_count(const struct anv_shader_bin *bin)
871 {
872 return DIV_ROUND_UP(bin->bind_map.sampler_count, 4);
873 }
874
875 static inline uint32_t
876 get_binding_table_entry_count(const struct anv_shader_bin *bin)
877 {
878 return DIV_ROUND_UP(bin->bind_map.surface_count, 32);
879 }
880
881 static inline struct anv_address
882 get_scratch_address(struct anv_pipeline *pipeline,
883 gl_shader_stage stage,
884 const struct anv_shader_bin *bin)
885 {
886 return (struct anv_address) {
887 .bo = anv_scratch_pool_alloc(pipeline->device,
888 &pipeline->device->scratch_pool,
889 stage, bin->prog_data->total_scratch),
890 .offset = 0,
891 };
892 }
893
894 static inline uint32_t
895 get_scratch_space(const struct anv_shader_bin *bin)
896 {
897 return ffs(bin->prog_data->total_scratch / 2048);
898 }
899
900 static inline uint32_t
901 get_urb_output_offset()
902 {
903 /* Skip the VUE header and position slots */
904 return 1;
905 }
906
907 static inline uint32_t
908 get_urb_output_length(const struct anv_shader_bin *bin)
909 {
910 const struct brw_vue_prog_data *prog_data =
911 (const struct brw_vue_prog_data *)bin->prog_data;
912
913 return (prog_data->vue_map.num_slots + 1) / 2 - get_urb_output_offset();
914 }
915
916 static void
917 emit_3dstate_vs(struct anv_pipeline *pipeline)
918 {
919 const struct gen_device_info *devinfo = &pipeline->device->info;
920 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
921 const struct anv_shader_bin *vs_bin =
922 pipeline->shaders[MESA_SHADER_VERTEX];
923
924 assert(anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX));
925
926 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VS), vs) {
927 vs.FunctionEnable = true;
928 vs.StatisticsEnable = true;
929 vs.KernelStartPointer = vs_bin->kernel.offset;
930 #if GEN_GEN >= 8
931 vs.SIMD8DispatchEnable =
932 vs_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8;
933 #endif
934
935 assert(!vs_prog_data->base.base.use_alt_mode);
936 vs.SingleVertexDispatch = false;
937 vs.VectorMaskEnable = false;
938 vs.SamplerCount = get_sampler_count(vs_bin);
939 vs.BindingTableEntryCount = get_binding_table_entry_count(vs_bin);
940 vs.FloatingPointMode = IEEE754;
941 vs.IllegalOpcodeExceptionEnable = false;
942 vs.SoftwareExceptionEnable = false;
943 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
944 vs.VertexCacheDisable = false;
945
946 vs.VertexURBEntryReadLength = vs_prog_data->base.urb_read_length;
947 vs.VertexURBEntryReadOffset = 0;
948 vs.DispatchGRFStartRegisterForURBData =
949 vs_prog_data->base.base.dispatch_grf_start_reg;
950
951 #if GEN_GEN >= 8
952 vs.VertexURBEntryOutputReadOffset = get_urb_output_offset();
953 vs.VertexURBEntryOutputLength = get_urb_output_length(vs_bin);
954
955 vs.UserClipDistanceClipTestEnableBitmask =
956 vs_prog_data->base.clip_distance_mask;
957 vs.UserClipDistanceCullTestEnableBitmask =
958 vs_prog_data->base.cull_distance_mask;
959 #endif
960
961 vs.PerThreadScratchSpace = get_scratch_space(vs_bin);
962 vs.ScratchSpaceBasePointer =
963 get_scratch_address(pipeline, MESA_SHADER_VERTEX, vs_bin);
964 }
965 }
966
967 static void
968 emit_3dstate_gs(struct anv_pipeline *pipeline)
969 {
970 const struct gen_device_info *devinfo = &pipeline->device->info;
971 const struct anv_shader_bin *gs_bin =
972 pipeline->shaders[MESA_SHADER_GEOMETRY];
973
974 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
975 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs);
976 return;
977 }
978
979 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
980
981 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs) {
982 gs.FunctionEnable = true;
983 gs.StatisticsEnable = true;
984 gs.KernelStartPointer = gs_bin->kernel.offset;
985 gs.DispatchMode = gs_prog_data->base.dispatch_mode;
986
987 gs.SingleProgramFlow = false;
988 gs.VectorMaskEnable = false;
989 gs.SamplerCount = get_sampler_count(gs_bin);
990 gs.BindingTableEntryCount = get_binding_table_entry_count(gs_bin);
991 gs.IncludeVertexHandles = gs_prog_data->base.include_vue_handles;
992 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
993
994 if (GEN_GEN == 8) {
995 /* Broadwell is weird. It needs us to divide by 2. */
996 gs.MaximumNumberofThreads = devinfo->max_gs_threads / 2 - 1;
997 } else {
998 gs.MaximumNumberofThreads = devinfo->max_gs_threads - 1;
999 }
1000
1001 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
1002 gs.OutputTopology = gs_prog_data->output_topology;
1003 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1004 gs.ControlDataFormat = gs_prog_data->control_data_format;
1005 gs.ControlDataHeaderSize = gs_prog_data->control_data_header_size_hwords;
1006 gs.InstanceControl = MAX2(gs_prog_data->invocations, 1) - 1;
1007 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1008 gs.ReorderMode = TRAILING;
1009 #else
1010 gs.ReorderEnable = true;
1011 #endif
1012
1013 #if GEN_GEN >= 8
1014 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
1015 gs.StaticOutput = gs_prog_data->static_vertex_count >= 0;
1016 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count >= 0 ?
1017 gs_prog_data->static_vertex_count : 0;
1018 #endif
1019
1020 gs.VertexURBEntryReadOffset = 0;
1021 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1022 gs.DispatchGRFStartRegisterForURBData =
1023 gs_prog_data->base.base.dispatch_grf_start_reg;
1024
1025 #if GEN_GEN >= 8
1026 gs.VertexURBEntryOutputReadOffset = get_urb_output_offset();
1027 gs.VertexURBEntryOutputLength = get_urb_output_length(gs_bin);
1028
1029 gs.UserClipDistanceClipTestEnableBitmask =
1030 gs_prog_data->base.clip_distance_mask;
1031 gs.UserClipDistanceCullTestEnableBitmask =
1032 gs_prog_data->base.cull_distance_mask;
1033 #endif
1034
1035 gs.PerThreadScratchSpace = get_scratch_space(gs_bin);
1036 gs.ScratchSpaceBasePointer =
1037 get_scratch_address(pipeline, MESA_SHADER_GEOMETRY, gs_bin);
1038 }
1039 }
1040
1041 static void
1042 emit_3dstate_wm(struct anv_pipeline *pipeline, struct anv_subpass *subpass,
1043 const VkPipelineMultisampleStateCreateInfo *multisample)
1044 {
1045 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1046
1047 MAYBE_UNUSED uint32_t samples =
1048 multisample ? multisample->rasterizationSamples : 1;
1049
1050 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_WM), wm) {
1051 wm.StatisticsEnable = true;
1052 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1053 wm.LineAntialiasingRegionWidth = _10pixels;
1054 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1055
1056 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1057 if (wm_prog_data->early_fragment_tests) {
1058 wm.EarlyDepthStencilControl = EDSC_PREPS;
1059 } else if (wm_prog_data->has_side_effects) {
1060 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
1061 } else {
1062 wm.EarlyDepthStencilControl = EDSC_NORMAL;
1063 }
1064
1065 wm.BarycentricInterpolationMode =
1066 wm_prog_data->barycentric_interp_modes;
1067
1068 #if GEN_GEN < 8
1069 /* FIXME: This needs a lot more work, cf gen7 upload_wm_state(). */
1070 wm.ThreadDispatchEnable = true;
1071
1072 wm.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1073 wm.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1074 wm.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1075 wm.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1076
1077 /* If the subpass has a depth or stencil self-dependency, then we
1078 * need to force the hardware to do the depth/stencil write *after*
1079 * fragment shader execution. Otherwise, the writes may hit memory
1080 * before we get around to fetching from the input attachment and we
1081 * may get the depth or stencil value from the current draw rather
1082 * than the previous one.
1083 */
1084 wm.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1085 wm_prog_data->uses_kill;
1086
1087 if (samples > 1) {
1088 wm.MultisampleRasterizationMode = MSRASTMODE_ON_PATTERN;
1089 if (wm_prog_data->persample_dispatch) {
1090 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1091 } else {
1092 wm.MultisampleDispatchMode = MSDISPMODE_PERPIXEL;
1093 }
1094 } else {
1095 wm.MultisampleRasterizationMode = MSRASTMODE_OFF_PIXEL;
1096 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1097 }
1098 #endif
1099 }
1100 }
1101 }
1102
1103 static bool
1104 is_dual_src_blend_factor(VkBlendFactor factor)
1105 {
1106 return factor == VK_BLEND_FACTOR_SRC1_COLOR ||
1107 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR ||
1108 factor == VK_BLEND_FACTOR_SRC1_ALPHA ||
1109 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
1110 }
1111
1112 static void
1113 emit_3dstate_ps(struct anv_pipeline *pipeline,
1114 const VkPipelineColorBlendStateCreateInfo *blend)
1115 {
1116 MAYBE_UNUSED const struct gen_device_info *devinfo = &pipeline->device->info;
1117 const struct anv_shader_bin *fs_bin =
1118 pipeline->shaders[MESA_SHADER_FRAGMENT];
1119
1120 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1121 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1122 #if GEN_GEN == 7
1123 /* Even if no fragments are ever dispatched, gen7 hardware hangs if
1124 * we don't at least set the maximum number of threads.
1125 */
1126 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1127 #endif
1128 }
1129 return;
1130 }
1131
1132 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1133
1134 #if GEN_GEN < 8
1135 /* The hardware wedges if you have this bit set but don't turn on any dual
1136 * source blend factors.
1137 */
1138 bool dual_src_blend = false;
1139 if (wm_prog_data->dual_src_blend) {
1140 for (uint32_t i = 0; i < blend->attachmentCount; i++) {
1141 const VkPipelineColorBlendAttachmentState *bstate =
1142 &blend->pAttachments[i];
1143
1144 if (bstate->blendEnable &&
1145 (is_dual_src_blend_factor(bstate->srcColorBlendFactor) ||
1146 is_dual_src_blend_factor(bstate->dstColorBlendFactor) ||
1147 is_dual_src_blend_factor(bstate->srcAlphaBlendFactor) ||
1148 is_dual_src_blend_factor(bstate->dstAlphaBlendFactor))) {
1149 dual_src_blend = true;
1150 break;
1151 }
1152 }
1153 }
1154 #endif
1155
1156 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1157 ps.KernelStartPointer0 = fs_bin->kernel.offset;
1158 ps.KernelStartPointer1 = 0;
1159 ps.KernelStartPointer2 = fs_bin->kernel.offset +
1160 wm_prog_data->prog_offset_2;
1161 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
1162 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
1163 ps._32PixelDispatchEnable = false;
1164
1165 ps.SingleProgramFlow = false;
1166 ps.VectorMaskEnable = true;
1167 ps.SamplerCount = get_sampler_count(fs_bin);
1168 ps.BindingTableEntryCount = get_binding_table_entry_count(fs_bin);
1169 ps.PushConstantEnable = wm_prog_data->base.nr_params > 0;
1170 ps.PositionXYOffsetSelect = wm_prog_data->uses_pos_offset ?
1171 POSOFFSET_SAMPLE: POSOFFSET_NONE;
1172 #if GEN_GEN < 8
1173 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1174 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1175 ps.DualSourceBlendEnable = dual_src_blend;
1176 #endif
1177
1178 #if GEN_IS_HASWELL
1179 /* Haswell requires the sample mask to be set in this packet as well
1180 * as in 3DSTATE_SAMPLE_MASK; the values should match.
1181 */
1182 ps.SampleMask = 0xff;
1183 #endif
1184
1185 #if GEN_GEN >= 9
1186 ps.MaximumNumberofThreadsPerPSD = 64 - 1;
1187 #elif GEN_GEN >= 8
1188 ps.MaximumNumberofThreadsPerPSD = 64 - 2;
1189 #else
1190 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1191 #endif
1192
1193 ps.DispatchGRFStartRegisterForConstantSetupData0 =
1194 wm_prog_data->base.dispatch_grf_start_reg;
1195 ps.DispatchGRFStartRegisterForConstantSetupData1 = 0;
1196 ps.DispatchGRFStartRegisterForConstantSetupData2 =
1197 wm_prog_data->dispatch_grf_start_reg_2;
1198
1199 ps.PerThreadScratchSpace = get_scratch_space(fs_bin);
1200 ps.ScratchSpaceBasePointer =
1201 get_scratch_address(pipeline, MESA_SHADER_FRAGMENT, fs_bin);
1202 }
1203 }
1204
1205 #if GEN_GEN >= 8
1206 static void
1207 emit_3dstate_ps_extra(struct anv_pipeline *pipeline,
1208 struct anv_subpass *subpass)
1209 {
1210 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1211
1212 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1213 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps);
1214 return;
1215 }
1216
1217 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps) {
1218 ps.PixelShaderValid = true;
1219 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1220 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1221 ps.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
1222 ps.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1223 ps.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1224 ps.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1225
1226 /* If the subpass has a depth or stencil self-dependency, then we need
1227 * to force the hardware to do the depth/stencil write *after* fragment
1228 * shader execution. Otherwise, the writes may hit memory before we get
1229 * around to fetching from the input attachment and we may get the depth
1230 * or stencil value from the current draw rather than the previous one.
1231 */
1232 ps.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1233 wm_prog_data->uses_kill;
1234
1235 #if GEN_GEN >= 9
1236 ps.PixelShaderPullsBary = wm_prog_data->pulls_bary;
1237 ps.InputCoverageMaskState = wm_prog_data->uses_sample_mask ?
1238 ICMS_INNER_CONSERVATIVE : ICMS_NONE;
1239 #else
1240 ps.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1241 #endif
1242 }
1243 }
1244
1245 static void
1246 emit_3dstate_vf_topology(struct anv_pipeline *pipeline)
1247 {
1248 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_TOPOLOGY), vft) {
1249 vft.PrimitiveTopologyType = pipeline->topology;
1250 }
1251 }
1252 #endif
1253
1254 static VkResult
1255 genX(graphics_pipeline_create)(
1256 VkDevice _device,
1257 struct anv_pipeline_cache * cache,
1258 const VkGraphicsPipelineCreateInfo* pCreateInfo,
1259 const VkAllocationCallbacks* pAllocator,
1260 VkPipeline* pPipeline)
1261 {
1262 ANV_FROM_HANDLE(anv_device, device, _device);
1263 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
1264 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
1265 struct anv_pipeline *pipeline;
1266 VkResult result;
1267
1268 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
1269
1270 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
1271 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1272 if (pipeline == NULL)
1273 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1274
1275 result = anv_pipeline_init(pipeline, device, cache,
1276 pCreateInfo, pAllocator);
1277 if (result != VK_SUCCESS) {
1278 vk_free2(&device->alloc, pAllocator, pipeline);
1279 return result;
1280 }
1281
1282 assert(pCreateInfo->pVertexInputState);
1283 emit_vertex_input(pipeline, pCreateInfo->pVertexInputState);
1284 assert(pCreateInfo->pRasterizationState);
1285 emit_rs_state(pipeline, pCreateInfo->pRasterizationState,
1286 pCreateInfo->pMultisampleState, pass, subpass);
1287 emit_ms_state(pipeline, pCreateInfo->pMultisampleState);
1288 emit_ds_state(pipeline, pCreateInfo->pDepthStencilState, pass, subpass);
1289 emit_cb_state(pipeline, pCreateInfo->pColorBlendState,
1290 pCreateInfo->pMultisampleState);
1291
1292 emit_urb_setup(pipeline);
1293
1294 emit_3dstate_clip(pipeline, pCreateInfo->pViewportState,
1295 pCreateInfo->pRasterizationState);
1296 emit_3dstate_streamout(pipeline, pCreateInfo->pRasterizationState);
1297
1298 #if 0
1299 /* From gen7_vs_state.c */
1300
1301 /**
1302 * From Graphics BSpec: 3D-Media-GPGPU Engine > 3D Pipeline Stages >
1303 * Geometry > Geometry Shader > State:
1304 *
1305 * "Note: Because of corruption in IVB:GT2, software needs to flush the
1306 * whole fixed function pipeline when the GS enable changes value in
1307 * the 3DSTATE_GS."
1308 *
1309 * The hardware architects have clarified that in this context "flush the
1310 * whole fixed function pipeline" means to emit a PIPE_CONTROL with the "CS
1311 * Stall" bit set.
1312 */
1313 if (!brw->is_haswell && !brw->is_baytrail)
1314 gen7_emit_vs_workaround_flush(brw);
1315 #endif
1316
1317 emit_3dstate_vs(pipeline);
1318 emit_3dstate_gs(pipeline);
1319 emit_3dstate_sbe(pipeline);
1320 emit_3dstate_wm(pipeline, subpass, pCreateInfo->pMultisampleState);
1321 emit_3dstate_ps(pipeline, pCreateInfo->pColorBlendState);
1322 #if GEN_GEN >= 8
1323 emit_3dstate_ps_extra(pipeline, subpass);
1324 emit_3dstate_vf_topology(pipeline);
1325 #endif
1326
1327 *pPipeline = anv_pipeline_to_handle(pipeline);
1328
1329 return VK_SUCCESS;
1330 }
1331
1332 static VkResult
1333 compute_pipeline_create(
1334 VkDevice _device,
1335 struct anv_pipeline_cache * cache,
1336 const VkComputePipelineCreateInfo* pCreateInfo,
1337 const VkAllocationCallbacks* pAllocator,
1338 VkPipeline* pPipeline)
1339 {
1340 ANV_FROM_HANDLE(anv_device, device, _device);
1341 const struct anv_physical_device *physical_device =
1342 &device->instance->physicalDevice;
1343 const struct gen_device_info *devinfo = &physical_device->info;
1344 struct anv_pipeline *pipeline;
1345 VkResult result;
1346
1347 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO);
1348
1349 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
1350 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1351 if (pipeline == NULL)
1352 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1353
1354 pipeline->device = device;
1355 pipeline->layout = anv_pipeline_layout_from_handle(pCreateInfo->layout);
1356
1357 pipeline->blend_state.map = NULL;
1358
1359 result = anv_reloc_list_init(&pipeline->batch_relocs,
1360 pAllocator ? pAllocator : &device->alloc);
1361 if (result != VK_SUCCESS) {
1362 vk_free2(&device->alloc, pAllocator, pipeline);
1363 return result;
1364 }
1365 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
1366 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
1367 pipeline->batch.relocs = &pipeline->batch_relocs;
1368
1369 /* When we free the pipeline, we detect stages based on the NULL status
1370 * of various prog_data pointers. Make them NULL by default.
1371 */
1372 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
1373
1374 pipeline->active_stages = 0;
1375
1376 pipeline->needs_data_cache = false;
1377
1378 assert(pCreateInfo->stage.stage == VK_SHADER_STAGE_COMPUTE_BIT);
1379 ANV_FROM_HANDLE(anv_shader_module, module, pCreateInfo->stage.module);
1380 result = anv_pipeline_compile_cs(pipeline, cache, pCreateInfo, module,
1381 pCreateInfo->stage.pName,
1382 pCreateInfo->stage.pSpecializationInfo);
1383 if (result != VK_SUCCESS) {
1384 vk_free2(&device->alloc, pAllocator, pipeline);
1385 return result;
1386 }
1387
1388 const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
1389
1390 anv_pipeline_setup_l3_config(pipeline, cs_prog_data->base.total_shared > 0);
1391
1392 uint32_t group_size = cs_prog_data->local_size[0] *
1393 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
1394 uint32_t remainder = group_size & (cs_prog_data->simd_size - 1);
1395
1396 if (remainder > 0)
1397 pipeline->cs_right_mask = ~0u >> (32 - remainder);
1398 else
1399 pipeline->cs_right_mask = ~0u >> (32 - cs_prog_data->simd_size);
1400
1401 const uint32_t vfe_curbe_allocation =
1402 ALIGN(cs_prog_data->push.per_thread.regs * cs_prog_data->threads +
1403 cs_prog_data->push.cross_thread.regs, 2);
1404
1405 const uint32_t subslices = MAX2(physical_device->subslice_total, 1);
1406
1407 const struct anv_shader_bin *cs_bin =
1408 pipeline->shaders[MESA_SHADER_COMPUTE];
1409
1410 anv_batch_emit(&pipeline->batch, GENX(MEDIA_VFE_STATE), vfe) {
1411 #if GEN_GEN > 7
1412 vfe.StackSize = 0;
1413 #else
1414 vfe.GPGPUMode = true;
1415 #endif
1416 vfe.MaximumNumberofThreads =
1417 devinfo->max_cs_threads * subslices - 1;
1418 vfe.NumberofURBEntries = GEN_GEN <= 7 ? 0 : 2;
1419 vfe.ResetGatewayTimer = true;
1420 #if GEN_GEN <= 8
1421 vfe.BypassGatewayControl = true;
1422 #endif
1423 vfe.URBEntryAllocationSize = GEN_GEN <= 7 ? 0 : 2;
1424 vfe.CURBEAllocationSize = vfe_curbe_allocation;
1425
1426 vfe.PerThreadScratchSpace = get_scratch_space(cs_bin);
1427 vfe.ScratchSpaceBasePointer =
1428 get_scratch_address(pipeline, MESA_SHADER_COMPUTE, cs_bin);
1429 }
1430
1431 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
1432 .KernelStartPointer = cs_bin->kernel.offset,
1433
1434 .SamplerCount = get_sampler_count(cs_bin),
1435 .BindingTableEntryCount = get_binding_table_entry_count(cs_bin),
1436 .BarrierEnable = cs_prog_data->uses_barrier,
1437 .SharedLocalMemorySize =
1438 encode_slm_size(GEN_GEN, cs_prog_data->base.total_shared),
1439
1440 #if !GEN_IS_HASWELL
1441 .ConstantURBEntryReadOffset = 0,
1442 #endif
1443 .ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs,
1444 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1445 .CrossThreadConstantDataReadLength =
1446 cs_prog_data->push.cross_thread.regs,
1447 #endif
1448
1449 .NumberofThreadsinGPGPUThreadGroup = cs_prog_data->threads,
1450 };
1451 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL,
1452 pipeline->interface_descriptor_data,
1453 &desc);
1454
1455 *pPipeline = anv_pipeline_to_handle(pipeline);
1456
1457 return VK_SUCCESS;
1458 }
1459
1460 VkResult genX(CreateGraphicsPipelines)(
1461 VkDevice _device,
1462 VkPipelineCache pipelineCache,
1463 uint32_t count,
1464 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1465 const VkAllocationCallbacks* pAllocator,
1466 VkPipeline* pPipelines)
1467 {
1468 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
1469
1470 VkResult result = VK_SUCCESS;
1471
1472 unsigned i = 0;
1473 for (; i < count; i++) {
1474 result = genX(graphics_pipeline_create)(_device,
1475 pipeline_cache,
1476 &pCreateInfos[i],
1477 pAllocator, &pPipelines[i]);
1478 if (result != VK_SUCCESS) {
1479 for (unsigned j = 0; j < i; j++) {
1480 anv_DestroyPipeline(_device, pPipelines[j], pAllocator);
1481 }
1482
1483 return result;
1484 }
1485 }
1486
1487 return VK_SUCCESS;
1488 }
1489
1490 VkResult genX(CreateComputePipelines)(
1491 VkDevice _device,
1492 VkPipelineCache pipelineCache,
1493 uint32_t count,
1494 const VkComputePipelineCreateInfo* pCreateInfos,
1495 const VkAllocationCallbacks* pAllocator,
1496 VkPipeline* pPipelines)
1497 {
1498 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
1499
1500 VkResult result = VK_SUCCESS;
1501
1502 unsigned i = 0;
1503 for (; i < count; i++) {
1504 result = compute_pipeline_create(_device, pipeline_cache,
1505 &pCreateInfos[i],
1506 pAllocator, &pPipelines[i]);
1507 if (result != VK_SUCCESS) {
1508 for (unsigned j = 0; j < i; j++) {
1509 anv_DestroyPipeline(_device, pPipelines[j], pAllocator);
1510 }
1511
1512 return result;
1513 }
1514 }
1515
1516 return VK_SUCCESS;
1517 }