radeonsi/gfx10: fix unnecessary LDS overallocation for NGG GS
[mesa.git] / src / gallium / drivers / radeonsi / si_shader.c
1 /*
2 * Copyright 2012 Advanced Micro Devices, Inc.
3 * All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * on the rights to use, copy, modify, merge, publish, distribute, sub
9 * license, and/or sell copies of the Software, and to permit persons to whom
10 * the Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
14 * Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
20 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22 * USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 #include "util/u_memory.h"
26 #include "util/u_string.h"
27 #include "tgsi/tgsi_build.h"
28 #include "tgsi/tgsi_strings.h"
29 #include "tgsi/tgsi_util.h"
30 #include "tgsi/tgsi_dump.h"
31 #include "tgsi/tgsi_from_mesa.h"
32
33 #include "ac_binary.h"
34 #include "ac_exp_param.h"
35 #include "ac_shader_util.h"
36 #include "ac_rtld.h"
37 #include "ac_llvm_util.h"
38 #include "si_shader_internal.h"
39 #include "si_pipe.h"
40 #include "sid.h"
41
42 #include "compiler/nir/nir.h"
43
44 static const char scratch_rsrc_dword0_symbol[] =
45 "SCRATCH_RSRC_DWORD0";
46
47 static const char scratch_rsrc_dword1_symbol[] =
48 "SCRATCH_RSRC_DWORD1";
49
50 static void si_init_shader_ctx(struct si_shader_context *ctx,
51 struct si_screen *sscreen,
52 struct ac_llvm_compiler *compiler);
53
54 static void si_llvm_emit_barrier(const struct lp_build_tgsi_action *action,
55 struct lp_build_tgsi_context *bld_base,
56 struct lp_build_emit_data *emit_data);
57
58 static void si_dump_shader_key(const struct si_shader *shader, FILE *f);
59
60 static void si_build_vs_prolog_function(struct si_shader_context *ctx,
61 union si_shader_part_key *key);
62 static void si_build_tcs_epilog_function(struct si_shader_context *ctx,
63 union si_shader_part_key *key);
64 static void si_build_ps_prolog_function(struct si_shader_context *ctx,
65 union si_shader_part_key *key);
66 static void si_build_ps_epilog_function(struct si_shader_context *ctx,
67 union si_shader_part_key *key);
68 static void si_fix_resource_usage(struct si_screen *sscreen,
69 struct si_shader *shader);
70
71 /* Ideally pass the sample mask input to the PS epilog as v14, which
72 * is its usual location, so that the shader doesn't have to add v_mov.
73 */
74 #define PS_EPILOG_SAMPLEMASK_MIN_LOC 14
75
76 static bool llvm_type_is_64bit(struct si_shader_context *ctx,
77 LLVMTypeRef type)
78 {
79 if (type == ctx->ac.i64 || type == ctx->ac.f64)
80 return true;
81
82 return false;
83 }
84
85 /** Whether the shader runs as a combination of multiple API shaders */
86 static bool is_multi_part_shader(struct si_shader_context *ctx)
87 {
88 if (ctx->screen->info.chip_class <= GFX8)
89 return false;
90
91 return ctx->shader->key.as_ls ||
92 ctx->shader->key.as_es ||
93 ctx->type == PIPE_SHADER_TESS_CTRL ||
94 ctx->type == PIPE_SHADER_GEOMETRY;
95 }
96
97 /** Whether the shader runs on a merged HW stage (LSHS or ESGS) */
98 static bool is_merged_shader(struct si_shader_context *ctx)
99 {
100 return ctx->shader->key.as_ngg || is_multi_part_shader(ctx);
101 }
102
103 void si_init_function_info(struct si_function_info *fninfo)
104 {
105 fninfo->num_params = 0;
106 fninfo->num_sgpr_params = 0;
107 }
108
109 unsigned add_arg_assign(struct si_function_info *fninfo,
110 enum si_arg_regfile regfile, LLVMTypeRef type,
111 LLVMValueRef *assign)
112 {
113 assert(regfile != ARG_SGPR || fninfo->num_sgpr_params == fninfo->num_params);
114
115 unsigned idx = fninfo->num_params++;
116 assert(idx < ARRAY_SIZE(fninfo->types));
117
118 if (regfile == ARG_SGPR)
119 fninfo->num_sgpr_params = fninfo->num_params;
120
121 fninfo->types[idx] = type;
122 fninfo->assign[idx] = assign;
123 return idx;
124 }
125
126 static unsigned add_arg(struct si_function_info *fninfo,
127 enum si_arg_regfile regfile, LLVMTypeRef type)
128 {
129 return add_arg_assign(fninfo, regfile, type, NULL);
130 }
131
132 static void add_arg_assign_checked(struct si_function_info *fninfo,
133 enum si_arg_regfile regfile, LLVMTypeRef type,
134 LLVMValueRef *assign, unsigned idx)
135 {
136 MAYBE_UNUSED unsigned actual = add_arg_assign(fninfo, regfile, type, assign);
137 assert(actual == idx);
138 }
139
140 static void add_arg_checked(struct si_function_info *fninfo,
141 enum si_arg_regfile regfile, LLVMTypeRef type,
142 unsigned idx)
143 {
144 add_arg_assign_checked(fninfo, regfile, type, NULL, idx);
145 }
146
147 /**
148 * Returns a unique index for a per-patch semantic name and index. The index
149 * must be less than 32, so that a 32-bit bitmask of used inputs or outputs
150 * can be calculated.
151 */
152 unsigned si_shader_io_get_unique_index_patch(unsigned semantic_name, unsigned index)
153 {
154 switch (semantic_name) {
155 case TGSI_SEMANTIC_TESSOUTER:
156 return 0;
157 case TGSI_SEMANTIC_TESSINNER:
158 return 1;
159 case TGSI_SEMANTIC_PATCH:
160 assert(index < 30);
161 return 2 + index;
162
163 default:
164 assert(!"invalid semantic name");
165 return 0;
166 }
167 }
168
169 /**
170 * Returns a unique index for a semantic name and index. The index must be
171 * less than 64, so that a 64-bit bitmask of used inputs or outputs can be
172 * calculated.
173 */
174 unsigned si_shader_io_get_unique_index(unsigned semantic_name, unsigned index,
175 unsigned is_varying)
176 {
177 switch (semantic_name) {
178 case TGSI_SEMANTIC_POSITION:
179 return 0;
180 case TGSI_SEMANTIC_GENERIC:
181 /* Since some shader stages use the the highest used IO index
182 * to determine the size to allocate for inputs/outputs
183 * (in LDS, tess and GS rings). GENERIC should be placed right
184 * after POSITION to make that size as small as possible.
185 */
186 if (index < SI_MAX_IO_GENERIC)
187 return 1 + index;
188
189 assert(!"invalid generic index");
190 return 0;
191 case TGSI_SEMANTIC_FOG:
192 return SI_MAX_IO_GENERIC + 1;
193 case TGSI_SEMANTIC_COLOR:
194 assert(index < 2);
195 return SI_MAX_IO_GENERIC + 2 + index;
196 case TGSI_SEMANTIC_BCOLOR:
197 assert(index < 2);
198 /* If it's a varying, COLOR and BCOLOR alias. */
199 if (is_varying)
200 return SI_MAX_IO_GENERIC + 2 + index;
201 else
202 return SI_MAX_IO_GENERIC + 4 + index;
203 case TGSI_SEMANTIC_TEXCOORD:
204 assert(index < 8);
205 return SI_MAX_IO_GENERIC + 6 + index;
206
207 /* These are rarely used between LS and HS or ES and GS. */
208 case TGSI_SEMANTIC_CLIPDIST:
209 assert(index < 2);
210 return SI_MAX_IO_GENERIC + 6 + 8 + index;
211 case TGSI_SEMANTIC_CLIPVERTEX:
212 return SI_MAX_IO_GENERIC + 6 + 8 + 2;
213 case TGSI_SEMANTIC_PSIZE:
214 return SI_MAX_IO_GENERIC + 6 + 8 + 3;
215
216 /* These can't be written by LS, HS, and ES. */
217 case TGSI_SEMANTIC_LAYER:
218 return SI_MAX_IO_GENERIC + 6 + 8 + 4;
219 case TGSI_SEMANTIC_VIEWPORT_INDEX:
220 return SI_MAX_IO_GENERIC + 6 + 8 + 5;
221 case TGSI_SEMANTIC_PRIMID:
222 STATIC_ASSERT(SI_MAX_IO_GENERIC + 6 + 8 + 6 <= 63);
223 return SI_MAX_IO_GENERIC + 6 + 8 + 6;
224 default:
225 fprintf(stderr, "invalid semantic name = %u\n", semantic_name);
226 assert(!"invalid semantic name");
227 return 0;
228 }
229 }
230
231 /**
232 * Get the value of a shader input parameter and extract a bitfield.
233 */
234 static LLVMValueRef unpack_llvm_param(struct si_shader_context *ctx,
235 LLVMValueRef value, unsigned rshift,
236 unsigned bitwidth)
237 {
238 if (LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMFloatTypeKind)
239 value = ac_to_integer(&ctx->ac, value);
240
241 if (rshift)
242 value = LLVMBuildLShr(ctx->ac.builder, value,
243 LLVMConstInt(ctx->i32, rshift, 0), "");
244
245 if (rshift + bitwidth < 32) {
246 unsigned mask = (1 << bitwidth) - 1;
247 value = LLVMBuildAnd(ctx->ac.builder, value,
248 LLVMConstInt(ctx->i32, mask, 0), "");
249 }
250
251 return value;
252 }
253
254 LLVMValueRef si_unpack_param(struct si_shader_context *ctx,
255 unsigned param, unsigned rshift,
256 unsigned bitwidth)
257 {
258 LLVMValueRef value = LLVMGetParam(ctx->main_fn, param);
259
260 return unpack_llvm_param(ctx, value, rshift, bitwidth);
261 }
262
263 static LLVMValueRef get_rel_patch_id(struct si_shader_context *ctx)
264 {
265 switch (ctx->type) {
266 case PIPE_SHADER_TESS_CTRL:
267 return unpack_llvm_param(ctx, ctx->abi.tcs_rel_ids, 0, 8);
268
269 case PIPE_SHADER_TESS_EVAL:
270 return LLVMGetParam(ctx->main_fn,
271 ctx->param_tes_rel_patch_id);
272
273 default:
274 assert(0);
275 return NULL;
276 }
277 }
278
279 /* Tessellation shaders pass outputs to the next shader using LDS.
280 *
281 * LS outputs = TCS inputs
282 * TCS outputs = TES inputs
283 *
284 * The LDS layout is:
285 * - TCS inputs for patch 0
286 * - TCS inputs for patch 1
287 * - TCS inputs for patch 2 = get_tcs_in_current_patch_offset (if RelPatchID==2)
288 * - ...
289 * - TCS outputs for patch 0 = get_tcs_out_patch0_offset
290 * - Per-patch TCS outputs for patch 0 = get_tcs_out_patch0_patch_data_offset
291 * - TCS outputs for patch 1
292 * - Per-patch TCS outputs for patch 1
293 * - TCS outputs for patch 2 = get_tcs_out_current_patch_offset (if RelPatchID==2)
294 * - Per-patch TCS outputs for patch 2 = get_tcs_out_current_patch_data_offset (if RelPatchID==2)
295 * - ...
296 *
297 * All three shaders VS(LS), TCS, TES share the same LDS space.
298 */
299
300 static LLVMValueRef
301 get_tcs_in_patch_stride(struct si_shader_context *ctx)
302 {
303 return si_unpack_param(ctx, ctx->param_vs_state_bits, 8, 13);
304 }
305
306 static unsigned get_tcs_out_vertex_dw_stride_constant(struct si_shader_context *ctx)
307 {
308 assert(ctx->type == PIPE_SHADER_TESS_CTRL);
309
310 if (ctx->shader->key.mono.u.ff_tcs_inputs_to_copy)
311 return util_last_bit64(ctx->shader->key.mono.u.ff_tcs_inputs_to_copy) * 4;
312
313 return util_last_bit64(ctx->shader->selector->outputs_written) * 4;
314 }
315
316 static LLVMValueRef get_tcs_out_vertex_dw_stride(struct si_shader_context *ctx)
317 {
318 unsigned stride = get_tcs_out_vertex_dw_stride_constant(ctx);
319
320 return LLVMConstInt(ctx->i32, stride, 0);
321 }
322
323 static LLVMValueRef get_tcs_out_patch_stride(struct si_shader_context *ctx)
324 {
325 if (ctx->shader->key.mono.u.ff_tcs_inputs_to_copy)
326 return si_unpack_param(ctx, ctx->param_tcs_out_lds_layout, 0, 13);
327
328 const struct tgsi_shader_info *info = &ctx->shader->selector->info;
329 unsigned tcs_out_vertices = info->properties[TGSI_PROPERTY_TCS_VERTICES_OUT];
330 unsigned vertex_dw_stride = get_tcs_out_vertex_dw_stride_constant(ctx);
331 unsigned num_patch_outputs = util_last_bit64(ctx->shader->selector->patch_outputs_written);
332 unsigned patch_dw_stride = tcs_out_vertices * vertex_dw_stride +
333 num_patch_outputs * 4;
334 return LLVMConstInt(ctx->i32, patch_dw_stride, 0);
335 }
336
337 static LLVMValueRef
338 get_tcs_out_patch0_offset(struct si_shader_context *ctx)
339 {
340 return LLVMBuildMul(ctx->ac.builder,
341 si_unpack_param(ctx,
342 ctx->param_tcs_out_lds_offsets,
343 0, 16),
344 LLVMConstInt(ctx->i32, 4, 0), "");
345 }
346
347 static LLVMValueRef
348 get_tcs_out_patch0_patch_data_offset(struct si_shader_context *ctx)
349 {
350 return LLVMBuildMul(ctx->ac.builder,
351 si_unpack_param(ctx,
352 ctx->param_tcs_out_lds_offsets,
353 16, 16),
354 LLVMConstInt(ctx->i32, 4, 0), "");
355 }
356
357 static LLVMValueRef
358 get_tcs_in_current_patch_offset(struct si_shader_context *ctx)
359 {
360 LLVMValueRef patch_stride = get_tcs_in_patch_stride(ctx);
361 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
362
363 return LLVMBuildMul(ctx->ac.builder, patch_stride, rel_patch_id, "");
364 }
365
366 static LLVMValueRef
367 get_tcs_out_current_patch_offset(struct si_shader_context *ctx)
368 {
369 LLVMValueRef patch0_offset = get_tcs_out_patch0_offset(ctx);
370 LLVMValueRef patch_stride = get_tcs_out_patch_stride(ctx);
371 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
372
373 return ac_build_imad(&ctx->ac, patch_stride, rel_patch_id, patch0_offset);
374 }
375
376 static LLVMValueRef
377 get_tcs_out_current_patch_data_offset(struct si_shader_context *ctx)
378 {
379 LLVMValueRef patch0_patch_data_offset =
380 get_tcs_out_patch0_patch_data_offset(ctx);
381 LLVMValueRef patch_stride = get_tcs_out_patch_stride(ctx);
382 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
383
384 return ac_build_imad(&ctx->ac, patch_stride, rel_patch_id, patch0_patch_data_offset);
385 }
386
387 static LLVMValueRef get_num_tcs_out_vertices(struct si_shader_context *ctx)
388 {
389 unsigned tcs_out_vertices =
390 ctx->shader->selector ?
391 ctx->shader->selector->info.properties[TGSI_PROPERTY_TCS_VERTICES_OUT] : 0;
392
393 /* If !tcs_out_vertices, it's either the fixed-func TCS or the TCS epilog. */
394 if (ctx->type == PIPE_SHADER_TESS_CTRL && tcs_out_vertices)
395 return LLVMConstInt(ctx->i32, tcs_out_vertices, 0);
396
397 return si_unpack_param(ctx, ctx->param_tcs_offchip_layout, 6, 6);
398 }
399
400 static LLVMValueRef get_tcs_in_vertex_dw_stride(struct si_shader_context *ctx)
401 {
402 unsigned stride;
403
404 switch (ctx->type) {
405 case PIPE_SHADER_VERTEX:
406 stride = ctx->shader->selector->lshs_vertex_stride / 4;
407 return LLVMConstInt(ctx->i32, stride, 0);
408
409 case PIPE_SHADER_TESS_CTRL:
410 if (ctx->screen->info.chip_class >= GFX9 &&
411 ctx->shader->is_monolithic) {
412 stride = ctx->shader->key.part.tcs.ls->lshs_vertex_stride / 4;
413 return LLVMConstInt(ctx->i32, stride, 0);
414 }
415 return si_unpack_param(ctx, ctx->param_vs_state_bits, 24, 8);
416
417 default:
418 assert(0);
419 return NULL;
420 }
421 }
422
423 static LLVMValueRef unpack_sint16(struct si_shader_context *ctx,
424 LLVMValueRef i32, unsigned index)
425 {
426 assert(index <= 1);
427
428 if (index == 1)
429 return LLVMBuildAShr(ctx->ac.builder, i32,
430 LLVMConstInt(ctx->i32, 16, 0), "");
431
432 return LLVMBuildSExt(ctx->ac.builder,
433 LLVMBuildTrunc(ctx->ac.builder, i32,
434 ctx->ac.i16, ""),
435 ctx->i32, "");
436 }
437
438 void si_llvm_load_input_vs(
439 struct si_shader_context *ctx,
440 unsigned input_index,
441 LLVMValueRef out[4])
442 {
443 const struct tgsi_shader_info *info = &ctx->shader->selector->info;
444 unsigned vs_blit_property = info->properties[TGSI_PROPERTY_VS_BLIT_SGPRS];
445
446 if (vs_blit_property) {
447 LLVMValueRef vertex_id = ctx->abi.vertex_id;
448 LLVMValueRef sel_x1 = LLVMBuildICmp(ctx->ac.builder,
449 LLVMIntULE, vertex_id,
450 ctx->i32_1, "");
451 /* Use LLVMIntNE, because we have 3 vertices and only
452 * the middle one should use y2.
453 */
454 LLVMValueRef sel_y1 = LLVMBuildICmp(ctx->ac.builder,
455 LLVMIntNE, vertex_id,
456 ctx->i32_1, "");
457
458 if (input_index == 0) {
459 /* Position: */
460 LLVMValueRef x1y1 = LLVMGetParam(ctx->main_fn,
461 ctx->param_vs_blit_inputs);
462 LLVMValueRef x2y2 = LLVMGetParam(ctx->main_fn,
463 ctx->param_vs_blit_inputs + 1);
464
465 LLVMValueRef x1 = unpack_sint16(ctx, x1y1, 0);
466 LLVMValueRef y1 = unpack_sint16(ctx, x1y1, 1);
467 LLVMValueRef x2 = unpack_sint16(ctx, x2y2, 0);
468 LLVMValueRef y2 = unpack_sint16(ctx, x2y2, 1);
469
470 LLVMValueRef x = LLVMBuildSelect(ctx->ac.builder, sel_x1,
471 x1, x2, "");
472 LLVMValueRef y = LLVMBuildSelect(ctx->ac.builder, sel_y1,
473 y1, y2, "");
474
475 out[0] = LLVMBuildSIToFP(ctx->ac.builder, x, ctx->f32, "");
476 out[1] = LLVMBuildSIToFP(ctx->ac.builder, y, ctx->f32, "");
477 out[2] = LLVMGetParam(ctx->main_fn,
478 ctx->param_vs_blit_inputs + 2);
479 out[3] = ctx->ac.f32_1;
480 return;
481 }
482
483 /* Color or texture coordinates: */
484 assert(input_index == 1);
485
486 if (vs_blit_property == SI_VS_BLIT_SGPRS_POS_COLOR) {
487 for (int i = 0; i < 4; i++) {
488 out[i] = LLVMGetParam(ctx->main_fn,
489 ctx->param_vs_blit_inputs + 3 + i);
490 }
491 } else {
492 assert(vs_blit_property == SI_VS_BLIT_SGPRS_POS_TEXCOORD);
493 LLVMValueRef x1 = LLVMGetParam(ctx->main_fn,
494 ctx->param_vs_blit_inputs + 3);
495 LLVMValueRef y1 = LLVMGetParam(ctx->main_fn,
496 ctx->param_vs_blit_inputs + 4);
497 LLVMValueRef x2 = LLVMGetParam(ctx->main_fn,
498 ctx->param_vs_blit_inputs + 5);
499 LLVMValueRef y2 = LLVMGetParam(ctx->main_fn,
500 ctx->param_vs_blit_inputs + 6);
501
502 out[0] = LLVMBuildSelect(ctx->ac.builder, sel_x1,
503 x1, x2, "");
504 out[1] = LLVMBuildSelect(ctx->ac.builder, sel_y1,
505 y1, y2, "");
506 out[2] = LLVMGetParam(ctx->main_fn,
507 ctx->param_vs_blit_inputs + 7);
508 out[3] = LLVMGetParam(ctx->main_fn,
509 ctx->param_vs_blit_inputs + 8);
510 }
511 return;
512 }
513
514 union si_vs_fix_fetch fix_fetch;
515 LLVMValueRef t_list_ptr;
516 LLVMValueRef t_offset;
517 LLVMValueRef t_list;
518 LLVMValueRef vertex_index;
519 LLVMValueRef tmp;
520
521 /* Load the T list */
522 t_list_ptr = LLVMGetParam(ctx->main_fn, ctx->param_vertex_buffers);
523
524 t_offset = LLVMConstInt(ctx->i32, input_index, 0);
525
526 t_list = ac_build_load_to_sgpr(&ctx->ac, t_list_ptr, t_offset);
527
528 vertex_index = LLVMGetParam(ctx->main_fn,
529 ctx->param_vertex_index0 +
530 input_index);
531
532 /* Use the open-coded implementation for all loads of doubles and
533 * of dword-sized data that needs fixups. We need to insert conversion
534 * code anyway, and the amd/common code does it for us.
535 *
536 * Note: On LLVM <= 8, we can only open-code formats with
537 * channel size >= 4 bytes.
538 */
539 bool opencode = ctx->shader->key.mono.vs_fetch_opencode & (1 << input_index);
540 fix_fetch.bits = ctx->shader->key.mono.vs_fix_fetch[input_index].bits;
541 if (opencode ||
542 (fix_fetch.u.log_size == 3 && fix_fetch.u.format == AC_FETCH_FORMAT_FLOAT) ||
543 (fix_fetch.u.log_size == 2)) {
544 tmp = ac_build_opencoded_load_format(
545 &ctx->ac, fix_fetch.u.log_size, fix_fetch.u.num_channels_m1 + 1,
546 fix_fetch.u.format, fix_fetch.u.reverse, !opencode,
547 t_list, vertex_index, ctx->ac.i32_0, ctx->ac.i32_0, 0, true);
548 for (unsigned i = 0; i < 4; ++i)
549 out[i] = LLVMBuildExtractElement(ctx->ac.builder, tmp, LLVMConstInt(ctx->i32, i, false), "");
550 return;
551 }
552
553 /* Do multiple loads for special formats. */
554 unsigned required_channels = util_last_bit(info->input_usage_mask[input_index]);
555 LLVMValueRef fetches[4];
556 unsigned num_fetches;
557 unsigned fetch_stride;
558 unsigned channels_per_fetch;
559
560 if (fix_fetch.u.log_size <= 1 && fix_fetch.u.num_channels_m1 == 2) {
561 num_fetches = MIN2(required_channels, 3);
562 fetch_stride = 1 << fix_fetch.u.log_size;
563 channels_per_fetch = 1;
564 } else {
565 num_fetches = 1;
566 fetch_stride = 0;
567 channels_per_fetch = required_channels;
568 }
569
570 for (unsigned i = 0; i < num_fetches; ++i) {
571 LLVMValueRef voffset = LLVMConstInt(ctx->i32, fetch_stride * i, 0);
572 fetches[i] = ac_build_buffer_load_format(&ctx->ac, t_list, vertex_index, voffset,
573 channels_per_fetch, 0, true);
574 }
575
576 if (num_fetches == 1 && channels_per_fetch > 1) {
577 LLVMValueRef fetch = fetches[0];
578 for (unsigned i = 0; i < channels_per_fetch; ++i) {
579 tmp = LLVMConstInt(ctx->i32, i, false);
580 fetches[i] = LLVMBuildExtractElement(
581 ctx->ac.builder, fetch, tmp, "");
582 }
583 num_fetches = channels_per_fetch;
584 channels_per_fetch = 1;
585 }
586
587 for (unsigned i = num_fetches; i < 4; ++i)
588 fetches[i] = LLVMGetUndef(ctx->f32);
589
590 if (fix_fetch.u.log_size <= 1 && fix_fetch.u.num_channels_m1 == 2 &&
591 required_channels == 4) {
592 if (fix_fetch.u.format == AC_FETCH_FORMAT_UINT || fix_fetch.u.format == AC_FETCH_FORMAT_SINT)
593 fetches[3] = ctx->ac.i32_1;
594 else
595 fetches[3] = ctx->ac.f32_1;
596 } else if (fix_fetch.u.log_size == 3 &&
597 (fix_fetch.u.format == AC_FETCH_FORMAT_SNORM ||
598 fix_fetch.u.format == AC_FETCH_FORMAT_SSCALED ||
599 fix_fetch.u.format == AC_FETCH_FORMAT_SINT) &&
600 required_channels == 4) {
601 /* For 2_10_10_10, the hardware returns an unsigned value;
602 * convert it to a signed one.
603 */
604 LLVMValueRef tmp = fetches[3];
605 LLVMValueRef c30 = LLVMConstInt(ctx->i32, 30, 0);
606
607 /* First, recover the sign-extended signed integer value. */
608 if (fix_fetch.u.format == AC_FETCH_FORMAT_SSCALED)
609 tmp = LLVMBuildFPToUI(ctx->ac.builder, tmp, ctx->i32, "");
610 else
611 tmp = ac_to_integer(&ctx->ac, tmp);
612
613 /* For the integer-like cases, do a natural sign extension.
614 *
615 * For the SNORM case, the values are 0.0, 0.333, 0.666, 1.0
616 * and happen to contain 0, 1, 2, 3 as the two LSBs of the
617 * exponent.
618 */
619 tmp = LLVMBuildShl(ctx->ac.builder, tmp,
620 fix_fetch.u.format == AC_FETCH_FORMAT_SNORM ?
621 LLVMConstInt(ctx->i32, 7, 0) : c30, "");
622 tmp = LLVMBuildAShr(ctx->ac.builder, tmp, c30, "");
623
624 /* Convert back to the right type. */
625 if (fix_fetch.u.format == AC_FETCH_FORMAT_SNORM) {
626 LLVMValueRef clamp;
627 LLVMValueRef neg_one = LLVMConstReal(ctx->f32, -1.0);
628 tmp = LLVMBuildSIToFP(ctx->ac.builder, tmp, ctx->f32, "");
629 clamp = LLVMBuildFCmp(ctx->ac.builder, LLVMRealULT, tmp, neg_one, "");
630 tmp = LLVMBuildSelect(ctx->ac.builder, clamp, neg_one, tmp, "");
631 } else if (fix_fetch.u.format == AC_FETCH_FORMAT_SSCALED) {
632 tmp = LLVMBuildSIToFP(ctx->ac.builder, tmp, ctx->f32, "");
633 }
634
635 fetches[3] = tmp;
636 }
637
638 for (unsigned i = 0; i < 4; ++i)
639 out[i] = ac_to_float(&ctx->ac, fetches[i]);
640 }
641
642 static void declare_input_vs(
643 struct si_shader_context *ctx,
644 unsigned input_index,
645 const struct tgsi_full_declaration *decl,
646 LLVMValueRef out[4])
647 {
648 si_llvm_load_input_vs(ctx, input_index, out);
649 }
650
651 LLVMValueRef si_get_primitive_id(struct si_shader_context *ctx,
652 unsigned swizzle)
653 {
654 if (swizzle > 0)
655 return ctx->i32_0;
656
657 switch (ctx->type) {
658 case PIPE_SHADER_VERTEX:
659 return LLVMGetParam(ctx->main_fn,
660 ctx->param_vs_prim_id);
661 case PIPE_SHADER_TESS_CTRL:
662 return ctx->abi.tcs_patch_id;
663 case PIPE_SHADER_TESS_EVAL:
664 return ctx->abi.tes_patch_id;
665 case PIPE_SHADER_GEOMETRY:
666 return ctx->abi.gs_prim_id;
667 default:
668 assert(0);
669 return ctx->i32_0;
670 }
671 }
672
673 /**
674 * Return the value of tgsi_ind_register for indexing.
675 * This is the indirect index with the constant offset added to it.
676 */
677 LLVMValueRef si_get_indirect_index(struct si_shader_context *ctx,
678 const struct tgsi_ind_register *ind,
679 unsigned addr_mul,
680 int rel_index)
681 {
682 LLVMValueRef result;
683
684 if (ind->File == TGSI_FILE_ADDRESS) {
685 result = ctx->addrs[ind->Index][ind->Swizzle];
686 result = LLVMBuildLoad(ctx->ac.builder, result, "");
687 } else {
688 struct tgsi_full_src_register src = {};
689
690 src.Register.File = ind->File;
691 src.Register.Index = ind->Index;
692
693 /* Set the second index to 0 for constants. */
694 if (ind->File == TGSI_FILE_CONSTANT)
695 src.Register.Dimension = 1;
696
697 result = ctx->bld_base.emit_fetch_funcs[ind->File](&ctx->bld_base, &src,
698 TGSI_TYPE_SIGNED,
699 ind->Swizzle);
700 result = ac_to_integer(&ctx->ac, result);
701 }
702
703 return ac_build_imad(&ctx->ac, result, LLVMConstInt(ctx->i32, addr_mul, 0),
704 LLVMConstInt(ctx->i32, rel_index, 0));
705 }
706
707 /**
708 * Like si_get_indirect_index, but restricts the return value to a (possibly
709 * undefined) value inside [0..num).
710 */
711 LLVMValueRef si_get_bounded_indirect_index(struct si_shader_context *ctx,
712 const struct tgsi_ind_register *ind,
713 int rel_index, unsigned num)
714 {
715 LLVMValueRef result = si_get_indirect_index(ctx, ind, 1, rel_index);
716
717 return si_llvm_bound_index(ctx, result, num);
718 }
719
720 static LLVMValueRef get_dw_address_from_generic_indices(struct si_shader_context *ctx,
721 LLVMValueRef vertex_dw_stride,
722 LLVMValueRef base_addr,
723 LLVMValueRef vertex_index,
724 LLVMValueRef param_index,
725 unsigned input_index,
726 ubyte *name,
727 ubyte *index,
728 bool is_patch)
729 {
730 if (vertex_dw_stride) {
731 base_addr = ac_build_imad(&ctx->ac, vertex_index,
732 vertex_dw_stride, base_addr);
733 }
734
735 if (param_index) {
736 base_addr = ac_build_imad(&ctx->ac, param_index,
737 LLVMConstInt(ctx->i32, 4, 0), base_addr);
738 }
739
740 int param = is_patch ?
741 si_shader_io_get_unique_index_patch(name[input_index],
742 index[input_index]) :
743 si_shader_io_get_unique_index(name[input_index],
744 index[input_index], false);
745
746 /* Add the base address of the element. */
747 return LLVMBuildAdd(ctx->ac.builder, base_addr,
748 LLVMConstInt(ctx->i32, param * 4, 0), "");
749 }
750
751 /**
752 * Calculate a dword address given an input or output register and a stride.
753 */
754 static LLVMValueRef get_dw_address(struct si_shader_context *ctx,
755 const struct tgsi_full_dst_register *dst,
756 const struct tgsi_full_src_register *src,
757 LLVMValueRef vertex_dw_stride,
758 LLVMValueRef base_addr)
759 {
760 struct tgsi_shader_info *info = &ctx->shader->selector->info;
761 ubyte *name, *index, *array_first;
762 int input_index;
763 struct tgsi_full_dst_register reg;
764 LLVMValueRef vertex_index = NULL;
765 LLVMValueRef ind_index = NULL;
766
767 /* Set the register description. The address computation is the same
768 * for sources and destinations. */
769 if (src) {
770 reg.Register.File = src->Register.File;
771 reg.Register.Index = src->Register.Index;
772 reg.Register.Indirect = src->Register.Indirect;
773 reg.Register.Dimension = src->Register.Dimension;
774 reg.Indirect = src->Indirect;
775 reg.Dimension = src->Dimension;
776 reg.DimIndirect = src->DimIndirect;
777 } else
778 reg = *dst;
779
780 /* If the register is 2-dimensional (e.g. an array of vertices
781 * in a primitive), calculate the base address of the vertex. */
782 if (reg.Register.Dimension) {
783 if (reg.Dimension.Indirect)
784 vertex_index = si_get_indirect_index(ctx, &reg.DimIndirect,
785 1, reg.Dimension.Index);
786 else
787 vertex_index = LLVMConstInt(ctx->i32, reg.Dimension.Index, 0);
788 }
789
790 /* Get information about the register. */
791 if (reg.Register.File == TGSI_FILE_INPUT) {
792 name = info->input_semantic_name;
793 index = info->input_semantic_index;
794 array_first = info->input_array_first;
795 } else if (reg.Register.File == TGSI_FILE_OUTPUT) {
796 name = info->output_semantic_name;
797 index = info->output_semantic_index;
798 array_first = info->output_array_first;
799 } else {
800 assert(0);
801 return NULL;
802 }
803
804 if (reg.Register.Indirect) {
805 /* Add the relative address of the element. */
806 if (reg.Indirect.ArrayID)
807 input_index = array_first[reg.Indirect.ArrayID];
808 else
809 input_index = reg.Register.Index;
810
811 ind_index = si_get_indirect_index(ctx, &reg.Indirect,
812 1, reg.Register.Index - input_index);
813 } else {
814 input_index = reg.Register.Index;
815 }
816
817 return get_dw_address_from_generic_indices(ctx, vertex_dw_stride,
818 base_addr, vertex_index,
819 ind_index, input_index,
820 name, index,
821 !reg.Register.Dimension);
822 }
823
824 /* The offchip buffer layout for TCS->TES is
825 *
826 * - attribute 0 of patch 0 vertex 0
827 * - attribute 0 of patch 0 vertex 1
828 * - attribute 0 of patch 0 vertex 2
829 * ...
830 * - attribute 0 of patch 1 vertex 0
831 * - attribute 0 of patch 1 vertex 1
832 * ...
833 * - attribute 1 of patch 0 vertex 0
834 * - attribute 1 of patch 0 vertex 1
835 * ...
836 * - per patch attribute 0 of patch 0
837 * - per patch attribute 0 of patch 1
838 * ...
839 *
840 * Note that every attribute has 4 components.
841 */
842 static LLVMValueRef get_tcs_tes_buffer_address(struct si_shader_context *ctx,
843 LLVMValueRef rel_patch_id,
844 LLVMValueRef vertex_index,
845 LLVMValueRef param_index)
846 {
847 LLVMValueRef base_addr, vertices_per_patch, num_patches, total_vertices;
848 LLVMValueRef param_stride, constant16;
849
850 vertices_per_patch = get_num_tcs_out_vertices(ctx);
851 num_patches = si_unpack_param(ctx, ctx->param_tcs_offchip_layout, 0, 6);
852 total_vertices = LLVMBuildMul(ctx->ac.builder, vertices_per_patch,
853 num_patches, "");
854
855 constant16 = LLVMConstInt(ctx->i32, 16, 0);
856 if (vertex_index) {
857 base_addr = ac_build_imad(&ctx->ac, rel_patch_id,
858 vertices_per_patch, vertex_index);
859 param_stride = total_vertices;
860 } else {
861 base_addr = rel_patch_id;
862 param_stride = num_patches;
863 }
864
865 base_addr = ac_build_imad(&ctx->ac, param_index, param_stride, base_addr);
866 base_addr = LLVMBuildMul(ctx->ac.builder, base_addr, constant16, "");
867
868 if (!vertex_index) {
869 LLVMValueRef patch_data_offset =
870 si_unpack_param(ctx, ctx->param_tcs_offchip_layout, 12, 20);
871
872 base_addr = LLVMBuildAdd(ctx->ac.builder, base_addr,
873 patch_data_offset, "");
874 }
875 return base_addr;
876 }
877
878 /* This is a generic helper that can be shared by the NIR and TGSI backends */
879 static LLVMValueRef get_tcs_tes_buffer_address_from_generic_indices(
880 struct si_shader_context *ctx,
881 LLVMValueRef vertex_index,
882 LLVMValueRef param_index,
883 unsigned param_base,
884 ubyte *name,
885 ubyte *index,
886 bool is_patch)
887 {
888 unsigned param_index_base;
889
890 param_index_base = is_patch ?
891 si_shader_io_get_unique_index_patch(name[param_base], index[param_base]) :
892 si_shader_io_get_unique_index(name[param_base], index[param_base], false);
893
894 if (param_index) {
895 param_index = LLVMBuildAdd(ctx->ac.builder, param_index,
896 LLVMConstInt(ctx->i32, param_index_base, 0),
897 "");
898 } else {
899 param_index = LLVMConstInt(ctx->i32, param_index_base, 0);
900 }
901
902 return get_tcs_tes_buffer_address(ctx, get_rel_patch_id(ctx),
903 vertex_index, param_index);
904 }
905
906 static LLVMValueRef get_tcs_tes_buffer_address_from_reg(
907 struct si_shader_context *ctx,
908 const struct tgsi_full_dst_register *dst,
909 const struct tgsi_full_src_register *src)
910 {
911 struct tgsi_shader_info *info = &ctx->shader->selector->info;
912 ubyte *name, *index, *array_first;
913 struct tgsi_full_src_register reg;
914 LLVMValueRef vertex_index = NULL;
915 LLVMValueRef param_index = NULL;
916 unsigned param_base;
917
918 reg = src ? *src : tgsi_full_src_register_from_dst(dst);
919
920 if (reg.Register.Dimension) {
921
922 if (reg.Dimension.Indirect)
923 vertex_index = si_get_indirect_index(ctx, &reg.DimIndirect,
924 1, reg.Dimension.Index);
925 else
926 vertex_index = LLVMConstInt(ctx->i32, reg.Dimension.Index, 0);
927 }
928
929 /* Get information about the register. */
930 if (reg.Register.File == TGSI_FILE_INPUT) {
931 name = info->input_semantic_name;
932 index = info->input_semantic_index;
933 array_first = info->input_array_first;
934 } else if (reg.Register.File == TGSI_FILE_OUTPUT) {
935 name = info->output_semantic_name;
936 index = info->output_semantic_index;
937 array_first = info->output_array_first;
938 } else {
939 assert(0);
940 return NULL;
941 }
942
943 if (reg.Register.Indirect) {
944 if (reg.Indirect.ArrayID)
945 param_base = array_first[reg.Indirect.ArrayID];
946 else
947 param_base = reg.Register.Index;
948
949 param_index = si_get_indirect_index(ctx, &reg.Indirect,
950 1, reg.Register.Index - param_base);
951
952 } else {
953 param_base = reg.Register.Index;
954 }
955
956 return get_tcs_tes_buffer_address_from_generic_indices(ctx, vertex_index,
957 param_index, param_base,
958 name, index, !reg.Register.Dimension);
959 }
960
961 static LLVMValueRef buffer_load(struct lp_build_tgsi_context *bld_base,
962 LLVMTypeRef type, unsigned swizzle,
963 LLVMValueRef buffer, LLVMValueRef offset,
964 LLVMValueRef base, bool can_speculate)
965 {
966 struct si_shader_context *ctx = si_shader_context(bld_base);
967 LLVMValueRef value, value2;
968 LLVMTypeRef vec_type = LLVMVectorType(type, 4);
969
970 if (swizzle == ~0) {
971 value = ac_build_buffer_load(&ctx->ac, buffer, 4, NULL, base, offset,
972 0, ac_glc, can_speculate, false);
973
974 return LLVMBuildBitCast(ctx->ac.builder, value, vec_type, "");
975 }
976
977 if (!llvm_type_is_64bit(ctx, type)) {
978 value = ac_build_buffer_load(&ctx->ac, buffer, 4, NULL, base, offset,
979 0, ac_glc, can_speculate, false);
980
981 value = LLVMBuildBitCast(ctx->ac.builder, value, vec_type, "");
982 return LLVMBuildExtractElement(ctx->ac.builder, value,
983 LLVMConstInt(ctx->i32, swizzle, 0), "");
984 }
985
986 value = ac_build_buffer_load(&ctx->ac, buffer, 1, NULL, base, offset,
987 swizzle * 4, ac_glc, can_speculate, false);
988
989 value2 = ac_build_buffer_load(&ctx->ac, buffer, 1, NULL, base, offset,
990 swizzle * 4 + 4, ac_glc, can_speculate, false);
991
992 return si_llvm_emit_fetch_64bit(bld_base, type, value, value2);
993 }
994
995 /**
996 * Load from LSHS LDS storage.
997 *
998 * \param type output value type
999 * \param swizzle offset (typically 0..3); it can be ~0, which loads a vec4
1000 * \param dw_addr address in dwords
1001 */
1002 static LLVMValueRef lshs_lds_load(struct lp_build_tgsi_context *bld_base,
1003 LLVMTypeRef type, unsigned swizzle,
1004 LLVMValueRef dw_addr)
1005 {
1006 struct si_shader_context *ctx = si_shader_context(bld_base);
1007 LLVMValueRef value;
1008
1009 if (swizzle == ~0) {
1010 LLVMValueRef values[TGSI_NUM_CHANNELS];
1011
1012 for (unsigned chan = 0; chan < TGSI_NUM_CHANNELS; chan++)
1013 values[chan] = lshs_lds_load(bld_base, type, chan, dw_addr);
1014
1015 return ac_build_gather_values(&ctx->ac, values,
1016 TGSI_NUM_CHANNELS);
1017 }
1018
1019 /* Split 64-bit loads. */
1020 if (llvm_type_is_64bit(ctx, type)) {
1021 LLVMValueRef lo, hi;
1022
1023 lo = lshs_lds_load(bld_base, ctx->i32, swizzle, dw_addr);
1024 hi = lshs_lds_load(bld_base, ctx->i32, swizzle + 1, dw_addr);
1025 return si_llvm_emit_fetch_64bit(bld_base, type, lo, hi);
1026 }
1027
1028 dw_addr = LLVMBuildAdd(ctx->ac.builder, dw_addr,
1029 LLVMConstInt(ctx->i32, swizzle, 0), "");
1030
1031 value = ac_lds_load(&ctx->ac, dw_addr);
1032
1033 return LLVMBuildBitCast(ctx->ac.builder, value, type, "");
1034 }
1035
1036 /**
1037 * Store to LSHS LDS storage.
1038 *
1039 * \param swizzle offset (typically 0..3)
1040 * \param dw_addr address in dwords
1041 * \param value value to store
1042 */
1043 static void lshs_lds_store(struct si_shader_context *ctx,
1044 unsigned dw_offset_imm, LLVMValueRef dw_addr,
1045 LLVMValueRef value)
1046 {
1047 dw_addr = LLVMBuildAdd(ctx->ac.builder, dw_addr,
1048 LLVMConstInt(ctx->i32, dw_offset_imm, 0), "");
1049
1050 ac_lds_store(&ctx->ac, dw_addr, value);
1051 }
1052
1053 enum si_tess_ring {
1054 TCS_FACTOR_RING,
1055 TESS_OFFCHIP_RING_TCS,
1056 TESS_OFFCHIP_RING_TES,
1057 };
1058
1059 static LLVMValueRef get_tess_ring_descriptor(struct si_shader_context *ctx,
1060 enum si_tess_ring ring)
1061 {
1062 LLVMBuilderRef builder = ctx->ac.builder;
1063 unsigned param = ring == TESS_OFFCHIP_RING_TES ? ctx->param_tes_offchip_addr :
1064 ctx->param_tcs_out_lds_layout;
1065 LLVMValueRef addr = LLVMGetParam(ctx->main_fn, param);
1066
1067 /* TCS only receives high 13 bits of the address. */
1068 if (ring == TESS_OFFCHIP_RING_TCS || ring == TCS_FACTOR_RING) {
1069 addr = LLVMBuildAnd(builder, addr,
1070 LLVMConstInt(ctx->i32, 0xfff80000, 0), "");
1071 }
1072
1073 if (ring == TCS_FACTOR_RING) {
1074 unsigned tf_offset = ctx->screen->tess_offchip_ring_size;
1075 addr = LLVMBuildAdd(builder, addr,
1076 LLVMConstInt(ctx->i32, tf_offset, 0), "");
1077 }
1078
1079 uint32_t rsrc3 = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1080 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1081 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1082 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
1083
1084 if (ctx->screen->info.chip_class >= GFX10)
1085 rsrc3 |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
1086 S_008F0C_OOB_SELECT(3) |
1087 S_008F0C_RESOURCE_LEVEL(1);
1088 else
1089 rsrc3 |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1090 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
1091
1092 LLVMValueRef desc[4];
1093 desc[0] = addr;
1094 desc[1] = LLVMConstInt(ctx->i32,
1095 S_008F04_BASE_ADDRESS_HI(ctx->screen->info.address32_hi), 0);
1096 desc[2] = LLVMConstInt(ctx->i32, 0xffffffff, 0);
1097 desc[3] = LLVMConstInt(ctx->i32, rsrc3, false);
1098
1099 return ac_build_gather_values(&ctx->ac, desc, 4);
1100 }
1101
1102 static LLVMValueRef fetch_input_tcs(
1103 struct lp_build_tgsi_context *bld_base,
1104 const struct tgsi_full_src_register *reg,
1105 enum tgsi_opcode_type type, unsigned swizzle_in)
1106 {
1107 struct si_shader_context *ctx = si_shader_context(bld_base);
1108 LLVMValueRef dw_addr, stride;
1109 unsigned swizzle = swizzle_in & 0xffff;
1110 stride = get_tcs_in_vertex_dw_stride(ctx);
1111 dw_addr = get_tcs_in_current_patch_offset(ctx);
1112 dw_addr = get_dw_address(ctx, NULL, reg, stride, dw_addr);
1113
1114 return lshs_lds_load(bld_base, tgsi2llvmtype(bld_base, type), swizzle, dw_addr);
1115 }
1116
1117 static LLVMValueRef si_nir_load_tcs_varyings(struct ac_shader_abi *abi,
1118 LLVMTypeRef type,
1119 LLVMValueRef vertex_index,
1120 LLVMValueRef param_index,
1121 unsigned const_index,
1122 unsigned location,
1123 unsigned driver_location,
1124 unsigned component,
1125 unsigned num_components,
1126 bool is_patch,
1127 bool is_compact,
1128 bool load_input)
1129 {
1130 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1131 struct tgsi_shader_info *info = &ctx->shader->selector->info;
1132 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
1133 LLVMValueRef dw_addr, stride;
1134
1135 driver_location = driver_location / 4;
1136
1137 if (load_input) {
1138 stride = get_tcs_in_vertex_dw_stride(ctx);
1139 dw_addr = get_tcs_in_current_patch_offset(ctx);
1140 } else {
1141 if (is_patch) {
1142 stride = NULL;
1143 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1144 } else {
1145 stride = get_tcs_out_vertex_dw_stride(ctx);
1146 dw_addr = get_tcs_out_current_patch_offset(ctx);
1147 }
1148 }
1149
1150 if (param_index) {
1151 /* Add the constant index to the indirect index */
1152 param_index = LLVMBuildAdd(ctx->ac.builder, param_index,
1153 LLVMConstInt(ctx->i32, const_index, 0), "");
1154 } else {
1155 param_index = LLVMConstInt(ctx->i32, const_index, 0);
1156 }
1157
1158 ubyte *names;
1159 ubyte *indices;
1160 if (load_input) {
1161 names = info->input_semantic_name;
1162 indices = info->input_semantic_index;
1163 } else {
1164 names = info->output_semantic_name;
1165 indices = info->output_semantic_index;
1166 }
1167
1168 dw_addr = get_dw_address_from_generic_indices(ctx, stride, dw_addr,
1169 vertex_index, param_index,
1170 driver_location,
1171 names, indices,
1172 is_patch);
1173
1174 LLVMValueRef value[4];
1175 for (unsigned i = 0; i < num_components; i++) {
1176 unsigned offset = i;
1177 if (llvm_type_is_64bit(ctx, type))
1178 offset *= 2;
1179
1180 offset += component;
1181 value[i + component] = lshs_lds_load(bld_base, type, offset, dw_addr);
1182 }
1183
1184 return ac_build_varying_gather_values(&ctx->ac, value, num_components, component);
1185 }
1186
1187 static LLVMValueRef fetch_output_tcs(
1188 struct lp_build_tgsi_context *bld_base,
1189 const struct tgsi_full_src_register *reg,
1190 enum tgsi_opcode_type type, unsigned swizzle_in)
1191 {
1192 struct si_shader_context *ctx = si_shader_context(bld_base);
1193 LLVMValueRef dw_addr, stride;
1194 unsigned swizzle = (swizzle_in & 0xffff);
1195
1196 if (reg->Register.Dimension) {
1197 stride = get_tcs_out_vertex_dw_stride(ctx);
1198 dw_addr = get_tcs_out_current_patch_offset(ctx);
1199 dw_addr = get_dw_address(ctx, NULL, reg, stride, dw_addr);
1200 } else {
1201 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1202 dw_addr = get_dw_address(ctx, NULL, reg, NULL, dw_addr);
1203 }
1204
1205 return lshs_lds_load(bld_base, tgsi2llvmtype(bld_base, type), swizzle, dw_addr);
1206 }
1207
1208 static LLVMValueRef fetch_input_tes(
1209 struct lp_build_tgsi_context *bld_base,
1210 const struct tgsi_full_src_register *reg,
1211 enum tgsi_opcode_type type, unsigned swizzle_in)
1212 {
1213 struct si_shader_context *ctx = si_shader_context(bld_base);
1214 LLVMValueRef base, addr;
1215 unsigned swizzle = (swizzle_in & 0xffff);
1216
1217 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1218 addr = get_tcs_tes_buffer_address_from_reg(ctx, NULL, reg);
1219
1220 return buffer_load(bld_base, tgsi2llvmtype(bld_base, type), swizzle,
1221 ctx->tess_offchip_ring, base, addr, true);
1222 }
1223
1224 LLVMValueRef si_nir_load_input_tes(struct ac_shader_abi *abi,
1225 LLVMTypeRef type,
1226 LLVMValueRef vertex_index,
1227 LLVMValueRef param_index,
1228 unsigned const_index,
1229 unsigned location,
1230 unsigned driver_location,
1231 unsigned component,
1232 unsigned num_components,
1233 bool is_patch,
1234 bool is_compact,
1235 bool load_input)
1236 {
1237 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1238 struct tgsi_shader_info *info = &ctx->shader->selector->info;
1239 LLVMValueRef base, addr;
1240
1241 driver_location = driver_location / 4;
1242
1243 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1244
1245 if (param_index) {
1246 /* Add the constant index to the indirect index */
1247 param_index = LLVMBuildAdd(ctx->ac.builder, param_index,
1248 LLVMConstInt(ctx->i32, const_index, 0), "");
1249 } else {
1250 param_index = LLVMConstInt(ctx->i32, const_index, 0);
1251 }
1252
1253 addr = get_tcs_tes_buffer_address_from_generic_indices(ctx, vertex_index,
1254 param_index, driver_location,
1255 info->input_semantic_name,
1256 info->input_semantic_index,
1257 is_patch);
1258
1259 /* TODO: This will generate rather ordinary llvm code, although it
1260 * should be easy for the optimiser to fix up. In future we might want
1261 * to refactor buffer_load(), but for now this maximises code sharing
1262 * between the NIR and TGSI backends.
1263 */
1264 LLVMValueRef value[4];
1265 for (unsigned i = 0; i < num_components; i++) {
1266 unsigned offset = i;
1267 if (llvm_type_is_64bit(ctx, type)) {
1268 offset *= 2;
1269 if (offset == 4) {
1270 addr = get_tcs_tes_buffer_address_from_generic_indices(ctx,
1271 vertex_index,
1272 param_index,
1273 driver_location + 1,
1274 info->input_semantic_name,
1275 info->input_semantic_index,
1276 is_patch);
1277 }
1278
1279 offset = offset % 4;
1280 }
1281
1282 offset += component;
1283 value[i + component] = buffer_load(&ctx->bld_base, type, offset,
1284 ctx->tess_offchip_ring, base, addr, true);
1285 }
1286
1287 return ac_build_varying_gather_values(&ctx->ac, value, num_components, component);
1288 }
1289
1290 static void store_output_tcs(struct lp_build_tgsi_context *bld_base,
1291 const struct tgsi_full_instruction *inst,
1292 const struct tgsi_opcode_info *info,
1293 unsigned index,
1294 LLVMValueRef dst[4])
1295 {
1296 struct si_shader_context *ctx = si_shader_context(bld_base);
1297 const struct tgsi_full_dst_register *reg = &inst->Dst[index];
1298 const struct tgsi_shader_info *sh_info = &ctx->shader->selector->info;
1299 unsigned chan_index;
1300 LLVMValueRef dw_addr, stride;
1301 LLVMValueRef buffer, base, buf_addr;
1302 LLVMValueRef values[4];
1303 bool skip_lds_store;
1304 bool is_tess_factor = false, is_tess_inner = false;
1305
1306 /* Only handle per-patch and per-vertex outputs here.
1307 * Vectors will be lowered to scalars and this function will be called again.
1308 */
1309 if (reg->Register.File != TGSI_FILE_OUTPUT ||
1310 (dst[0] && LLVMGetTypeKind(LLVMTypeOf(dst[0])) == LLVMVectorTypeKind)) {
1311 si_llvm_emit_store(bld_base, inst, info, index, dst);
1312 return;
1313 }
1314
1315 if (reg->Register.Dimension) {
1316 stride = get_tcs_out_vertex_dw_stride(ctx);
1317 dw_addr = get_tcs_out_current_patch_offset(ctx);
1318 dw_addr = get_dw_address(ctx, reg, NULL, stride, dw_addr);
1319 skip_lds_store = !sh_info->reads_pervertex_outputs;
1320 } else {
1321 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1322 dw_addr = get_dw_address(ctx, reg, NULL, NULL, dw_addr);
1323 skip_lds_store = !sh_info->reads_perpatch_outputs;
1324
1325 if (!reg->Register.Indirect) {
1326 int name = sh_info->output_semantic_name[reg->Register.Index];
1327
1328 /* Always write tess factors into LDS for the TCS epilog. */
1329 if (name == TGSI_SEMANTIC_TESSINNER ||
1330 name == TGSI_SEMANTIC_TESSOUTER) {
1331 /* The epilog doesn't read LDS if invocation 0 defines tess factors. */
1332 skip_lds_store = !sh_info->reads_tessfactor_outputs &&
1333 ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs;
1334 is_tess_factor = true;
1335 is_tess_inner = name == TGSI_SEMANTIC_TESSINNER;
1336 }
1337 }
1338 }
1339
1340 buffer = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TCS);
1341
1342 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1343 buf_addr = get_tcs_tes_buffer_address_from_reg(ctx, reg, NULL);
1344
1345 uint32_t writemask = reg->Register.WriteMask;
1346 while (writemask) {
1347 chan_index = u_bit_scan(&writemask);
1348 LLVMValueRef value = dst[chan_index];
1349
1350 if (inst->Instruction.Saturate)
1351 value = ac_build_clamp(&ctx->ac, value);
1352
1353 /* Skip LDS stores if there is no LDS read of this output. */
1354 if (!skip_lds_store)
1355 lshs_lds_store(ctx, chan_index, dw_addr, value);
1356
1357 value = ac_to_integer(&ctx->ac, value);
1358 values[chan_index] = value;
1359
1360 if (reg->Register.WriteMask != 0xF && !is_tess_factor) {
1361 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 1,
1362 buf_addr, base,
1363 4 * chan_index, ac_glc, false);
1364 }
1365
1366 /* Write tess factors into VGPRs for the epilog. */
1367 if (is_tess_factor &&
1368 ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs) {
1369 if (!is_tess_inner) {
1370 LLVMBuildStore(ctx->ac.builder, value, /* outer */
1371 ctx->invoc0_tess_factors[chan_index]);
1372 } else if (chan_index < 2) {
1373 LLVMBuildStore(ctx->ac.builder, value, /* inner */
1374 ctx->invoc0_tess_factors[4 + chan_index]);
1375 }
1376 }
1377 }
1378
1379 if (reg->Register.WriteMask == 0xF && !is_tess_factor) {
1380 LLVMValueRef value = ac_build_gather_values(&ctx->ac,
1381 values, 4);
1382 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 4, buf_addr,
1383 base, 0, ac_glc, false);
1384 }
1385 }
1386
1387 static void si_nir_store_output_tcs(struct ac_shader_abi *abi,
1388 const struct nir_variable *var,
1389 LLVMValueRef vertex_index,
1390 LLVMValueRef param_index,
1391 unsigned const_index,
1392 LLVMValueRef src,
1393 unsigned writemask)
1394 {
1395 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1396 struct tgsi_shader_info *info = &ctx->shader->selector->info;
1397 const unsigned component = var->data.location_frac;
1398 const bool is_patch = var->data.patch;
1399 unsigned driver_location = var->data.driver_location;
1400 LLVMValueRef dw_addr, stride;
1401 LLVMValueRef buffer, base, addr;
1402 LLVMValueRef values[8];
1403 bool skip_lds_store;
1404 bool is_tess_factor = false, is_tess_inner = false;
1405
1406 driver_location = driver_location / 4;
1407
1408 if (param_index) {
1409 /* Add the constant index to the indirect index */
1410 param_index = LLVMBuildAdd(ctx->ac.builder, param_index,
1411 LLVMConstInt(ctx->i32, const_index, 0), "");
1412 } else {
1413 if (const_index != 0)
1414 param_index = LLVMConstInt(ctx->i32, const_index, 0);
1415 }
1416
1417 if (!is_patch) {
1418 stride = get_tcs_out_vertex_dw_stride(ctx);
1419 dw_addr = get_tcs_out_current_patch_offset(ctx);
1420 dw_addr = get_dw_address_from_generic_indices(ctx, stride, dw_addr,
1421 vertex_index, param_index,
1422 driver_location,
1423 info->output_semantic_name,
1424 info->output_semantic_index,
1425 is_patch);
1426
1427 skip_lds_store = !info->reads_pervertex_outputs;
1428 } else {
1429 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1430 dw_addr = get_dw_address_from_generic_indices(ctx, NULL, dw_addr,
1431 vertex_index, param_index,
1432 driver_location,
1433 info->output_semantic_name,
1434 info->output_semantic_index,
1435 is_patch);
1436
1437 skip_lds_store = !info->reads_perpatch_outputs;
1438
1439 if (!param_index) {
1440 int name = info->output_semantic_name[driver_location];
1441
1442 /* Always write tess factors into LDS for the TCS epilog. */
1443 if (name == TGSI_SEMANTIC_TESSINNER ||
1444 name == TGSI_SEMANTIC_TESSOUTER) {
1445 /* The epilog doesn't read LDS if invocation 0 defines tess factors. */
1446 skip_lds_store = !info->reads_tessfactor_outputs &&
1447 ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs;
1448 is_tess_factor = true;
1449 is_tess_inner = name == TGSI_SEMANTIC_TESSINNER;
1450 }
1451 }
1452 }
1453
1454 buffer = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TCS);
1455
1456 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1457
1458 addr = get_tcs_tes_buffer_address_from_generic_indices(ctx, vertex_index,
1459 param_index, driver_location,
1460 info->output_semantic_name,
1461 info->output_semantic_index,
1462 is_patch);
1463
1464 for (unsigned chan = 0; chan < 8; chan++) {
1465 if (!(writemask & (1 << chan)))
1466 continue;
1467 LLVMValueRef value = ac_llvm_extract_elem(&ctx->ac, src, chan - component);
1468
1469 unsigned buffer_store_offset = chan % 4;
1470 if (chan == 4) {
1471 addr = get_tcs_tes_buffer_address_from_generic_indices(ctx,
1472 vertex_index,
1473 param_index,
1474 driver_location + 1,
1475 info->output_semantic_name,
1476 info->output_semantic_index,
1477 is_patch);
1478 }
1479
1480 /* Skip LDS stores if there is no LDS read of this output. */
1481 if (!skip_lds_store)
1482 lshs_lds_store(ctx, chan, dw_addr, value);
1483
1484 value = ac_to_integer(&ctx->ac, value);
1485 values[chan] = value;
1486
1487 if (writemask != 0xF && !is_tess_factor) {
1488 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 1,
1489 addr, base,
1490 4 * buffer_store_offset,
1491 ac_glc, false);
1492 }
1493
1494 /* Write tess factors into VGPRs for the epilog. */
1495 if (is_tess_factor &&
1496 ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs) {
1497 if (!is_tess_inner) {
1498 LLVMBuildStore(ctx->ac.builder, value, /* outer */
1499 ctx->invoc0_tess_factors[chan]);
1500 } else if (chan < 2) {
1501 LLVMBuildStore(ctx->ac.builder, value, /* inner */
1502 ctx->invoc0_tess_factors[4 + chan]);
1503 }
1504 }
1505 }
1506
1507 if (writemask == 0xF && !is_tess_factor) {
1508 LLVMValueRef value = ac_build_gather_values(&ctx->ac,
1509 values, 4);
1510 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 4, addr,
1511 base, 0, ac_glc, false);
1512 }
1513 }
1514
1515 LLVMValueRef si_llvm_load_input_gs(struct ac_shader_abi *abi,
1516 unsigned input_index,
1517 unsigned vtx_offset_param,
1518 LLVMTypeRef type,
1519 unsigned swizzle)
1520 {
1521 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1522 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
1523 struct si_shader *shader = ctx->shader;
1524 LLVMValueRef vtx_offset, soffset;
1525 struct tgsi_shader_info *info = &shader->selector->info;
1526 unsigned semantic_name = info->input_semantic_name[input_index];
1527 unsigned semantic_index = info->input_semantic_index[input_index];
1528 unsigned param;
1529 LLVMValueRef value;
1530
1531 param = si_shader_io_get_unique_index(semantic_name, semantic_index, false);
1532
1533 /* GFX9 has the ESGS ring in LDS. */
1534 if (ctx->screen->info.chip_class >= GFX9) {
1535 unsigned index = vtx_offset_param;
1536
1537 switch (index / 2) {
1538 case 0:
1539 vtx_offset = si_unpack_param(ctx, ctx->param_gs_vtx01_offset,
1540 index % 2 ? 16 : 0, 16);
1541 break;
1542 case 1:
1543 vtx_offset = si_unpack_param(ctx, ctx->param_gs_vtx23_offset,
1544 index % 2 ? 16 : 0, 16);
1545 break;
1546 case 2:
1547 vtx_offset = si_unpack_param(ctx, ctx->param_gs_vtx45_offset,
1548 index % 2 ? 16 : 0, 16);
1549 break;
1550 default:
1551 assert(0);
1552 return NULL;
1553 }
1554
1555 unsigned offset = param * 4 + swizzle;
1556 vtx_offset = LLVMBuildAdd(ctx->ac.builder, vtx_offset,
1557 LLVMConstInt(ctx->i32, offset, false), "");
1558
1559 LLVMValueRef ptr = ac_build_gep0(&ctx->ac, ctx->esgs_ring, vtx_offset);
1560 LLVMValueRef value = LLVMBuildLoad(ctx->ac.builder, ptr, "");
1561 if (llvm_type_is_64bit(ctx, type)) {
1562 ptr = LLVMBuildGEP(ctx->ac.builder, ptr,
1563 &ctx->ac.i32_1, 1, "");
1564 LLVMValueRef values[2] = {
1565 value,
1566 LLVMBuildLoad(ctx->ac.builder, ptr, "")
1567 };
1568 value = ac_build_gather_values(&ctx->ac, values, 2);
1569 }
1570 return LLVMBuildBitCast(ctx->ac.builder, value, type, "");
1571 }
1572
1573 /* GFX6: input load from the ESGS ring in memory. */
1574 if (swizzle == ~0) {
1575 LLVMValueRef values[TGSI_NUM_CHANNELS];
1576 unsigned chan;
1577 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
1578 values[chan] = si_llvm_load_input_gs(abi, input_index, vtx_offset_param,
1579 type, chan);
1580 }
1581 return ac_build_gather_values(&ctx->ac, values,
1582 TGSI_NUM_CHANNELS);
1583 }
1584
1585 /* Get the vertex offset parameter on GFX6. */
1586 LLVMValueRef gs_vtx_offset = ctx->gs_vtx_offset[vtx_offset_param];
1587
1588 vtx_offset = LLVMBuildMul(ctx->ac.builder, gs_vtx_offset,
1589 LLVMConstInt(ctx->i32, 4, 0), "");
1590
1591 soffset = LLVMConstInt(ctx->i32, (param * 4 + swizzle) * 256, 0);
1592
1593 value = ac_build_buffer_load(&ctx->ac, ctx->esgs_ring, 1, ctx->i32_0,
1594 vtx_offset, soffset, 0, ac_glc, true, false);
1595 if (llvm_type_is_64bit(ctx, type)) {
1596 LLVMValueRef value2;
1597 soffset = LLVMConstInt(ctx->i32, (param * 4 + swizzle + 1) * 256, 0);
1598
1599 value2 = ac_build_buffer_load(&ctx->ac, ctx->esgs_ring, 1,
1600 ctx->i32_0, vtx_offset, soffset,
1601 0, ac_glc, true, false);
1602 return si_llvm_emit_fetch_64bit(bld_base, type, value, value2);
1603 }
1604 return LLVMBuildBitCast(ctx->ac.builder, value, type, "");
1605 }
1606
1607 static LLVMValueRef si_nir_load_input_gs(struct ac_shader_abi *abi,
1608 unsigned location,
1609 unsigned driver_location,
1610 unsigned component,
1611 unsigned num_components,
1612 unsigned vertex_index,
1613 unsigned const_index,
1614 LLVMTypeRef type)
1615 {
1616 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1617
1618 LLVMValueRef value[4];
1619 for (unsigned i = 0; i < num_components; i++) {
1620 unsigned offset = i;
1621 if (llvm_type_is_64bit(ctx, type))
1622 offset *= 2;
1623
1624 offset += component;
1625 value[i + component] = si_llvm_load_input_gs(&ctx->abi, driver_location / 4,
1626 vertex_index, type, offset);
1627 }
1628
1629 return ac_build_varying_gather_values(&ctx->ac, value, num_components, component);
1630 }
1631
1632 static LLVMValueRef fetch_input_gs(
1633 struct lp_build_tgsi_context *bld_base,
1634 const struct tgsi_full_src_register *reg,
1635 enum tgsi_opcode_type type,
1636 unsigned swizzle_in)
1637 {
1638 struct si_shader_context *ctx = si_shader_context(bld_base);
1639 struct tgsi_shader_info *info = &ctx->shader->selector->info;
1640 unsigned swizzle = swizzle_in & 0xffff;
1641
1642 unsigned semantic_name = info->input_semantic_name[reg->Register.Index];
1643 if (swizzle != ~0 && semantic_name == TGSI_SEMANTIC_PRIMID)
1644 return si_get_primitive_id(ctx, swizzle);
1645
1646 if (!reg->Register.Dimension)
1647 return NULL;
1648
1649 return si_llvm_load_input_gs(&ctx->abi, reg->Register.Index,
1650 reg->Dimension.Index,
1651 tgsi2llvmtype(bld_base, type),
1652 swizzle);
1653 }
1654
1655 static int lookup_interp_param_index(unsigned interpolate, unsigned location)
1656 {
1657 switch (interpolate) {
1658 case TGSI_INTERPOLATE_CONSTANT:
1659 return 0;
1660
1661 case TGSI_INTERPOLATE_LINEAR:
1662 if (location == TGSI_INTERPOLATE_LOC_SAMPLE)
1663 return SI_PARAM_LINEAR_SAMPLE;
1664 else if (location == TGSI_INTERPOLATE_LOC_CENTROID)
1665 return SI_PARAM_LINEAR_CENTROID;
1666 else
1667 return SI_PARAM_LINEAR_CENTER;
1668 break;
1669 case TGSI_INTERPOLATE_COLOR:
1670 case TGSI_INTERPOLATE_PERSPECTIVE:
1671 if (location == TGSI_INTERPOLATE_LOC_SAMPLE)
1672 return SI_PARAM_PERSP_SAMPLE;
1673 else if (location == TGSI_INTERPOLATE_LOC_CENTROID)
1674 return SI_PARAM_PERSP_CENTROID;
1675 else
1676 return SI_PARAM_PERSP_CENTER;
1677 break;
1678 default:
1679 fprintf(stderr, "Warning: Unhandled interpolation mode.\n");
1680 return -1;
1681 }
1682 }
1683
1684 static LLVMValueRef si_build_fs_interp(struct si_shader_context *ctx,
1685 unsigned attr_index, unsigned chan,
1686 LLVMValueRef prim_mask,
1687 LLVMValueRef i, LLVMValueRef j)
1688 {
1689 if (i || j) {
1690 return ac_build_fs_interp(&ctx->ac,
1691 LLVMConstInt(ctx->i32, chan, 0),
1692 LLVMConstInt(ctx->i32, attr_index, 0),
1693 prim_mask, i, j);
1694 }
1695 return ac_build_fs_interp_mov(&ctx->ac,
1696 LLVMConstInt(ctx->i32, 2, 0), /* P0 */
1697 LLVMConstInt(ctx->i32, chan, 0),
1698 LLVMConstInt(ctx->i32, attr_index, 0),
1699 prim_mask);
1700 }
1701
1702 /**
1703 * Interpolate a fragment shader input.
1704 *
1705 * @param ctx context
1706 * @param input_index index of the input in hardware
1707 * @param semantic_name TGSI_SEMANTIC_*
1708 * @param semantic_index semantic index
1709 * @param num_interp_inputs number of all interpolated inputs (= BCOLOR offset)
1710 * @param colors_read_mask color components read (4 bits for each color, 8 bits in total)
1711 * @param interp_param interpolation weights (i,j)
1712 * @param prim_mask SI_PARAM_PRIM_MASK
1713 * @param face SI_PARAM_FRONT_FACE
1714 * @param result the return value (4 components)
1715 */
1716 static void interp_fs_input(struct si_shader_context *ctx,
1717 unsigned input_index,
1718 unsigned semantic_name,
1719 unsigned semantic_index,
1720 unsigned num_interp_inputs,
1721 unsigned colors_read_mask,
1722 LLVMValueRef interp_param,
1723 LLVMValueRef prim_mask,
1724 LLVMValueRef face,
1725 LLVMValueRef result[4])
1726 {
1727 LLVMValueRef i = NULL, j = NULL;
1728 unsigned chan;
1729
1730 /* fs.constant returns the param from the middle vertex, so it's not
1731 * really useful for flat shading. It's meant to be used for custom
1732 * interpolation (but the intrinsic can't fetch from the other two
1733 * vertices).
1734 *
1735 * Luckily, it doesn't matter, because we rely on the FLAT_SHADE state
1736 * to do the right thing. The only reason we use fs.constant is that
1737 * fs.interp cannot be used on integers, because they can be equal
1738 * to NaN.
1739 *
1740 * When interp is false we will use fs.constant or for newer llvm,
1741 * amdgcn.interp.mov.
1742 */
1743 bool interp = interp_param != NULL;
1744
1745 if (interp) {
1746 interp_param = LLVMBuildBitCast(ctx->ac.builder, interp_param,
1747 LLVMVectorType(ctx->f32, 2), "");
1748
1749 i = LLVMBuildExtractElement(ctx->ac.builder, interp_param,
1750 ctx->i32_0, "");
1751 j = LLVMBuildExtractElement(ctx->ac.builder, interp_param,
1752 ctx->i32_1, "");
1753 }
1754
1755 if (semantic_name == TGSI_SEMANTIC_COLOR &&
1756 ctx->shader->key.part.ps.prolog.color_two_side) {
1757 LLVMValueRef is_face_positive;
1758
1759 /* If BCOLOR0 is used, BCOLOR1 is at offset "num_inputs + 1",
1760 * otherwise it's at offset "num_inputs".
1761 */
1762 unsigned back_attr_offset = num_interp_inputs;
1763 if (semantic_index == 1 && colors_read_mask & 0xf)
1764 back_attr_offset += 1;
1765
1766 is_face_positive = LLVMBuildICmp(ctx->ac.builder, LLVMIntNE,
1767 face, ctx->i32_0, "");
1768
1769 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
1770 LLVMValueRef front, back;
1771
1772 front = si_build_fs_interp(ctx,
1773 input_index, chan,
1774 prim_mask, i, j);
1775 back = si_build_fs_interp(ctx,
1776 back_attr_offset, chan,
1777 prim_mask, i, j);
1778
1779 result[chan] = LLVMBuildSelect(ctx->ac.builder,
1780 is_face_positive,
1781 front,
1782 back,
1783 "");
1784 }
1785 } else if (semantic_name == TGSI_SEMANTIC_FOG) {
1786 result[0] = si_build_fs_interp(ctx, input_index,
1787 0, prim_mask, i, j);
1788 result[1] =
1789 result[2] = LLVMConstReal(ctx->f32, 0.0f);
1790 result[3] = LLVMConstReal(ctx->f32, 1.0f);
1791 } else {
1792 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
1793 result[chan] = si_build_fs_interp(ctx,
1794 input_index, chan,
1795 prim_mask, i, j);
1796 }
1797 }
1798 }
1799
1800 void si_llvm_load_input_fs(
1801 struct si_shader_context *ctx,
1802 unsigned input_index,
1803 LLVMValueRef out[4])
1804 {
1805 struct si_shader *shader = ctx->shader;
1806 struct tgsi_shader_info *info = &shader->selector->info;
1807 LLVMValueRef main_fn = ctx->main_fn;
1808 LLVMValueRef interp_param = NULL;
1809 int interp_param_idx;
1810 enum tgsi_semantic semantic_name = info->input_semantic_name[input_index];
1811 unsigned semantic_index = info->input_semantic_index[input_index];
1812 enum tgsi_interpolate_mode interp_mode = info->input_interpolate[input_index];
1813 enum tgsi_interpolate_loc interp_loc = info->input_interpolate_loc[input_index];
1814
1815 /* Get colors from input VGPRs (set by the prolog). */
1816 if (semantic_name == TGSI_SEMANTIC_COLOR) {
1817 unsigned colors_read = shader->selector->info.colors_read;
1818 unsigned mask = colors_read >> (semantic_index * 4);
1819 unsigned offset = SI_PARAM_POS_FIXED_PT + 1 +
1820 (semantic_index ? util_bitcount(colors_read & 0xf) : 0);
1821 LLVMValueRef undef = LLVMGetUndef(ctx->f32);
1822
1823 out[0] = mask & 0x1 ? LLVMGetParam(main_fn, offset++) : undef;
1824 out[1] = mask & 0x2 ? LLVMGetParam(main_fn, offset++) : undef;
1825 out[2] = mask & 0x4 ? LLVMGetParam(main_fn, offset++) : undef;
1826 out[3] = mask & 0x8 ? LLVMGetParam(main_fn, offset++) : undef;
1827 return;
1828 }
1829
1830 interp_param_idx = lookup_interp_param_index(interp_mode, interp_loc);
1831 if (interp_param_idx == -1)
1832 return;
1833 else if (interp_param_idx) {
1834 interp_param = LLVMGetParam(ctx->main_fn, interp_param_idx);
1835 }
1836
1837 interp_fs_input(ctx, input_index, semantic_name,
1838 semantic_index, 0, /* this param is unused */
1839 shader->selector->info.colors_read, interp_param,
1840 ctx->abi.prim_mask,
1841 LLVMGetParam(main_fn, SI_PARAM_FRONT_FACE),
1842 &out[0]);
1843 }
1844
1845 static void declare_input_fs(
1846 struct si_shader_context *ctx,
1847 unsigned input_index,
1848 const struct tgsi_full_declaration *decl,
1849 LLVMValueRef out[4])
1850 {
1851 si_llvm_load_input_fs(ctx, input_index, out);
1852 }
1853
1854 LLVMValueRef si_get_sample_id(struct si_shader_context *ctx)
1855 {
1856 return si_unpack_param(ctx, SI_PARAM_ANCILLARY, 8, 4);
1857 }
1858
1859 static LLVMValueRef get_base_vertex(struct ac_shader_abi *abi)
1860 {
1861 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1862
1863 /* For non-indexed draws, the base vertex set by the driver
1864 * (for direct draws) or the CP (for indirect draws) is the
1865 * first vertex ID, but GLSL expects 0 to be returned.
1866 */
1867 LLVMValueRef vs_state = LLVMGetParam(ctx->main_fn,
1868 ctx->param_vs_state_bits);
1869 LLVMValueRef indexed;
1870
1871 indexed = LLVMBuildLShr(ctx->ac.builder, vs_state, ctx->i32_1, "");
1872 indexed = LLVMBuildTrunc(ctx->ac.builder, indexed, ctx->i1, "");
1873
1874 return LLVMBuildSelect(ctx->ac.builder, indexed, ctx->abi.base_vertex,
1875 ctx->i32_0, "");
1876 }
1877
1878 static LLVMValueRef get_block_size(struct ac_shader_abi *abi)
1879 {
1880 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1881
1882 LLVMValueRef values[3];
1883 LLVMValueRef result;
1884 unsigned i;
1885 unsigned *properties = ctx->shader->selector->info.properties;
1886
1887 if (properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH] != 0) {
1888 unsigned sizes[3] = {
1889 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH],
1890 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT],
1891 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH]
1892 };
1893
1894 for (i = 0; i < 3; ++i)
1895 values[i] = LLVMConstInt(ctx->i32, sizes[i], 0);
1896
1897 result = ac_build_gather_values(&ctx->ac, values, 3);
1898 } else {
1899 result = LLVMGetParam(ctx->main_fn, ctx->param_block_size);
1900 }
1901
1902 return result;
1903 }
1904
1905 /**
1906 * Load a dword from a constant buffer.
1907 */
1908 static LLVMValueRef buffer_load_const(struct si_shader_context *ctx,
1909 LLVMValueRef resource,
1910 LLVMValueRef offset)
1911 {
1912 return ac_build_buffer_load(&ctx->ac, resource, 1, NULL, offset, NULL,
1913 0, 0, true, true);
1914 }
1915
1916 static LLVMValueRef load_sample_position(struct ac_shader_abi *abi, LLVMValueRef sample_id)
1917 {
1918 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1919 LLVMValueRef desc = LLVMGetParam(ctx->main_fn, ctx->param_rw_buffers);
1920 LLVMValueRef buf_index = LLVMConstInt(ctx->i32, SI_PS_CONST_SAMPLE_POSITIONS, 0);
1921 LLVMValueRef resource = ac_build_load_to_sgpr(&ctx->ac, desc, buf_index);
1922
1923 /* offset = sample_id * 8 (8 = 2 floats containing samplepos.xy) */
1924 LLVMValueRef offset0 = LLVMBuildMul(ctx->ac.builder, sample_id, LLVMConstInt(ctx->i32, 8, 0), "");
1925 LLVMValueRef offset1 = LLVMBuildAdd(ctx->ac.builder, offset0, LLVMConstInt(ctx->i32, 4, 0), "");
1926
1927 LLVMValueRef pos[4] = {
1928 buffer_load_const(ctx, resource, offset0),
1929 buffer_load_const(ctx, resource, offset1),
1930 LLVMConstReal(ctx->f32, 0),
1931 LLVMConstReal(ctx->f32, 0)
1932 };
1933
1934 return ac_build_gather_values(&ctx->ac, pos, 4);
1935 }
1936
1937 static LLVMValueRef load_sample_mask_in(struct ac_shader_abi *abi)
1938 {
1939 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1940 return ac_to_integer(&ctx->ac, abi->sample_coverage);
1941 }
1942
1943 static LLVMValueRef si_load_tess_coord(struct ac_shader_abi *abi)
1944 {
1945 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1946 LLVMValueRef coord[4] = {
1947 LLVMGetParam(ctx->main_fn, ctx->param_tes_u),
1948 LLVMGetParam(ctx->main_fn, ctx->param_tes_v),
1949 ctx->ac.f32_0,
1950 ctx->ac.f32_0
1951 };
1952
1953 /* For triangles, the vector should be (u, v, 1-u-v). */
1954 if (ctx->shader->selector->info.properties[TGSI_PROPERTY_TES_PRIM_MODE] ==
1955 PIPE_PRIM_TRIANGLES) {
1956 coord[2] = LLVMBuildFSub(ctx->ac.builder, ctx->ac.f32_1,
1957 LLVMBuildFAdd(ctx->ac.builder,
1958 coord[0], coord[1], ""), "");
1959 }
1960 return ac_build_gather_values(&ctx->ac, coord, 4);
1961 }
1962
1963 static LLVMValueRef load_tess_level(struct si_shader_context *ctx,
1964 unsigned semantic_name)
1965 {
1966 LLVMValueRef base, addr;
1967
1968 int param = si_shader_io_get_unique_index_patch(semantic_name, 0);
1969
1970 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
1971 addr = get_tcs_tes_buffer_address(ctx, get_rel_patch_id(ctx), NULL,
1972 LLVMConstInt(ctx->i32, param, 0));
1973
1974 return buffer_load(&ctx->bld_base, ctx->f32,
1975 ~0, ctx->tess_offchip_ring, base, addr, true);
1976
1977 }
1978
1979 static LLVMValueRef si_load_tess_level(struct ac_shader_abi *abi,
1980 unsigned varying_id)
1981 {
1982 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
1983 unsigned semantic_name;
1984
1985 switch (varying_id) {
1986 case VARYING_SLOT_TESS_LEVEL_INNER:
1987 semantic_name = TGSI_SEMANTIC_TESSINNER;
1988 break;
1989 case VARYING_SLOT_TESS_LEVEL_OUTER:
1990 semantic_name = TGSI_SEMANTIC_TESSOUTER;
1991 break;
1992 default:
1993 unreachable("unknown tess level");
1994 }
1995
1996 return load_tess_level(ctx, semantic_name);
1997
1998 }
1999
2000 static LLVMValueRef si_load_patch_vertices_in(struct ac_shader_abi *abi)
2001 {
2002 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
2003 if (ctx->type == PIPE_SHADER_TESS_CTRL)
2004 return si_unpack_param(ctx, ctx->param_tcs_out_lds_layout, 13, 6);
2005 else if (ctx->type == PIPE_SHADER_TESS_EVAL)
2006 return get_num_tcs_out_vertices(ctx);
2007 else
2008 unreachable("invalid shader stage for TGSI_SEMANTIC_VERTICESIN");
2009 }
2010
2011 void si_load_system_value(struct si_shader_context *ctx,
2012 unsigned index,
2013 const struct tgsi_full_declaration *decl)
2014 {
2015 LLVMValueRef value = 0;
2016
2017 assert(index < RADEON_LLVM_MAX_SYSTEM_VALUES);
2018
2019 switch (decl->Semantic.Name) {
2020 case TGSI_SEMANTIC_INSTANCEID:
2021 value = ctx->abi.instance_id;
2022 break;
2023
2024 case TGSI_SEMANTIC_VERTEXID:
2025 value = LLVMBuildAdd(ctx->ac.builder,
2026 ctx->abi.vertex_id,
2027 ctx->abi.base_vertex, "");
2028 break;
2029
2030 case TGSI_SEMANTIC_VERTEXID_NOBASE:
2031 /* Unused. Clarify the meaning in indexed vs. non-indexed
2032 * draws if this is ever used again. */
2033 assert(false);
2034 break;
2035
2036 case TGSI_SEMANTIC_BASEVERTEX:
2037 value = get_base_vertex(&ctx->abi);
2038 break;
2039
2040 case TGSI_SEMANTIC_BASEINSTANCE:
2041 value = ctx->abi.start_instance;
2042 break;
2043
2044 case TGSI_SEMANTIC_DRAWID:
2045 value = ctx->abi.draw_id;
2046 break;
2047
2048 case TGSI_SEMANTIC_INVOCATIONID:
2049 if (ctx->type == PIPE_SHADER_TESS_CTRL) {
2050 value = unpack_llvm_param(ctx, ctx->abi.tcs_rel_ids, 8, 5);
2051 } else if (ctx->type == PIPE_SHADER_GEOMETRY) {
2052 if (ctx->screen->info.chip_class >= GFX10) {
2053 value = LLVMBuildAnd(ctx->ac.builder,
2054 ctx->abi.gs_invocation_id,
2055 LLVMConstInt(ctx->i32, 127, 0), "");
2056 } else {
2057 value = ctx->abi.gs_invocation_id;
2058 }
2059 } else {
2060 assert(!"INVOCATIONID not implemented");
2061 }
2062 break;
2063
2064 case TGSI_SEMANTIC_POSITION:
2065 {
2066 LLVMValueRef pos[4] = {
2067 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_X_FLOAT),
2068 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_Y_FLOAT),
2069 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_Z_FLOAT),
2070 ac_build_fdiv(&ctx->ac, ctx->ac.f32_1,
2071 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_W_FLOAT)),
2072 };
2073 value = ac_build_gather_values(&ctx->ac, pos, 4);
2074 break;
2075 }
2076
2077 case TGSI_SEMANTIC_FACE:
2078 value = ctx->abi.front_face;
2079 break;
2080
2081 case TGSI_SEMANTIC_SAMPLEID:
2082 value = si_get_sample_id(ctx);
2083 break;
2084
2085 case TGSI_SEMANTIC_SAMPLEPOS: {
2086 LLVMValueRef pos[4] = {
2087 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_X_FLOAT),
2088 LLVMGetParam(ctx->main_fn, SI_PARAM_POS_Y_FLOAT),
2089 LLVMConstReal(ctx->f32, 0),
2090 LLVMConstReal(ctx->f32, 0)
2091 };
2092 pos[0] = ac_build_fract(&ctx->ac, pos[0], 32);
2093 pos[1] = ac_build_fract(&ctx->ac, pos[1], 32);
2094 value = ac_build_gather_values(&ctx->ac, pos, 4);
2095 break;
2096 }
2097
2098 case TGSI_SEMANTIC_SAMPLEMASK:
2099 /* This can only occur with the OpenGL Core profile, which
2100 * doesn't support smoothing.
2101 */
2102 value = LLVMGetParam(ctx->main_fn, SI_PARAM_SAMPLE_COVERAGE);
2103 break;
2104
2105 case TGSI_SEMANTIC_TESSCOORD:
2106 value = si_load_tess_coord(&ctx->abi);
2107 break;
2108
2109 case TGSI_SEMANTIC_VERTICESIN:
2110 value = si_load_patch_vertices_in(&ctx->abi);
2111 break;
2112
2113 case TGSI_SEMANTIC_TESSINNER:
2114 case TGSI_SEMANTIC_TESSOUTER:
2115 value = load_tess_level(ctx, decl->Semantic.Name);
2116 break;
2117
2118 case TGSI_SEMANTIC_DEFAULT_TESSOUTER_SI:
2119 case TGSI_SEMANTIC_DEFAULT_TESSINNER_SI:
2120 {
2121 LLVMValueRef buf, slot, val[4];
2122 int i, offset;
2123
2124 slot = LLVMConstInt(ctx->i32, SI_HS_CONST_DEFAULT_TESS_LEVELS, 0);
2125 buf = LLVMGetParam(ctx->main_fn, ctx->param_rw_buffers);
2126 buf = ac_build_load_to_sgpr(&ctx->ac, buf, slot);
2127 offset = decl->Semantic.Name == TGSI_SEMANTIC_DEFAULT_TESSINNER_SI ? 4 : 0;
2128
2129 for (i = 0; i < 4; i++)
2130 val[i] = buffer_load_const(ctx, buf,
2131 LLVMConstInt(ctx->i32, (offset + i) * 4, 0));
2132 value = ac_build_gather_values(&ctx->ac, val, 4);
2133 break;
2134 }
2135
2136 case TGSI_SEMANTIC_PRIMID:
2137 value = si_get_primitive_id(ctx, 0);
2138 break;
2139
2140 case TGSI_SEMANTIC_GRID_SIZE:
2141 value = ctx->abi.num_work_groups;
2142 break;
2143
2144 case TGSI_SEMANTIC_BLOCK_SIZE:
2145 value = get_block_size(&ctx->abi);
2146 break;
2147
2148 case TGSI_SEMANTIC_BLOCK_ID:
2149 {
2150 LLVMValueRef values[3];
2151
2152 for (int i = 0; i < 3; i++) {
2153 values[i] = ctx->i32_0;
2154 if (ctx->abi.workgroup_ids[i]) {
2155 values[i] = ctx->abi.workgroup_ids[i];
2156 }
2157 }
2158 value = ac_build_gather_values(&ctx->ac, values, 3);
2159 break;
2160 }
2161
2162 case TGSI_SEMANTIC_THREAD_ID:
2163 value = ctx->abi.local_invocation_ids;
2164 break;
2165
2166 case TGSI_SEMANTIC_HELPER_INVOCATION:
2167 value = ac_build_load_helper_invocation(&ctx->ac);
2168 break;
2169
2170 case TGSI_SEMANTIC_SUBGROUP_SIZE:
2171 value = LLVMConstInt(ctx->i32, 64, 0);
2172 break;
2173
2174 case TGSI_SEMANTIC_SUBGROUP_INVOCATION:
2175 value = ac_get_thread_id(&ctx->ac);
2176 break;
2177
2178 case TGSI_SEMANTIC_SUBGROUP_EQ_MASK:
2179 {
2180 LLVMValueRef id = ac_get_thread_id(&ctx->ac);
2181 id = LLVMBuildZExt(ctx->ac.builder, id, ctx->i64, "");
2182 value = LLVMBuildShl(ctx->ac.builder, LLVMConstInt(ctx->i64, 1, 0), id, "");
2183 value = LLVMBuildBitCast(ctx->ac.builder, value, ctx->v2i32, "");
2184 break;
2185 }
2186
2187 case TGSI_SEMANTIC_SUBGROUP_GE_MASK:
2188 case TGSI_SEMANTIC_SUBGROUP_GT_MASK:
2189 case TGSI_SEMANTIC_SUBGROUP_LE_MASK:
2190 case TGSI_SEMANTIC_SUBGROUP_LT_MASK:
2191 {
2192 LLVMValueRef id = ac_get_thread_id(&ctx->ac);
2193 if (decl->Semantic.Name == TGSI_SEMANTIC_SUBGROUP_GT_MASK ||
2194 decl->Semantic.Name == TGSI_SEMANTIC_SUBGROUP_LE_MASK) {
2195 /* All bits set except LSB */
2196 value = LLVMConstInt(ctx->i64, -2, 0);
2197 } else {
2198 /* All bits set */
2199 value = LLVMConstInt(ctx->i64, -1, 0);
2200 }
2201 id = LLVMBuildZExt(ctx->ac.builder, id, ctx->i64, "");
2202 value = LLVMBuildShl(ctx->ac.builder, value, id, "");
2203 if (decl->Semantic.Name == TGSI_SEMANTIC_SUBGROUP_LE_MASK ||
2204 decl->Semantic.Name == TGSI_SEMANTIC_SUBGROUP_LT_MASK)
2205 value = LLVMBuildNot(ctx->ac.builder, value, "");
2206 value = LLVMBuildBitCast(ctx->ac.builder, value, ctx->v2i32, "");
2207 break;
2208 }
2209
2210 case TGSI_SEMANTIC_CS_USER_DATA:
2211 value = LLVMGetParam(ctx->main_fn, ctx->param_cs_user_data);
2212 break;
2213
2214 default:
2215 assert(!"unknown system value");
2216 return;
2217 }
2218
2219 ctx->system_values[index] = value;
2220 }
2221
2222 void si_declare_compute_memory(struct si_shader_context *ctx)
2223 {
2224 struct si_shader_selector *sel = ctx->shader->selector;
2225 unsigned lds_size = sel->info.properties[TGSI_PROPERTY_CS_LOCAL_SIZE];
2226
2227 LLVMTypeRef i8p = LLVMPointerType(ctx->i8, AC_ADDR_SPACE_LDS);
2228 LLVMValueRef var;
2229
2230 assert(!ctx->ac.lds);
2231
2232 var = LLVMAddGlobalInAddressSpace(ctx->ac.module,
2233 LLVMArrayType(ctx->i8, lds_size),
2234 "compute_lds",
2235 AC_ADDR_SPACE_LDS);
2236 LLVMSetAlignment(var, 64 * 1024);
2237
2238 ctx->ac.lds = LLVMBuildBitCast(ctx->ac.builder, var, i8p, "");
2239 }
2240
2241 void si_tgsi_declare_compute_memory(struct si_shader_context *ctx,
2242 const struct tgsi_full_declaration *decl)
2243 {
2244 assert(decl->Declaration.MemType == TGSI_MEMORY_TYPE_SHARED);
2245 assert(decl->Range.First == decl->Range.Last);
2246
2247 si_declare_compute_memory(ctx);
2248 }
2249
2250 static LLVMValueRef load_const_buffer_desc_fast_path(struct si_shader_context *ctx)
2251 {
2252 LLVMValueRef ptr =
2253 LLVMGetParam(ctx->main_fn, ctx->param_const_and_shader_buffers);
2254 struct si_shader_selector *sel = ctx->shader->selector;
2255
2256 /* Do the bounds checking with a descriptor, because
2257 * doing computation and manual bounds checking of 64-bit
2258 * addresses generates horrible VALU code with very high
2259 * VGPR usage and very low SIMD occupancy.
2260 */
2261 ptr = LLVMBuildPtrToInt(ctx->ac.builder, ptr, ctx->ac.intptr, "");
2262
2263 LLVMValueRef desc0, desc1;
2264 desc0 = ptr;
2265 desc1 = LLVMConstInt(ctx->i32,
2266 S_008F04_BASE_ADDRESS_HI(ctx->screen->info.address32_hi), 0);
2267
2268 uint32_t rsrc3 = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2269 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2270 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2271 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2272
2273 if (ctx->screen->info.chip_class >= GFX10)
2274 rsrc3 |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2275 S_008F0C_OOB_SELECT(3) |
2276 S_008F0C_RESOURCE_LEVEL(1);
2277 else
2278 rsrc3 |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2279 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2280
2281 LLVMValueRef desc_elems[] = {
2282 desc0,
2283 desc1,
2284 LLVMConstInt(ctx->i32, (sel->info.const_file_max[0] + 1) * 16, 0),
2285 LLVMConstInt(ctx->i32, rsrc3, false)
2286 };
2287
2288 return ac_build_gather_values(&ctx->ac, desc_elems, 4);
2289 }
2290
2291 static LLVMValueRef load_const_buffer_desc(struct si_shader_context *ctx, int i)
2292 {
2293 LLVMValueRef list_ptr = LLVMGetParam(ctx->main_fn,
2294 ctx->param_const_and_shader_buffers);
2295
2296 return ac_build_load_to_sgpr(&ctx->ac, list_ptr,
2297 LLVMConstInt(ctx->i32, si_get_constbuf_slot(i), 0));
2298 }
2299
2300 static LLVMValueRef load_ubo(struct ac_shader_abi *abi, LLVMValueRef index)
2301 {
2302 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
2303 struct si_shader_selector *sel = ctx->shader->selector;
2304
2305 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, ctx->param_const_and_shader_buffers);
2306
2307 if (sel->info.const_buffers_declared == 1 &&
2308 sel->info.shader_buffers_declared == 0) {
2309 return load_const_buffer_desc_fast_path(ctx);
2310 }
2311
2312 index = si_llvm_bound_index(ctx, index, ctx->num_const_buffers);
2313 index = LLVMBuildAdd(ctx->ac.builder, index,
2314 LLVMConstInt(ctx->i32, SI_NUM_SHADER_BUFFERS, 0), "");
2315
2316 return ac_build_load_to_sgpr(&ctx->ac, ptr, index);
2317 }
2318
2319 static LLVMValueRef
2320 load_ssbo(struct ac_shader_abi *abi, LLVMValueRef index, bool write)
2321 {
2322 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
2323 LLVMValueRef rsrc_ptr = LLVMGetParam(ctx->main_fn,
2324 ctx->param_const_and_shader_buffers);
2325
2326 index = si_llvm_bound_index(ctx, index, ctx->num_shader_buffers);
2327 index = LLVMBuildSub(ctx->ac.builder,
2328 LLVMConstInt(ctx->i32, SI_NUM_SHADER_BUFFERS - 1, 0),
2329 index, "");
2330
2331 return ac_build_load_to_sgpr(&ctx->ac, rsrc_ptr, index);
2332 }
2333
2334 static LLVMValueRef fetch_constant(
2335 struct lp_build_tgsi_context *bld_base,
2336 const struct tgsi_full_src_register *reg,
2337 enum tgsi_opcode_type type,
2338 unsigned swizzle_in)
2339 {
2340 struct si_shader_context *ctx = si_shader_context(bld_base);
2341 struct si_shader_selector *sel = ctx->shader->selector;
2342 const struct tgsi_ind_register *ireg = &reg->Indirect;
2343 unsigned buf, idx;
2344 unsigned swizzle = swizzle_in & 0xffff;
2345
2346 LLVMValueRef addr, bufp;
2347
2348 if (swizzle_in == LP_CHAN_ALL) {
2349 unsigned chan;
2350 LLVMValueRef values[4];
2351 for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan)
2352 values[chan] = fetch_constant(bld_base, reg, type, chan);
2353
2354 return ac_build_gather_values(&ctx->ac, values, 4);
2355 }
2356
2357 /* Split 64-bit loads. */
2358 if (tgsi_type_is_64bit(type)) {
2359 LLVMValueRef lo, hi;
2360
2361 lo = fetch_constant(bld_base, reg, TGSI_TYPE_UNSIGNED, swizzle);
2362 hi = fetch_constant(bld_base, reg, TGSI_TYPE_UNSIGNED, (swizzle_in >> 16));
2363 return si_llvm_emit_fetch_64bit(bld_base, tgsi2llvmtype(bld_base, type),
2364 lo, hi);
2365 }
2366
2367 idx = reg->Register.Index * 4 + swizzle;
2368 if (reg->Register.Indirect) {
2369 addr = si_get_indirect_index(ctx, ireg, 16, idx * 4);
2370 } else {
2371 addr = LLVMConstInt(ctx->i32, idx * 4, 0);
2372 }
2373
2374 /* Fast path when user data SGPRs point to constant buffer 0 directly. */
2375 if (sel->info.const_buffers_declared == 1 &&
2376 sel->info.shader_buffers_declared == 0) {
2377 LLVMValueRef desc = load_const_buffer_desc_fast_path(ctx);
2378 LLVMValueRef result = buffer_load_const(ctx, desc, addr);
2379 return bitcast(bld_base, type, result);
2380 }
2381
2382 assert(reg->Register.Dimension);
2383 buf = reg->Dimension.Index;
2384
2385 if (reg->Dimension.Indirect) {
2386 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, ctx->param_const_and_shader_buffers);
2387 LLVMValueRef index;
2388 index = si_get_bounded_indirect_index(ctx, &reg->DimIndirect,
2389 reg->Dimension.Index,
2390 ctx->num_const_buffers);
2391 index = LLVMBuildAdd(ctx->ac.builder, index,
2392 LLVMConstInt(ctx->i32, SI_NUM_SHADER_BUFFERS, 0), "");
2393 bufp = ac_build_load_to_sgpr(&ctx->ac, ptr, index);
2394 } else
2395 bufp = load_const_buffer_desc(ctx, buf);
2396
2397 return bitcast(bld_base, type, buffer_load_const(ctx, bufp, addr));
2398 }
2399
2400 /* Initialize arguments for the shader export intrinsic */
2401 static void si_llvm_init_export_args(struct si_shader_context *ctx,
2402 LLVMValueRef *values,
2403 unsigned target,
2404 struct ac_export_args *args)
2405 {
2406 LLVMValueRef f32undef = LLVMGetUndef(ctx->ac.f32);
2407 unsigned spi_shader_col_format = V_028714_SPI_SHADER_32_ABGR;
2408 unsigned chan;
2409 bool is_int8, is_int10;
2410
2411 /* Default is 0xf. Adjusted below depending on the format. */
2412 args->enabled_channels = 0xf; /* writemask */
2413
2414 /* Specify whether the EXEC mask represents the valid mask */
2415 args->valid_mask = 0;
2416
2417 /* Specify whether this is the last export */
2418 args->done = 0;
2419
2420 /* Specify the target we are exporting */
2421 args->target = target;
2422
2423 if (ctx->type == PIPE_SHADER_FRAGMENT) {
2424 const struct si_shader_key *key = &ctx->shader->key;
2425 unsigned col_formats = key->part.ps.epilog.spi_shader_col_format;
2426 int cbuf = target - V_008DFC_SQ_EXP_MRT;
2427
2428 assert(cbuf >= 0 && cbuf < 8);
2429 spi_shader_col_format = (col_formats >> (cbuf * 4)) & 0xf;
2430 is_int8 = (key->part.ps.epilog.color_is_int8 >> cbuf) & 0x1;
2431 is_int10 = (key->part.ps.epilog.color_is_int10 >> cbuf) & 0x1;
2432 }
2433
2434 args->compr = false;
2435 args->out[0] = f32undef;
2436 args->out[1] = f32undef;
2437 args->out[2] = f32undef;
2438 args->out[3] = f32undef;
2439
2440 LLVMValueRef (*packf)(struct ac_llvm_context *ctx, LLVMValueRef args[2]) = NULL;
2441 LLVMValueRef (*packi)(struct ac_llvm_context *ctx, LLVMValueRef args[2],
2442 unsigned bits, bool hi) = NULL;
2443
2444 switch (spi_shader_col_format) {
2445 case V_028714_SPI_SHADER_ZERO:
2446 args->enabled_channels = 0; /* writemask */
2447 args->target = V_008DFC_SQ_EXP_NULL;
2448 break;
2449
2450 case V_028714_SPI_SHADER_32_R:
2451 args->enabled_channels = 1; /* writemask */
2452 args->out[0] = values[0];
2453 break;
2454
2455 case V_028714_SPI_SHADER_32_GR:
2456 args->enabled_channels = 0x3; /* writemask */
2457 args->out[0] = values[0];
2458 args->out[1] = values[1];
2459 break;
2460
2461 case V_028714_SPI_SHADER_32_AR:
2462 if (ctx->screen->info.chip_class >= GFX10) {
2463 args->enabled_channels = 0x3; /* writemask */
2464 args->out[0] = values[0];
2465 args->out[1] = values[3];
2466 } else {
2467 args->enabled_channels = 0x9; /* writemask */
2468 args->out[0] = values[0];
2469 args->out[3] = values[3];
2470 }
2471 break;
2472
2473 case V_028714_SPI_SHADER_FP16_ABGR:
2474 packf = ac_build_cvt_pkrtz_f16;
2475 break;
2476
2477 case V_028714_SPI_SHADER_UNORM16_ABGR:
2478 packf = ac_build_cvt_pknorm_u16;
2479 break;
2480
2481 case V_028714_SPI_SHADER_SNORM16_ABGR:
2482 packf = ac_build_cvt_pknorm_i16;
2483 break;
2484
2485 case V_028714_SPI_SHADER_UINT16_ABGR:
2486 packi = ac_build_cvt_pk_u16;
2487 break;
2488
2489 case V_028714_SPI_SHADER_SINT16_ABGR:
2490 packi = ac_build_cvt_pk_i16;
2491 break;
2492
2493 case V_028714_SPI_SHADER_32_ABGR:
2494 memcpy(&args->out[0], values, sizeof(values[0]) * 4);
2495 break;
2496 }
2497
2498 /* Pack f16 or norm_i16/u16. */
2499 if (packf) {
2500 for (chan = 0; chan < 2; chan++) {
2501 LLVMValueRef pack_args[2] = {
2502 values[2 * chan],
2503 values[2 * chan + 1]
2504 };
2505 LLVMValueRef packed;
2506
2507 packed = packf(&ctx->ac, pack_args);
2508 args->out[chan] = ac_to_float(&ctx->ac, packed);
2509 }
2510 args->compr = 1; /* COMPR flag */
2511 }
2512 /* Pack i16/u16. */
2513 if (packi) {
2514 for (chan = 0; chan < 2; chan++) {
2515 LLVMValueRef pack_args[2] = {
2516 ac_to_integer(&ctx->ac, values[2 * chan]),
2517 ac_to_integer(&ctx->ac, values[2 * chan + 1])
2518 };
2519 LLVMValueRef packed;
2520
2521 packed = packi(&ctx->ac, pack_args,
2522 is_int8 ? 8 : is_int10 ? 10 : 16,
2523 chan == 1);
2524 args->out[chan] = ac_to_float(&ctx->ac, packed);
2525 }
2526 args->compr = 1; /* COMPR flag */
2527 }
2528 }
2529
2530 static void si_alpha_test(struct lp_build_tgsi_context *bld_base,
2531 LLVMValueRef alpha)
2532 {
2533 struct si_shader_context *ctx = si_shader_context(bld_base);
2534
2535 if (ctx->shader->key.part.ps.epilog.alpha_func != PIPE_FUNC_NEVER) {
2536 static LLVMRealPredicate cond_map[PIPE_FUNC_ALWAYS + 1] = {
2537 [PIPE_FUNC_LESS] = LLVMRealOLT,
2538 [PIPE_FUNC_EQUAL] = LLVMRealOEQ,
2539 [PIPE_FUNC_LEQUAL] = LLVMRealOLE,
2540 [PIPE_FUNC_GREATER] = LLVMRealOGT,
2541 [PIPE_FUNC_NOTEQUAL] = LLVMRealONE,
2542 [PIPE_FUNC_GEQUAL] = LLVMRealOGE,
2543 };
2544 LLVMRealPredicate cond = cond_map[ctx->shader->key.part.ps.epilog.alpha_func];
2545 assert(cond);
2546
2547 LLVMValueRef alpha_ref = LLVMGetParam(ctx->main_fn,
2548 SI_PARAM_ALPHA_REF);
2549 LLVMValueRef alpha_pass =
2550 LLVMBuildFCmp(ctx->ac.builder, cond, alpha, alpha_ref, "");
2551 ac_build_kill_if_false(&ctx->ac, alpha_pass);
2552 } else {
2553 ac_build_kill_if_false(&ctx->ac, ctx->i1false);
2554 }
2555 }
2556
2557 static LLVMValueRef si_scale_alpha_by_sample_mask(struct lp_build_tgsi_context *bld_base,
2558 LLVMValueRef alpha,
2559 unsigned samplemask_param)
2560 {
2561 struct si_shader_context *ctx = si_shader_context(bld_base);
2562 LLVMValueRef coverage;
2563
2564 /* alpha = alpha * popcount(coverage) / SI_NUM_SMOOTH_AA_SAMPLES */
2565 coverage = LLVMGetParam(ctx->main_fn,
2566 samplemask_param);
2567 coverage = ac_to_integer(&ctx->ac, coverage);
2568
2569 coverage = ac_build_intrinsic(&ctx->ac, "llvm.ctpop.i32",
2570 ctx->i32,
2571 &coverage, 1, AC_FUNC_ATTR_READNONE);
2572
2573 coverage = LLVMBuildUIToFP(ctx->ac.builder, coverage,
2574 ctx->f32, "");
2575
2576 coverage = LLVMBuildFMul(ctx->ac.builder, coverage,
2577 LLVMConstReal(ctx->f32,
2578 1.0 / SI_NUM_SMOOTH_AA_SAMPLES), "");
2579
2580 return LLVMBuildFMul(ctx->ac.builder, alpha, coverage, "");
2581 }
2582
2583 static void si_llvm_emit_clipvertex(struct si_shader_context *ctx,
2584 struct ac_export_args *pos, LLVMValueRef *out_elts)
2585 {
2586 unsigned reg_index;
2587 unsigned chan;
2588 unsigned const_chan;
2589 LLVMValueRef base_elt;
2590 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, ctx->param_rw_buffers);
2591 LLVMValueRef constbuf_index = LLVMConstInt(ctx->i32,
2592 SI_VS_CONST_CLIP_PLANES, 0);
2593 LLVMValueRef const_resource = ac_build_load_to_sgpr(&ctx->ac, ptr, constbuf_index);
2594
2595 for (reg_index = 0; reg_index < 2; reg_index ++) {
2596 struct ac_export_args *args = &pos[2 + reg_index];
2597
2598 args->out[0] =
2599 args->out[1] =
2600 args->out[2] =
2601 args->out[3] = LLVMConstReal(ctx->f32, 0.0f);
2602
2603 /* Compute dot products of position and user clip plane vectors */
2604 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
2605 for (const_chan = 0; const_chan < TGSI_NUM_CHANNELS; const_chan++) {
2606 LLVMValueRef addr =
2607 LLVMConstInt(ctx->i32, ((reg_index * 4 + chan) * 4 +
2608 const_chan) * 4, 0);
2609 base_elt = buffer_load_const(ctx, const_resource,
2610 addr);
2611 args->out[chan] = ac_build_fmad(&ctx->ac, base_elt,
2612 out_elts[const_chan], args->out[chan]);
2613 }
2614 }
2615
2616 args->enabled_channels = 0xf;
2617 args->valid_mask = 0;
2618 args->done = 0;
2619 args->target = V_008DFC_SQ_EXP_POS + 2 + reg_index;
2620 args->compr = 0;
2621 }
2622 }
2623
2624 static void si_dump_streamout(struct pipe_stream_output_info *so)
2625 {
2626 unsigned i;
2627
2628 if (so->num_outputs)
2629 fprintf(stderr, "STREAMOUT\n");
2630
2631 for (i = 0; i < so->num_outputs; i++) {
2632 unsigned mask = ((1 << so->output[i].num_components) - 1) <<
2633 so->output[i].start_component;
2634 fprintf(stderr, " %i: BUF%i[%i..%i] <- OUT[%i].%s%s%s%s\n",
2635 i, so->output[i].output_buffer,
2636 so->output[i].dst_offset, so->output[i].dst_offset + so->output[i].num_components - 1,
2637 so->output[i].register_index,
2638 mask & 1 ? "x" : "",
2639 mask & 2 ? "y" : "",
2640 mask & 4 ? "z" : "",
2641 mask & 8 ? "w" : "");
2642 }
2643 }
2644
2645 void si_emit_streamout_output(struct si_shader_context *ctx,
2646 LLVMValueRef const *so_buffers,
2647 LLVMValueRef const *so_write_offsets,
2648 struct pipe_stream_output *stream_out,
2649 struct si_shader_output_values *shader_out)
2650 {
2651 unsigned buf_idx = stream_out->output_buffer;
2652 unsigned start = stream_out->start_component;
2653 unsigned num_comps = stream_out->num_components;
2654 LLVMValueRef out[4];
2655
2656 assert(num_comps && num_comps <= 4);
2657 if (!num_comps || num_comps > 4)
2658 return;
2659
2660 /* Load the output as int. */
2661 for (int j = 0; j < num_comps; j++) {
2662 assert(stream_out->stream == shader_out->vertex_stream[start + j]);
2663
2664 out[j] = ac_to_integer(&ctx->ac, shader_out->values[start + j]);
2665 }
2666
2667 /* Pack the output. */
2668 LLVMValueRef vdata = NULL;
2669
2670 switch (num_comps) {
2671 case 1: /* as i32 */
2672 vdata = out[0];
2673 break;
2674 case 2: /* as v2i32 */
2675 case 3: /* as v3i32 */
2676 if (ac_has_vec3_support(ctx->screen->info.chip_class, false)) {
2677 vdata = ac_build_gather_values(&ctx->ac, out, num_comps);
2678 break;
2679 }
2680 /* as v4i32 (aligned to 4) */
2681 out[3] = LLVMGetUndef(ctx->i32);
2682 /* fall through */
2683 case 4: /* as v4i32 */
2684 vdata = ac_build_gather_values(&ctx->ac, out, util_next_power_of_two(num_comps));
2685 break;
2686 }
2687
2688 ac_build_buffer_store_dword(&ctx->ac, so_buffers[buf_idx],
2689 vdata, num_comps,
2690 so_write_offsets[buf_idx],
2691 ctx->i32_0,
2692 stream_out->dst_offset * 4, ac_glc | ac_slc, false);
2693 }
2694
2695 /**
2696 * Write streamout data to buffers for vertex stream @p stream (different
2697 * vertex streams can occur for GS copy shaders).
2698 */
2699 static void si_llvm_emit_streamout(struct si_shader_context *ctx,
2700 struct si_shader_output_values *outputs,
2701 unsigned noutput, unsigned stream)
2702 {
2703 struct si_shader_selector *sel = ctx->shader->selector;
2704 struct pipe_stream_output_info *so = &sel->so;
2705 LLVMBuilderRef builder = ctx->ac.builder;
2706 int i;
2707 struct lp_build_if_state if_ctx;
2708
2709 /* Get bits [22:16], i.e. (so_param >> 16) & 127; */
2710 LLVMValueRef so_vtx_count =
2711 si_unpack_param(ctx, ctx->param_streamout_config, 16, 7);
2712
2713 LLVMValueRef tid = ac_get_thread_id(&ctx->ac);
2714
2715 /* can_emit = tid < so_vtx_count; */
2716 LLVMValueRef can_emit =
2717 LLVMBuildICmp(builder, LLVMIntULT, tid, so_vtx_count, "");
2718
2719 /* Emit the streamout code conditionally. This actually avoids
2720 * out-of-bounds buffer access. The hw tells us via the SGPR
2721 * (so_vtx_count) which threads are allowed to emit streamout data. */
2722 lp_build_if(&if_ctx, &ctx->gallivm, can_emit);
2723 {
2724 /* The buffer offset is computed as follows:
2725 * ByteOffset = streamout_offset[buffer_id]*4 +
2726 * (streamout_write_index + thread_id)*stride[buffer_id] +
2727 * attrib_offset
2728 */
2729
2730 LLVMValueRef so_write_index =
2731 LLVMGetParam(ctx->main_fn,
2732 ctx->param_streamout_write_index);
2733
2734 /* Compute (streamout_write_index + thread_id). */
2735 so_write_index = LLVMBuildAdd(builder, so_write_index, tid, "");
2736
2737 /* Load the descriptor and compute the write offset for each
2738 * enabled buffer. */
2739 LLVMValueRef so_write_offset[4] = {};
2740 LLVMValueRef so_buffers[4];
2741 LLVMValueRef buf_ptr = LLVMGetParam(ctx->main_fn,
2742 ctx->param_rw_buffers);
2743
2744 for (i = 0; i < 4; i++) {
2745 if (!so->stride[i])
2746 continue;
2747
2748 LLVMValueRef offset = LLVMConstInt(ctx->i32,
2749 SI_VS_STREAMOUT_BUF0 + i, 0);
2750
2751 so_buffers[i] = ac_build_load_to_sgpr(&ctx->ac, buf_ptr, offset);
2752
2753 LLVMValueRef so_offset = LLVMGetParam(ctx->main_fn,
2754 ctx->param_streamout_offset[i]);
2755 so_offset = LLVMBuildMul(builder, so_offset, LLVMConstInt(ctx->i32, 4, 0), "");
2756
2757 so_write_offset[i] = ac_build_imad(&ctx->ac, so_write_index,
2758 LLVMConstInt(ctx->i32, so->stride[i]*4, 0),
2759 so_offset);
2760 }
2761
2762 /* Write streamout data. */
2763 for (i = 0; i < so->num_outputs; i++) {
2764 unsigned reg = so->output[i].register_index;
2765
2766 if (reg >= noutput)
2767 continue;
2768
2769 if (stream != so->output[i].stream)
2770 continue;
2771
2772 si_emit_streamout_output(ctx, so_buffers, so_write_offset,
2773 &so->output[i], &outputs[reg]);
2774 }
2775 }
2776 lp_build_endif(&if_ctx);
2777 }
2778
2779 static void si_export_param(struct si_shader_context *ctx, unsigned index,
2780 LLVMValueRef *values)
2781 {
2782 struct ac_export_args args;
2783
2784 si_llvm_init_export_args(ctx, values,
2785 V_008DFC_SQ_EXP_PARAM + index, &args);
2786 ac_build_export(&ctx->ac, &args);
2787 }
2788
2789 static void si_build_param_exports(struct si_shader_context *ctx,
2790 struct si_shader_output_values *outputs,
2791 unsigned noutput)
2792 {
2793 struct si_shader *shader = ctx->shader;
2794 unsigned param_count = 0;
2795
2796 for (unsigned i = 0; i < noutput; i++) {
2797 unsigned semantic_name = outputs[i].semantic_name;
2798 unsigned semantic_index = outputs[i].semantic_index;
2799
2800 if (outputs[i].vertex_stream[0] != 0 &&
2801 outputs[i].vertex_stream[1] != 0 &&
2802 outputs[i].vertex_stream[2] != 0 &&
2803 outputs[i].vertex_stream[3] != 0)
2804 continue;
2805
2806 switch (semantic_name) {
2807 case TGSI_SEMANTIC_LAYER:
2808 case TGSI_SEMANTIC_VIEWPORT_INDEX:
2809 case TGSI_SEMANTIC_CLIPDIST:
2810 case TGSI_SEMANTIC_COLOR:
2811 case TGSI_SEMANTIC_BCOLOR:
2812 case TGSI_SEMANTIC_PRIMID:
2813 case TGSI_SEMANTIC_FOG:
2814 case TGSI_SEMANTIC_TEXCOORD:
2815 case TGSI_SEMANTIC_GENERIC:
2816 break;
2817 default:
2818 continue;
2819 }
2820
2821 if ((semantic_name != TGSI_SEMANTIC_GENERIC ||
2822 semantic_index < SI_MAX_IO_GENERIC) &&
2823 shader->key.opt.kill_outputs &
2824 (1ull << si_shader_io_get_unique_index(semantic_name,
2825 semantic_index, true)))
2826 continue;
2827
2828 si_export_param(ctx, param_count, outputs[i].values);
2829
2830 assert(i < ARRAY_SIZE(shader->info.vs_output_param_offset));
2831 shader->info.vs_output_param_offset[i] = param_count++;
2832 }
2833
2834 shader->info.nr_param_exports = param_count;
2835 }
2836
2837 /**
2838 * Vertex color clamping.
2839 *
2840 * This uses a state constant loaded in a user data SGPR and
2841 * an IF statement is added that clamps all colors if the constant
2842 * is true.
2843 */
2844 static void si_vertex_color_clamping(struct si_shader_context *ctx,
2845 struct si_shader_output_values *outputs,
2846 unsigned noutput)
2847 {
2848 LLVMValueRef addr[SI_MAX_VS_OUTPUTS][4];
2849 bool has_colors = false;
2850
2851 /* Store original colors to alloca variables. */
2852 for (unsigned i = 0; i < noutput; i++) {
2853 if (outputs[i].semantic_name != TGSI_SEMANTIC_COLOR &&
2854 outputs[i].semantic_name != TGSI_SEMANTIC_BCOLOR)
2855 continue;
2856
2857 for (unsigned j = 0; j < 4; j++) {
2858 addr[i][j] = ac_build_alloca_undef(&ctx->ac, ctx->f32, "");
2859 LLVMBuildStore(ctx->ac.builder, outputs[i].values[j], addr[i][j]);
2860 }
2861 has_colors = true;
2862 }
2863
2864 if (!has_colors)
2865 return;
2866
2867 /* The state is in the first bit of the user SGPR. */
2868 LLVMValueRef cond = LLVMGetParam(ctx->main_fn, ctx->param_vs_state_bits);
2869 cond = LLVMBuildTrunc(ctx->ac.builder, cond, ctx->i1, "");
2870
2871 struct lp_build_if_state if_ctx;
2872 lp_build_if(&if_ctx, &ctx->gallivm, cond);
2873
2874 /* Store clamped colors to alloca variables within the conditional block. */
2875 for (unsigned i = 0; i < noutput; i++) {
2876 if (outputs[i].semantic_name != TGSI_SEMANTIC_COLOR &&
2877 outputs[i].semantic_name != TGSI_SEMANTIC_BCOLOR)
2878 continue;
2879
2880 for (unsigned j = 0; j < 4; j++) {
2881 LLVMBuildStore(ctx->ac.builder,
2882 ac_build_clamp(&ctx->ac, outputs[i].values[j]),
2883 addr[i][j]);
2884 }
2885 }
2886 lp_build_endif(&if_ctx);
2887
2888 /* Load clamped colors */
2889 for (unsigned i = 0; i < noutput; i++) {
2890 if (outputs[i].semantic_name != TGSI_SEMANTIC_COLOR &&
2891 outputs[i].semantic_name != TGSI_SEMANTIC_BCOLOR)
2892 continue;
2893
2894 for (unsigned j = 0; j < 4; j++) {
2895 outputs[i].values[j] =
2896 LLVMBuildLoad(ctx->ac.builder, addr[i][j], "");
2897 }
2898 }
2899 }
2900
2901 /* Generate export instructions for hardware VS shader stage or NGG GS stage
2902 * (position and parameter data only).
2903 */
2904 void si_llvm_export_vs(struct si_shader_context *ctx,
2905 struct si_shader_output_values *outputs,
2906 unsigned noutput)
2907 {
2908 struct si_shader *shader = ctx->shader;
2909 struct ac_export_args pos_args[4] = {};
2910 LLVMValueRef psize_value = NULL, edgeflag_value = NULL, layer_value = NULL, viewport_index_value = NULL;
2911 unsigned pos_idx;
2912 int i;
2913
2914 si_vertex_color_clamping(ctx, outputs, noutput);
2915
2916 /* Build position exports. */
2917 for (i = 0; i < noutput; i++) {
2918 switch (outputs[i].semantic_name) {
2919 case TGSI_SEMANTIC_POSITION:
2920 si_llvm_init_export_args(ctx, outputs[i].values,
2921 V_008DFC_SQ_EXP_POS, &pos_args[0]);
2922 break;
2923 case TGSI_SEMANTIC_PSIZE:
2924 psize_value = outputs[i].values[0];
2925 break;
2926 case TGSI_SEMANTIC_LAYER:
2927 layer_value = outputs[i].values[0];
2928 break;
2929 case TGSI_SEMANTIC_VIEWPORT_INDEX:
2930 viewport_index_value = outputs[i].values[0];
2931 break;
2932 case TGSI_SEMANTIC_EDGEFLAG:
2933 edgeflag_value = outputs[i].values[0];
2934 break;
2935 case TGSI_SEMANTIC_CLIPDIST:
2936 if (!shader->key.opt.clip_disable) {
2937 unsigned index = 2 + outputs[i].semantic_index;
2938 si_llvm_init_export_args(ctx, outputs[i].values,
2939 V_008DFC_SQ_EXP_POS + index,
2940 &pos_args[index]);
2941 }
2942 break;
2943 case TGSI_SEMANTIC_CLIPVERTEX:
2944 if (!shader->key.opt.clip_disable) {
2945 si_llvm_emit_clipvertex(ctx, pos_args,
2946 outputs[i].values);
2947 }
2948 break;
2949 }
2950 }
2951
2952 /* We need to add the position output manually if it's missing. */
2953 if (!pos_args[0].out[0]) {
2954 pos_args[0].enabled_channels = 0xf; /* writemask */
2955 pos_args[0].valid_mask = 0; /* EXEC mask */
2956 pos_args[0].done = 0; /* last export? */
2957 pos_args[0].target = V_008DFC_SQ_EXP_POS;
2958 pos_args[0].compr = 0; /* COMPR flag */
2959 pos_args[0].out[0] = ctx->ac.f32_0; /* X */
2960 pos_args[0].out[1] = ctx->ac.f32_0; /* Y */
2961 pos_args[0].out[2] = ctx->ac.f32_0; /* Z */
2962 pos_args[0].out[3] = ctx->ac.f32_1; /* W */
2963 }
2964
2965 /* Write the misc vector (point size, edgeflag, layer, viewport). */
2966 if (shader->selector->info.writes_psize ||
2967 shader->selector->info.writes_edgeflag ||
2968 shader->selector->info.writes_viewport_index ||
2969 shader->selector->info.writes_layer) {
2970 pos_args[1].enabled_channels = shader->selector->info.writes_psize |
2971 (shader->selector->info.writes_edgeflag << 1) |
2972 (shader->selector->info.writes_layer << 2);
2973
2974 pos_args[1].valid_mask = 0; /* EXEC mask */
2975 pos_args[1].done = 0; /* last export? */
2976 pos_args[1].target = V_008DFC_SQ_EXP_POS + 1;
2977 pos_args[1].compr = 0; /* COMPR flag */
2978 pos_args[1].out[0] = ctx->ac.f32_0; /* X */
2979 pos_args[1].out[1] = ctx->ac.f32_0; /* Y */
2980 pos_args[1].out[2] = ctx->ac.f32_0; /* Z */
2981 pos_args[1].out[3] = ctx->ac.f32_0; /* W */
2982
2983 if (shader->selector->info.writes_psize)
2984 pos_args[1].out[0] = psize_value;
2985
2986 if (shader->selector->info.writes_edgeflag) {
2987 /* The output is a float, but the hw expects an integer
2988 * with the first bit containing the edge flag. */
2989 edgeflag_value = LLVMBuildFPToUI(ctx->ac.builder,
2990 edgeflag_value,
2991 ctx->i32, "");
2992 edgeflag_value = ac_build_umin(&ctx->ac,
2993 edgeflag_value,
2994 ctx->i32_1);
2995
2996 /* The LLVM intrinsic expects a float. */
2997 pos_args[1].out[1] = ac_to_float(&ctx->ac, edgeflag_value);
2998 }
2999
3000 if (ctx->screen->info.chip_class >= GFX9) {
3001 /* GFX9 has the layer in out.z[10:0] and the viewport
3002 * index in out.z[19:16].
3003 */
3004 if (shader->selector->info.writes_layer)
3005 pos_args[1].out[2] = layer_value;
3006
3007 if (shader->selector->info.writes_viewport_index) {
3008 LLVMValueRef v = viewport_index_value;
3009
3010 v = ac_to_integer(&ctx->ac, v);
3011 v = LLVMBuildShl(ctx->ac.builder, v,
3012 LLVMConstInt(ctx->i32, 16, 0), "");
3013 v = LLVMBuildOr(ctx->ac.builder, v,
3014 ac_to_integer(&ctx->ac, pos_args[1].out[2]), "");
3015 pos_args[1].out[2] = ac_to_float(&ctx->ac, v);
3016 pos_args[1].enabled_channels |= 1 << 2;
3017 }
3018 } else {
3019 if (shader->selector->info.writes_layer)
3020 pos_args[1].out[2] = layer_value;
3021
3022 if (shader->selector->info.writes_viewport_index) {
3023 pos_args[1].out[3] = viewport_index_value;
3024 pos_args[1].enabled_channels |= 1 << 3;
3025 }
3026 }
3027 }
3028
3029 for (i = 0; i < 4; i++)
3030 if (pos_args[i].out[0])
3031 shader->info.nr_pos_exports++;
3032
3033 /* Navi10-14 skip POS0 exports if EXEC=0 and DONE=0, causing a hang.
3034 * Setting valid_mask=1 prevents it and has no other effect.
3035 */
3036 if (ctx->screen->info.family == CHIP_NAVI10 ||
3037 ctx->screen->info.family == CHIP_NAVI12 ||
3038 ctx->screen->info.family == CHIP_NAVI14)
3039 pos_args[0].valid_mask = 1;
3040
3041 pos_idx = 0;
3042 for (i = 0; i < 4; i++) {
3043 if (!pos_args[i].out[0])
3044 continue;
3045
3046 /* Specify the target we are exporting */
3047 pos_args[i].target = V_008DFC_SQ_EXP_POS + pos_idx++;
3048
3049 if (pos_idx == shader->info.nr_pos_exports)
3050 /* Specify that this is the last export */
3051 pos_args[i].done = 1;
3052
3053 ac_build_export(&ctx->ac, &pos_args[i]);
3054 }
3055
3056 /* Build parameter exports. */
3057 si_build_param_exports(ctx, outputs, noutput);
3058 }
3059
3060 /**
3061 * Forward all outputs from the vertex shader to the TES. This is only used
3062 * for the fixed function TCS.
3063 */
3064 static void si_copy_tcs_inputs(struct lp_build_tgsi_context *bld_base)
3065 {
3066 struct si_shader_context *ctx = si_shader_context(bld_base);
3067 LLVMValueRef invocation_id, buffer, buffer_offset;
3068 LLVMValueRef lds_vertex_stride, lds_base;
3069 uint64_t inputs;
3070
3071 invocation_id = unpack_llvm_param(ctx, ctx->abi.tcs_rel_ids, 8, 5);
3072 buffer = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TCS);
3073 buffer_offset = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
3074
3075 lds_vertex_stride = get_tcs_in_vertex_dw_stride(ctx);
3076 lds_base = get_tcs_in_current_patch_offset(ctx);
3077 lds_base = ac_build_imad(&ctx->ac, invocation_id, lds_vertex_stride,
3078 lds_base);
3079
3080 inputs = ctx->shader->key.mono.u.ff_tcs_inputs_to_copy;
3081 while (inputs) {
3082 unsigned i = u_bit_scan64(&inputs);
3083
3084 LLVMValueRef lds_ptr = LLVMBuildAdd(ctx->ac.builder, lds_base,
3085 LLVMConstInt(ctx->i32, 4 * i, 0),
3086 "");
3087
3088 LLVMValueRef buffer_addr = get_tcs_tes_buffer_address(ctx,
3089 get_rel_patch_id(ctx),
3090 invocation_id,
3091 LLVMConstInt(ctx->i32, i, 0));
3092
3093 LLVMValueRef value = lshs_lds_load(bld_base, ctx->ac.i32, ~0, lds_ptr);
3094
3095 ac_build_buffer_store_dword(&ctx->ac, buffer, value, 4, buffer_addr,
3096 buffer_offset, 0, ac_glc, false);
3097 }
3098 }
3099
3100 static void si_write_tess_factors(struct lp_build_tgsi_context *bld_base,
3101 LLVMValueRef rel_patch_id,
3102 LLVMValueRef invocation_id,
3103 LLVMValueRef tcs_out_current_patch_data_offset,
3104 LLVMValueRef invoc0_tf_outer[4],
3105 LLVMValueRef invoc0_tf_inner[2])
3106 {
3107 struct si_shader_context *ctx = si_shader_context(bld_base);
3108 struct si_shader *shader = ctx->shader;
3109 unsigned tess_inner_index, tess_outer_index;
3110 LLVMValueRef lds_base, lds_inner, lds_outer, byteoffset, buffer;
3111 LLVMValueRef out[6], vec0, vec1, tf_base, inner[4], outer[4];
3112 unsigned stride, outer_comps, inner_comps, i, offset;
3113 struct lp_build_if_state if_ctx, inner_if_ctx;
3114
3115 /* Add a barrier before loading tess factors from LDS. */
3116 if (!shader->key.part.tcs.epilog.invoc0_tess_factors_are_def)
3117 si_llvm_emit_barrier(NULL, bld_base, NULL);
3118
3119 /* Do this only for invocation 0, because the tess levels are per-patch,
3120 * not per-vertex.
3121 *
3122 * This can't jump, because invocation 0 executes this. It should
3123 * at least mask out the loads and stores for other invocations.
3124 */
3125 lp_build_if(&if_ctx, &ctx->gallivm,
3126 LLVMBuildICmp(ctx->ac.builder, LLVMIntEQ,
3127 invocation_id, ctx->i32_0, ""));
3128
3129 /* Determine the layout of one tess factor element in the buffer. */
3130 switch (shader->key.part.tcs.epilog.prim_mode) {
3131 case PIPE_PRIM_LINES:
3132 stride = 2; /* 2 dwords, 1 vec2 store */
3133 outer_comps = 2;
3134 inner_comps = 0;
3135 break;
3136 case PIPE_PRIM_TRIANGLES:
3137 stride = 4; /* 4 dwords, 1 vec4 store */
3138 outer_comps = 3;
3139 inner_comps = 1;
3140 break;
3141 case PIPE_PRIM_QUADS:
3142 stride = 6; /* 6 dwords, 2 stores (vec4 + vec2) */
3143 outer_comps = 4;
3144 inner_comps = 2;
3145 break;
3146 default:
3147 assert(0);
3148 return;
3149 }
3150
3151 for (i = 0; i < 4; i++) {
3152 inner[i] = LLVMGetUndef(ctx->i32);
3153 outer[i] = LLVMGetUndef(ctx->i32);
3154 }
3155
3156 if (shader->key.part.tcs.epilog.invoc0_tess_factors_are_def) {
3157 /* Tess factors are in VGPRs. */
3158 for (i = 0; i < outer_comps; i++)
3159 outer[i] = out[i] = invoc0_tf_outer[i];
3160 for (i = 0; i < inner_comps; i++)
3161 inner[i] = out[outer_comps+i] = invoc0_tf_inner[i];
3162 } else {
3163 /* Load tess_inner and tess_outer from LDS.
3164 * Any invocation can write them, so we can't get them from a temporary.
3165 */
3166 tess_inner_index = si_shader_io_get_unique_index_patch(TGSI_SEMANTIC_TESSINNER, 0);
3167 tess_outer_index = si_shader_io_get_unique_index_patch(TGSI_SEMANTIC_TESSOUTER, 0);
3168
3169 lds_base = tcs_out_current_patch_data_offset;
3170 lds_inner = LLVMBuildAdd(ctx->ac.builder, lds_base,
3171 LLVMConstInt(ctx->i32,
3172 tess_inner_index * 4, 0), "");
3173 lds_outer = LLVMBuildAdd(ctx->ac.builder, lds_base,
3174 LLVMConstInt(ctx->i32,
3175 tess_outer_index * 4, 0), "");
3176
3177 for (i = 0; i < outer_comps; i++) {
3178 outer[i] = out[i] =
3179 lshs_lds_load(bld_base, ctx->ac.i32, i, lds_outer);
3180 }
3181 for (i = 0; i < inner_comps; i++) {
3182 inner[i] = out[outer_comps+i] =
3183 lshs_lds_load(bld_base, ctx->ac.i32, i, lds_inner);
3184 }
3185 }
3186
3187 if (shader->key.part.tcs.epilog.prim_mode == PIPE_PRIM_LINES) {
3188 /* For isolines, the hardware expects tess factors in the
3189 * reverse order from what GLSL / TGSI specify.
3190 */
3191 LLVMValueRef tmp = out[0];
3192 out[0] = out[1];
3193 out[1] = tmp;
3194 }
3195
3196 /* Convert the outputs to vectors for stores. */
3197 vec0 = ac_build_gather_values(&ctx->ac, out, MIN2(stride, 4));
3198 vec1 = NULL;
3199
3200 if (stride > 4)
3201 vec1 = ac_build_gather_values(&ctx->ac, out+4, stride - 4);
3202
3203 /* Get the buffer. */
3204 buffer = get_tess_ring_descriptor(ctx, TCS_FACTOR_RING);
3205
3206 /* Get the offset. */
3207 tf_base = LLVMGetParam(ctx->main_fn,
3208 ctx->param_tcs_factor_offset);
3209 byteoffset = LLVMBuildMul(ctx->ac.builder, rel_patch_id,
3210 LLVMConstInt(ctx->i32, 4 * stride, 0), "");
3211
3212 lp_build_if(&inner_if_ctx, &ctx->gallivm,
3213 LLVMBuildICmp(ctx->ac.builder, LLVMIntEQ,
3214 rel_patch_id, ctx->i32_0, ""));
3215
3216 /* Store the dynamic HS control word. */
3217 offset = 0;
3218 if (ctx->screen->info.chip_class <= GFX8) {
3219 ac_build_buffer_store_dword(&ctx->ac, buffer,
3220 LLVMConstInt(ctx->i32, 0x80000000, 0),
3221 1, ctx->i32_0, tf_base,
3222 offset, ac_glc, false);
3223 offset += 4;
3224 }
3225
3226 lp_build_endif(&inner_if_ctx);
3227
3228 /* Store the tessellation factors. */
3229 ac_build_buffer_store_dword(&ctx->ac, buffer, vec0,
3230 MIN2(stride, 4), byteoffset, tf_base,
3231 offset, ac_glc, false);
3232 offset += 16;
3233 if (vec1)
3234 ac_build_buffer_store_dword(&ctx->ac, buffer, vec1,
3235 stride - 4, byteoffset, tf_base,
3236 offset, ac_glc, false);
3237
3238 /* Store the tess factors into the offchip buffer if TES reads them. */
3239 if (shader->key.part.tcs.epilog.tes_reads_tess_factors) {
3240 LLVMValueRef buf, base, inner_vec, outer_vec, tf_outer_offset;
3241 LLVMValueRef tf_inner_offset;
3242 unsigned param_outer, param_inner;
3243
3244 buf = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TCS);
3245 base = LLVMGetParam(ctx->main_fn, ctx->param_tcs_offchip_offset);
3246
3247 param_outer = si_shader_io_get_unique_index_patch(
3248 TGSI_SEMANTIC_TESSOUTER, 0);
3249 tf_outer_offset = get_tcs_tes_buffer_address(ctx, rel_patch_id, NULL,
3250 LLVMConstInt(ctx->i32, param_outer, 0));
3251
3252 unsigned outer_vec_size =
3253 ac_has_vec3_support(ctx->screen->info.chip_class, false) ?
3254 outer_comps : util_next_power_of_two(outer_comps);
3255 outer_vec = ac_build_gather_values(&ctx->ac, outer, outer_vec_size);
3256
3257 ac_build_buffer_store_dword(&ctx->ac, buf, outer_vec,
3258 outer_comps, tf_outer_offset,
3259 base, 0, ac_glc, false);
3260 if (inner_comps) {
3261 param_inner = si_shader_io_get_unique_index_patch(
3262 TGSI_SEMANTIC_TESSINNER, 0);
3263 tf_inner_offset = get_tcs_tes_buffer_address(ctx, rel_patch_id, NULL,
3264 LLVMConstInt(ctx->i32, param_inner, 0));
3265
3266 inner_vec = inner_comps == 1 ? inner[0] :
3267 ac_build_gather_values(&ctx->ac, inner, inner_comps);
3268 ac_build_buffer_store_dword(&ctx->ac, buf, inner_vec,
3269 inner_comps, tf_inner_offset,
3270 base, 0, ac_glc, false);
3271 }
3272 }
3273
3274 lp_build_endif(&if_ctx);
3275 }
3276
3277 static LLVMValueRef
3278 si_insert_input_ret(struct si_shader_context *ctx, LLVMValueRef ret,
3279 unsigned param, unsigned return_index)
3280 {
3281 return LLVMBuildInsertValue(ctx->ac.builder, ret,
3282 LLVMGetParam(ctx->main_fn, param),
3283 return_index, "");
3284 }
3285
3286 static LLVMValueRef
3287 si_insert_input_ret_float(struct si_shader_context *ctx, LLVMValueRef ret,
3288 unsigned param, unsigned return_index)
3289 {
3290 LLVMBuilderRef builder = ctx->ac.builder;
3291 LLVMValueRef p = LLVMGetParam(ctx->main_fn, param);
3292
3293 return LLVMBuildInsertValue(builder, ret,
3294 ac_to_float(&ctx->ac, p),
3295 return_index, "");
3296 }
3297
3298 static LLVMValueRef
3299 si_insert_input_ptr(struct si_shader_context *ctx, LLVMValueRef ret,
3300 unsigned param, unsigned return_index)
3301 {
3302 LLVMBuilderRef builder = ctx->ac.builder;
3303 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, param);
3304 ptr = LLVMBuildPtrToInt(builder, ptr, ctx->i32, "");
3305 return LLVMBuildInsertValue(builder, ret, ptr, return_index, "");
3306 }
3307
3308 /* This only writes the tessellation factor levels. */
3309 static void si_llvm_emit_tcs_epilogue(struct ac_shader_abi *abi,
3310 unsigned max_outputs,
3311 LLVMValueRef *addrs)
3312 {
3313 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3314 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
3315 LLVMBuilderRef builder = ctx->ac.builder;
3316 LLVMValueRef rel_patch_id, invocation_id, tf_lds_offset;
3317
3318 si_copy_tcs_inputs(bld_base);
3319
3320 rel_patch_id = get_rel_patch_id(ctx);
3321 invocation_id = unpack_llvm_param(ctx, ctx->abi.tcs_rel_ids, 8, 5);
3322 tf_lds_offset = get_tcs_out_current_patch_data_offset(ctx);
3323
3324 if (ctx->screen->info.chip_class >= GFX9) {
3325 LLVMBasicBlockRef blocks[2] = {
3326 LLVMGetInsertBlock(builder),
3327 ctx->merged_wrap_if_state.entry_block
3328 };
3329 LLVMValueRef values[2];
3330
3331 lp_build_endif(&ctx->merged_wrap_if_state);
3332
3333 values[0] = rel_patch_id;
3334 values[1] = LLVMGetUndef(ctx->i32);
3335 rel_patch_id = ac_build_phi(&ctx->ac, ctx->i32, 2, values, blocks);
3336
3337 values[0] = tf_lds_offset;
3338 values[1] = LLVMGetUndef(ctx->i32);
3339 tf_lds_offset = ac_build_phi(&ctx->ac, ctx->i32, 2, values, blocks);
3340
3341 values[0] = invocation_id;
3342 values[1] = ctx->i32_1; /* cause the epilog to skip threads */
3343 invocation_id = ac_build_phi(&ctx->ac, ctx->i32, 2, values, blocks);
3344 }
3345
3346 /* Return epilog parameters from this function. */
3347 LLVMValueRef ret = ctx->return_value;
3348 unsigned vgpr;
3349
3350 if (ctx->screen->info.chip_class >= GFX9) {
3351 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_layout,
3352 8 + GFX9_SGPR_TCS_OFFCHIP_LAYOUT);
3353 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_out_lds_layout,
3354 8 + GFX9_SGPR_TCS_OUT_LAYOUT);
3355 /* Tess offchip and tess factor offsets are at the beginning. */
3356 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_offset, 2);
3357 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_factor_offset, 4);
3358 vgpr = 8 + GFX9_SGPR_TCS_OUT_LAYOUT + 1;
3359 } else {
3360 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_layout,
3361 GFX6_SGPR_TCS_OFFCHIP_LAYOUT);
3362 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_out_lds_layout,
3363 GFX6_SGPR_TCS_OUT_LAYOUT);
3364 /* Tess offchip and tess factor offsets are after user SGPRs. */
3365 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_offset,
3366 GFX6_TCS_NUM_USER_SGPR);
3367 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_factor_offset,
3368 GFX6_TCS_NUM_USER_SGPR + 1);
3369 vgpr = GFX6_TCS_NUM_USER_SGPR + 2;
3370 }
3371
3372 /* VGPRs */
3373 rel_patch_id = ac_to_float(&ctx->ac, rel_patch_id);
3374 invocation_id = ac_to_float(&ctx->ac, invocation_id);
3375 tf_lds_offset = ac_to_float(&ctx->ac, tf_lds_offset);
3376
3377 /* Leave a hole corresponding to the two input VGPRs. This ensures that
3378 * the invocation_id output does not alias the tcs_rel_ids input,
3379 * which saves a V_MOV on gfx9.
3380 */
3381 vgpr += 2;
3382
3383 ret = LLVMBuildInsertValue(builder, ret, rel_patch_id, vgpr++, "");
3384 ret = LLVMBuildInsertValue(builder, ret, invocation_id, vgpr++, "");
3385
3386 if (ctx->shader->selector->tcs_info.tessfactors_are_def_in_all_invocs) {
3387 vgpr++; /* skip the tess factor LDS offset */
3388 for (unsigned i = 0; i < 6; i++) {
3389 LLVMValueRef value =
3390 LLVMBuildLoad(builder, ctx->invoc0_tess_factors[i], "");
3391 value = ac_to_float(&ctx->ac, value);
3392 ret = LLVMBuildInsertValue(builder, ret, value, vgpr++, "");
3393 }
3394 } else {
3395 ret = LLVMBuildInsertValue(builder, ret, tf_lds_offset, vgpr++, "");
3396 }
3397 ctx->return_value = ret;
3398 }
3399
3400 /* Pass TCS inputs from LS to TCS on GFX9. */
3401 static void si_set_ls_return_value_for_tcs(struct si_shader_context *ctx)
3402 {
3403 LLVMValueRef ret = ctx->return_value;
3404
3405 ret = si_insert_input_ptr(ctx, ret, 0, 0);
3406 ret = si_insert_input_ptr(ctx, ret, 1, 1);
3407 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_offset, 2);
3408 ret = si_insert_input_ret(ctx, ret, ctx->param_merged_wave_info, 3);
3409 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_factor_offset, 4);
3410 ret = si_insert_input_ret(ctx, ret, ctx->param_merged_scratch_offset, 5);
3411
3412 ret = si_insert_input_ptr(ctx, ret, ctx->param_rw_buffers,
3413 8 + SI_SGPR_RW_BUFFERS);
3414 ret = si_insert_input_ptr(ctx, ret,
3415 ctx->param_bindless_samplers_and_images,
3416 8 + SI_SGPR_BINDLESS_SAMPLERS_AND_IMAGES);
3417
3418 ret = si_insert_input_ret(ctx, ret, ctx->param_vs_state_bits,
3419 8 + SI_SGPR_VS_STATE_BITS);
3420
3421 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_offchip_layout,
3422 8 + GFX9_SGPR_TCS_OFFCHIP_LAYOUT);
3423 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_out_lds_offsets,
3424 8 + GFX9_SGPR_TCS_OUT_OFFSETS);
3425 ret = si_insert_input_ret(ctx, ret, ctx->param_tcs_out_lds_layout,
3426 8 + GFX9_SGPR_TCS_OUT_LAYOUT);
3427
3428 unsigned vgpr = 8 + GFX9_TCS_NUM_USER_SGPR;
3429 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
3430 ac_to_float(&ctx->ac, ctx->abi.tcs_patch_id),
3431 vgpr++, "");
3432 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
3433 ac_to_float(&ctx->ac, ctx->abi.tcs_rel_ids),
3434 vgpr++, "");
3435 ctx->return_value = ret;
3436 }
3437
3438 /* Pass GS inputs from ES to GS on GFX9. */
3439 static void si_set_es_return_value_for_gs(struct si_shader_context *ctx)
3440 {
3441 LLVMBuilderRef builder = ctx->ac.builder;
3442 LLVMValueRef ret = ctx->return_value;
3443
3444 ret = si_insert_input_ptr(ctx, ret, 0, 0);
3445 ret = si_insert_input_ptr(ctx, ret, 1, 1);
3446 if (ctx->shader->key.as_ngg)
3447 ret = LLVMBuildInsertValue(builder, ret, ctx->gs_tg_info, 2, "");
3448 else
3449 ret = si_insert_input_ret(ctx, ret, ctx->param_gs2vs_offset, 2);
3450 ret = si_insert_input_ret(ctx, ret, ctx->param_merged_wave_info, 3);
3451 ret = si_insert_input_ret(ctx, ret, ctx->param_merged_scratch_offset, 5);
3452
3453 ret = si_insert_input_ptr(ctx, ret, ctx->param_rw_buffers,
3454 8 + SI_SGPR_RW_BUFFERS);
3455 ret = si_insert_input_ptr(ctx, ret,
3456 ctx->param_bindless_samplers_and_images,
3457 8 + SI_SGPR_BINDLESS_SAMPLERS_AND_IMAGES);
3458 if (ctx->screen->info.chip_class >= GFX10) {
3459 ret = si_insert_input_ptr(ctx, ret, ctx->param_vs_state_bits,
3460 8 + SI_SGPR_VS_STATE_BITS);
3461 }
3462
3463 unsigned vgpr;
3464 if (ctx->type == PIPE_SHADER_VERTEX)
3465 vgpr = 8 + GFX9_VSGS_NUM_USER_SGPR;
3466 else
3467 vgpr = 8 + GFX9_TESGS_NUM_USER_SGPR;
3468
3469 for (unsigned i = 0; i < 5; i++) {
3470 unsigned param = ctx->param_gs_vtx01_offset + i;
3471 ret = si_insert_input_ret_float(ctx, ret, param, vgpr++);
3472 }
3473 ctx->return_value = ret;
3474 }
3475
3476 static void si_llvm_emit_ls_epilogue(struct ac_shader_abi *abi,
3477 unsigned max_outputs,
3478 LLVMValueRef *addrs)
3479 {
3480 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3481 struct si_shader *shader = ctx->shader;
3482 struct tgsi_shader_info *info = &shader->selector->info;
3483 unsigned i, chan;
3484 LLVMValueRef vertex_id = LLVMGetParam(ctx->main_fn,
3485 ctx->param_rel_auto_id);
3486 LLVMValueRef vertex_dw_stride = get_tcs_in_vertex_dw_stride(ctx);
3487 LLVMValueRef base_dw_addr = LLVMBuildMul(ctx->ac.builder, vertex_id,
3488 vertex_dw_stride, "");
3489
3490 /* Write outputs to LDS. The next shader (TCS aka HS) will read
3491 * its inputs from it. */
3492 for (i = 0; i < info->num_outputs; i++) {
3493 unsigned name = info->output_semantic_name[i];
3494 unsigned index = info->output_semantic_index[i];
3495
3496 /* The ARB_shader_viewport_layer_array spec contains the
3497 * following issue:
3498 *
3499 * 2) What happens if gl_ViewportIndex or gl_Layer is
3500 * written in the vertex shader and a geometry shader is
3501 * present?
3502 *
3503 * RESOLVED: The value written by the last vertex processing
3504 * stage is used. If the last vertex processing stage
3505 * (vertex, tessellation evaluation or geometry) does not
3506 * statically assign to gl_ViewportIndex or gl_Layer, index
3507 * or layer zero is assumed.
3508 *
3509 * So writes to those outputs in VS-as-LS are simply ignored.
3510 */
3511 if (name == TGSI_SEMANTIC_LAYER ||
3512 name == TGSI_SEMANTIC_VIEWPORT_INDEX)
3513 continue;
3514
3515 int param = si_shader_io_get_unique_index(name, index, false);
3516 LLVMValueRef dw_addr = LLVMBuildAdd(ctx->ac.builder, base_dw_addr,
3517 LLVMConstInt(ctx->i32, param * 4, 0), "");
3518
3519 for (chan = 0; chan < 4; chan++) {
3520 if (!(info->output_usagemask[i] & (1 << chan)))
3521 continue;
3522
3523 lshs_lds_store(ctx, chan, dw_addr,
3524 LLVMBuildLoad(ctx->ac.builder, addrs[4 * i + chan], ""));
3525 }
3526 }
3527
3528 if (ctx->screen->info.chip_class >= GFX9)
3529 si_set_ls_return_value_for_tcs(ctx);
3530 }
3531
3532 static void si_llvm_emit_es_epilogue(struct ac_shader_abi *abi,
3533 unsigned max_outputs,
3534 LLVMValueRef *addrs)
3535 {
3536 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3537 struct si_shader *es = ctx->shader;
3538 struct tgsi_shader_info *info = &es->selector->info;
3539 LLVMValueRef soffset = LLVMGetParam(ctx->main_fn,
3540 ctx->param_es2gs_offset);
3541 LLVMValueRef lds_base = NULL;
3542 unsigned chan;
3543 int i;
3544
3545 if (ctx->screen->info.chip_class >= GFX9 && info->num_outputs) {
3546 unsigned itemsize_dw = es->selector->esgs_itemsize / 4;
3547 LLVMValueRef vertex_idx = ac_get_thread_id(&ctx->ac);
3548 LLVMValueRef wave_idx = si_unpack_param(ctx, ctx->param_merged_wave_info, 24, 4);
3549 vertex_idx = LLVMBuildOr(ctx->ac.builder, vertex_idx,
3550 LLVMBuildMul(ctx->ac.builder, wave_idx,
3551 LLVMConstInt(ctx->i32, 64, false), ""), "");
3552 lds_base = LLVMBuildMul(ctx->ac.builder, vertex_idx,
3553 LLVMConstInt(ctx->i32, itemsize_dw, 0), "");
3554 }
3555
3556 for (i = 0; i < info->num_outputs; i++) {
3557 int param;
3558
3559 if (info->output_semantic_name[i] == TGSI_SEMANTIC_VIEWPORT_INDEX ||
3560 info->output_semantic_name[i] == TGSI_SEMANTIC_LAYER)
3561 continue;
3562
3563 param = si_shader_io_get_unique_index(info->output_semantic_name[i],
3564 info->output_semantic_index[i], false);
3565
3566 for (chan = 0; chan < 4; chan++) {
3567 if (!(info->output_usagemask[i] & (1 << chan)))
3568 continue;
3569
3570 LLVMValueRef out_val = LLVMBuildLoad(ctx->ac.builder, addrs[4 * i + chan], "");
3571 out_val = ac_to_integer(&ctx->ac, out_val);
3572
3573 /* GFX9 has the ESGS ring in LDS. */
3574 if (ctx->screen->info.chip_class >= GFX9) {
3575 LLVMValueRef idx = LLVMConstInt(ctx->i32, param * 4 + chan, false);
3576 idx = LLVMBuildAdd(ctx->ac.builder, lds_base, idx, "");
3577 ac_build_indexed_store(&ctx->ac, ctx->esgs_ring, idx, out_val);
3578 continue;
3579 }
3580
3581 ac_build_buffer_store_dword(&ctx->ac,
3582 ctx->esgs_ring,
3583 out_val, 1, NULL, soffset,
3584 (4 * param + chan) * 4,
3585 ac_glc | ac_slc, true);
3586 }
3587 }
3588
3589 if (ctx->screen->info.chip_class >= GFX9)
3590 si_set_es_return_value_for_gs(ctx);
3591 }
3592
3593 static LLVMValueRef si_get_gs_wave_id(struct si_shader_context *ctx)
3594 {
3595 if (ctx->screen->info.chip_class >= GFX9)
3596 return si_unpack_param(ctx, ctx->param_merged_wave_info, 16, 8);
3597 else
3598 return LLVMGetParam(ctx->main_fn, ctx->param_gs_wave_id);
3599 }
3600
3601 static void emit_gs_epilogue(struct si_shader_context *ctx)
3602 {
3603 if (ctx->shader->key.as_ngg) {
3604 gfx10_ngg_gs_emit_epilogue(ctx);
3605 return;
3606 }
3607
3608 if (ctx->screen->info.chip_class >= GFX10)
3609 LLVMBuildFence(ctx->ac.builder, LLVMAtomicOrderingRelease, false, "");
3610
3611 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_NOP | AC_SENDMSG_GS_DONE,
3612 si_get_gs_wave_id(ctx));
3613
3614 if (ctx->screen->info.chip_class >= GFX9)
3615 lp_build_endif(&ctx->merged_wrap_if_state);
3616 }
3617
3618 static void si_llvm_emit_gs_epilogue(struct ac_shader_abi *abi,
3619 unsigned max_outputs,
3620 LLVMValueRef *addrs)
3621 {
3622 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3623 struct tgsi_shader_info UNUSED *info = &ctx->shader->selector->info;
3624
3625 assert(info->num_outputs <= max_outputs);
3626
3627 emit_gs_epilogue(ctx);
3628 }
3629
3630 static void si_tgsi_emit_gs_epilogue(struct lp_build_tgsi_context *bld_base)
3631 {
3632 struct si_shader_context *ctx = si_shader_context(bld_base);
3633 emit_gs_epilogue(ctx);
3634 }
3635
3636 static void si_llvm_emit_vs_epilogue(struct ac_shader_abi *abi,
3637 unsigned max_outputs,
3638 LLVMValueRef *addrs)
3639 {
3640 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3641 struct tgsi_shader_info *info = &ctx->shader->selector->info;
3642 struct si_shader_output_values *outputs = NULL;
3643 int i,j;
3644
3645 assert(!ctx->shader->is_gs_copy_shader);
3646 assert(info->num_outputs <= max_outputs);
3647
3648 outputs = MALLOC((info->num_outputs + 1) * sizeof(outputs[0]));
3649
3650 for (i = 0; i < info->num_outputs; i++) {
3651 outputs[i].semantic_name = info->output_semantic_name[i];
3652 outputs[i].semantic_index = info->output_semantic_index[i];
3653
3654 for (j = 0; j < 4; j++) {
3655 outputs[i].values[j] =
3656 LLVMBuildLoad(ctx->ac.builder,
3657 addrs[4 * i + j],
3658 "");
3659 outputs[i].vertex_stream[j] =
3660 (info->output_streams[i] >> (2 * j)) & 3;
3661 }
3662 }
3663
3664 if (ctx->ac.chip_class <= GFX9 &&
3665 ctx->shader->selector->so.num_outputs)
3666 si_llvm_emit_streamout(ctx, outputs, i, 0);
3667
3668 /* Export PrimitiveID. */
3669 if (ctx->shader->key.mono.u.vs_export_prim_id) {
3670 outputs[i].semantic_name = TGSI_SEMANTIC_PRIMID;
3671 outputs[i].semantic_index = 0;
3672 outputs[i].values[0] = ac_to_float(&ctx->ac, si_get_primitive_id(ctx, 0));
3673 for (j = 1; j < 4; j++)
3674 outputs[i].values[j] = LLVMConstReal(ctx->f32, 0);
3675
3676 memset(outputs[i].vertex_stream, 0,
3677 sizeof(outputs[i].vertex_stream));
3678 i++;
3679 }
3680
3681 si_llvm_export_vs(ctx, outputs, i);
3682 FREE(outputs);
3683 }
3684
3685 static void si_llvm_emit_prim_discard_cs_epilogue(struct ac_shader_abi *abi,
3686 unsigned max_outputs,
3687 LLVMValueRef *addrs)
3688 {
3689 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3690 struct tgsi_shader_info *info = &ctx->shader->selector->info;
3691 LLVMValueRef pos[4] = {};
3692
3693 assert(info->num_outputs <= max_outputs);
3694
3695 for (unsigned i = 0; i < info->num_outputs; i++) {
3696 if (info->output_semantic_name[i] != TGSI_SEMANTIC_POSITION)
3697 continue;
3698
3699 for (unsigned chan = 0; chan < 4; chan++)
3700 pos[chan] = LLVMBuildLoad(ctx->ac.builder, addrs[4 * i + chan], "");
3701 break;
3702 }
3703 assert(pos[0] != NULL);
3704
3705 /* Return the position output. */
3706 LLVMValueRef ret = ctx->return_value;
3707 for (unsigned chan = 0; chan < 4; chan++)
3708 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, pos[chan], chan, "");
3709 ctx->return_value = ret;
3710 }
3711
3712 static void si_tgsi_emit_epilogue(struct lp_build_tgsi_context *bld_base)
3713 {
3714 struct si_shader_context *ctx = si_shader_context(bld_base);
3715
3716 ctx->abi.emit_outputs(&ctx->abi, RADEON_LLVM_MAX_OUTPUTS,
3717 &ctx->outputs[0][0]);
3718 }
3719
3720 struct si_ps_exports {
3721 unsigned num;
3722 struct ac_export_args args[10];
3723 };
3724
3725 static void si_export_mrt_z(struct lp_build_tgsi_context *bld_base,
3726 LLVMValueRef depth, LLVMValueRef stencil,
3727 LLVMValueRef samplemask, struct si_ps_exports *exp)
3728 {
3729 struct si_shader_context *ctx = si_shader_context(bld_base);
3730 struct ac_export_args args;
3731
3732 ac_export_mrt_z(&ctx->ac, depth, stencil, samplemask, &args);
3733
3734 memcpy(&exp->args[exp->num++], &args, sizeof(args));
3735 }
3736
3737 static void si_export_mrt_color(struct lp_build_tgsi_context *bld_base,
3738 LLVMValueRef *color, unsigned index,
3739 unsigned samplemask_param,
3740 bool is_last, struct si_ps_exports *exp)
3741 {
3742 struct si_shader_context *ctx = si_shader_context(bld_base);
3743 int i;
3744
3745 /* Clamp color */
3746 if (ctx->shader->key.part.ps.epilog.clamp_color)
3747 for (i = 0; i < 4; i++)
3748 color[i] = ac_build_clamp(&ctx->ac, color[i]);
3749
3750 /* Alpha to one */
3751 if (ctx->shader->key.part.ps.epilog.alpha_to_one)
3752 color[3] = ctx->ac.f32_1;
3753
3754 /* Alpha test */
3755 if (index == 0 &&
3756 ctx->shader->key.part.ps.epilog.alpha_func != PIPE_FUNC_ALWAYS)
3757 si_alpha_test(bld_base, color[3]);
3758
3759 /* Line & polygon smoothing */
3760 if (ctx->shader->key.part.ps.epilog.poly_line_smoothing)
3761 color[3] = si_scale_alpha_by_sample_mask(bld_base, color[3],
3762 samplemask_param);
3763
3764 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
3765 if (ctx->shader->key.part.ps.epilog.last_cbuf > 0) {
3766 struct ac_export_args args[8];
3767 int c, last = -1;
3768
3769 /* Get the export arguments, also find out what the last one is. */
3770 for (c = 0; c <= ctx->shader->key.part.ps.epilog.last_cbuf; c++) {
3771 si_llvm_init_export_args(ctx, color,
3772 V_008DFC_SQ_EXP_MRT + c, &args[c]);
3773 if (args[c].enabled_channels)
3774 last = c;
3775 }
3776
3777 /* Emit all exports. */
3778 for (c = 0; c <= ctx->shader->key.part.ps.epilog.last_cbuf; c++) {
3779 if (is_last && last == c) {
3780 args[c].valid_mask = 1; /* whether the EXEC mask is valid */
3781 args[c].done = 1; /* DONE bit */
3782 } else if (!args[c].enabled_channels)
3783 continue; /* unnecessary NULL export */
3784
3785 memcpy(&exp->args[exp->num++], &args[c], sizeof(args[c]));
3786 }
3787 } else {
3788 struct ac_export_args args;
3789
3790 /* Export */
3791 si_llvm_init_export_args(ctx, color, V_008DFC_SQ_EXP_MRT + index,
3792 &args);
3793 if (is_last) {
3794 args.valid_mask = 1; /* whether the EXEC mask is valid */
3795 args.done = 1; /* DONE bit */
3796 } else if (!args.enabled_channels)
3797 return; /* unnecessary NULL export */
3798
3799 memcpy(&exp->args[exp->num++], &args, sizeof(args));
3800 }
3801 }
3802
3803 static void si_emit_ps_exports(struct si_shader_context *ctx,
3804 struct si_ps_exports *exp)
3805 {
3806 for (unsigned i = 0; i < exp->num; i++)
3807 ac_build_export(&ctx->ac, &exp->args[i]);
3808 }
3809
3810 /**
3811 * Return PS outputs in this order:
3812 *
3813 * v[0:3] = color0.xyzw
3814 * v[4:7] = color1.xyzw
3815 * ...
3816 * vN+0 = Depth
3817 * vN+1 = Stencil
3818 * vN+2 = SampleMask
3819 * vN+3 = SampleMaskIn (used for OpenGL smoothing)
3820 *
3821 * The alpha-ref SGPR is returned via its original location.
3822 */
3823 static void si_llvm_return_fs_outputs(struct ac_shader_abi *abi,
3824 unsigned max_outputs,
3825 LLVMValueRef *addrs)
3826 {
3827 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
3828 struct si_shader *shader = ctx->shader;
3829 struct tgsi_shader_info *info = &shader->selector->info;
3830 LLVMBuilderRef builder = ctx->ac.builder;
3831 unsigned i, j, first_vgpr, vgpr;
3832
3833 LLVMValueRef color[8][4] = {};
3834 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
3835 LLVMValueRef ret;
3836
3837 if (ctx->postponed_kill)
3838 ac_build_kill_if_false(&ctx->ac, LLVMBuildLoad(builder, ctx->postponed_kill, ""));
3839
3840 /* Read the output values. */
3841 for (i = 0; i < info->num_outputs; i++) {
3842 unsigned semantic_name = info->output_semantic_name[i];
3843 unsigned semantic_index = info->output_semantic_index[i];
3844
3845 switch (semantic_name) {
3846 case TGSI_SEMANTIC_COLOR:
3847 assert(semantic_index < 8);
3848 for (j = 0; j < 4; j++) {
3849 LLVMValueRef ptr = addrs[4 * i + j];
3850 LLVMValueRef result = LLVMBuildLoad(builder, ptr, "");
3851 color[semantic_index][j] = result;
3852 }
3853 break;
3854 case TGSI_SEMANTIC_POSITION:
3855 depth = LLVMBuildLoad(builder,
3856 addrs[4 * i + 2], "");
3857 break;
3858 case TGSI_SEMANTIC_STENCIL:
3859 stencil = LLVMBuildLoad(builder,
3860 addrs[4 * i + 1], "");
3861 break;
3862 case TGSI_SEMANTIC_SAMPLEMASK:
3863 samplemask = LLVMBuildLoad(builder,
3864 addrs[4 * i + 0], "");
3865 break;
3866 default:
3867 fprintf(stderr, "Warning: GFX6 unhandled fs output type:%d\n",
3868 semantic_name);
3869 }
3870 }
3871
3872 /* Fill the return structure. */
3873 ret = ctx->return_value;
3874
3875 /* Set SGPRs. */
3876 ret = LLVMBuildInsertValue(builder, ret,
3877 ac_to_integer(&ctx->ac,
3878 LLVMGetParam(ctx->main_fn,
3879 SI_PARAM_ALPHA_REF)),
3880 SI_SGPR_ALPHA_REF, "");
3881
3882 /* Set VGPRs */
3883 first_vgpr = vgpr = SI_SGPR_ALPHA_REF + 1;
3884 for (i = 0; i < ARRAY_SIZE(color); i++) {
3885 if (!color[i][0])
3886 continue;
3887
3888 for (j = 0; j < 4; j++)
3889 ret = LLVMBuildInsertValue(builder, ret, color[i][j], vgpr++, "");
3890 }
3891 if (depth)
3892 ret = LLVMBuildInsertValue(builder, ret, depth, vgpr++, "");
3893 if (stencil)
3894 ret = LLVMBuildInsertValue(builder, ret, stencil, vgpr++, "");
3895 if (samplemask)
3896 ret = LLVMBuildInsertValue(builder, ret, samplemask, vgpr++, "");
3897
3898 /* Add the input sample mask for smoothing at the end. */
3899 if (vgpr < first_vgpr + PS_EPILOG_SAMPLEMASK_MIN_LOC)
3900 vgpr = first_vgpr + PS_EPILOG_SAMPLEMASK_MIN_LOC;
3901 ret = LLVMBuildInsertValue(builder, ret,
3902 LLVMGetParam(ctx->main_fn,
3903 SI_PARAM_SAMPLE_COVERAGE), vgpr++, "");
3904
3905 ctx->return_value = ret;
3906 }
3907
3908 static void membar_emit(
3909 const struct lp_build_tgsi_action *action,
3910 struct lp_build_tgsi_context *bld_base,
3911 struct lp_build_emit_data *emit_data)
3912 {
3913 struct si_shader_context *ctx = si_shader_context(bld_base);
3914 LLVMValueRef src0 = lp_build_emit_fetch(bld_base, emit_data->inst, 0, 0);
3915 unsigned flags = LLVMConstIntGetZExtValue(src0);
3916 unsigned wait_flags = 0;
3917
3918 if (flags & TGSI_MEMBAR_THREAD_GROUP)
3919 wait_flags |= AC_WAIT_LGKM | AC_WAIT_VLOAD | AC_WAIT_VSTORE;
3920
3921 if (flags & (TGSI_MEMBAR_ATOMIC_BUFFER |
3922 TGSI_MEMBAR_SHADER_BUFFER |
3923 TGSI_MEMBAR_SHADER_IMAGE))
3924 wait_flags |= AC_WAIT_VLOAD | AC_WAIT_VSTORE;
3925
3926 if (flags & TGSI_MEMBAR_SHARED)
3927 wait_flags |= AC_WAIT_LGKM;
3928
3929 ac_build_waitcnt(&ctx->ac, wait_flags);
3930 }
3931
3932 static void clock_emit(
3933 const struct lp_build_tgsi_action *action,
3934 struct lp_build_tgsi_context *bld_base,
3935 struct lp_build_emit_data *emit_data)
3936 {
3937 struct si_shader_context *ctx = si_shader_context(bld_base);
3938 LLVMValueRef tmp = ac_build_shader_clock(&ctx->ac);
3939
3940 emit_data->output[0] =
3941 LLVMBuildExtractElement(ctx->ac.builder, tmp, ctx->i32_0, "");
3942 emit_data->output[1] =
3943 LLVMBuildExtractElement(ctx->ac.builder, tmp, ctx->i32_1, "");
3944 }
3945
3946 static void si_llvm_emit_ddxy(
3947 const struct lp_build_tgsi_action *action,
3948 struct lp_build_tgsi_context *bld_base,
3949 struct lp_build_emit_data *emit_data)
3950 {
3951 struct si_shader_context *ctx = si_shader_context(bld_base);
3952 unsigned opcode = emit_data->info->opcode;
3953 LLVMValueRef val;
3954 int idx;
3955 unsigned mask;
3956
3957 if (opcode == TGSI_OPCODE_DDX_FINE)
3958 mask = AC_TID_MASK_LEFT;
3959 else if (opcode == TGSI_OPCODE_DDY_FINE)
3960 mask = AC_TID_MASK_TOP;
3961 else
3962 mask = AC_TID_MASK_TOP_LEFT;
3963
3964 /* for DDX we want to next X pixel, DDY next Y pixel. */
3965 idx = (opcode == TGSI_OPCODE_DDX || opcode == TGSI_OPCODE_DDX_FINE) ? 1 : 2;
3966
3967 val = ac_to_integer(&ctx->ac, emit_data->args[0]);
3968 val = ac_build_ddxy(&ctx->ac, mask, idx, val);
3969 emit_data->output[emit_data->chan] = val;
3970 }
3971
3972 static void build_interp_intrinsic(const struct lp_build_tgsi_action *action,
3973 struct lp_build_tgsi_context *bld_base,
3974 struct lp_build_emit_data *emit_data)
3975 {
3976 struct si_shader_context *ctx = si_shader_context(bld_base);
3977 struct si_shader *shader = ctx->shader;
3978 const struct tgsi_shader_info *info = &shader->selector->info;
3979 LLVMValueRef interp_param;
3980 const struct tgsi_full_instruction *inst = emit_data->inst;
3981 const struct tgsi_full_src_register *input = &inst->Src[0];
3982 int input_base, input_array_size;
3983 int chan;
3984 int i;
3985 LLVMValueRef prim_mask = ctx->abi.prim_mask;
3986 LLVMValueRef array_idx, offset_x = NULL, offset_y = NULL;
3987 int interp_param_idx;
3988 unsigned interp;
3989 unsigned location;
3990
3991 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET) {
3992 /* offset is in second src, first two channels */
3993 offset_x = lp_build_emit_fetch(bld_base, emit_data->inst, 1,
3994 TGSI_CHAN_X);
3995 offset_y = lp_build_emit_fetch(bld_base, emit_data->inst, 1,
3996 TGSI_CHAN_Y);
3997 } else if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE) {
3998 LLVMValueRef sample_position;
3999 LLVMValueRef sample_id;
4000 LLVMValueRef halfval = LLVMConstReal(ctx->f32, 0.5f);
4001
4002 /* fetch sample ID, then fetch its sample position,
4003 * and place into first two channels.
4004 */
4005 sample_id = lp_build_emit_fetch(bld_base,
4006 emit_data->inst, 1, TGSI_CHAN_X);
4007 sample_id = ac_to_integer(&ctx->ac, sample_id);
4008
4009 /* Section 8.13.2 (Interpolation Functions) of the OpenGL Shading
4010 * Language 4.50 spec says about interpolateAtSample:
4011 *
4012 * "Returns the value of the input interpolant variable at
4013 * the location of sample number sample. If multisample
4014 * buffers are not available, the input variable will be
4015 * evaluated at the center of the pixel. If sample sample
4016 * does not exist, the position used to interpolate the
4017 * input variable is undefined."
4018 *
4019 * This means that sample_id values outside of the valid are
4020 * in fact valid input, and the usual mechanism for loading the
4021 * sample position doesn't work.
4022 */
4023 if (ctx->shader->key.mono.u.ps.interpolate_at_sample_force_center) {
4024 LLVMValueRef center[4] = {
4025 LLVMConstReal(ctx->f32, 0.5),
4026 LLVMConstReal(ctx->f32, 0.5),
4027 ctx->ac.f32_0,
4028 ctx->ac.f32_0,
4029 };
4030
4031 sample_position = ac_build_gather_values(&ctx->ac, center, 4);
4032 } else {
4033 sample_position = load_sample_position(&ctx->abi, sample_id);
4034 }
4035
4036 offset_x = LLVMBuildExtractElement(ctx->ac.builder, sample_position,
4037 ctx->i32_0, "");
4038
4039 offset_x = LLVMBuildFSub(ctx->ac.builder, offset_x, halfval, "");
4040 offset_y = LLVMBuildExtractElement(ctx->ac.builder, sample_position,
4041 ctx->i32_1, "");
4042 offset_y = LLVMBuildFSub(ctx->ac.builder, offset_y, halfval, "");
4043 }
4044
4045 assert(input->Register.File == TGSI_FILE_INPUT);
4046
4047 if (input->Register.Indirect) {
4048 unsigned array_id = input->Indirect.ArrayID;
4049
4050 if (array_id) {
4051 input_base = info->input_array_first[array_id];
4052 input_array_size = info->input_array_last[array_id] - input_base + 1;
4053 } else {
4054 input_base = inst->Src[0].Register.Index;
4055 input_array_size = info->num_inputs - input_base;
4056 }
4057
4058 array_idx = si_get_indirect_index(ctx, &input->Indirect,
4059 1, input->Register.Index - input_base);
4060 } else {
4061 input_base = inst->Src[0].Register.Index;
4062 input_array_size = 1;
4063 array_idx = ctx->i32_0;
4064 }
4065
4066 interp = shader->selector->info.input_interpolate[input_base];
4067
4068 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET ||
4069 inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE)
4070 location = TGSI_INTERPOLATE_LOC_CENTER;
4071 else
4072 location = TGSI_INTERPOLATE_LOC_CENTROID;
4073
4074 interp_param_idx = lookup_interp_param_index(interp, location);
4075 if (interp_param_idx == -1)
4076 return;
4077 else if (interp_param_idx)
4078 interp_param = LLVMGetParam(ctx->main_fn, interp_param_idx);
4079 else
4080 interp_param = NULL;
4081
4082 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET ||
4083 inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE) {
4084 LLVMValueRef ij_out[2];
4085 LLVMValueRef ddxy_out = ac_build_ddxy_interp(&ctx->ac, interp_param);
4086
4087 /*
4088 * take the I then J parameters, and the DDX/Y for it, and
4089 * calculate the IJ inputs for the interpolator.
4090 * temp1 = ddx * offset/sample.x + I;
4091 * interp_param.I = ddy * offset/sample.y + temp1;
4092 * temp1 = ddx * offset/sample.x + J;
4093 * interp_param.J = ddy * offset/sample.y + temp1;
4094 */
4095 for (i = 0; i < 2; i++) {
4096 LLVMValueRef ix_ll = LLVMConstInt(ctx->i32, i, 0);
4097 LLVMValueRef iy_ll = LLVMConstInt(ctx->i32, i + 2, 0);
4098 LLVMValueRef ddx_el = LLVMBuildExtractElement(ctx->ac.builder,
4099 ddxy_out, ix_ll, "");
4100 LLVMValueRef ddy_el = LLVMBuildExtractElement(ctx->ac.builder,
4101 ddxy_out, iy_ll, "");
4102 LLVMValueRef interp_el = LLVMBuildExtractElement(ctx->ac.builder,
4103 interp_param, ix_ll, "");
4104 LLVMValueRef temp;
4105
4106 interp_el = ac_to_float(&ctx->ac, interp_el);
4107
4108 temp = ac_build_fmad(&ctx->ac, ddx_el, offset_x, interp_el);
4109 ij_out[i] = ac_build_fmad(&ctx->ac, ddy_el, offset_y, temp);
4110 }
4111 interp_param = ac_build_gather_values(&ctx->ac, ij_out, 2);
4112 }
4113
4114 if (interp_param)
4115 interp_param = ac_to_float(&ctx->ac, interp_param);
4116
4117 for (chan = 0; chan < 4; chan++) {
4118 LLVMValueRef gather = LLVMGetUndef(LLVMVectorType(ctx->f32, input_array_size));
4119 unsigned schan = tgsi_util_get_full_src_register_swizzle(&inst->Src[0], chan);
4120
4121 for (unsigned idx = 0; idx < input_array_size; ++idx) {
4122 LLVMValueRef v, i = NULL, j = NULL;
4123
4124 if (interp_param) {
4125 i = LLVMBuildExtractElement(
4126 ctx->ac.builder, interp_param, ctx->i32_0, "");
4127 j = LLVMBuildExtractElement(
4128 ctx->ac.builder, interp_param, ctx->i32_1, "");
4129 }
4130 v = si_build_fs_interp(ctx, input_base + idx, schan,
4131 prim_mask, i, j);
4132
4133 gather = LLVMBuildInsertElement(ctx->ac.builder,
4134 gather, v, LLVMConstInt(ctx->i32, idx, false), "");
4135 }
4136
4137 emit_data->output[chan] = LLVMBuildExtractElement(
4138 ctx->ac.builder, gather, array_idx, "");
4139 }
4140 }
4141
4142 static void vote_all_emit(
4143 const struct lp_build_tgsi_action *action,
4144 struct lp_build_tgsi_context *bld_base,
4145 struct lp_build_emit_data *emit_data)
4146 {
4147 struct si_shader_context *ctx = si_shader_context(bld_base);
4148
4149 LLVMValueRef tmp = ac_build_vote_all(&ctx->ac, emit_data->args[0]);
4150 emit_data->output[emit_data->chan] =
4151 LLVMBuildSExt(ctx->ac.builder, tmp, ctx->i32, "");
4152 }
4153
4154 static void vote_any_emit(
4155 const struct lp_build_tgsi_action *action,
4156 struct lp_build_tgsi_context *bld_base,
4157 struct lp_build_emit_data *emit_data)
4158 {
4159 struct si_shader_context *ctx = si_shader_context(bld_base);
4160
4161 LLVMValueRef tmp = ac_build_vote_any(&ctx->ac, emit_data->args[0]);
4162 emit_data->output[emit_data->chan] =
4163 LLVMBuildSExt(ctx->ac.builder, tmp, ctx->i32, "");
4164 }
4165
4166 static void vote_eq_emit(
4167 const struct lp_build_tgsi_action *action,
4168 struct lp_build_tgsi_context *bld_base,
4169 struct lp_build_emit_data *emit_data)
4170 {
4171 struct si_shader_context *ctx = si_shader_context(bld_base);
4172
4173 LLVMValueRef tmp = ac_build_vote_eq(&ctx->ac, emit_data->args[0]);
4174 emit_data->output[emit_data->chan] =
4175 LLVMBuildSExt(ctx->ac.builder, tmp, ctx->i32, "");
4176 }
4177
4178 static void ballot_emit(
4179 const struct lp_build_tgsi_action *action,
4180 struct lp_build_tgsi_context *bld_base,
4181 struct lp_build_emit_data *emit_data)
4182 {
4183 struct si_shader_context *ctx = si_shader_context(bld_base);
4184 LLVMBuilderRef builder = ctx->ac.builder;
4185 LLVMValueRef tmp;
4186
4187 tmp = lp_build_emit_fetch(bld_base, emit_data->inst, 0, TGSI_CHAN_X);
4188 tmp = ac_build_ballot(&ctx->ac, tmp);
4189 tmp = LLVMBuildBitCast(builder, tmp, ctx->v2i32, "");
4190
4191 emit_data->output[0] = LLVMBuildExtractElement(builder, tmp, ctx->i32_0, "");
4192 emit_data->output[1] = LLVMBuildExtractElement(builder, tmp, ctx->i32_1, "");
4193 }
4194
4195 static void read_lane_emit(
4196 const struct lp_build_tgsi_action *action,
4197 struct lp_build_tgsi_context *bld_base,
4198 struct lp_build_emit_data *emit_data)
4199 {
4200 struct si_shader_context *ctx = si_shader_context(bld_base);
4201
4202 if (emit_data->inst->Instruction.Opcode == TGSI_OPCODE_READ_INVOC) {
4203 emit_data->args[0] = lp_build_emit_fetch(bld_base, emit_data->inst,
4204 0, emit_data->src_chan);
4205
4206 /* Always read the source invocation (= lane) from the X channel. */
4207 emit_data->args[1] = lp_build_emit_fetch(bld_base, emit_data->inst,
4208 1, TGSI_CHAN_X);
4209 emit_data->arg_count = 2;
4210 }
4211
4212 /* We currently have no other way to prevent LLVM from lifting the icmp
4213 * calls to a dominating basic block.
4214 */
4215 ac_build_optimization_barrier(&ctx->ac, &emit_data->args[0]);
4216
4217 for (unsigned i = 0; i < emit_data->arg_count; ++i)
4218 emit_data->args[i] = ac_to_integer(&ctx->ac, emit_data->args[i]);
4219
4220 emit_data->output[emit_data->chan] =
4221 ac_build_intrinsic(&ctx->ac, action->intr_name,
4222 ctx->i32, emit_data->args, emit_data->arg_count,
4223 AC_FUNC_ATTR_READNONE |
4224 AC_FUNC_ATTR_CONVERGENT);
4225 }
4226
4227 static unsigned si_llvm_get_stream(struct lp_build_tgsi_context *bld_base,
4228 struct lp_build_emit_data *emit_data)
4229 {
4230 struct si_shader_context *ctx = si_shader_context(bld_base);
4231 struct tgsi_src_register src0 = emit_data->inst->Src[0].Register;
4232 LLVMValueRef imm;
4233 unsigned stream;
4234
4235 assert(src0.File == TGSI_FILE_IMMEDIATE);
4236
4237 imm = ctx->imms[src0.Index * TGSI_NUM_CHANNELS + src0.SwizzleX];
4238 stream = LLVMConstIntGetZExtValue(imm) & 0x3;
4239 return stream;
4240 }
4241
4242 /* Emit one vertex from the geometry shader */
4243 static void si_llvm_emit_vertex(struct ac_shader_abi *abi,
4244 unsigned stream,
4245 LLVMValueRef *addrs)
4246 {
4247 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
4248
4249 if (ctx->shader->key.as_ngg) {
4250 gfx10_ngg_gs_emit_vertex(ctx, stream, addrs);
4251 return;
4252 }
4253
4254 struct tgsi_shader_info *info = &ctx->shader->selector->info;
4255 struct si_shader *shader = ctx->shader;
4256 struct lp_build_if_state if_state;
4257 LLVMValueRef soffset = LLVMGetParam(ctx->main_fn,
4258 ctx->param_gs2vs_offset);
4259 LLVMValueRef gs_next_vertex;
4260 LLVMValueRef can_emit;
4261 unsigned chan, offset;
4262 int i;
4263
4264 /* Write vertex attribute values to GSVS ring */
4265 gs_next_vertex = LLVMBuildLoad(ctx->ac.builder,
4266 ctx->gs_next_vertex[stream],
4267 "");
4268
4269 /* If this thread has already emitted the declared maximum number of
4270 * vertices, skip the write: excessive vertex emissions are not
4271 * supposed to have any effect.
4272 *
4273 * If the shader has no writes to memory, kill it instead. This skips
4274 * further memory loads and may allow LLVM to skip to the end
4275 * altogether.
4276 */
4277 can_emit = LLVMBuildICmp(ctx->ac.builder, LLVMIntULT, gs_next_vertex,
4278 LLVMConstInt(ctx->i32,
4279 shader->selector->gs_max_out_vertices, 0), "");
4280
4281 bool use_kill = !info->writes_memory;
4282 if (use_kill) {
4283 ac_build_kill_if_false(&ctx->ac, can_emit);
4284 } else {
4285 lp_build_if(&if_state, &ctx->gallivm, can_emit);
4286 }
4287
4288 offset = 0;
4289 for (i = 0; i < info->num_outputs; i++) {
4290 for (chan = 0; chan < 4; chan++) {
4291 if (!(info->output_usagemask[i] & (1 << chan)) ||
4292 ((info->output_streams[i] >> (2 * chan)) & 3) != stream)
4293 continue;
4294
4295 LLVMValueRef out_val = LLVMBuildLoad(ctx->ac.builder, addrs[4 * i + chan], "");
4296 LLVMValueRef voffset =
4297 LLVMConstInt(ctx->i32, offset *
4298 shader->selector->gs_max_out_vertices, 0);
4299 offset++;
4300
4301 voffset = LLVMBuildAdd(ctx->ac.builder, voffset, gs_next_vertex, "");
4302 voffset = LLVMBuildMul(ctx->ac.builder, voffset,
4303 LLVMConstInt(ctx->i32, 4, 0), "");
4304
4305 out_val = ac_to_integer(&ctx->ac, out_val);
4306
4307 ac_build_buffer_store_dword(&ctx->ac,
4308 ctx->gsvs_ring[stream],
4309 out_val, 1,
4310 voffset, soffset, 0,
4311 ac_glc | ac_slc, true);
4312 }
4313 }
4314
4315 gs_next_vertex = LLVMBuildAdd(ctx->ac.builder, gs_next_vertex, ctx->i32_1, "");
4316 LLVMBuildStore(ctx->ac.builder, gs_next_vertex, ctx->gs_next_vertex[stream]);
4317
4318 /* Signal vertex emission if vertex data was written. */
4319 if (offset) {
4320 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_EMIT | AC_SENDMSG_GS | (stream << 8),
4321 si_get_gs_wave_id(ctx));
4322 }
4323
4324 if (!use_kill)
4325 lp_build_endif(&if_state);
4326 }
4327
4328 /* Emit one vertex from the geometry shader */
4329 static void si_tgsi_emit_vertex(
4330 const struct lp_build_tgsi_action *action,
4331 struct lp_build_tgsi_context *bld_base,
4332 struct lp_build_emit_data *emit_data)
4333 {
4334 struct si_shader_context *ctx = si_shader_context(bld_base);
4335 unsigned stream = si_llvm_get_stream(bld_base, emit_data);
4336
4337 si_llvm_emit_vertex(&ctx->abi, stream, ctx->outputs[0]);
4338 }
4339
4340 /* Cut one primitive from the geometry shader */
4341 static void si_llvm_emit_primitive(struct ac_shader_abi *abi,
4342 unsigned stream)
4343 {
4344 struct si_shader_context *ctx = si_shader_context_from_abi(abi);
4345
4346 if (ctx->shader->key.as_ngg) {
4347 LLVMBuildStore(ctx->ac.builder, ctx->ac.i32_0, ctx->gs_curprim_verts[stream]);
4348 return;
4349 }
4350
4351 /* Signal primitive cut */
4352 ac_build_sendmsg(&ctx->ac, AC_SENDMSG_GS_OP_CUT | AC_SENDMSG_GS | (stream << 8),
4353 si_get_gs_wave_id(ctx));
4354 }
4355
4356 /* Cut one primitive from the geometry shader */
4357 static void si_tgsi_emit_primitive(
4358 const struct lp_build_tgsi_action *action,
4359 struct lp_build_tgsi_context *bld_base,
4360 struct lp_build_emit_data *emit_data)
4361 {
4362 struct si_shader_context *ctx = si_shader_context(bld_base);
4363
4364 si_llvm_emit_primitive(&ctx->abi, si_llvm_get_stream(bld_base, emit_data));
4365 }
4366
4367 static void si_llvm_emit_barrier(const struct lp_build_tgsi_action *action,
4368 struct lp_build_tgsi_context *bld_base,
4369 struct lp_build_emit_data *emit_data)
4370 {
4371 struct si_shader_context *ctx = si_shader_context(bld_base);
4372
4373 /* GFX6 only (thanks to a hw bug workaround):
4374 * The real barrier instruction isn’t needed, because an entire patch
4375 * always fits into a single wave.
4376 */
4377 if (ctx->screen->info.chip_class == GFX6 &&
4378 ctx->type == PIPE_SHADER_TESS_CTRL) {
4379 ac_build_waitcnt(&ctx->ac, AC_WAIT_LGKM | AC_WAIT_VLOAD | AC_WAIT_VSTORE);
4380 return;
4381 }
4382
4383 ac_build_s_barrier(&ctx->ac);
4384 }
4385
4386 void si_create_function(struct si_shader_context *ctx,
4387 const char *name,
4388 LLVMTypeRef *returns, unsigned num_returns,
4389 struct si_function_info *fninfo,
4390 unsigned max_workgroup_size)
4391 {
4392 int i;
4393
4394 si_llvm_create_func(ctx, name, returns, num_returns,
4395 fninfo->types, fninfo->num_params);
4396 ctx->return_value = LLVMGetUndef(ctx->return_type);
4397
4398 for (i = 0; i < fninfo->num_sgpr_params; ++i) {
4399 LLVMValueRef P = LLVMGetParam(ctx->main_fn, i);
4400
4401 /* The combination of:
4402 * - noalias
4403 * - dereferenceable
4404 * - invariant.load
4405 * allows the optimization passes to move loads and reduces
4406 * SGPR spilling significantly.
4407 */
4408 ac_add_function_attr(ctx->ac.context, ctx->main_fn, i + 1,
4409 AC_FUNC_ATTR_INREG);
4410
4411 if (LLVMGetTypeKind(LLVMTypeOf(P)) == LLVMPointerTypeKind) {
4412 ac_add_function_attr(ctx->ac.context, ctx->main_fn, i + 1,
4413 AC_FUNC_ATTR_NOALIAS);
4414 ac_add_attr_dereferenceable(P, UINT64_MAX);
4415 }
4416 }
4417
4418 for (i = 0; i < fninfo->num_params; ++i) {
4419 if (fninfo->assign[i])
4420 *fninfo->assign[i] = LLVMGetParam(ctx->main_fn, i);
4421 }
4422
4423 if (ctx->screen->info.address32_hi) {
4424 ac_llvm_add_target_dep_function_attr(ctx->main_fn,
4425 "amdgpu-32bit-address-high-bits",
4426 ctx->screen->info.address32_hi);
4427 }
4428
4429 ac_llvm_set_workgroup_size(ctx->main_fn, max_workgroup_size);
4430
4431 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4432 "no-signed-zeros-fp-math",
4433 "true");
4434
4435 if (ctx->screen->debug_flags & DBG(UNSAFE_MATH)) {
4436 /* These were copied from some LLVM test. */
4437 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4438 "less-precise-fpmad",
4439 "true");
4440 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4441 "no-infs-fp-math",
4442 "true");
4443 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4444 "no-nans-fp-math",
4445 "true");
4446 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
4447 "unsafe-fp-math",
4448 "true");
4449 }
4450 }
4451
4452 static void declare_streamout_params(struct si_shader_context *ctx,
4453 struct pipe_stream_output_info *so,
4454 struct si_function_info *fninfo)
4455 {
4456 if (ctx->ac.chip_class >= GFX10)
4457 return;
4458
4459 /* Streamout SGPRs. */
4460 if (so->num_outputs) {
4461 if (ctx->type != PIPE_SHADER_TESS_EVAL)
4462 ctx->param_streamout_config = add_arg(fninfo, ARG_SGPR, ctx->ac.i32);
4463 else
4464 ctx->param_streamout_config = fninfo->num_params - 1;
4465
4466 ctx->param_streamout_write_index = add_arg(fninfo, ARG_SGPR, ctx->ac.i32);
4467 }
4468 /* A streamout buffer offset is loaded if the stride is non-zero. */
4469 for (int i = 0; i < 4; i++) {
4470 if (!so->stride[i])
4471 continue;
4472
4473 ctx->param_streamout_offset[i] = add_arg(fninfo, ARG_SGPR, ctx->ac.i32);
4474 }
4475 }
4476
4477 static unsigned si_get_max_workgroup_size(const struct si_shader *shader)
4478 {
4479 switch (shader->selector->type) {
4480 case PIPE_SHADER_VERTEX:
4481 case PIPE_SHADER_TESS_EVAL:
4482 return shader->key.as_ngg ? 128 : 0;
4483
4484 case PIPE_SHADER_TESS_CTRL:
4485 /* Return this so that LLVM doesn't remove s_barrier
4486 * instructions on chips where we use s_barrier. */
4487 return shader->selector->screen->info.chip_class >= GFX7 ? 128 : 64;
4488
4489 case PIPE_SHADER_GEOMETRY:
4490 return shader->selector->screen->info.chip_class >= GFX9 ? 128 : 64;
4491
4492 case PIPE_SHADER_COMPUTE:
4493 break; /* see below */
4494
4495 default:
4496 return 0;
4497 }
4498
4499 const unsigned *properties = shader->selector->info.properties;
4500 unsigned max_work_group_size =
4501 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH] *
4502 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT] *
4503 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH];
4504
4505 if (!max_work_group_size) {
4506 /* This is a variable group size compute shader,
4507 * compile it for the maximum possible group size.
4508 */
4509 max_work_group_size = SI_MAX_VARIABLE_THREADS_PER_BLOCK;
4510 }
4511 return max_work_group_size;
4512 }
4513
4514 static void declare_const_and_shader_buffers(struct si_shader_context *ctx,
4515 struct si_function_info *fninfo,
4516 bool assign_params)
4517 {
4518 LLVMTypeRef const_shader_buf_type;
4519
4520 if (ctx->shader->selector->info.const_buffers_declared == 1 &&
4521 ctx->shader->selector->info.shader_buffers_declared == 0)
4522 const_shader_buf_type = ctx->f32;
4523 else
4524 const_shader_buf_type = ctx->v4i32;
4525
4526 unsigned const_and_shader_buffers =
4527 add_arg(fninfo, ARG_SGPR,
4528 ac_array_in_const32_addr_space(const_shader_buf_type));
4529
4530 if (assign_params)
4531 ctx->param_const_and_shader_buffers = const_and_shader_buffers;
4532 }
4533
4534 static void declare_samplers_and_images(struct si_shader_context *ctx,
4535 struct si_function_info *fninfo,
4536 bool assign_params)
4537 {
4538 unsigned samplers_and_images =
4539 add_arg(fninfo, ARG_SGPR,
4540 ac_array_in_const32_addr_space(ctx->v8i32));
4541
4542 if (assign_params)
4543 ctx->param_samplers_and_images = samplers_and_images;
4544 }
4545
4546 static void declare_per_stage_desc_pointers(struct si_shader_context *ctx,
4547 struct si_function_info *fninfo,
4548 bool assign_params)
4549 {
4550 declare_const_and_shader_buffers(ctx, fninfo, assign_params);
4551 declare_samplers_and_images(ctx, fninfo, assign_params);
4552 }
4553
4554 static void declare_global_desc_pointers(struct si_shader_context *ctx,
4555 struct si_function_info *fninfo)
4556 {
4557 ctx->param_rw_buffers = add_arg(fninfo, ARG_SGPR,
4558 ac_array_in_const32_addr_space(ctx->v4i32));
4559 ctx->param_bindless_samplers_and_images = add_arg(fninfo, ARG_SGPR,
4560 ac_array_in_const32_addr_space(ctx->v8i32));
4561 }
4562
4563 static void declare_vs_specific_input_sgprs(struct si_shader_context *ctx,
4564 struct si_function_info *fninfo)
4565 {
4566 ctx->param_vs_state_bits = add_arg(fninfo, ARG_SGPR, ctx->i32);
4567 add_arg_assign(fninfo, ARG_SGPR, ctx->i32, &ctx->abi.base_vertex);
4568 add_arg_assign(fninfo, ARG_SGPR, ctx->i32, &ctx->abi.start_instance);
4569 add_arg_assign(fninfo, ARG_SGPR, ctx->i32, &ctx->abi.draw_id);
4570 }
4571
4572 static void declare_vs_input_vgprs(struct si_shader_context *ctx,
4573 struct si_function_info *fninfo,
4574 unsigned *num_prolog_vgprs)
4575 {
4576 struct si_shader *shader = ctx->shader;
4577
4578 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.vertex_id);
4579 if (shader->key.as_ls) {
4580 ctx->param_rel_auto_id = add_arg(fninfo, ARG_VGPR, ctx->i32);
4581 if (ctx->screen->info.chip_class >= GFX10) {
4582 add_arg(fninfo, ARG_VGPR, ctx->i32); /* user VGPR */
4583 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.instance_id);
4584 } else {
4585 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.instance_id);
4586 add_arg(fninfo, ARG_VGPR, ctx->i32); /* unused */
4587 }
4588 } else if (ctx->screen->info.chip_class == GFX10 &&
4589 !shader->is_gs_copy_shader) {
4590 add_arg(fninfo, ARG_VGPR, ctx->i32); /* user vgpr */
4591 add_arg(fninfo, ARG_VGPR, ctx->i32); /* user vgpr */
4592 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.instance_id);
4593 } else {
4594 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.instance_id);
4595 ctx->param_vs_prim_id = add_arg(fninfo, ARG_VGPR, ctx->i32);
4596 add_arg(fninfo, ARG_VGPR, ctx->i32); /* unused */
4597 }
4598
4599 if (!shader->is_gs_copy_shader) {
4600 /* Vertex load indices. */
4601 ctx->param_vertex_index0 = fninfo->num_params;
4602 for (unsigned i = 0; i < shader->selector->info.num_inputs; i++)
4603 add_arg(fninfo, ARG_VGPR, ctx->i32);
4604 *num_prolog_vgprs += shader->selector->info.num_inputs;
4605 }
4606 }
4607
4608 static void declare_vs_blit_inputs(struct si_shader_context *ctx,
4609 struct si_function_info *fninfo,
4610 unsigned vs_blit_property)
4611 {
4612 ctx->param_vs_blit_inputs = fninfo->num_params;
4613 add_arg(fninfo, ARG_SGPR, ctx->i32); /* i16 x1, y1 */
4614 add_arg(fninfo, ARG_SGPR, ctx->i32); /* i16 x2, y2 */
4615 add_arg(fninfo, ARG_SGPR, ctx->f32); /* depth */
4616
4617 if (vs_blit_property == SI_VS_BLIT_SGPRS_POS_COLOR) {
4618 add_arg(fninfo, ARG_SGPR, ctx->f32); /* color0 */
4619 add_arg(fninfo, ARG_SGPR, ctx->f32); /* color1 */
4620 add_arg(fninfo, ARG_SGPR, ctx->f32); /* color2 */
4621 add_arg(fninfo, ARG_SGPR, ctx->f32); /* color3 */
4622 } else if (vs_blit_property == SI_VS_BLIT_SGPRS_POS_TEXCOORD) {
4623 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.x1 */
4624 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.y1 */
4625 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.x2 */
4626 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.y2 */
4627 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.z */
4628 add_arg(fninfo, ARG_SGPR, ctx->f32); /* texcoord.w */
4629 }
4630 }
4631
4632 static void declare_tes_input_vgprs(struct si_shader_context *ctx,
4633 struct si_function_info *fninfo)
4634 {
4635 ctx->param_tes_u = add_arg(fninfo, ARG_VGPR, ctx->f32);
4636 ctx->param_tes_v = add_arg(fninfo, ARG_VGPR, ctx->f32);
4637 ctx->param_tes_rel_patch_id = add_arg(fninfo, ARG_VGPR, ctx->i32);
4638 add_arg_assign(fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tes_patch_id);
4639 }
4640
4641 enum {
4642 /* Convenient merged shader definitions. */
4643 SI_SHADER_MERGED_VERTEX_TESSCTRL = PIPE_SHADER_TYPES,
4644 SI_SHADER_MERGED_VERTEX_OR_TESSEVAL_GEOMETRY,
4645 };
4646
4647 static void create_function(struct si_shader_context *ctx)
4648 {
4649 struct si_shader *shader = ctx->shader;
4650 struct si_function_info fninfo;
4651 LLVMTypeRef returns[16+32*4];
4652 unsigned i, num_return_sgprs;
4653 unsigned num_returns = 0;
4654 unsigned num_prolog_vgprs = 0;
4655 unsigned type = ctx->type;
4656 unsigned vs_blit_property =
4657 shader->selector->info.properties[TGSI_PROPERTY_VS_BLIT_SGPRS];
4658
4659 si_init_function_info(&fninfo);
4660
4661 /* Set MERGED shaders. */
4662 if (ctx->screen->info.chip_class >= GFX9) {
4663 if (shader->key.as_ls || type == PIPE_SHADER_TESS_CTRL)
4664 type = SI_SHADER_MERGED_VERTEX_TESSCTRL; /* LS or HS */
4665 else if (shader->key.as_es || shader->key.as_ngg || type == PIPE_SHADER_GEOMETRY)
4666 type = SI_SHADER_MERGED_VERTEX_OR_TESSEVAL_GEOMETRY;
4667 }
4668
4669 LLVMTypeRef v3i32 = LLVMVectorType(ctx->i32, 3);
4670
4671 switch (type) {
4672 case PIPE_SHADER_VERTEX:
4673 declare_global_desc_pointers(ctx, &fninfo);
4674
4675 if (vs_blit_property) {
4676 declare_vs_blit_inputs(ctx, &fninfo, vs_blit_property);
4677
4678 /* VGPRs */
4679 declare_vs_input_vgprs(ctx, &fninfo, &num_prolog_vgprs);
4680 break;
4681 }
4682
4683 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4684 declare_vs_specific_input_sgprs(ctx, &fninfo);
4685 ctx->param_vertex_buffers = add_arg(&fninfo, ARG_SGPR,
4686 ac_array_in_const32_addr_space(ctx->v4i32));
4687
4688 if (shader->key.as_es) {
4689 ctx->param_es2gs_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4690 } else if (shader->key.as_ls) {
4691 /* no extra parameters */
4692 } else {
4693 if (shader->is_gs_copy_shader) {
4694 fninfo.num_params = ctx->param_vs_state_bits + 1;
4695 fninfo.num_sgpr_params = fninfo.num_params;
4696 }
4697
4698 /* The locations of the other parameters are assigned dynamically. */
4699 declare_streamout_params(ctx, &shader->selector->so,
4700 &fninfo);
4701 }
4702
4703 /* VGPRs */
4704 declare_vs_input_vgprs(ctx, &fninfo, &num_prolog_vgprs);
4705
4706 /* Return values */
4707 if (shader->key.opt.vs_as_prim_discard_cs) {
4708 for (i = 0; i < 4; i++)
4709 returns[num_returns++] = ctx->f32; /* VGPRs */
4710 }
4711 break;
4712
4713 case PIPE_SHADER_TESS_CTRL: /* GFX6-GFX8 */
4714 declare_global_desc_pointers(ctx, &fninfo);
4715 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4716 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4717 ctx->param_tcs_out_lds_offsets = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4718 ctx->param_tcs_out_lds_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4719 ctx->param_vs_state_bits = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4720 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4721 ctx->param_tcs_factor_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4722
4723 /* VGPRs */
4724 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tcs_patch_id);
4725 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tcs_rel_ids);
4726
4727 /* param_tcs_offchip_offset and param_tcs_factor_offset are
4728 * placed after the user SGPRs.
4729 */
4730 for (i = 0; i < GFX6_TCS_NUM_USER_SGPR + 2; i++)
4731 returns[num_returns++] = ctx->i32; /* SGPRs */
4732 for (i = 0; i < 11; i++)
4733 returns[num_returns++] = ctx->f32; /* VGPRs */
4734 break;
4735
4736 case SI_SHADER_MERGED_VERTEX_TESSCTRL:
4737 /* Merged stages have 8 system SGPRs at the beginning. */
4738 /* SPI_SHADER_USER_DATA_ADDR_LO/HI_HS */
4739 declare_per_stage_desc_pointers(ctx, &fninfo,
4740 ctx->type == PIPE_SHADER_TESS_CTRL);
4741 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4742 ctx->param_merged_wave_info = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4743 ctx->param_tcs_factor_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4744 ctx->param_merged_scratch_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4745 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* unused */
4746 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* unused */
4747
4748 declare_global_desc_pointers(ctx, &fninfo);
4749 declare_per_stage_desc_pointers(ctx, &fninfo,
4750 ctx->type == PIPE_SHADER_VERTEX);
4751 declare_vs_specific_input_sgprs(ctx, &fninfo);
4752
4753 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4754 ctx->param_tcs_out_lds_offsets = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4755 ctx->param_tcs_out_lds_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4756 ctx->param_vertex_buffers = add_arg(&fninfo, ARG_SGPR,
4757 ac_array_in_const32_addr_space(ctx->v4i32));
4758
4759 /* VGPRs (first TCS, then VS) */
4760 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tcs_patch_id);
4761 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.tcs_rel_ids);
4762
4763 if (ctx->type == PIPE_SHADER_VERTEX) {
4764 declare_vs_input_vgprs(ctx, &fninfo,
4765 &num_prolog_vgprs);
4766
4767 /* LS return values are inputs to the TCS main shader part. */
4768 for (i = 0; i < 8 + GFX9_TCS_NUM_USER_SGPR; i++)
4769 returns[num_returns++] = ctx->i32; /* SGPRs */
4770 for (i = 0; i < 2; i++)
4771 returns[num_returns++] = ctx->f32; /* VGPRs */
4772 } else {
4773 /* TCS return values are inputs to the TCS epilog.
4774 *
4775 * param_tcs_offchip_offset, param_tcs_factor_offset,
4776 * param_tcs_offchip_layout, and param_rw_buffers
4777 * should be passed to the epilog.
4778 */
4779 for (i = 0; i <= 8 + GFX9_SGPR_TCS_OUT_LAYOUT; i++)
4780 returns[num_returns++] = ctx->i32; /* SGPRs */
4781 for (i = 0; i < 11; i++)
4782 returns[num_returns++] = ctx->f32; /* VGPRs */
4783 }
4784 break;
4785
4786 case SI_SHADER_MERGED_VERTEX_OR_TESSEVAL_GEOMETRY:
4787 /* Merged stages have 8 system SGPRs at the beginning. */
4788 /* SPI_SHADER_USER_DATA_ADDR_LO/HI_GS */
4789 declare_per_stage_desc_pointers(ctx, &fninfo,
4790 ctx->type == PIPE_SHADER_GEOMETRY);
4791
4792 if (ctx->shader->key.as_ngg)
4793 add_arg_assign(&fninfo, ARG_SGPR, ctx->i32, &ctx->gs_tg_info);
4794 else
4795 ctx->param_gs2vs_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4796
4797 ctx->param_merged_wave_info = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4798 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4799 ctx->param_merged_scratch_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4800 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* unused (SPI_SHADER_PGM_LO/HI_GS << 8) */
4801 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* unused (SPI_SHADER_PGM_LO/HI_GS >> 24) */
4802
4803 declare_global_desc_pointers(ctx, &fninfo);
4804 if (ctx->type != PIPE_SHADER_VERTEX || !vs_blit_property) {
4805 declare_per_stage_desc_pointers(ctx, &fninfo,
4806 (ctx->type == PIPE_SHADER_VERTEX ||
4807 ctx->type == PIPE_SHADER_TESS_EVAL));
4808 }
4809
4810 if (ctx->type == PIPE_SHADER_VERTEX) {
4811 if (vs_blit_property)
4812 declare_vs_blit_inputs(ctx, &fninfo, vs_blit_property);
4813 else
4814 declare_vs_specific_input_sgprs(ctx, &fninfo);
4815 } else {
4816 ctx->param_vs_state_bits = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4817 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4818 ctx->param_tes_offchip_addr = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4819 /* Declare as many input SGPRs as the VS has. */
4820 }
4821
4822 if (ctx->type == PIPE_SHADER_VERTEX) {
4823 ctx->param_vertex_buffers = add_arg(&fninfo, ARG_SGPR,
4824 ac_array_in_const32_addr_space(ctx->v4i32));
4825 }
4826
4827 /* VGPRs (first GS, then VS/TES) */
4828 ctx->param_gs_vtx01_offset = add_arg(&fninfo, ARG_VGPR, ctx->i32);
4829 ctx->param_gs_vtx23_offset = add_arg(&fninfo, ARG_VGPR, ctx->i32);
4830 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.gs_prim_id);
4831 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.gs_invocation_id);
4832 ctx->param_gs_vtx45_offset = add_arg(&fninfo, ARG_VGPR, ctx->i32);
4833
4834 if (ctx->type == PIPE_SHADER_VERTEX) {
4835 declare_vs_input_vgprs(ctx, &fninfo,
4836 &num_prolog_vgprs);
4837 } else if (ctx->type == PIPE_SHADER_TESS_EVAL) {
4838 declare_tes_input_vgprs(ctx, &fninfo);
4839 }
4840
4841 if (ctx->shader->key.as_es &&
4842 (ctx->type == PIPE_SHADER_VERTEX ||
4843 ctx->type == PIPE_SHADER_TESS_EVAL)) {
4844 unsigned num_user_sgprs;
4845
4846 if (ctx->type == PIPE_SHADER_VERTEX)
4847 num_user_sgprs = GFX9_VSGS_NUM_USER_SGPR;
4848 else
4849 num_user_sgprs = GFX9_TESGS_NUM_USER_SGPR;
4850
4851 /* ES return values are inputs to GS. */
4852 for (i = 0; i < 8 + num_user_sgprs; i++)
4853 returns[num_returns++] = ctx->i32; /* SGPRs */
4854 for (i = 0; i < 5; i++)
4855 returns[num_returns++] = ctx->f32; /* VGPRs */
4856 }
4857 break;
4858
4859 case PIPE_SHADER_TESS_EVAL:
4860 declare_global_desc_pointers(ctx, &fninfo);
4861 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4862 ctx->param_vs_state_bits = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4863 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4864 ctx->param_tes_offchip_addr = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4865
4866 if (shader->key.as_es) {
4867 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4868 add_arg(&fninfo, ARG_SGPR, ctx->i32);
4869 ctx->param_es2gs_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4870 } else {
4871 add_arg(&fninfo, ARG_SGPR, ctx->i32);
4872 declare_streamout_params(ctx, &shader->selector->so,
4873 &fninfo);
4874 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4875 }
4876
4877 /* VGPRs */
4878 declare_tes_input_vgprs(ctx, &fninfo);
4879 break;
4880
4881 case PIPE_SHADER_GEOMETRY:
4882 declare_global_desc_pointers(ctx, &fninfo);
4883 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4884 ctx->param_gs2vs_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4885 ctx->param_gs_wave_id = add_arg(&fninfo, ARG_SGPR, ctx->i32);
4886
4887 /* VGPRs */
4888 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[0]);
4889 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[1]);
4890 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.gs_prim_id);
4891 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[2]);
4892 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[3]);
4893 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[4]);
4894 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->gs_vtx_offset[5]);
4895 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &ctx->abi.gs_invocation_id);
4896 break;
4897
4898 case PIPE_SHADER_FRAGMENT:
4899 declare_global_desc_pointers(ctx, &fninfo);
4900 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4901 add_arg_checked(&fninfo, ARG_SGPR, ctx->f32, SI_PARAM_ALPHA_REF);
4902 add_arg_assign_checked(&fninfo, ARG_SGPR, ctx->i32,
4903 &ctx->abi.prim_mask, SI_PARAM_PRIM_MASK);
4904
4905 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_PERSP_SAMPLE);
4906 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_PERSP_CENTER);
4907 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_PERSP_CENTROID);
4908 add_arg_checked(&fninfo, ARG_VGPR, v3i32, SI_PARAM_PERSP_PULL_MODEL);
4909 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_LINEAR_SAMPLE);
4910 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_LINEAR_CENTER);
4911 add_arg_checked(&fninfo, ARG_VGPR, ctx->v2i32, SI_PARAM_LINEAR_CENTROID);
4912 add_arg_checked(&fninfo, ARG_VGPR, ctx->f32, SI_PARAM_LINE_STIPPLE_TEX);
4913 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4914 &ctx->abi.frag_pos[0], SI_PARAM_POS_X_FLOAT);
4915 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4916 &ctx->abi.frag_pos[1], SI_PARAM_POS_Y_FLOAT);
4917 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4918 &ctx->abi.frag_pos[2], SI_PARAM_POS_Z_FLOAT);
4919 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4920 &ctx->abi.frag_pos[3], SI_PARAM_POS_W_FLOAT);
4921 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->i32,
4922 &ctx->abi.front_face, SI_PARAM_FRONT_FACE);
4923 shader->info.face_vgpr_index = 20;
4924 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->i32,
4925 &ctx->abi.ancillary, SI_PARAM_ANCILLARY);
4926 shader->info.ancillary_vgpr_index = 21;
4927 add_arg_assign_checked(&fninfo, ARG_VGPR, ctx->f32,
4928 &ctx->abi.sample_coverage, SI_PARAM_SAMPLE_COVERAGE);
4929 add_arg_checked(&fninfo, ARG_VGPR, ctx->i32, SI_PARAM_POS_FIXED_PT);
4930
4931 /* Color inputs from the prolog. */
4932 if (shader->selector->info.colors_read) {
4933 unsigned num_color_elements =
4934 util_bitcount(shader->selector->info.colors_read);
4935
4936 assert(fninfo.num_params + num_color_elements <= ARRAY_SIZE(fninfo.types));
4937 for (i = 0; i < num_color_elements; i++)
4938 add_arg(&fninfo, ARG_VGPR, ctx->f32);
4939
4940 num_prolog_vgprs += num_color_elements;
4941 }
4942
4943 /* Outputs for the epilog. */
4944 num_return_sgprs = SI_SGPR_ALPHA_REF + 1;
4945 num_returns =
4946 num_return_sgprs +
4947 util_bitcount(shader->selector->info.colors_written) * 4 +
4948 shader->selector->info.writes_z +
4949 shader->selector->info.writes_stencil +
4950 shader->selector->info.writes_samplemask +
4951 1 /* SampleMaskIn */;
4952
4953 num_returns = MAX2(num_returns,
4954 num_return_sgprs +
4955 PS_EPILOG_SAMPLEMASK_MIN_LOC + 1);
4956
4957 for (i = 0; i < num_return_sgprs; i++)
4958 returns[i] = ctx->i32;
4959 for (; i < num_returns; i++)
4960 returns[i] = ctx->f32;
4961 break;
4962
4963 case PIPE_SHADER_COMPUTE:
4964 declare_global_desc_pointers(ctx, &fninfo);
4965 declare_per_stage_desc_pointers(ctx, &fninfo, true);
4966 if (shader->selector->info.uses_grid_size)
4967 add_arg_assign(&fninfo, ARG_SGPR, v3i32, &ctx->abi.num_work_groups);
4968 if (shader->selector->info.uses_block_size &&
4969 shader->selector->info.properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH] == 0)
4970 ctx->param_block_size = add_arg(&fninfo, ARG_SGPR, v3i32);
4971
4972 unsigned cs_user_data_dwords =
4973 shader->selector->info.properties[TGSI_PROPERTY_CS_USER_DATA_DWORDS];
4974 if (cs_user_data_dwords) {
4975 ctx->param_cs_user_data = add_arg(&fninfo, ARG_SGPR,
4976 LLVMVectorType(ctx->i32, cs_user_data_dwords));
4977 }
4978
4979 for (i = 0; i < 3; i++) {
4980 ctx->abi.workgroup_ids[i] = NULL;
4981 if (shader->selector->info.uses_block_id[i])
4982 add_arg_assign(&fninfo, ARG_SGPR, ctx->i32, &ctx->abi.workgroup_ids[i]);
4983 }
4984
4985 add_arg_assign(&fninfo, ARG_VGPR, v3i32, &ctx->abi.local_invocation_ids);
4986 break;
4987 default:
4988 assert(0 && "unimplemented shader");
4989 return;
4990 }
4991
4992 si_create_function(ctx, "main", returns, num_returns, &fninfo,
4993 si_get_max_workgroup_size(shader));
4994
4995 /* Reserve register locations for VGPR inputs the PS prolog may need. */
4996 if (ctx->type == PIPE_SHADER_FRAGMENT && !ctx->shader->is_monolithic) {
4997 ac_llvm_add_target_dep_function_attr(ctx->main_fn,
4998 "InitialPSInputAddr",
4999 S_0286D0_PERSP_SAMPLE_ENA(1) |
5000 S_0286D0_PERSP_CENTER_ENA(1) |
5001 S_0286D0_PERSP_CENTROID_ENA(1) |
5002 S_0286D0_LINEAR_SAMPLE_ENA(1) |
5003 S_0286D0_LINEAR_CENTER_ENA(1) |
5004 S_0286D0_LINEAR_CENTROID_ENA(1) |
5005 S_0286D0_FRONT_FACE_ENA(1) |
5006 S_0286D0_ANCILLARY_ENA(1) |
5007 S_0286D0_POS_FIXED_PT_ENA(1));
5008 }
5009
5010 shader->info.num_input_sgprs = 0;
5011 shader->info.num_input_vgprs = 0;
5012
5013 for (i = 0; i < fninfo.num_sgpr_params; ++i)
5014 shader->info.num_input_sgprs += ac_get_type_size(fninfo.types[i]) / 4;
5015
5016 for (; i < fninfo.num_params; ++i)
5017 shader->info.num_input_vgprs += ac_get_type_size(fninfo.types[i]) / 4;
5018
5019 assert(shader->info.num_input_vgprs >= num_prolog_vgprs);
5020 shader->info.num_input_vgprs -= num_prolog_vgprs;
5021
5022 if (shader->key.as_ls || ctx->type == PIPE_SHADER_TESS_CTRL) {
5023 if (USE_LDS_SYMBOLS && HAVE_LLVM >= 0x0900) {
5024 /* The LSHS size is not known until draw time, so we append it
5025 * at the end of whatever LDS use there may be in the rest of
5026 * the shader (currently none, unless LLVM decides to do its
5027 * own LDS-based lowering).
5028 */
5029 ctx->ac.lds = LLVMAddGlobalInAddressSpace(
5030 ctx->ac.module, LLVMArrayType(ctx->i32, 0),
5031 "__lds_end", AC_ADDR_SPACE_LDS);
5032 LLVMSetAlignment(ctx->ac.lds, 256);
5033 } else {
5034 ac_declare_lds_as_pointer(&ctx->ac);
5035 }
5036 }
5037 }
5038
5039 /* Ensure that the esgs ring is declared.
5040 *
5041 * We declare it with 64KB alignment as a hint that the
5042 * pointer value will always be 0.
5043 */
5044 static void declare_esgs_ring(struct si_shader_context *ctx)
5045 {
5046 if (ctx->esgs_ring)
5047 return;
5048
5049 assert(!LLVMGetNamedGlobal(ctx->ac.module, "esgs_ring"));
5050
5051 ctx->esgs_ring = LLVMAddGlobalInAddressSpace(
5052 ctx->ac.module, LLVMArrayType(ctx->i32, 0),
5053 "esgs_ring",
5054 AC_ADDR_SPACE_LDS);
5055 LLVMSetLinkage(ctx->esgs_ring, LLVMExternalLinkage);
5056 LLVMSetAlignment(ctx->esgs_ring, 64 * 1024);
5057 }
5058
5059 /**
5060 * Load ESGS and GSVS ring buffer resource descriptors and save the variables
5061 * for later use.
5062 */
5063 static void preload_ring_buffers(struct si_shader_context *ctx)
5064 {
5065 LLVMBuilderRef builder = ctx->ac.builder;
5066
5067 LLVMValueRef buf_ptr = LLVMGetParam(ctx->main_fn,
5068 ctx->param_rw_buffers);
5069
5070 if (ctx->shader->key.as_es || ctx->type == PIPE_SHADER_GEOMETRY) {
5071 if (ctx->screen->info.chip_class <= GFX8) {
5072 unsigned ring =
5073 ctx->type == PIPE_SHADER_GEOMETRY ? SI_GS_RING_ESGS
5074 : SI_ES_RING_ESGS;
5075 LLVMValueRef offset = LLVMConstInt(ctx->i32, ring, 0);
5076
5077 ctx->esgs_ring =
5078 ac_build_load_to_sgpr(&ctx->ac, buf_ptr, offset);
5079 } else {
5080 if (USE_LDS_SYMBOLS && HAVE_LLVM >= 0x0900) {
5081 /* Declare the ESGS ring as an explicit LDS symbol. */
5082 declare_esgs_ring(ctx);
5083 } else {
5084 ac_declare_lds_as_pointer(&ctx->ac);
5085 ctx->esgs_ring = ctx->ac.lds;
5086 }
5087 }
5088 }
5089
5090 if (ctx->shader->is_gs_copy_shader) {
5091 LLVMValueRef offset = LLVMConstInt(ctx->i32, SI_RING_GSVS, 0);
5092
5093 ctx->gsvs_ring[0] =
5094 ac_build_load_to_sgpr(&ctx->ac, buf_ptr, offset);
5095 } else if (ctx->type == PIPE_SHADER_GEOMETRY) {
5096 const struct si_shader_selector *sel = ctx->shader->selector;
5097 LLVMValueRef offset = LLVMConstInt(ctx->i32, SI_RING_GSVS, 0);
5098 LLVMValueRef base_ring;
5099
5100 base_ring = ac_build_load_to_sgpr(&ctx->ac, buf_ptr, offset);
5101
5102 /* The conceptual layout of the GSVS ring is
5103 * v0c0 .. vLv0 v0c1 .. vLc1 ..
5104 * but the real memory layout is swizzled across
5105 * threads:
5106 * t0v0c0 .. t15v0c0 t0v1c0 .. t15v1c0 ... t15vLcL
5107 * t16v0c0 ..
5108 * Override the buffer descriptor accordingly.
5109 */
5110 LLVMTypeRef v2i64 = LLVMVectorType(ctx->i64, 2);
5111 uint64_t stream_offset = 0;
5112
5113 for (unsigned stream = 0; stream < 4; ++stream) {
5114 unsigned num_components;
5115 unsigned stride;
5116 unsigned num_records;
5117 LLVMValueRef ring, tmp;
5118
5119 num_components = sel->info.num_stream_output_components[stream];
5120 if (!num_components)
5121 continue;
5122
5123 stride = 4 * num_components * sel->gs_max_out_vertices;
5124
5125 /* Limit on the stride field for <= GFX7. */
5126 assert(stride < (1 << 14));
5127
5128 num_records = 64;
5129
5130 ring = LLVMBuildBitCast(builder, base_ring, v2i64, "");
5131 tmp = LLVMBuildExtractElement(builder, ring, ctx->i32_0, "");
5132 tmp = LLVMBuildAdd(builder, tmp,
5133 LLVMConstInt(ctx->i64,
5134 stream_offset, 0), "");
5135 stream_offset += stride * 64;
5136
5137 ring = LLVMBuildInsertElement(builder, ring, tmp, ctx->i32_0, "");
5138 ring = LLVMBuildBitCast(builder, ring, ctx->v4i32, "");
5139 tmp = LLVMBuildExtractElement(builder, ring, ctx->i32_1, "");
5140 tmp = LLVMBuildOr(builder, tmp,
5141 LLVMConstInt(ctx->i32,
5142 S_008F04_STRIDE(stride) |
5143 S_008F04_SWIZZLE_ENABLE(1), 0), "");
5144 ring = LLVMBuildInsertElement(builder, ring, tmp, ctx->i32_1, "");
5145 ring = LLVMBuildInsertElement(builder, ring,
5146 LLVMConstInt(ctx->i32, num_records, 0),
5147 LLVMConstInt(ctx->i32, 2, 0), "");
5148
5149 uint32_t rsrc3 =
5150 S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
5151 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
5152 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
5153 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
5154 S_008F0C_INDEX_STRIDE(1) | /* index_stride = 16 (elements) */
5155 S_008F0C_ADD_TID_ENABLE(1);
5156
5157 if (ctx->ac.chip_class >= GFX10) {
5158 rsrc3 |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
5159 S_008F0C_OOB_SELECT(2) |
5160 S_008F0C_RESOURCE_LEVEL(1);
5161 } else {
5162 rsrc3 |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
5163 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
5164 S_008F0C_ELEMENT_SIZE(1); /* element_size = 4 (bytes) */
5165 }
5166
5167 ring = LLVMBuildInsertElement(builder, ring,
5168 LLVMConstInt(ctx->i32, rsrc3, false),
5169 LLVMConstInt(ctx->i32, 3, 0), "");
5170
5171 ctx->gsvs_ring[stream] = ring;
5172 }
5173 } else if (ctx->type == PIPE_SHADER_TESS_EVAL) {
5174 ctx->tess_offchip_ring = get_tess_ring_descriptor(ctx, TESS_OFFCHIP_RING_TES);
5175 }
5176 }
5177
5178 static void si_llvm_emit_polygon_stipple(struct si_shader_context *ctx,
5179 LLVMValueRef param_rw_buffers,
5180 unsigned param_pos_fixed_pt)
5181 {
5182 LLVMBuilderRef builder = ctx->ac.builder;
5183 LLVMValueRef slot, desc, offset, row, bit, address[2];
5184
5185 /* Use the fixed-point gl_FragCoord input.
5186 * Since the stipple pattern is 32x32 and it repeats, just get 5 bits
5187 * per coordinate to get the repeating effect.
5188 */
5189 address[0] = si_unpack_param(ctx, param_pos_fixed_pt, 0, 5);
5190 address[1] = si_unpack_param(ctx, param_pos_fixed_pt, 16, 5);
5191
5192 /* Load the buffer descriptor. */
5193 slot = LLVMConstInt(ctx->i32, SI_PS_CONST_POLY_STIPPLE, 0);
5194 desc = ac_build_load_to_sgpr(&ctx->ac, param_rw_buffers, slot);
5195
5196 /* The stipple pattern is 32x32, each row has 32 bits. */
5197 offset = LLVMBuildMul(builder, address[1],
5198 LLVMConstInt(ctx->i32, 4, 0), "");
5199 row = buffer_load_const(ctx, desc, offset);
5200 row = ac_to_integer(&ctx->ac, row);
5201 bit = LLVMBuildLShr(builder, row, address[0], "");
5202 bit = LLVMBuildTrunc(builder, bit, ctx->i1, "");
5203 ac_build_kill_if_false(&ctx->ac, bit);
5204 }
5205
5206 /* For the UMR disassembler. */
5207 #define DEBUGGER_END_OF_CODE_MARKER 0xbf9f0000 /* invalid instruction */
5208 #define DEBUGGER_NUM_MARKERS 5
5209
5210 static bool si_shader_binary_open(struct si_screen *screen,
5211 struct si_shader *shader,
5212 struct ac_rtld_binary *rtld)
5213 {
5214 const struct si_shader_selector *sel = shader->selector;
5215 enum pipe_shader_type shader_type = sel ? sel->type : PIPE_SHADER_COMPUTE;
5216 const char *part_elfs[5];
5217 size_t part_sizes[5];
5218 unsigned num_parts = 0;
5219
5220 #define add_part(shader_or_part) \
5221 if (shader_or_part) { \
5222 part_elfs[num_parts] = (shader_or_part)->binary.elf_buffer; \
5223 part_sizes[num_parts] = (shader_or_part)->binary.elf_size; \
5224 num_parts++; \
5225 }
5226
5227 add_part(shader->prolog);
5228 add_part(shader->previous_stage);
5229 add_part(shader->prolog2);
5230 add_part(shader);
5231 add_part(shader->epilog);
5232
5233 #undef add_part
5234
5235 struct ac_rtld_symbol lds_symbols[2];
5236 unsigned num_lds_symbols = 0;
5237 unsigned esgs_ring_size = 0;
5238
5239 if (sel && screen->info.chip_class >= GFX9 &&
5240 sel->type == PIPE_SHADER_GEOMETRY && !shader->is_gs_copy_shader) {
5241 esgs_ring_size = shader->gs_info.esgs_ring_size;
5242 }
5243
5244 if (sel && shader->key.as_ngg) {
5245 if (sel->type != PIPE_SHADER_GEOMETRY && sel->so.num_outputs) {
5246 unsigned esgs_vertex_bytes = 4 * (4 * sel->info.num_outputs + 1);
5247 esgs_ring_size = MAX2(esgs_ring_size,
5248 shader->ngg.max_out_verts * esgs_vertex_bytes);
5249 }
5250
5251 /* GS stores Primitive IDs into LDS at the address corresponding
5252 * to the ES thread of the provoking vertex. All ES threads
5253 * load and export PrimitiveID for their thread.
5254 */
5255 if (sel->type == PIPE_SHADER_VERTEX &&
5256 shader->key.mono.u.vs_export_prim_id)
5257 esgs_ring_size = MAX2(esgs_ring_size, shader->ngg.max_out_verts * 4);
5258 }
5259
5260 if (esgs_ring_size) {
5261 /* We add this symbol even on LLVM <= 8 to ensure that
5262 * shader->config.lds_size is set correctly below.
5263 */
5264 struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
5265 sym->name = "esgs_ring";
5266 sym->size = esgs_ring_size;
5267 sym->align = 64 * 1024;
5268 }
5269
5270 if (shader->key.as_ngg && sel->type == PIPE_SHADER_GEOMETRY) {
5271 struct ac_rtld_symbol *sym = &lds_symbols[num_lds_symbols++];
5272 sym->name = "ngg_emit";
5273 sym->size = shader->ngg.ngg_emit_size * 4;
5274 sym->align = 4;
5275 }
5276
5277 bool ok = ac_rtld_open(rtld, (struct ac_rtld_open_info){
5278 .info = &screen->info,
5279 .options = {
5280 .halt_at_entry = screen->options.halt_shaders,
5281 },
5282 .shader_type = tgsi_processor_to_shader_stage(shader_type),
5283 .num_parts = num_parts,
5284 .elf_ptrs = part_elfs,
5285 .elf_sizes = part_sizes,
5286 .num_shared_lds_symbols = num_lds_symbols,
5287 .shared_lds_symbols = lds_symbols });
5288
5289 if (rtld->lds_size > 0) {
5290 unsigned alloc_granularity = screen->info.chip_class >= GFX7 ? 512 : 256;
5291 shader->config.lds_size =
5292 align(rtld->lds_size, alloc_granularity) / alloc_granularity;
5293 }
5294
5295 return ok;
5296 }
5297
5298 static unsigned si_get_shader_binary_size(struct si_screen *screen, struct si_shader *shader)
5299 {
5300 struct ac_rtld_binary rtld;
5301 si_shader_binary_open(screen, shader, &rtld);
5302 return rtld.rx_size;
5303 }
5304
5305 static bool si_get_external_symbol(void *data, const char *name, uint64_t *value)
5306 {
5307 uint64_t *scratch_va = data;
5308
5309 if (!strcmp(scratch_rsrc_dword0_symbol, name)) {
5310 *value = (uint32_t)*scratch_va;
5311 return true;
5312 }
5313 if (!strcmp(scratch_rsrc_dword1_symbol, name)) {
5314 /* Enable scratch coalescing. */
5315 *value = S_008F04_BASE_ADDRESS_HI(*scratch_va >> 32) |
5316 S_008F04_SWIZZLE_ENABLE(1);
5317 if (HAVE_LLVM < 0x0800) {
5318 /* Old LLVM created an R_ABS32_HI relocation for
5319 * this symbol. */
5320 *value <<= 32;
5321 }
5322 return true;
5323 }
5324
5325 return false;
5326 }
5327
5328 bool si_shader_binary_upload(struct si_screen *sscreen, struct si_shader *shader,
5329 uint64_t scratch_va)
5330 {
5331 struct ac_rtld_binary binary;
5332 if (!si_shader_binary_open(sscreen, shader, &binary))
5333 return false;
5334
5335 si_resource_reference(&shader->bo, NULL);
5336 shader->bo = si_aligned_buffer_create(&sscreen->b,
5337 sscreen->cpdma_prefetch_writes_memory ?
5338 0 : SI_RESOURCE_FLAG_READ_ONLY,
5339 PIPE_USAGE_IMMUTABLE,
5340 align(binary.rx_size, SI_CPDMA_ALIGNMENT),
5341 256);
5342 if (!shader->bo)
5343 return false;
5344
5345 /* Upload. */
5346 struct ac_rtld_upload_info u = {};
5347 u.binary = &binary;
5348 u.get_external_symbol = si_get_external_symbol;
5349 u.cb_data = &scratch_va;
5350 u.rx_va = shader->bo->gpu_address;
5351 u.rx_ptr = sscreen->ws->buffer_map(shader->bo->buf, NULL,
5352 PIPE_TRANSFER_READ_WRITE |
5353 PIPE_TRANSFER_UNSYNCHRONIZED |
5354 RADEON_TRANSFER_TEMPORARY);
5355 if (!u.rx_ptr)
5356 return false;
5357
5358 bool ok = ac_rtld_upload(&u);
5359
5360 sscreen->ws->buffer_unmap(shader->bo->buf);
5361 ac_rtld_close(&binary);
5362
5363 return ok;
5364 }
5365
5366 static void si_shader_dump_disassembly(struct si_screen *screen,
5367 const struct si_shader_binary *binary,
5368 enum pipe_shader_type shader_type,
5369 struct pipe_debug_callback *debug,
5370 const char *name, FILE *file)
5371 {
5372 struct ac_rtld_binary rtld_binary;
5373
5374 if (!ac_rtld_open(&rtld_binary, (struct ac_rtld_open_info){
5375 .info = &screen->info,
5376 .shader_type = tgsi_processor_to_shader_stage(shader_type),
5377 .num_parts = 1,
5378 .elf_ptrs = &binary->elf_buffer,
5379 .elf_sizes = &binary->elf_size }))
5380 return;
5381
5382 const char *disasm;
5383 size_t nbytes;
5384
5385 if (!ac_rtld_get_section_by_name(&rtld_binary, ".AMDGPU.disasm", &disasm, &nbytes))
5386 goto out;
5387
5388 if (nbytes > INT_MAX)
5389 goto out;
5390
5391 if (debug && debug->debug_message) {
5392 /* Very long debug messages are cut off, so send the
5393 * disassembly one line at a time. This causes more
5394 * overhead, but on the plus side it simplifies
5395 * parsing of resulting logs.
5396 */
5397 pipe_debug_message(debug, SHADER_INFO,
5398 "Shader Disassembly Begin");
5399
5400 uint64_t line = 0;
5401 while (line < nbytes) {
5402 int count = nbytes - line;
5403 const char *nl = memchr(disasm + line, '\n', nbytes - line);
5404 if (nl)
5405 count = nl - (disasm + line);
5406
5407 if (count) {
5408 pipe_debug_message(debug, SHADER_INFO,
5409 "%.*s", count, disasm + line);
5410 }
5411
5412 line += count + 1;
5413 }
5414
5415 pipe_debug_message(debug, SHADER_INFO,
5416 "Shader Disassembly End");
5417 }
5418
5419 if (file) {
5420 fprintf(file, "Shader %s disassembly:\n", name);
5421 fprintf(file, "%*s", (int)nbytes, disasm);
5422 }
5423
5424 out:
5425 ac_rtld_close(&rtld_binary);
5426 }
5427
5428 static void si_calculate_max_simd_waves(struct si_shader *shader)
5429 {
5430 struct si_screen *sscreen = shader->selector->screen;
5431 struct ac_shader_config *conf = &shader->config;
5432 unsigned num_inputs = shader->selector->info.num_inputs;
5433 unsigned lds_increment = sscreen->info.chip_class >= GFX7 ? 512 : 256;
5434 unsigned lds_per_wave = 0;
5435 unsigned max_simd_waves;
5436
5437 max_simd_waves = ac_get_max_simd_waves(sscreen->info.family);
5438
5439 /* Compute LDS usage for PS. */
5440 switch (shader->selector->type) {
5441 case PIPE_SHADER_FRAGMENT:
5442 /* The minimum usage per wave is (num_inputs * 48). The maximum
5443 * usage is (num_inputs * 48 * 16).
5444 * We can get anything in between and it varies between waves.
5445 *
5446 * The 48 bytes per input for a single primitive is equal to
5447 * 4 bytes/component * 4 components/input * 3 points.
5448 *
5449 * Other stages don't know the size at compile time or don't
5450 * allocate LDS per wave, but instead they do it per thread group.
5451 */
5452 lds_per_wave = conf->lds_size * lds_increment +
5453 align(num_inputs * 48, lds_increment);
5454 break;
5455 case PIPE_SHADER_COMPUTE:
5456 if (shader->selector) {
5457 unsigned max_workgroup_size =
5458 si_get_max_workgroup_size(shader);
5459 lds_per_wave = (conf->lds_size * lds_increment) /
5460 DIV_ROUND_UP(max_workgroup_size, 64);
5461 }
5462 break;
5463 default:;
5464 }
5465
5466 /* Compute the per-SIMD wave counts. */
5467 if (conf->num_sgprs) {
5468 max_simd_waves =
5469 MIN2(max_simd_waves,
5470 ac_get_num_physical_sgprs(sscreen->info.chip_class) / conf->num_sgprs);
5471 }
5472
5473 if (conf->num_vgprs)
5474 max_simd_waves = MIN2(max_simd_waves, 256 / conf->num_vgprs);
5475
5476 /* LDS is 64KB per CU (4 SIMDs), which is 16KB per SIMD (usage above
5477 * 16KB makes some SIMDs unoccupied). */
5478 if (lds_per_wave)
5479 max_simd_waves = MIN2(max_simd_waves, 16384 / lds_per_wave);
5480
5481 shader->info.max_simd_waves = max_simd_waves;
5482 }
5483
5484 void si_shader_dump_stats_for_shader_db(struct si_screen *screen,
5485 struct si_shader *shader,
5486 struct pipe_debug_callback *debug)
5487 {
5488 const struct ac_shader_config *conf = &shader->config;
5489
5490 if (screen->options.debug_disassembly)
5491 si_shader_dump_disassembly(screen, &shader->binary,
5492 shader->selector->type,
5493 debug, "main", NULL);
5494
5495 pipe_debug_message(debug, SHADER_INFO,
5496 "Shader Stats: SGPRS: %d VGPRS: %d Code Size: %d "
5497 "LDS: %d Scratch: %d Max Waves: %d Spilled SGPRs: %d "
5498 "Spilled VGPRs: %d PrivMem VGPRs: %d",
5499 conf->num_sgprs, conf->num_vgprs,
5500 si_get_shader_binary_size(screen, shader),
5501 conf->lds_size, conf->scratch_bytes_per_wave,
5502 shader->info.max_simd_waves, conf->spilled_sgprs,
5503 conf->spilled_vgprs, shader->info.private_mem_vgprs);
5504 }
5505
5506 static void si_shader_dump_stats(struct si_screen *sscreen,
5507 struct si_shader *shader,
5508 FILE *file,
5509 bool check_debug_option)
5510 {
5511 const struct ac_shader_config *conf = &shader->config;
5512 enum pipe_shader_type shader_type =
5513 shader->selector ? shader->selector->type : PIPE_SHADER_COMPUTE;
5514
5515 if (!check_debug_option ||
5516 si_can_dump_shader(sscreen, shader_type)) {
5517 if (shader_type == PIPE_SHADER_FRAGMENT) {
5518 fprintf(file, "*** SHADER CONFIG ***\n"
5519 "SPI_PS_INPUT_ADDR = 0x%04x\n"
5520 "SPI_PS_INPUT_ENA = 0x%04x\n",
5521 conf->spi_ps_input_addr, conf->spi_ps_input_ena);
5522 }
5523
5524 fprintf(file, "*** SHADER STATS ***\n"
5525 "SGPRS: %d\n"
5526 "VGPRS: %d\n"
5527 "Spilled SGPRs: %d\n"
5528 "Spilled VGPRs: %d\n"
5529 "Private memory VGPRs: %d\n"
5530 "Code Size: %d bytes\n"
5531 "LDS: %d blocks\n"
5532 "Scratch: %d bytes per wave\n"
5533 "Max Waves: %d\n"
5534 "********************\n\n\n",
5535 conf->num_sgprs, conf->num_vgprs,
5536 conf->spilled_sgprs, conf->spilled_vgprs,
5537 shader->info.private_mem_vgprs,
5538 si_get_shader_binary_size(sscreen, shader),
5539 conf->lds_size, conf->scratch_bytes_per_wave,
5540 shader->info.max_simd_waves);
5541 }
5542 }
5543
5544 const char *si_get_shader_name(const struct si_shader *shader)
5545 {
5546 enum pipe_shader_type shader_type =
5547 shader->selector ? shader->selector->type : PIPE_SHADER_COMPUTE;
5548
5549 switch (shader_type) {
5550 case PIPE_SHADER_VERTEX:
5551 if (shader->key.as_es)
5552 return "Vertex Shader as ES";
5553 else if (shader->key.as_ls)
5554 return "Vertex Shader as LS";
5555 else if (shader->key.opt.vs_as_prim_discard_cs)
5556 return "Vertex Shader as Primitive Discard CS";
5557 else if (shader->key.as_ngg)
5558 return "Vertex Shader as ESGS";
5559 else
5560 return "Vertex Shader as VS";
5561 case PIPE_SHADER_TESS_CTRL:
5562 return "Tessellation Control Shader";
5563 case PIPE_SHADER_TESS_EVAL:
5564 if (shader->key.as_es)
5565 return "Tessellation Evaluation Shader as ES";
5566 else if (shader->key.as_ngg)
5567 return "Tessellation Evaluation Shader as ESGS";
5568 else
5569 return "Tessellation Evaluation Shader as VS";
5570 case PIPE_SHADER_GEOMETRY:
5571 if (shader->is_gs_copy_shader)
5572 return "GS Copy Shader as VS";
5573 else
5574 return "Geometry Shader";
5575 case PIPE_SHADER_FRAGMENT:
5576 return "Pixel Shader";
5577 case PIPE_SHADER_COMPUTE:
5578 return "Compute Shader";
5579 default:
5580 return "Unknown Shader";
5581 }
5582 }
5583
5584 void si_shader_dump(struct si_screen *sscreen, struct si_shader *shader,
5585 struct pipe_debug_callback *debug,
5586 FILE *file, bool check_debug_option)
5587 {
5588 enum pipe_shader_type shader_type =
5589 shader->selector ? shader->selector->type : PIPE_SHADER_COMPUTE;
5590
5591 if (!check_debug_option ||
5592 si_can_dump_shader(sscreen, shader_type))
5593 si_dump_shader_key(shader, file);
5594
5595 if (!check_debug_option && shader->binary.llvm_ir_string) {
5596 if (shader->previous_stage &&
5597 shader->previous_stage->binary.llvm_ir_string) {
5598 fprintf(file, "\n%s - previous stage - LLVM IR:\n\n",
5599 si_get_shader_name(shader));
5600 fprintf(file, "%s\n", shader->previous_stage->binary.llvm_ir_string);
5601 }
5602
5603 fprintf(file, "\n%s - main shader part - LLVM IR:\n\n",
5604 si_get_shader_name(shader));
5605 fprintf(file, "%s\n", shader->binary.llvm_ir_string);
5606 }
5607
5608 if (!check_debug_option ||
5609 (si_can_dump_shader(sscreen, shader_type) &&
5610 !(sscreen->debug_flags & DBG(NO_ASM)))) {
5611 fprintf(file, "\n%s:\n", si_get_shader_name(shader));
5612
5613 if (shader->prolog)
5614 si_shader_dump_disassembly(sscreen, &shader->prolog->binary,
5615 shader_type, debug, "prolog", file);
5616 if (shader->previous_stage)
5617 si_shader_dump_disassembly(sscreen, &shader->previous_stage->binary,
5618 shader_type, debug, "previous stage", file);
5619 if (shader->prolog2)
5620 si_shader_dump_disassembly(sscreen, &shader->prolog2->binary,
5621 shader_type, debug, "prolog2", file);
5622
5623 si_shader_dump_disassembly(sscreen, &shader->binary, shader_type, debug, "main", file);
5624
5625 if (shader->epilog)
5626 si_shader_dump_disassembly(sscreen, &shader->epilog->binary,
5627 shader_type, debug, "epilog", file);
5628 fprintf(file, "\n");
5629 }
5630
5631 si_shader_dump_stats(sscreen, shader, file, check_debug_option);
5632 }
5633
5634 static int si_compile_llvm(struct si_screen *sscreen,
5635 struct si_shader_binary *binary,
5636 struct ac_shader_config *conf,
5637 struct ac_llvm_compiler *compiler,
5638 LLVMModuleRef mod,
5639 struct pipe_debug_callback *debug,
5640 enum pipe_shader_type shader_type,
5641 const char *name,
5642 bool less_optimized)
5643 {
5644 unsigned count = p_atomic_inc_return(&sscreen->num_compilations);
5645
5646 if (si_can_dump_shader(sscreen, shader_type)) {
5647 fprintf(stderr, "radeonsi: Compiling shader %d\n", count);
5648
5649 if (!(sscreen->debug_flags & (DBG(NO_IR) | DBG(PREOPT_IR)))) {
5650 fprintf(stderr, "%s LLVM IR:\n\n", name);
5651 ac_dump_module(mod);
5652 fprintf(stderr, "\n");
5653 }
5654 }
5655
5656 if (sscreen->record_llvm_ir) {
5657 char *ir = LLVMPrintModuleToString(mod);
5658 binary->llvm_ir_string = strdup(ir);
5659 LLVMDisposeMessage(ir);
5660 }
5661
5662 if (!si_replace_shader(count, binary)) {
5663 unsigned r = si_llvm_compile(mod, binary, compiler, debug,
5664 less_optimized);
5665 if (r)
5666 return r;
5667 }
5668
5669 struct ac_rtld_binary rtld;
5670 if (!ac_rtld_open(&rtld, (struct ac_rtld_open_info){
5671 .info = &sscreen->info,
5672 .shader_type = tgsi_processor_to_shader_stage(shader_type),
5673 .num_parts = 1,
5674 .elf_ptrs = &binary->elf_buffer,
5675 .elf_sizes = &binary->elf_size }))
5676 return -1;
5677
5678 bool ok = ac_rtld_read_config(&rtld, conf);
5679 ac_rtld_close(&rtld);
5680 if (!ok)
5681 return -1;
5682
5683 /* Enable 64-bit and 16-bit denormals, because there is no performance
5684 * cost.
5685 *
5686 * If denormals are enabled, all floating-point output modifiers are
5687 * ignored.
5688 *
5689 * Don't enable denormals for 32-bit floats, because:
5690 * - Floating-point output modifiers would be ignored by the hw.
5691 * - Some opcodes don't support denormals, such as v_mad_f32. We would
5692 * have to stop using those.
5693 * - GFX6 & GFX7 would be very slow.
5694 */
5695 conf->float_mode |= V_00B028_FP_64_DENORMS;
5696
5697 return 0;
5698 }
5699
5700 static void si_llvm_build_ret(struct si_shader_context *ctx, LLVMValueRef ret)
5701 {
5702 if (LLVMGetTypeKind(LLVMTypeOf(ret)) == LLVMVoidTypeKind)
5703 LLVMBuildRetVoid(ctx->ac.builder);
5704 else
5705 LLVMBuildRet(ctx->ac.builder, ret);
5706 }
5707
5708 /* Generate code for the hardware VS shader stage to go with a geometry shader */
5709 struct si_shader *
5710 si_generate_gs_copy_shader(struct si_screen *sscreen,
5711 struct ac_llvm_compiler *compiler,
5712 struct si_shader_selector *gs_selector,
5713 struct pipe_debug_callback *debug)
5714 {
5715 struct si_shader_context ctx;
5716 struct si_shader *shader;
5717 LLVMBuilderRef builder;
5718 struct si_shader_output_values outputs[SI_MAX_VS_OUTPUTS];
5719 struct tgsi_shader_info *gsinfo = &gs_selector->info;
5720 int i;
5721
5722
5723 shader = CALLOC_STRUCT(si_shader);
5724 if (!shader)
5725 return NULL;
5726
5727 /* We can leave the fence as permanently signaled because the GS copy
5728 * shader only becomes visible globally after it has been compiled. */
5729 util_queue_fence_init(&shader->ready);
5730
5731 shader->selector = gs_selector;
5732 shader->is_gs_copy_shader = true;
5733
5734 si_init_shader_ctx(&ctx, sscreen, compiler);
5735 ctx.shader = shader;
5736 ctx.type = PIPE_SHADER_VERTEX;
5737
5738 builder = ctx.ac.builder;
5739
5740 create_function(&ctx);
5741 preload_ring_buffers(&ctx);
5742
5743 LLVMValueRef voffset =
5744 LLVMBuildMul(ctx.ac.builder, ctx.abi.vertex_id,
5745 LLVMConstInt(ctx.i32, 4, 0), "");
5746
5747 /* Fetch the vertex stream ID.*/
5748 LLVMValueRef stream_id;
5749
5750 if (ctx.ac.chip_class <= GFX9 && gs_selector->so.num_outputs)
5751 stream_id = si_unpack_param(&ctx, ctx.param_streamout_config, 24, 2);
5752 else
5753 stream_id = ctx.i32_0;
5754
5755 /* Fill in output information. */
5756 for (i = 0; i < gsinfo->num_outputs; ++i) {
5757 outputs[i].semantic_name = gsinfo->output_semantic_name[i];
5758 outputs[i].semantic_index = gsinfo->output_semantic_index[i];
5759
5760 for (int chan = 0; chan < 4; chan++) {
5761 outputs[i].vertex_stream[chan] =
5762 (gsinfo->output_streams[i] >> (2 * chan)) & 3;
5763 }
5764 }
5765
5766 LLVMBasicBlockRef end_bb;
5767 LLVMValueRef switch_inst;
5768
5769 end_bb = LLVMAppendBasicBlockInContext(ctx.ac.context, ctx.main_fn, "end");
5770 switch_inst = LLVMBuildSwitch(builder, stream_id, end_bb, 4);
5771
5772 for (int stream = 0; stream < 4; stream++) {
5773 LLVMBasicBlockRef bb;
5774 unsigned offset;
5775
5776 if (!gsinfo->num_stream_output_components[stream])
5777 continue;
5778
5779 if (stream > 0 && !gs_selector->so.num_outputs)
5780 continue;
5781
5782 bb = LLVMInsertBasicBlockInContext(ctx.ac.context, end_bb, "out");
5783 LLVMAddCase(switch_inst, LLVMConstInt(ctx.i32, stream, 0), bb);
5784 LLVMPositionBuilderAtEnd(builder, bb);
5785
5786 /* Fetch vertex data from GSVS ring */
5787 offset = 0;
5788 for (i = 0; i < gsinfo->num_outputs; ++i) {
5789 for (unsigned chan = 0; chan < 4; chan++) {
5790 if (!(gsinfo->output_usagemask[i] & (1 << chan)) ||
5791 outputs[i].vertex_stream[chan] != stream) {
5792 outputs[i].values[chan] = LLVMGetUndef(ctx.f32);
5793 continue;
5794 }
5795
5796 LLVMValueRef soffset = LLVMConstInt(ctx.i32,
5797 offset * gs_selector->gs_max_out_vertices * 16 * 4, 0);
5798 offset++;
5799
5800 outputs[i].values[chan] =
5801 ac_build_buffer_load(&ctx.ac,
5802 ctx.gsvs_ring[0], 1,
5803 ctx.i32_0, voffset,
5804 soffset, 0, ac_glc | ac_slc,
5805 true, false);
5806 }
5807 }
5808
5809 /* Streamout and exports. */
5810 if (ctx.ac.chip_class <= GFX9 && gs_selector->so.num_outputs) {
5811 si_llvm_emit_streamout(&ctx, outputs,
5812 gsinfo->num_outputs,
5813 stream);
5814 }
5815
5816 if (stream == 0)
5817 si_llvm_export_vs(&ctx, outputs, gsinfo->num_outputs);
5818
5819 LLVMBuildBr(builder, end_bb);
5820 }
5821
5822 LLVMPositionBuilderAtEnd(builder, end_bb);
5823
5824 LLVMBuildRetVoid(ctx.ac.builder);
5825
5826 ctx.type = PIPE_SHADER_GEOMETRY; /* override for shader dumping */
5827 si_llvm_optimize_module(&ctx);
5828
5829 bool ok = false;
5830 if (si_compile_llvm(sscreen, &ctx.shader->binary,
5831 &ctx.shader->config, ctx.compiler,
5832 ctx.ac.module,
5833 debug, PIPE_SHADER_GEOMETRY,
5834 "GS Copy Shader", false) == 0) {
5835 if (si_can_dump_shader(sscreen, PIPE_SHADER_GEOMETRY))
5836 fprintf(stderr, "GS Copy Shader:\n");
5837 si_shader_dump(sscreen, ctx.shader, debug, stderr, true);
5838
5839 if (!ctx.shader->config.scratch_bytes_per_wave)
5840 ok = si_shader_binary_upload(sscreen, ctx.shader, 0);
5841 else
5842 ok = true;
5843 }
5844
5845 si_llvm_dispose(&ctx);
5846
5847 if (!ok) {
5848 FREE(shader);
5849 shader = NULL;
5850 } else {
5851 si_fix_resource_usage(sscreen, shader);
5852 }
5853 return shader;
5854 }
5855
5856 static void si_dump_shader_key_vs(const struct si_shader_key *key,
5857 const struct si_vs_prolog_bits *prolog,
5858 const char *prefix, FILE *f)
5859 {
5860 fprintf(f, " %s.instance_divisor_is_one = %u\n",
5861 prefix, prolog->instance_divisor_is_one);
5862 fprintf(f, " %s.instance_divisor_is_fetched = %u\n",
5863 prefix, prolog->instance_divisor_is_fetched);
5864 fprintf(f, " %s.unpack_instance_id_from_vertex_id = %u\n",
5865 prefix, prolog->unpack_instance_id_from_vertex_id);
5866 fprintf(f, " %s.ls_vgpr_fix = %u\n",
5867 prefix, prolog->ls_vgpr_fix);
5868
5869 fprintf(f, " mono.vs.fetch_opencode = %x\n", key->mono.vs_fetch_opencode);
5870 fprintf(f, " mono.vs.fix_fetch = {");
5871 for (int i = 0; i < SI_MAX_ATTRIBS; i++) {
5872 union si_vs_fix_fetch fix = key->mono.vs_fix_fetch[i];
5873 if (i)
5874 fprintf(f, ", ");
5875 if (!fix.bits)
5876 fprintf(f, "0");
5877 else
5878 fprintf(f, "%u.%u.%u.%u", fix.u.reverse, fix.u.log_size,
5879 fix.u.num_channels_m1, fix.u.format);
5880 }
5881 fprintf(f, "}\n");
5882 }
5883
5884 static void si_dump_shader_key(const struct si_shader *shader, FILE *f)
5885 {
5886 const struct si_shader_key *key = &shader->key;
5887 enum pipe_shader_type shader_type =
5888 shader->selector ? shader->selector->type : PIPE_SHADER_COMPUTE;
5889
5890 fprintf(f, "SHADER KEY\n");
5891
5892 switch (shader_type) {
5893 case PIPE_SHADER_VERTEX:
5894 si_dump_shader_key_vs(key, &key->part.vs.prolog,
5895 "part.vs.prolog", f);
5896 fprintf(f, " as_es = %u\n", key->as_es);
5897 fprintf(f, " as_ls = %u\n", key->as_ls);
5898 fprintf(f, " mono.u.vs_export_prim_id = %u\n",
5899 key->mono.u.vs_export_prim_id);
5900 fprintf(f, " opt.vs_as_prim_discard_cs = %u\n",
5901 key->opt.vs_as_prim_discard_cs);
5902 fprintf(f, " opt.cs_prim_type = %s\n",
5903 tgsi_primitive_names[key->opt.cs_prim_type]);
5904 fprintf(f, " opt.cs_indexed = %u\n",
5905 key->opt.cs_indexed);
5906 fprintf(f, " opt.cs_instancing = %u\n",
5907 key->opt.cs_instancing);
5908 fprintf(f, " opt.cs_primitive_restart = %u\n",
5909 key->opt.cs_primitive_restart);
5910 fprintf(f, " opt.cs_provoking_vertex_first = %u\n",
5911 key->opt.cs_provoking_vertex_first);
5912 fprintf(f, " opt.cs_need_correct_orientation = %u\n",
5913 key->opt.cs_need_correct_orientation);
5914 fprintf(f, " opt.cs_cull_front = %u\n",
5915 key->opt.cs_cull_front);
5916 fprintf(f, " opt.cs_cull_back = %u\n",
5917 key->opt.cs_cull_back);
5918 fprintf(f, " opt.cs_cull_z = %u\n",
5919 key->opt.cs_cull_z);
5920 fprintf(f, " opt.cs_halfz_clip_space = %u\n",
5921 key->opt.cs_halfz_clip_space);
5922 break;
5923
5924 case PIPE_SHADER_TESS_CTRL:
5925 if (shader->selector->screen->info.chip_class >= GFX9) {
5926 si_dump_shader_key_vs(key, &key->part.tcs.ls_prolog,
5927 "part.tcs.ls_prolog", f);
5928 }
5929 fprintf(f, " part.tcs.epilog.prim_mode = %u\n", key->part.tcs.epilog.prim_mode);
5930 fprintf(f, " mono.u.ff_tcs_inputs_to_copy = 0x%"PRIx64"\n", key->mono.u.ff_tcs_inputs_to_copy);
5931 break;
5932
5933 case PIPE_SHADER_TESS_EVAL:
5934 fprintf(f, " as_es = %u\n", key->as_es);
5935 fprintf(f, " mono.u.vs_export_prim_id = %u\n",
5936 key->mono.u.vs_export_prim_id);
5937 break;
5938
5939 case PIPE_SHADER_GEOMETRY:
5940 if (shader->is_gs_copy_shader)
5941 break;
5942
5943 if (shader->selector->screen->info.chip_class >= GFX9 &&
5944 key->part.gs.es->type == PIPE_SHADER_VERTEX) {
5945 si_dump_shader_key_vs(key, &key->part.gs.vs_prolog,
5946 "part.gs.vs_prolog", f);
5947 }
5948 fprintf(f, " part.gs.prolog.tri_strip_adj_fix = %u\n", key->part.gs.prolog.tri_strip_adj_fix);
5949 break;
5950
5951 case PIPE_SHADER_COMPUTE:
5952 break;
5953
5954 case PIPE_SHADER_FRAGMENT:
5955 fprintf(f, " part.ps.prolog.color_two_side = %u\n", key->part.ps.prolog.color_two_side);
5956 fprintf(f, " part.ps.prolog.flatshade_colors = %u\n", key->part.ps.prolog.flatshade_colors);
5957 fprintf(f, " part.ps.prolog.poly_stipple = %u\n", key->part.ps.prolog.poly_stipple);
5958 fprintf(f, " part.ps.prolog.force_persp_sample_interp = %u\n", key->part.ps.prolog.force_persp_sample_interp);
5959 fprintf(f, " part.ps.prolog.force_linear_sample_interp = %u\n", key->part.ps.prolog.force_linear_sample_interp);
5960 fprintf(f, " part.ps.prolog.force_persp_center_interp = %u\n", key->part.ps.prolog.force_persp_center_interp);
5961 fprintf(f, " part.ps.prolog.force_linear_center_interp = %u\n", key->part.ps.prolog.force_linear_center_interp);
5962 fprintf(f, " part.ps.prolog.bc_optimize_for_persp = %u\n", key->part.ps.prolog.bc_optimize_for_persp);
5963 fprintf(f, " part.ps.prolog.bc_optimize_for_linear = %u\n", key->part.ps.prolog.bc_optimize_for_linear);
5964 fprintf(f, " part.ps.epilog.spi_shader_col_format = 0x%x\n", key->part.ps.epilog.spi_shader_col_format);
5965 fprintf(f, " part.ps.epilog.color_is_int8 = 0x%X\n", key->part.ps.epilog.color_is_int8);
5966 fprintf(f, " part.ps.epilog.color_is_int10 = 0x%X\n", key->part.ps.epilog.color_is_int10);
5967 fprintf(f, " part.ps.epilog.last_cbuf = %u\n", key->part.ps.epilog.last_cbuf);
5968 fprintf(f, " part.ps.epilog.alpha_func = %u\n", key->part.ps.epilog.alpha_func);
5969 fprintf(f, " part.ps.epilog.alpha_to_one = %u\n", key->part.ps.epilog.alpha_to_one);
5970 fprintf(f, " part.ps.epilog.poly_line_smoothing = %u\n", key->part.ps.epilog.poly_line_smoothing);
5971 fprintf(f, " part.ps.epilog.clamp_color = %u\n", key->part.ps.epilog.clamp_color);
5972 break;
5973
5974 default:
5975 assert(0);
5976 }
5977
5978 if ((shader_type == PIPE_SHADER_GEOMETRY ||
5979 shader_type == PIPE_SHADER_TESS_EVAL ||
5980 shader_type == PIPE_SHADER_VERTEX) &&
5981 !key->as_es && !key->as_ls) {
5982 fprintf(f, " opt.kill_outputs = 0x%"PRIx64"\n", key->opt.kill_outputs);
5983 fprintf(f, " opt.clip_disable = %u\n", key->opt.clip_disable);
5984 }
5985 }
5986
5987 static void si_init_shader_ctx(struct si_shader_context *ctx,
5988 struct si_screen *sscreen,
5989 struct ac_llvm_compiler *compiler)
5990 {
5991 struct lp_build_tgsi_context *bld_base;
5992
5993 si_llvm_context_init(ctx, sscreen, compiler);
5994
5995 bld_base = &ctx->bld_base;
5996 bld_base->emit_fetch_funcs[TGSI_FILE_CONSTANT] = fetch_constant;
5997
5998 bld_base->op_actions[TGSI_OPCODE_INTERP_CENTROID].emit = build_interp_intrinsic;
5999 bld_base->op_actions[TGSI_OPCODE_INTERP_SAMPLE].emit = build_interp_intrinsic;
6000 bld_base->op_actions[TGSI_OPCODE_INTERP_OFFSET].emit = build_interp_intrinsic;
6001
6002 bld_base->op_actions[TGSI_OPCODE_MEMBAR].emit = membar_emit;
6003
6004 bld_base->op_actions[TGSI_OPCODE_CLOCK].emit = clock_emit;
6005
6006 bld_base->op_actions[TGSI_OPCODE_DDX].emit = si_llvm_emit_ddxy;
6007 bld_base->op_actions[TGSI_OPCODE_DDY].emit = si_llvm_emit_ddxy;
6008 bld_base->op_actions[TGSI_OPCODE_DDX_FINE].emit = si_llvm_emit_ddxy;
6009 bld_base->op_actions[TGSI_OPCODE_DDY_FINE].emit = si_llvm_emit_ddxy;
6010
6011 bld_base->op_actions[TGSI_OPCODE_VOTE_ALL].emit = vote_all_emit;
6012 bld_base->op_actions[TGSI_OPCODE_VOTE_ANY].emit = vote_any_emit;
6013 bld_base->op_actions[TGSI_OPCODE_VOTE_EQ].emit = vote_eq_emit;
6014 bld_base->op_actions[TGSI_OPCODE_BALLOT].emit = ballot_emit;
6015 bld_base->op_actions[TGSI_OPCODE_READ_FIRST].intr_name = "llvm.amdgcn.readfirstlane";
6016 bld_base->op_actions[TGSI_OPCODE_READ_FIRST].emit = read_lane_emit;
6017 bld_base->op_actions[TGSI_OPCODE_READ_INVOC].intr_name = "llvm.amdgcn.readlane";
6018 bld_base->op_actions[TGSI_OPCODE_READ_INVOC].emit = read_lane_emit;
6019
6020 bld_base->op_actions[TGSI_OPCODE_EMIT].emit = si_tgsi_emit_vertex;
6021 bld_base->op_actions[TGSI_OPCODE_ENDPRIM].emit = si_tgsi_emit_primitive;
6022 bld_base->op_actions[TGSI_OPCODE_BARRIER].emit = si_llvm_emit_barrier;
6023 }
6024
6025 static void si_optimize_vs_outputs(struct si_shader_context *ctx)
6026 {
6027 struct si_shader *shader = ctx->shader;
6028 struct tgsi_shader_info *info = &shader->selector->info;
6029
6030 if ((ctx->type != PIPE_SHADER_VERTEX &&
6031 ctx->type != PIPE_SHADER_TESS_EVAL) ||
6032 shader->key.as_ls ||
6033 shader->key.as_es)
6034 return;
6035
6036 ac_optimize_vs_outputs(&ctx->ac,
6037 ctx->main_fn,
6038 shader->info.vs_output_param_offset,
6039 info->num_outputs,
6040 &shader->info.nr_param_exports);
6041 }
6042
6043 static void si_init_exec_from_input(struct si_shader_context *ctx,
6044 unsigned param, unsigned bitoffset)
6045 {
6046 LLVMValueRef args[] = {
6047 LLVMGetParam(ctx->main_fn, param),
6048 LLVMConstInt(ctx->i32, bitoffset, 0),
6049 };
6050 ac_build_intrinsic(&ctx->ac,
6051 "llvm.amdgcn.init.exec.from.input",
6052 ctx->voidt, args, 2, AC_FUNC_ATTR_CONVERGENT);
6053 }
6054
6055 static bool si_vs_needs_prolog(const struct si_shader_selector *sel,
6056 const struct si_vs_prolog_bits *key)
6057 {
6058 /* VGPR initialization fixup for Vega10 and Raven is always done in the
6059 * VS prolog. */
6060 return sel->vs_needs_prolog || key->ls_vgpr_fix;
6061 }
6062
6063 static bool si_compile_tgsi_main(struct si_shader_context *ctx)
6064 {
6065 struct si_shader *shader = ctx->shader;
6066 struct si_shader_selector *sel = shader->selector;
6067 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
6068
6069 // TODO clean all this up!
6070 switch (ctx->type) {
6071 case PIPE_SHADER_VERTEX:
6072 ctx->load_input = declare_input_vs;
6073 if (shader->key.as_ls)
6074 ctx->abi.emit_outputs = si_llvm_emit_ls_epilogue;
6075 else if (shader->key.as_es)
6076 ctx->abi.emit_outputs = si_llvm_emit_es_epilogue;
6077 else if (shader->key.opt.vs_as_prim_discard_cs)
6078 ctx->abi.emit_outputs = si_llvm_emit_prim_discard_cs_epilogue;
6079 else if (shader->key.as_ngg)
6080 ctx->abi.emit_outputs = gfx10_emit_ngg_epilogue;
6081 else
6082 ctx->abi.emit_outputs = si_llvm_emit_vs_epilogue;
6083 bld_base->emit_epilogue = si_tgsi_emit_epilogue;
6084 ctx->abi.load_base_vertex = get_base_vertex;
6085 break;
6086 case PIPE_SHADER_TESS_CTRL:
6087 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_tcs;
6088 ctx->abi.load_tess_varyings = si_nir_load_tcs_varyings;
6089 bld_base->emit_fetch_funcs[TGSI_FILE_OUTPUT] = fetch_output_tcs;
6090 bld_base->emit_store = store_output_tcs;
6091 ctx->abi.store_tcs_outputs = si_nir_store_output_tcs;
6092 ctx->abi.emit_outputs = si_llvm_emit_tcs_epilogue;
6093 ctx->abi.load_patch_vertices_in = si_load_patch_vertices_in;
6094 bld_base->emit_epilogue = si_tgsi_emit_epilogue;
6095 break;
6096 case PIPE_SHADER_TESS_EVAL:
6097 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_tes;
6098 ctx->abi.load_tess_varyings = si_nir_load_input_tes;
6099 ctx->abi.load_tess_coord = si_load_tess_coord;
6100 ctx->abi.load_tess_level = si_load_tess_level;
6101 ctx->abi.load_patch_vertices_in = si_load_patch_vertices_in;
6102 if (shader->key.as_es)
6103 ctx->abi.emit_outputs = si_llvm_emit_es_epilogue;
6104 else if (shader->key.as_ngg)
6105 ctx->abi.emit_outputs = gfx10_emit_ngg_epilogue;
6106 else
6107 ctx->abi.emit_outputs = si_llvm_emit_vs_epilogue;
6108 bld_base->emit_epilogue = si_tgsi_emit_epilogue;
6109 break;
6110 case PIPE_SHADER_GEOMETRY:
6111 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_gs;
6112 ctx->abi.load_inputs = si_nir_load_input_gs;
6113 ctx->abi.emit_vertex = si_llvm_emit_vertex;
6114 ctx->abi.emit_primitive = si_llvm_emit_primitive;
6115 ctx->abi.emit_outputs = si_llvm_emit_gs_epilogue;
6116 bld_base->emit_epilogue = si_tgsi_emit_gs_epilogue;
6117 break;
6118 case PIPE_SHADER_FRAGMENT:
6119 ctx->load_input = declare_input_fs;
6120 ctx->abi.emit_outputs = si_llvm_return_fs_outputs;
6121 bld_base->emit_epilogue = si_tgsi_emit_epilogue;
6122 ctx->abi.lookup_interp_param = si_nir_lookup_interp_param;
6123 ctx->abi.load_sample_position = load_sample_position;
6124 ctx->abi.load_sample_mask_in = load_sample_mask_in;
6125 ctx->abi.emit_kill = si_llvm_emit_kill;
6126 break;
6127 case PIPE_SHADER_COMPUTE:
6128 ctx->abi.load_local_group_size = get_block_size;
6129 break;
6130 default:
6131 assert(!"Unsupported shader type");
6132 return false;
6133 }
6134
6135 ctx->abi.load_ubo = load_ubo;
6136 ctx->abi.load_ssbo = load_ssbo;
6137
6138 create_function(ctx);
6139 preload_ring_buffers(ctx);
6140
6141 if (ctx->type == PIPE_SHADER_TESS_CTRL &&
6142 sel->tcs_info.tessfactors_are_def_in_all_invocs) {
6143 for (unsigned i = 0; i < 6; i++) {
6144 ctx->invoc0_tess_factors[i] =
6145 ac_build_alloca_undef(&ctx->ac, ctx->i32, "");
6146 }
6147 }
6148
6149 if (ctx->type == PIPE_SHADER_GEOMETRY) {
6150 for (unsigned i = 0; i < 4; i++) {
6151 ctx->gs_next_vertex[i] =
6152 ac_build_alloca(&ctx->ac, ctx->i32, "");
6153 }
6154 if (shader->key.as_ngg) {
6155 for (unsigned i = 0; i < 4; ++i) {
6156 ctx->gs_curprim_verts[i] =
6157 lp_build_alloca(&ctx->gallivm, ctx->ac.i32, "");
6158 ctx->gs_generated_prims[i] =
6159 lp_build_alloca(&ctx->gallivm, ctx->ac.i32, "");
6160 }
6161
6162 unsigned scratch_size = 8;
6163 if (sel->so.num_outputs)
6164 scratch_size = 44;
6165
6166 LLVMTypeRef ai32 = LLVMArrayType(ctx->i32, scratch_size);
6167 ctx->gs_ngg_scratch = LLVMAddGlobalInAddressSpace(ctx->ac.module,
6168 ai32, "ngg_scratch", AC_ADDR_SPACE_LDS);
6169 LLVMSetInitializer(ctx->gs_ngg_scratch, LLVMGetUndef(ai32));
6170 LLVMSetAlignment(ctx->gs_ngg_scratch, 4);
6171
6172 ctx->gs_ngg_emit = LLVMAddGlobalInAddressSpace(ctx->ac.module,
6173 LLVMArrayType(ctx->i32, 0), "ngg_emit", AC_ADDR_SPACE_LDS);
6174 LLVMSetLinkage(ctx->gs_ngg_emit, LLVMExternalLinkage);
6175 LLVMSetAlignment(ctx->gs_ngg_emit, 4);
6176 }
6177 }
6178
6179 if (shader->key.as_ngg && ctx->type != PIPE_SHADER_GEOMETRY) {
6180 /* Unconditionally declare scratch space base for streamout and
6181 * vertex compaction. Whether space is actually allocated is
6182 * determined during linking / PM4 creation.
6183 *
6184 * Add an extra dword per vertex to ensure an odd stride, which
6185 * avoids bank conflicts for SoA accesses.
6186 */
6187 declare_esgs_ring(ctx);
6188
6189 /* This is really only needed when streamout and / or vertex
6190 * compaction is enabled.
6191 */
6192 LLVMTypeRef asi32 = LLVMArrayType(ctx->i32, 8);
6193 ctx->gs_ngg_scratch = LLVMAddGlobalInAddressSpace(ctx->ac.module,
6194 asi32, "ngg_scratch", AC_ADDR_SPACE_LDS);
6195 LLVMSetInitializer(ctx->gs_ngg_scratch, LLVMGetUndef(asi32));
6196 LLVMSetAlignment(ctx->gs_ngg_scratch, 4);
6197 }
6198
6199 /* For GFX9 merged shaders:
6200 * - Set EXEC for the first shader. If the prolog is present, set
6201 * EXEC there instead.
6202 * - Add a barrier before the second shader.
6203 * - In the second shader, reset EXEC to ~0 and wrap the main part in
6204 * an if-statement. This is required for correctness in geometry
6205 * shaders, to ensure that empty GS waves do not send GS_EMIT and
6206 * GS_CUT messages.
6207 *
6208 * For monolithic merged shaders, the first shader is wrapped in an
6209 * if-block together with its prolog in si_build_wrapper_function.
6210 *
6211 * NGG vertex and tess eval shaders running as the last
6212 * vertex/geometry stage handle execution explicitly using
6213 * if-statements.
6214 */
6215 if (ctx->screen->info.chip_class >= GFX9) {
6216 if (!shader->is_monolithic &&
6217 sel->info.num_instructions > 1 && /* not empty shader */
6218 (shader->key.as_es || shader->key.as_ls) &&
6219 (ctx->type == PIPE_SHADER_TESS_EVAL ||
6220 (ctx->type == PIPE_SHADER_VERTEX &&
6221 !si_vs_needs_prolog(sel, &shader->key.part.vs.prolog)))) {
6222 si_init_exec_from_input(ctx,
6223 ctx->param_merged_wave_info, 0);
6224 } else if (ctx->type == PIPE_SHADER_TESS_CTRL ||
6225 ctx->type == PIPE_SHADER_GEOMETRY ||
6226 shader->key.as_ngg) {
6227 LLVMValueRef num_threads;
6228 bool nested_barrier;
6229
6230 if (!shader->is_monolithic ||
6231 (ctx->type == PIPE_SHADER_TESS_EVAL &&
6232 shader->key.as_ngg))
6233 ac_init_exec_full_mask(&ctx->ac);
6234
6235 if (ctx->type == PIPE_SHADER_TESS_CTRL ||
6236 ctx->type == PIPE_SHADER_GEOMETRY) {
6237 if (ctx->type == PIPE_SHADER_GEOMETRY && shader->key.as_ngg) {
6238 gfx10_ngg_gs_emit_prologue(ctx);
6239 nested_barrier = false;
6240 } else {
6241 nested_barrier = true;
6242 }
6243
6244 /* Number of patches / primitives */
6245 num_threads = si_unpack_param(ctx, ctx->param_merged_wave_info, 8, 8);
6246 } else {
6247 /* Number of vertices */
6248 num_threads = si_unpack_param(ctx, ctx->param_merged_wave_info, 0, 8);
6249 nested_barrier = false;
6250 }
6251
6252 LLVMValueRef ena =
6253 LLVMBuildICmp(ctx->ac.builder, LLVMIntULT,
6254 ac_get_thread_id(&ctx->ac), num_threads, "");
6255 lp_build_if(&ctx->merged_wrap_if_state, &ctx->gallivm, ena);
6256
6257 if (nested_barrier) {
6258 /* Execute a barrier before the second shader in
6259 * a merged shader.
6260 *
6261 * Execute the barrier inside the conditional block,
6262 * so that empty waves can jump directly to s_endpgm,
6263 * which will also signal the barrier.
6264 *
6265 * This is possible in gfx9, because an empty wave
6266 * for the second shader does not participate in
6267 * the epilogue. With NGG, empty waves may still
6268 * be required to export data (e.g. GS output vertices),
6269 * so we cannot let them exit early.
6270 *
6271 * If the shader is TCS and the TCS epilog is present
6272 * and contains a barrier, it will wait there and then
6273 * reach s_endpgm.
6274 */
6275 si_llvm_emit_barrier(NULL, bld_base, NULL);
6276 }
6277 }
6278 }
6279
6280 if (sel->force_correct_derivs_after_kill) {
6281 ctx->postponed_kill = ac_build_alloca_undef(&ctx->ac, ctx->i1, "");
6282 /* true = don't kill. */
6283 LLVMBuildStore(ctx->ac.builder, ctx->i1true,
6284 ctx->postponed_kill);
6285 }
6286
6287 if (sel->tokens) {
6288 if (!lp_build_tgsi_llvm(bld_base, sel->tokens)) {
6289 fprintf(stderr, "Failed to translate shader from TGSI to LLVM\n");
6290 return false;
6291 }
6292 } else {
6293 if (!si_nir_build_llvm(ctx, sel->nir)) {
6294 fprintf(stderr, "Failed to translate shader from NIR to LLVM\n");
6295 return false;
6296 }
6297 }
6298
6299 si_llvm_build_ret(ctx, ctx->return_value);
6300 return true;
6301 }
6302
6303 /**
6304 * Compute the VS prolog key, which contains all the information needed to
6305 * build the VS prolog function, and set shader->info bits where needed.
6306 *
6307 * \param info Shader info of the vertex shader.
6308 * \param num_input_sgprs Number of input SGPRs for the vertex shader.
6309 * \param prolog_key Key of the VS prolog
6310 * \param shader_out The vertex shader, or the next shader if merging LS+HS or ES+GS.
6311 * \param key Output shader part key.
6312 */
6313 static void si_get_vs_prolog_key(const struct tgsi_shader_info *info,
6314 unsigned num_input_sgprs,
6315 const struct si_vs_prolog_bits *prolog_key,
6316 struct si_shader *shader_out,
6317 union si_shader_part_key *key)
6318 {
6319 memset(key, 0, sizeof(*key));
6320 key->vs_prolog.states = *prolog_key;
6321 key->vs_prolog.num_input_sgprs = num_input_sgprs;
6322 key->vs_prolog.last_input = MAX2(1, info->num_inputs) - 1;
6323 key->vs_prolog.as_ls = shader_out->key.as_ls;
6324 key->vs_prolog.as_es = shader_out->key.as_es;
6325 key->vs_prolog.as_ngg = shader_out->key.as_ngg;
6326
6327 if (shader_out->selector->type == PIPE_SHADER_TESS_CTRL) {
6328 key->vs_prolog.as_ls = 1;
6329 key->vs_prolog.num_merged_next_stage_vgprs = 2;
6330 } else if (shader_out->selector->type == PIPE_SHADER_GEOMETRY) {
6331 key->vs_prolog.as_es = 1;
6332 key->vs_prolog.num_merged_next_stage_vgprs = 5;
6333 } else if (shader_out->key.as_ngg) {
6334 key->vs_prolog.num_merged_next_stage_vgprs = 5;
6335 }
6336
6337 /* Enable loading the InstanceID VGPR. */
6338 uint16_t input_mask = u_bit_consecutive(0, info->num_inputs);
6339
6340 if ((key->vs_prolog.states.instance_divisor_is_one |
6341 key->vs_prolog.states.instance_divisor_is_fetched) & input_mask)
6342 shader_out->info.uses_instanceid = true;
6343 }
6344
6345 /**
6346 * Compute the PS prolog key, which contains all the information needed to
6347 * build the PS prolog function, and set related bits in shader->config.
6348 */
6349 static void si_get_ps_prolog_key(struct si_shader *shader,
6350 union si_shader_part_key *key,
6351 bool separate_prolog)
6352 {
6353 struct tgsi_shader_info *info = &shader->selector->info;
6354
6355 memset(key, 0, sizeof(*key));
6356 key->ps_prolog.states = shader->key.part.ps.prolog;
6357 key->ps_prolog.colors_read = info->colors_read;
6358 key->ps_prolog.num_input_sgprs = shader->info.num_input_sgprs;
6359 key->ps_prolog.num_input_vgprs = shader->info.num_input_vgprs;
6360 key->ps_prolog.wqm = info->uses_derivatives &&
6361 (key->ps_prolog.colors_read ||
6362 key->ps_prolog.states.force_persp_sample_interp ||
6363 key->ps_prolog.states.force_linear_sample_interp ||
6364 key->ps_prolog.states.force_persp_center_interp ||
6365 key->ps_prolog.states.force_linear_center_interp ||
6366 key->ps_prolog.states.bc_optimize_for_persp ||
6367 key->ps_prolog.states.bc_optimize_for_linear);
6368 key->ps_prolog.ancillary_vgpr_index = shader->info.ancillary_vgpr_index;
6369
6370 if (info->colors_read) {
6371 unsigned *color = shader->selector->color_attr_index;
6372
6373 if (shader->key.part.ps.prolog.color_two_side) {
6374 /* BCOLORs are stored after the last input. */
6375 key->ps_prolog.num_interp_inputs = info->num_inputs;
6376 key->ps_prolog.face_vgpr_index = shader->info.face_vgpr_index;
6377 if (separate_prolog)
6378 shader->config.spi_ps_input_ena |= S_0286CC_FRONT_FACE_ENA(1);
6379 }
6380
6381 for (unsigned i = 0; i < 2; i++) {
6382 unsigned interp = info->input_interpolate[color[i]];
6383 unsigned location = info->input_interpolate_loc[color[i]];
6384
6385 if (!(info->colors_read & (0xf << i*4)))
6386 continue;
6387
6388 key->ps_prolog.color_attr_index[i] = color[i];
6389
6390 if (shader->key.part.ps.prolog.flatshade_colors &&
6391 interp == TGSI_INTERPOLATE_COLOR)
6392 interp = TGSI_INTERPOLATE_CONSTANT;
6393
6394 switch (interp) {
6395 case TGSI_INTERPOLATE_CONSTANT:
6396 key->ps_prolog.color_interp_vgpr_index[i] = -1;
6397 break;
6398 case TGSI_INTERPOLATE_PERSPECTIVE:
6399 case TGSI_INTERPOLATE_COLOR:
6400 /* Force the interpolation location for colors here. */
6401 if (shader->key.part.ps.prolog.force_persp_sample_interp)
6402 location = TGSI_INTERPOLATE_LOC_SAMPLE;
6403 if (shader->key.part.ps.prolog.force_persp_center_interp)
6404 location = TGSI_INTERPOLATE_LOC_CENTER;
6405
6406 switch (location) {
6407 case TGSI_INTERPOLATE_LOC_SAMPLE:
6408 key->ps_prolog.color_interp_vgpr_index[i] = 0;
6409 if (separate_prolog) {
6410 shader->config.spi_ps_input_ena |=
6411 S_0286CC_PERSP_SAMPLE_ENA(1);
6412 }
6413 break;
6414 case TGSI_INTERPOLATE_LOC_CENTER:
6415 key->ps_prolog.color_interp_vgpr_index[i] = 2;
6416 if (separate_prolog) {
6417 shader->config.spi_ps_input_ena |=
6418 S_0286CC_PERSP_CENTER_ENA(1);
6419 }
6420 break;
6421 case TGSI_INTERPOLATE_LOC_CENTROID:
6422 key->ps_prolog.color_interp_vgpr_index[i] = 4;
6423 if (separate_prolog) {
6424 shader->config.spi_ps_input_ena |=
6425 S_0286CC_PERSP_CENTROID_ENA(1);
6426 }
6427 break;
6428 default:
6429 assert(0);
6430 }
6431 break;
6432 case TGSI_INTERPOLATE_LINEAR:
6433 /* Force the interpolation location for colors here. */
6434 if (shader->key.part.ps.prolog.force_linear_sample_interp)
6435 location = TGSI_INTERPOLATE_LOC_SAMPLE;
6436 if (shader->key.part.ps.prolog.force_linear_center_interp)
6437 location = TGSI_INTERPOLATE_LOC_CENTER;
6438
6439 /* The VGPR assignment for non-monolithic shaders
6440 * works because InitialPSInputAddr is set on the
6441 * main shader and PERSP_PULL_MODEL is never used.
6442 */
6443 switch (location) {
6444 case TGSI_INTERPOLATE_LOC_SAMPLE:
6445 key->ps_prolog.color_interp_vgpr_index[i] =
6446 separate_prolog ? 6 : 9;
6447 if (separate_prolog) {
6448 shader->config.spi_ps_input_ena |=
6449 S_0286CC_LINEAR_SAMPLE_ENA(1);
6450 }
6451 break;
6452 case TGSI_INTERPOLATE_LOC_CENTER:
6453 key->ps_prolog.color_interp_vgpr_index[i] =
6454 separate_prolog ? 8 : 11;
6455 if (separate_prolog) {
6456 shader->config.spi_ps_input_ena |=
6457 S_0286CC_LINEAR_CENTER_ENA(1);
6458 }
6459 break;
6460 case TGSI_INTERPOLATE_LOC_CENTROID:
6461 key->ps_prolog.color_interp_vgpr_index[i] =
6462 separate_prolog ? 10 : 13;
6463 if (separate_prolog) {
6464 shader->config.spi_ps_input_ena |=
6465 S_0286CC_LINEAR_CENTROID_ENA(1);
6466 }
6467 break;
6468 default:
6469 assert(0);
6470 }
6471 break;
6472 default:
6473 assert(0);
6474 }
6475 }
6476 }
6477 }
6478
6479 /**
6480 * Check whether a PS prolog is required based on the key.
6481 */
6482 static bool si_need_ps_prolog(const union si_shader_part_key *key)
6483 {
6484 return key->ps_prolog.colors_read ||
6485 key->ps_prolog.states.force_persp_sample_interp ||
6486 key->ps_prolog.states.force_linear_sample_interp ||
6487 key->ps_prolog.states.force_persp_center_interp ||
6488 key->ps_prolog.states.force_linear_center_interp ||
6489 key->ps_prolog.states.bc_optimize_for_persp ||
6490 key->ps_prolog.states.bc_optimize_for_linear ||
6491 key->ps_prolog.states.poly_stipple ||
6492 key->ps_prolog.states.samplemask_log_ps_iter;
6493 }
6494
6495 /**
6496 * Compute the PS epilog key, which contains all the information needed to
6497 * build the PS epilog function.
6498 */
6499 static void si_get_ps_epilog_key(struct si_shader *shader,
6500 union si_shader_part_key *key)
6501 {
6502 struct tgsi_shader_info *info = &shader->selector->info;
6503 memset(key, 0, sizeof(*key));
6504 key->ps_epilog.colors_written = info->colors_written;
6505 key->ps_epilog.writes_z = info->writes_z;
6506 key->ps_epilog.writes_stencil = info->writes_stencil;
6507 key->ps_epilog.writes_samplemask = info->writes_samplemask;
6508 key->ps_epilog.states = shader->key.part.ps.epilog;
6509 }
6510
6511 /**
6512 * Build the GS prolog function. Rotate the input vertices for triangle strips
6513 * with adjacency.
6514 */
6515 static void si_build_gs_prolog_function(struct si_shader_context *ctx,
6516 union si_shader_part_key *key)
6517 {
6518 unsigned num_sgprs, num_vgprs;
6519 struct si_function_info fninfo;
6520 LLVMBuilderRef builder = ctx->ac.builder;
6521 LLVMTypeRef returns[48];
6522 LLVMValueRef func, ret;
6523
6524 si_init_function_info(&fninfo);
6525
6526 if (ctx->screen->info.chip_class >= GFX9) {
6527 if (key->gs_prolog.states.gfx9_prev_is_vs)
6528 num_sgprs = 8 + GFX9_VSGS_NUM_USER_SGPR;
6529 else
6530 num_sgprs = 8 + GFX9_TESGS_NUM_USER_SGPR;
6531 num_vgprs = 5; /* ES inputs are not needed by GS */
6532 } else {
6533 num_sgprs = GFX6_GS_NUM_USER_SGPR + 2;
6534 num_vgprs = 8;
6535 }
6536
6537 for (unsigned i = 0; i < num_sgprs; ++i) {
6538 add_arg(&fninfo, ARG_SGPR, ctx->i32);
6539 returns[i] = ctx->i32;
6540 }
6541
6542 for (unsigned i = 0; i < num_vgprs; ++i) {
6543 add_arg(&fninfo, ARG_VGPR, ctx->i32);
6544 returns[num_sgprs + i] = ctx->f32;
6545 }
6546
6547 /* Create the function. */
6548 si_create_function(ctx, "gs_prolog", returns, num_sgprs + num_vgprs,
6549 &fninfo, 0);
6550 func = ctx->main_fn;
6551
6552 /* Set the full EXEC mask for the prolog, because we are only fiddling
6553 * with registers here. The main shader part will set the correct EXEC
6554 * mask.
6555 */
6556 if (ctx->screen->info.chip_class >= GFX9 && !key->gs_prolog.is_monolithic)
6557 ac_init_exec_full_mask(&ctx->ac);
6558
6559 /* Copy inputs to outputs. This should be no-op, as the registers match,
6560 * but it will prevent the compiler from overwriting them unintentionally.
6561 */
6562 ret = ctx->return_value;
6563 for (unsigned i = 0; i < num_sgprs; i++) {
6564 LLVMValueRef p = LLVMGetParam(func, i);
6565 ret = LLVMBuildInsertValue(builder, ret, p, i, "");
6566 }
6567 for (unsigned i = 0; i < num_vgprs; i++) {
6568 LLVMValueRef p = LLVMGetParam(func, num_sgprs + i);
6569 p = ac_to_float(&ctx->ac, p);
6570 ret = LLVMBuildInsertValue(builder, ret, p, num_sgprs + i, "");
6571 }
6572
6573 if (key->gs_prolog.states.tri_strip_adj_fix) {
6574 /* Remap the input vertices for every other primitive. */
6575 const unsigned gfx6_vtx_params[6] = {
6576 num_sgprs,
6577 num_sgprs + 1,
6578 num_sgprs + 3,
6579 num_sgprs + 4,
6580 num_sgprs + 5,
6581 num_sgprs + 6
6582 };
6583 const unsigned gfx9_vtx_params[3] = {
6584 num_sgprs,
6585 num_sgprs + 1,
6586 num_sgprs + 4,
6587 };
6588 LLVMValueRef vtx_in[6], vtx_out[6];
6589 LLVMValueRef prim_id, rotate;
6590
6591 if (ctx->screen->info.chip_class >= GFX9) {
6592 for (unsigned i = 0; i < 3; i++) {
6593 vtx_in[i*2] = si_unpack_param(ctx, gfx9_vtx_params[i], 0, 16);
6594 vtx_in[i*2+1] = si_unpack_param(ctx, gfx9_vtx_params[i], 16, 16);
6595 }
6596 } else {
6597 for (unsigned i = 0; i < 6; i++)
6598 vtx_in[i] = LLVMGetParam(func, gfx6_vtx_params[i]);
6599 }
6600
6601 prim_id = LLVMGetParam(func, num_sgprs + 2);
6602 rotate = LLVMBuildTrunc(builder, prim_id, ctx->i1, "");
6603
6604 for (unsigned i = 0; i < 6; ++i) {
6605 LLVMValueRef base, rotated;
6606 base = vtx_in[i];
6607 rotated = vtx_in[(i + 4) % 6];
6608 vtx_out[i] = LLVMBuildSelect(builder, rotate, rotated, base, "");
6609 }
6610
6611 if (ctx->screen->info.chip_class >= GFX9) {
6612 for (unsigned i = 0; i < 3; i++) {
6613 LLVMValueRef hi, out;
6614
6615 hi = LLVMBuildShl(builder, vtx_out[i*2+1],
6616 LLVMConstInt(ctx->i32, 16, 0), "");
6617 out = LLVMBuildOr(builder, vtx_out[i*2], hi, "");
6618 out = ac_to_float(&ctx->ac, out);
6619 ret = LLVMBuildInsertValue(builder, ret, out,
6620 gfx9_vtx_params[i], "");
6621 }
6622 } else {
6623 for (unsigned i = 0; i < 6; i++) {
6624 LLVMValueRef out;
6625
6626 out = ac_to_float(&ctx->ac, vtx_out[i]);
6627 ret = LLVMBuildInsertValue(builder, ret, out,
6628 gfx6_vtx_params[i], "");
6629 }
6630 }
6631 }
6632
6633 LLVMBuildRet(builder, ret);
6634 }
6635
6636 /**
6637 * Given a list of shader part functions, build a wrapper function that
6638 * runs them in sequence to form a monolithic shader.
6639 */
6640 static void si_build_wrapper_function(struct si_shader_context *ctx,
6641 LLVMValueRef *parts,
6642 unsigned num_parts,
6643 unsigned main_part,
6644 unsigned next_shader_first_part)
6645 {
6646 LLVMBuilderRef builder = ctx->ac.builder;
6647 /* PS epilog has one arg per color component; gfx9 merged shader
6648 * prologs need to forward 32 user SGPRs.
6649 */
6650 struct si_function_info fninfo;
6651 LLVMValueRef initial[64], out[64];
6652 LLVMTypeRef function_type;
6653 unsigned num_first_params;
6654 unsigned num_out, initial_num_out;
6655 MAYBE_UNUSED unsigned num_out_sgpr; /* used in debug checks */
6656 MAYBE_UNUSED unsigned initial_num_out_sgpr; /* used in debug checks */
6657 unsigned num_sgprs, num_vgprs;
6658 unsigned gprs;
6659 struct lp_build_if_state if_state;
6660
6661 si_init_function_info(&fninfo);
6662
6663 for (unsigned i = 0; i < num_parts; ++i) {
6664 ac_add_function_attr(ctx->ac.context, parts[i], -1,
6665 AC_FUNC_ATTR_ALWAYSINLINE);
6666 LLVMSetLinkage(parts[i], LLVMPrivateLinkage);
6667 }
6668
6669 /* The parameters of the wrapper function correspond to those of the
6670 * first part in terms of SGPRs and VGPRs, but we use the types of the
6671 * main part to get the right types. This is relevant for the
6672 * dereferenceable attribute on descriptor table pointers.
6673 */
6674 num_sgprs = 0;
6675 num_vgprs = 0;
6676
6677 function_type = LLVMGetElementType(LLVMTypeOf(parts[0]));
6678 num_first_params = LLVMCountParamTypes(function_type);
6679
6680 for (unsigned i = 0; i < num_first_params; ++i) {
6681 LLVMValueRef param = LLVMGetParam(parts[0], i);
6682
6683 if (ac_is_sgpr_param(param)) {
6684 assert(num_vgprs == 0);
6685 num_sgprs += ac_get_type_size(LLVMTypeOf(param)) / 4;
6686 } else {
6687 num_vgprs += ac_get_type_size(LLVMTypeOf(param)) / 4;
6688 }
6689 }
6690
6691 gprs = 0;
6692 while (gprs < num_sgprs + num_vgprs) {
6693 LLVMValueRef param = LLVMGetParam(parts[main_part], fninfo.num_params);
6694 LLVMTypeRef type = LLVMTypeOf(param);
6695 unsigned size = ac_get_type_size(type) / 4;
6696
6697 add_arg(&fninfo, gprs < num_sgprs ? ARG_SGPR : ARG_VGPR, type);
6698
6699 assert(ac_is_sgpr_param(param) == (gprs < num_sgprs));
6700 assert(gprs + size <= num_sgprs + num_vgprs &&
6701 (gprs >= num_sgprs || gprs + size <= num_sgprs));
6702
6703 gprs += size;
6704 }
6705
6706 /* Prepare the return type. */
6707 unsigned num_returns = 0;
6708 LLVMTypeRef returns[32], last_func_type, return_type;
6709
6710 last_func_type = LLVMGetElementType(LLVMTypeOf(parts[num_parts - 1]));
6711 return_type = LLVMGetReturnType(last_func_type);
6712
6713 switch (LLVMGetTypeKind(return_type)) {
6714 case LLVMStructTypeKind:
6715 num_returns = LLVMCountStructElementTypes(return_type);
6716 assert(num_returns <= ARRAY_SIZE(returns));
6717 LLVMGetStructElementTypes(return_type, returns);
6718 break;
6719 case LLVMVoidTypeKind:
6720 break;
6721 default:
6722 unreachable("unexpected type");
6723 }
6724
6725 si_create_function(ctx, "wrapper", returns, num_returns, &fninfo,
6726 si_get_max_workgroup_size(ctx->shader));
6727
6728 if (is_merged_shader(ctx))
6729 ac_init_exec_full_mask(&ctx->ac);
6730
6731 /* Record the arguments of the function as if they were an output of
6732 * a previous part.
6733 */
6734 num_out = 0;
6735 num_out_sgpr = 0;
6736
6737 for (unsigned i = 0; i < fninfo.num_params; ++i) {
6738 LLVMValueRef param = LLVMGetParam(ctx->main_fn, i);
6739 LLVMTypeRef param_type = LLVMTypeOf(param);
6740 LLVMTypeRef out_type = i < fninfo.num_sgpr_params ? ctx->i32 : ctx->f32;
6741 unsigned size = ac_get_type_size(param_type) / 4;
6742
6743 if (size == 1) {
6744 if (LLVMGetTypeKind(param_type) == LLVMPointerTypeKind) {
6745 param = LLVMBuildPtrToInt(builder, param, ctx->i32, "");
6746 param_type = ctx->i32;
6747 }
6748
6749 if (param_type != out_type)
6750 param = LLVMBuildBitCast(builder, param, out_type, "");
6751 out[num_out++] = param;
6752 } else {
6753 LLVMTypeRef vector_type = LLVMVectorType(out_type, size);
6754
6755 if (LLVMGetTypeKind(param_type) == LLVMPointerTypeKind) {
6756 param = LLVMBuildPtrToInt(builder, param, ctx->i64, "");
6757 param_type = ctx->i64;
6758 }
6759
6760 if (param_type != vector_type)
6761 param = LLVMBuildBitCast(builder, param, vector_type, "");
6762
6763 for (unsigned j = 0; j < size; ++j)
6764 out[num_out++] = LLVMBuildExtractElement(
6765 builder, param, LLVMConstInt(ctx->i32, j, 0), "");
6766 }
6767
6768 if (i < fninfo.num_sgpr_params)
6769 num_out_sgpr = num_out;
6770 }
6771
6772 memcpy(initial, out, sizeof(out));
6773 initial_num_out = num_out;
6774 initial_num_out_sgpr = num_out_sgpr;
6775
6776 /* Now chain the parts. */
6777 LLVMValueRef ret;
6778 for (unsigned part = 0; part < num_parts; ++part) {
6779 LLVMValueRef in[48];
6780 LLVMTypeRef ret_type;
6781 unsigned out_idx = 0;
6782 unsigned num_params = LLVMCountParams(parts[part]);
6783
6784 /* Merged shaders are executed conditionally depending
6785 * on the number of enabled threads passed in the input SGPRs. */
6786 if (is_multi_part_shader(ctx) && part == 0) {
6787 LLVMValueRef ena, count = initial[3];
6788
6789 count = LLVMBuildAnd(builder, count,
6790 LLVMConstInt(ctx->i32, 0x7f, 0), "");
6791 ena = LLVMBuildICmp(builder, LLVMIntULT,
6792 ac_get_thread_id(&ctx->ac), count, "");
6793 lp_build_if(&if_state, &ctx->gallivm, ena);
6794 }
6795
6796 /* Derive arguments for the next part from outputs of the
6797 * previous one.
6798 */
6799 for (unsigned param_idx = 0; param_idx < num_params; ++param_idx) {
6800 LLVMValueRef param;
6801 LLVMTypeRef param_type;
6802 bool is_sgpr;
6803 unsigned param_size;
6804 LLVMValueRef arg = NULL;
6805
6806 param = LLVMGetParam(parts[part], param_idx);
6807 param_type = LLVMTypeOf(param);
6808 param_size = ac_get_type_size(param_type) / 4;
6809 is_sgpr = ac_is_sgpr_param(param);
6810
6811 if (is_sgpr) {
6812 ac_add_function_attr(ctx->ac.context, parts[part],
6813 param_idx + 1, AC_FUNC_ATTR_INREG);
6814 } else if (out_idx < num_out_sgpr) {
6815 /* Skip returned SGPRs the current part doesn't
6816 * declare on the input. */
6817 out_idx = num_out_sgpr;
6818 }
6819
6820 assert(out_idx + param_size <= (is_sgpr ? num_out_sgpr : num_out));
6821
6822 if (param_size == 1)
6823 arg = out[out_idx];
6824 else
6825 arg = ac_build_gather_values(&ctx->ac, &out[out_idx], param_size);
6826
6827 if (LLVMTypeOf(arg) != param_type) {
6828 if (LLVMGetTypeKind(param_type) == LLVMPointerTypeKind) {
6829 if (LLVMGetPointerAddressSpace(param_type) ==
6830 AC_ADDR_SPACE_CONST_32BIT) {
6831 arg = LLVMBuildBitCast(builder, arg, ctx->i32, "");
6832 arg = LLVMBuildIntToPtr(builder, arg, param_type, "");
6833 } else {
6834 arg = LLVMBuildBitCast(builder, arg, ctx->i64, "");
6835 arg = LLVMBuildIntToPtr(builder, arg, param_type, "");
6836 }
6837 } else {
6838 arg = LLVMBuildBitCast(builder, arg, param_type, "");
6839 }
6840 }
6841
6842 in[param_idx] = arg;
6843 out_idx += param_size;
6844 }
6845
6846 ret = ac_build_call(&ctx->ac, parts[part], in, num_params);
6847
6848 if (is_multi_part_shader(ctx) &&
6849 part + 1 == next_shader_first_part) {
6850 lp_build_endif(&if_state);
6851
6852 /* The second half of the merged shader should use
6853 * the inputs from the toplevel (wrapper) function,
6854 * not the return value from the last call.
6855 *
6856 * That's because the last call was executed condi-
6857 * tionally, so we can't consume it in the main
6858 * block.
6859 */
6860 memcpy(out, initial, sizeof(initial));
6861 num_out = initial_num_out;
6862 num_out_sgpr = initial_num_out_sgpr;
6863 continue;
6864 }
6865
6866 /* Extract the returned GPRs. */
6867 ret_type = LLVMTypeOf(ret);
6868 num_out = 0;
6869 num_out_sgpr = 0;
6870
6871 if (LLVMGetTypeKind(ret_type) != LLVMVoidTypeKind) {
6872 assert(LLVMGetTypeKind(ret_type) == LLVMStructTypeKind);
6873
6874 unsigned ret_size = LLVMCountStructElementTypes(ret_type);
6875
6876 for (unsigned i = 0; i < ret_size; ++i) {
6877 LLVMValueRef val =
6878 LLVMBuildExtractValue(builder, ret, i, "");
6879
6880 assert(num_out < ARRAY_SIZE(out));
6881 out[num_out++] = val;
6882
6883 if (LLVMTypeOf(val) == ctx->i32) {
6884 assert(num_out_sgpr + 1 == num_out);
6885 num_out_sgpr = num_out;
6886 }
6887 }
6888 }
6889 }
6890
6891 /* Return the value from the last part. */
6892 if (LLVMGetTypeKind(LLVMTypeOf(ret)) == LLVMVoidTypeKind)
6893 LLVMBuildRetVoid(builder);
6894 else
6895 LLVMBuildRet(builder, ret);
6896 }
6897
6898 static bool si_should_optimize_less(struct ac_llvm_compiler *compiler,
6899 struct si_shader_selector *sel)
6900 {
6901 if (!compiler->low_opt_passes)
6902 return false;
6903
6904 /* Assume a slow CPU. */
6905 assert(!sel->screen->info.has_dedicated_vram &&
6906 sel->screen->info.chip_class <= GFX8);
6907
6908 /* For a crazy dEQP test containing 2597 memory opcodes, mostly
6909 * buffer stores. */
6910 return sel->type == PIPE_SHADER_COMPUTE &&
6911 sel->info.num_memory_instructions > 1000;
6912 }
6913
6914 int si_compile_tgsi_shader(struct si_screen *sscreen,
6915 struct ac_llvm_compiler *compiler,
6916 struct si_shader *shader,
6917 struct pipe_debug_callback *debug)
6918 {
6919 struct si_shader_selector *sel = shader->selector;
6920 struct si_shader_context ctx;
6921 int r = -1;
6922
6923 /* Dump TGSI code before doing TGSI->LLVM conversion in case the
6924 * conversion fails. */
6925 if (si_can_dump_shader(sscreen, sel->type) &&
6926 !(sscreen->debug_flags & DBG(NO_TGSI))) {
6927 if (sel->tokens)
6928 tgsi_dump(sel->tokens, 0);
6929 else
6930 nir_print_shader(sel->nir, stderr);
6931 si_dump_streamout(&sel->so);
6932 }
6933
6934 si_init_shader_ctx(&ctx, sscreen, compiler);
6935 si_llvm_context_set_tgsi(&ctx, shader);
6936
6937 memset(shader->info.vs_output_param_offset, AC_EXP_PARAM_UNDEFINED,
6938 sizeof(shader->info.vs_output_param_offset));
6939
6940 shader->info.uses_instanceid = sel->info.uses_instanceid;
6941
6942 if (!si_compile_tgsi_main(&ctx)) {
6943 si_llvm_dispose(&ctx);
6944 return -1;
6945 }
6946
6947 if (shader->is_monolithic && ctx.type == PIPE_SHADER_VERTEX) {
6948 LLVMValueRef parts[2];
6949 bool need_prolog = sel->vs_needs_prolog;
6950
6951 parts[1] = ctx.main_fn;
6952
6953 if (need_prolog) {
6954 union si_shader_part_key prolog_key;
6955 si_get_vs_prolog_key(&sel->info,
6956 shader->info.num_input_sgprs,
6957 &shader->key.part.vs.prolog,
6958 shader, &prolog_key);
6959 si_build_vs_prolog_function(&ctx, &prolog_key);
6960 parts[0] = ctx.main_fn;
6961 }
6962
6963 si_build_wrapper_function(&ctx, parts + !need_prolog,
6964 1 + need_prolog, need_prolog, 0);
6965
6966 if (ctx.shader->key.opt.vs_as_prim_discard_cs)
6967 si_build_prim_discard_compute_shader(&ctx);
6968 } else if (shader->is_monolithic && ctx.type == PIPE_SHADER_TESS_CTRL) {
6969 if (sscreen->info.chip_class >= GFX9) {
6970 struct si_shader_selector *ls = shader->key.part.tcs.ls;
6971 LLVMValueRef parts[4];
6972 bool vs_needs_prolog =
6973 si_vs_needs_prolog(ls, &shader->key.part.tcs.ls_prolog);
6974
6975 /* TCS main part */
6976 parts[2] = ctx.main_fn;
6977
6978 /* TCS epilog */
6979 union si_shader_part_key tcs_epilog_key;
6980 memset(&tcs_epilog_key, 0, sizeof(tcs_epilog_key));
6981 tcs_epilog_key.tcs_epilog.states = shader->key.part.tcs.epilog;
6982 si_build_tcs_epilog_function(&ctx, &tcs_epilog_key);
6983 parts[3] = ctx.main_fn;
6984
6985 /* VS as LS main part */
6986 struct si_shader shader_ls = {};
6987 shader_ls.selector = ls;
6988 shader_ls.key.as_ls = 1;
6989 shader_ls.key.mono = shader->key.mono;
6990 shader_ls.key.opt = shader->key.opt;
6991 shader_ls.is_monolithic = true;
6992 si_llvm_context_set_tgsi(&ctx, &shader_ls);
6993
6994 if (!si_compile_tgsi_main(&ctx)) {
6995 si_llvm_dispose(&ctx);
6996 return -1;
6997 }
6998 shader->info.uses_instanceid |= ls->info.uses_instanceid;
6999 parts[1] = ctx.main_fn;
7000
7001 /* LS prolog */
7002 if (vs_needs_prolog) {
7003 union si_shader_part_key vs_prolog_key;
7004 si_get_vs_prolog_key(&ls->info,
7005 shader_ls.info.num_input_sgprs,
7006 &shader->key.part.tcs.ls_prolog,
7007 shader, &vs_prolog_key);
7008 vs_prolog_key.vs_prolog.is_monolithic = true;
7009 si_build_vs_prolog_function(&ctx, &vs_prolog_key);
7010 parts[0] = ctx.main_fn;
7011 }
7012
7013 /* Reset the shader context. */
7014 ctx.shader = shader;
7015 ctx.type = PIPE_SHADER_TESS_CTRL;
7016
7017 si_build_wrapper_function(&ctx,
7018 parts + !vs_needs_prolog,
7019 4 - !vs_needs_prolog, vs_needs_prolog,
7020 vs_needs_prolog ? 2 : 1);
7021 } else {
7022 LLVMValueRef parts[2];
7023 union si_shader_part_key epilog_key;
7024
7025 parts[0] = ctx.main_fn;
7026
7027 memset(&epilog_key, 0, sizeof(epilog_key));
7028 epilog_key.tcs_epilog.states = shader->key.part.tcs.epilog;
7029 si_build_tcs_epilog_function(&ctx, &epilog_key);
7030 parts[1] = ctx.main_fn;
7031
7032 si_build_wrapper_function(&ctx, parts, 2, 0, 0);
7033 }
7034 } else if (shader->is_monolithic && ctx.type == PIPE_SHADER_GEOMETRY) {
7035 if (ctx.screen->info.chip_class >= GFX9) {
7036 struct si_shader_selector *es = shader->key.part.gs.es;
7037 LLVMValueRef es_prolog = NULL;
7038 LLVMValueRef es_main = NULL;
7039 LLVMValueRef gs_prolog = NULL;
7040 LLVMValueRef gs_main = ctx.main_fn;
7041
7042 /* GS prolog */
7043 union si_shader_part_key gs_prolog_key;
7044 memset(&gs_prolog_key, 0, sizeof(gs_prolog_key));
7045 gs_prolog_key.gs_prolog.states = shader->key.part.gs.prolog;
7046 gs_prolog_key.gs_prolog.is_monolithic = true;
7047 si_build_gs_prolog_function(&ctx, &gs_prolog_key);
7048 gs_prolog = ctx.main_fn;
7049
7050 /* ES main part */
7051 struct si_shader shader_es = {};
7052 shader_es.selector = es;
7053 shader_es.key.as_es = 1;
7054 shader_es.key.mono = shader->key.mono;
7055 shader_es.key.opt = shader->key.opt;
7056 shader_es.is_monolithic = true;
7057 si_llvm_context_set_tgsi(&ctx, &shader_es);
7058
7059 if (!si_compile_tgsi_main(&ctx)) {
7060 si_llvm_dispose(&ctx);
7061 return -1;
7062 }
7063 shader->info.uses_instanceid |= es->info.uses_instanceid;
7064 es_main = ctx.main_fn;
7065
7066 /* ES prolog */
7067 if (es->vs_needs_prolog) {
7068 union si_shader_part_key vs_prolog_key;
7069 si_get_vs_prolog_key(&es->info,
7070 shader_es.info.num_input_sgprs,
7071 &shader->key.part.gs.vs_prolog,
7072 shader, &vs_prolog_key);
7073 vs_prolog_key.vs_prolog.is_monolithic = true;
7074 si_build_vs_prolog_function(&ctx, &vs_prolog_key);
7075 es_prolog = ctx.main_fn;
7076 }
7077
7078 /* Reset the shader context. */
7079 ctx.shader = shader;
7080 ctx.type = PIPE_SHADER_GEOMETRY;
7081
7082 /* Prepare the array of shader parts. */
7083 LLVMValueRef parts[4];
7084 unsigned num_parts = 0, main_part, next_first_part;
7085
7086 if (es_prolog)
7087 parts[num_parts++] = es_prolog;
7088
7089 parts[main_part = num_parts++] = es_main;
7090 parts[next_first_part = num_parts++] = gs_prolog;
7091 parts[num_parts++] = gs_main;
7092
7093 si_build_wrapper_function(&ctx, parts, num_parts,
7094 main_part, next_first_part);
7095 } else {
7096 LLVMValueRef parts[2];
7097 union si_shader_part_key prolog_key;
7098
7099 parts[1] = ctx.main_fn;
7100
7101 memset(&prolog_key, 0, sizeof(prolog_key));
7102 prolog_key.gs_prolog.states = shader->key.part.gs.prolog;
7103 si_build_gs_prolog_function(&ctx, &prolog_key);
7104 parts[0] = ctx.main_fn;
7105
7106 si_build_wrapper_function(&ctx, parts, 2, 1, 0);
7107 }
7108 } else if (shader->is_monolithic && ctx.type == PIPE_SHADER_FRAGMENT) {
7109 LLVMValueRef parts[3];
7110 union si_shader_part_key prolog_key;
7111 union si_shader_part_key epilog_key;
7112 bool need_prolog;
7113
7114 si_get_ps_prolog_key(shader, &prolog_key, false);
7115 need_prolog = si_need_ps_prolog(&prolog_key);
7116
7117 parts[need_prolog ? 1 : 0] = ctx.main_fn;
7118
7119 if (need_prolog) {
7120 si_build_ps_prolog_function(&ctx, &prolog_key);
7121 parts[0] = ctx.main_fn;
7122 }
7123
7124 si_get_ps_epilog_key(shader, &epilog_key);
7125 si_build_ps_epilog_function(&ctx, &epilog_key);
7126 parts[need_prolog ? 2 : 1] = ctx.main_fn;
7127
7128 si_build_wrapper_function(&ctx, parts, need_prolog ? 3 : 2,
7129 need_prolog ? 1 : 0, 0);
7130 }
7131
7132 si_llvm_optimize_module(&ctx);
7133
7134 /* Post-optimization transformations and analysis. */
7135 si_optimize_vs_outputs(&ctx);
7136
7137 if ((debug && debug->debug_message) ||
7138 si_can_dump_shader(sscreen, ctx.type)) {
7139 ctx.shader->info.private_mem_vgprs =
7140 ac_count_scratch_private_memory(ctx.main_fn);
7141 }
7142
7143 /* Make sure the input is a pointer and not integer followed by inttoptr. */
7144 assert(LLVMGetTypeKind(LLVMTypeOf(LLVMGetParam(ctx.main_fn, 0))) ==
7145 LLVMPointerTypeKind);
7146
7147 /* Compile to bytecode. */
7148 r = si_compile_llvm(sscreen, &shader->binary, &shader->config, compiler,
7149 ctx.ac.module, debug, ctx.type,
7150 si_get_shader_name(shader),
7151 si_should_optimize_less(compiler, shader->selector));
7152 si_llvm_dispose(&ctx);
7153 if (r) {
7154 fprintf(stderr, "LLVM failed to compile shader\n");
7155 return r;
7156 }
7157
7158 /* Validate SGPR and VGPR usage for compute to detect compiler bugs.
7159 * LLVM 3.9svn has this bug.
7160 */
7161 if (sel->type == PIPE_SHADER_COMPUTE) {
7162 unsigned wave_size = 64;
7163 unsigned max_vgprs = 256;
7164 unsigned max_sgprs = sscreen->info.chip_class >= GFX8 ? 800 : 512;
7165 unsigned max_sgprs_per_wave = 128;
7166 unsigned max_block_threads = si_get_max_workgroup_size(shader);
7167 unsigned min_waves_per_cu = DIV_ROUND_UP(max_block_threads, wave_size);
7168 unsigned min_waves_per_simd = DIV_ROUND_UP(min_waves_per_cu, 4);
7169
7170 max_vgprs = max_vgprs / min_waves_per_simd;
7171 max_sgprs = MIN2(max_sgprs / min_waves_per_simd, max_sgprs_per_wave);
7172
7173 if (shader->config.num_sgprs > max_sgprs ||
7174 shader->config.num_vgprs > max_vgprs) {
7175 fprintf(stderr, "LLVM failed to compile a shader correctly: "
7176 "SGPR:VGPR usage is %u:%u, but the hw limit is %u:%u\n",
7177 shader->config.num_sgprs, shader->config.num_vgprs,
7178 max_sgprs, max_vgprs);
7179
7180 /* Just terminate the process, because dependent
7181 * shaders can hang due to bad input data, but use
7182 * the env var to allow shader-db to work.
7183 */
7184 if (!debug_get_bool_option("SI_PASS_BAD_SHADERS", false))
7185 abort();
7186 }
7187 }
7188
7189 /* Add the scratch offset to input SGPRs. */
7190 if (shader->config.scratch_bytes_per_wave && !is_merged_shader(&ctx))
7191 shader->info.num_input_sgprs += 1; /* scratch byte offset */
7192
7193 /* Calculate the number of fragment input VGPRs. */
7194 if (ctx.type == PIPE_SHADER_FRAGMENT) {
7195 shader->info.num_input_vgprs = 0;
7196 shader->info.face_vgpr_index = -1;
7197 shader->info.ancillary_vgpr_index = -1;
7198
7199 if (G_0286CC_PERSP_SAMPLE_ENA(shader->config.spi_ps_input_addr))
7200 shader->info.num_input_vgprs += 2;
7201 if (G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_addr))
7202 shader->info.num_input_vgprs += 2;
7203 if (G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_addr))
7204 shader->info.num_input_vgprs += 2;
7205 if (G_0286CC_PERSP_PULL_MODEL_ENA(shader->config.spi_ps_input_addr))
7206 shader->info.num_input_vgprs += 3;
7207 if (G_0286CC_LINEAR_SAMPLE_ENA(shader->config.spi_ps_input_addr))
7208 shader->info.num_input_vgprs += 2;
7209 if (G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_addr))
7210 shader->info.num_input_vgprs += 2;
7211 if (G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_addr))
7212 shader->info.num_input_vgprs += 2;
7213 if (G_0286CC_LINE_STIPPLE_TEX_ENA(shader->config.spi_ps_input_addr))
7214 shader->info.num_input_vgprs += 1;
7215 if (G_0286CC_POS_X_FLOAT_ENA(shader->config.spi_ps_input_addr))
7216 shader->info.num_input_vgprs += 1;
7217 if (G_0286CC_POS_Y_FLOAT_ENA(shader->config.spi_ps_input_addr))
7218 shader->info.num_input_vgprs += 1;
7219 if (G_0286CC_POS_Z_FLOAT_ENA(shader->config.spi_ps_input_addr))
7220 shader->info.num_input_vgprs += 1;
7221 if (G_0286CC_POS_W_FLOAT_ENA(shader->config.spi_ps_input_addr))
7222 shader->info.num_input_vgprs += 1;
7223 if (G_0286CC_FRONT_FACE_ENA(shader->config.spi_ps_input_addr)) {
7224 shader->info.face_vgpr_index = shader->info.num_input_vgprs;
7225 shader->info.num_input_vgprs += 1;
7226 }
7227 if (G_0286CC_ANCILLARY_ENA(shader->config.spi_ps_input_addr)) {
7228 shader->info.ancillary_vgpr_index = shader->info.num_input_vgprs;
7229 shader->info.num_input_vgprs += 1;
7230 }
7231 if (G_0286CC_SAMPLE_COVERAGE_ENA(shader->config.spi_ps_input_addr))
7232 shader->info.num_input_vgprs += 1;
7233 if (G_0286CC_POS_FIXED_PT_ENA(shader->config.spi_ps_input_addr))
7234 shader->info.num_input_vgprs += 1;
7235 }
7236
7237 si_calculate_max_simd_waves(shader);
7238 si_shader_dump_stats_for_shader_db(sscreen, shader, debug);
7239 return 0;
7240 }
7241
7242 /**
7243 * Create, compile and return a shader part (prolog or epilog).
7244 *
7245 * \param sscreen screen
7246 * \param list list of shader parts of the same category
7247 * \param type shader type
7248 * \param key shader part key
7249 * \param prolog whether the part being requested is a prolog
7250 * \param tm LLVM target machine
7251 * \param debug debug callback
7252 * \param build the callback responsible for building the main function
7253 * \return non-NULL on success
7254 */
7255 static struct si_shader_part *
7256 si_get_shader_part(struct si_screen *sscreen,
7257 struct si_shader_part **list,
7258 enum pipe_shader_type type,
7259 bool prolog,
7260 union si_shader_part_key *key,
7261 struct ac_llvm_compiler *compiler,
7262 struct pipe_debug_callback *debug,
7263 void (*build)(struct si_shader_context *,
7264 union si_shader_part_key *),
7265 const char *name)
7266 {
7267 struct si_shader_part *result;
7268
7269 mtx_lock(&sscreen->shader_parts_mutex);
7270
7271 /* Find existing. */
7272 for (result = *list; result; result = result->next) {
7273 if (memcmp(&result->key, key, sizeof(*key)) == 0) {
7274 mtx_unlock(&sscreen->shader_parts_mutex);
7275 return result;
7276 }
7277 }
7278
7279 /* Compile a new one. */
7280 result = CALLOC_STRUCT(si_shader_part);
7281 result->key = *key;
7282
7283 struct si_shader shader = {};
7284 struct si_shader_context ctx;
7285
7286 si_init_shader_ctx(&ctx, sscreen, compiler);
7287 ctx.shader = &shader;
7288 ctx.type = type;
7289
7290 switch (type) {
7291 case PIPE_SHADER_VERTEX:
7292 shader.key.as_ls = key->vs_prolog.as_ls;
7293 shader.key.as_es = key->vs_prolog.as_es;
7294 shader.key.as_ngg = key->vs_prolog.as_ngg;
7295 break;
7296 case PIPE_SHADER_TESS_CTRL:
7297 assert(!prolog);
7298 shader.key.part.tcs.epilog = key->tcs_epilog.states;
7299 break;
7300 case PIPE_SHADER_GEOMETRY:
7301 assert(prolog);
7302 break;
7303 case PIPE_SHADER_FRAGMENT:
7304 if (prolog)
7305 shader.key.part.ps.prolog = key->ps_prolog.states;
7306 else
7307 shader.key.part.ps.epilog = key->ps_epilog.states;
7308 break;
7309 default:
7310 unreachable("bad shader part");
7311 }
7312
7313 build(&ctx, key);
7314
7315 /* Compile. */
7316 si_llvm_optimize_module(&ctx);
7317
7318 if (si_compile_llvm(sscreen, &result->binary, &result->config, compiler,
7319 ctx.ac.module, debug, ctx.type, name, false)) {
7320 FREE(result);
7321 result = NULL;
7322 goto out;
7323 }
7324
7325 result->next = *list;
7326 *list = result;
7327
7328 out:
7329 si_llvm_dispose(&ctx);
7330 mtx_unlock(&sscreen->shader_parts_mutex);
7331 return result;
7332 }
7333
7334 static LLVMValueRef si_prolog_get_rw_buffers(struct si_shader_context *ctx)
7335 {
7336 LLVMValueRef ptr[2], list;
7337 bool merged_shader = is_merged_shader(ctx);
7338
7339 ptr[0] = LLVMGetParam(ctx->main_fn, (merged_shader ? 8 : 0) + SI_SGPR_RW_BUFFERS);
7340 list = LLVMBuildIntToPtr(ctx->ac.builder, ptr[0],
7341 ac_array_in_const32_addr_space(ctx->v4i32), "");
7342 return list;
7343 }
7344
7345 /**
7346 * Build the vertex shader prolog function.
7347 *
7348 * The inputs are the same as VS (a lot of SGPRs and 4 VGPR system values).
7349 * All inputs are returned unmodified. The vertex load indices are
7350 * stored after them, which will be used by the API VS for fetching inputs.
7351 *
7352 * For example, the expected outputs for instance_divisors[] = {0, 1, 2} are:
7353 * input_v0,
7354 * input_v1,
7355 * input_v2,
7356 * input_v3,
7357 * (VertexID + BaseVertex),
7358 * (InstanceID + StartInstance),
7359 * (InstanceID / 2 + StartInstance)
7360 */
7361 static void si_build_vs_prolog_function(struct si_shader_context *ctx,
7362 union si_shader_part_key *key)
7363 {
7364 struct si_function_info fninfo;
7365 LLVMTypeRef *returns;
7366 LLVMValueRef ret, func;
7367 int num_returns, i;
7368 unsigned first_vs_vgpr = key->vs_prolog.num_merged_next_stage_vgprs;
7369 unsigned num_input_vgprs = key->vs_prolog.num_merged_next_stage_vgprs + 4;
7370 LLVMValueRef input_vgprs[9];
7371 unsigned num_all_input_regs = key->vs_prolog.num_input_sgprs +
7372 num_input_vgprs;
7373 unsigned user_sgpr_base = key->vs_prolog.num_merged_next_stage_vgprs ? 8 : 0;
7374
7375 si_init_function_info(&fninfo);
7376
7377 /* 4 preloaded VGPRs + vertex load indices as prolog outputs */
7378 returns = alloca((num_all_input_regs + key->vs_prolog.last_input + 1) *
7379 sizeof(LLVMTypeRef));
7380 num_returns = 0;
7381
7382 /* Declare input and output SGPRs. */
7383 for (i = 0; i < key->vs_prolog.num_input_sgprs; i++) {
7384 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7385 returns[num_returns++] = ctx->i32;
7386 }
7387
7388 /* Preloaded VGPRs (outputs must be floats) */
7389 for (i = 0; i < num_input_vgprs; i++) {
7390 add_arg_assign(&fninfo, ARG_VGPR, ctx->i32, &input_vgprs[i]);
7391 returns[num_returns++] = ctx->f32;
7392 }
7393
7394 /* Vertex load indices. */
7395 for (i = 0; i <= key->vs_prolog.last_input; i++)
7396 returns[num_returns++] = ctx->f32;
7397
7398 /* Create the function. */
7399 si_create_function(ctx, "vs_prolog", returns, num_returns, &fninfo, 0);
7400 func = ctx->main_fn;
7401
7402 if (key->vs_prolog.num_merged_next_stage_vgprs) {
7403 if (!key->vs_prolog.is_monolithic)
7404 si_init_exec_from_input(ctx, 3, 0);
7405
7406 if (key->vs_prolog.as_ls &&
7407 ctx->screen->has_ls_vgpr_init_bug) {
7408 /* If there are no HS threads, SPI loads the LS VGPRs
7409 * starting at VGPR 0. Shift them back to where they
7410 * belong.
7411 */
7412 LLVMValueRef has_hs_threads =
7413 LLVMBuildICmp(ctx->ac.builder, LLVMIntNE,
7414 si_unpack_param(ctx, 3, 8, 8),
7415 ctx->i32_0, "");
7416
7417 for (i = 4; i > 0; --i) {
7418 input_vgprs[i + 1] =
7419 LLVMBuildSelect(ctx->ac.builder, has_hs_threads,
7420 input_vgprs[i + 1],
7421 input_vgprs[i - 1], "");
7422 }
7423 }
7424 }
7425
7426 unsigned vertex_id_vgpr = first_vs_vgpr;
7427 unsigned instance_id_vgpr =
7428 ctx->screen->info.chip_class >= GFX10 ?
7429 first_vs_vgpr + 3 :
7430 first_vs_vgpr + (key->vs_prolog.as_ls ? 2 : 1);
7431
7432 ctx->abi.vertex_id = input_vgprs[vertex_id_vgpr];
7433 ctx->abi.instance_id = input_vgprs[instance_id_vgpr];
7434
7435 /* InstanceID = VertexID >> 16;
7436 * VertexID = VertexID & 0xffff;
7437 */
7438 if (key->vs_prolog.states.unpack_instance_id_from_vertex_id) {
7439 ctx->abi.instance_id = LLVMBuildLShr(ctx->ac.builder, ctx->abi.vertex_id,
7440 LLVMConstInt(ctx->i32, 16, 0), "");
7441 ctx->abi.vertex_id = LLVMBuildAnd(ctx->ac.builder, ctx->abi.vertex_id,
7442 LLVMConstInt(ctx->i32, 0xffff, 0), "");
7443 }
7444
7445 /* Copy inputs to outputs. This should be no-op, as the registers match,
7446 * but it will prevent the compiler from overwriting them unintentionally.
7447 */
7448 ret = ctx->return_value;
7449 for (i = 0; i < key->vs_prolog.num_input_sgprs; i++) {
7450 LLVMValueRef p = LLVMGetParam(func, i);
7451 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, p, i, "");
7452 }
7453 for (i = 0; i < num_input_vgprs; i++) {
7454 LLVMValueRef p = input_vgprs[i];
7455
7456 if (i == vertex_id_vgpr)
7457 p = ctx->abi.vertex_id;
7458 else if (i == instance_id_vgpr)
7459 p = ctx->abi.instance_id;
7460
7461 p = ac_to_float(&ctx->ac, p);
7462 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, p,
7463 key->vs_prolog.num_input_sgprs + i, "");
7464 }
7465
7466 struct lp_build_if_state wrap_if_state;
7467 LLVMValueRef original_ret = ret;
7468 bool wrapped = false;
7469
7470 if (key->vs_prolog.is_monolithic && key->vs_prolog.as_ngg) {
7471 LLVMValueRef num_threads;
7472 LLVMValueRef ena;
7473
7474 num_threads = si_unpack_param(ctx, 3, 0, 8);
7475 ena = LLVMBuildICmp(ctx->ac.builder, LLVMIntULT,
7476 ac_get_thread_id(&ctx->ac), num_threads, "");
7477 lp_build_if(&wrap_if_state, &ctx->gallivm, ena);
7478 wrapped = true;
7479 }
7480
7481 /* Compute vertex load indices from instance divisors. */
7482 LLVMValueRef instance_divisor_constbuf = NULL;
7483
7484 if (key->vs_prolog.states.instance_divisor_is_fetched) {
7485 LLVMValueRef list = si_prolog_get_rw_buffers(ctx);
7486 LLVMValueRef buf_index =
7487 LLVMConstInt(ctx->i32, SI_VS_CONST_INSTANCE_DIVISORS, 0);
7488 instance_divisor_constbuf =
7489 ac_build_load_to_sgpr(&ctx->ac, list, buf_index);
7490 }
7491
7492 for (i = 0; i <= key->vs_prolog.last_input; i++) {
7493 bool divisor_is_one =
7494 key->vs_prolog.states.instance_divisor_is_one & (1u << i);
7495 bool divisor_is_fetched =
7496 key->vs_prolog.states.instance_divisor_is_fetched & (1u << i);
7497 LLVMValueRef index = NULL;
7498
7499 if (divisor_is_one) {
7500 index = ctx->abi.instance_id;
7501 } else if (divisor_is_fetched) {
7502 LLVMValueRef udiv_factors[4];
7503
7504 for (unsigned j = 0; j < 4; j++) {
7505 udiv_factors[j] =
7506 buffer_load_const(ctx, instance_divisor_constbuf,
7507 LLVMConstInt(ctx->i32, i*16 + j*4, 0));
7508 udiv_factors[j] = ac_to_integer(&ctx->ac, udiv_factors[j]);
7509 }
7510 /* The faster NUW version doesn't work when InstanceID == UINT_MAX.
7511 * Such InstanceID might not be achievable in a reasonable time though.
7512 */
7513 index = ac_build_fast_udiv_nuw(&ctx->ac, ctx->abi.instance_id,
7514 udiv_factors[0], udiv_factors[1],
7515 udiv_factors[2], udiv_factors[3]);
7516 }
7517
7518 if (divisor_is_one || divisor_is_fetched) {
7519 /* Add StartInstance. */
7520 index = LLVMBuildAdd(ctx->ac.builder, index,
7521 LLVMGetParam(ctx->main_fn, user_sgpr_base +
7522 SI_SGPR_START_INSTANCE), "");
7523 } else {
7524 /* VertexID + BaseVertex */
7525 index = LLVMBuildAdd(ctx->ac.builder,
7526 ctx->abi.vertex_id,
7527 LLVMGetParam(func, user_sgpr_base +
7528 SI_SGPR_BASE_VERTEX), "");
7529 }
7530
7531 index = ac_to_float(&ctx->ac, index);
7532 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, index,
7533 fninfo.num_params + i, "");
7534 }
7535
7536 if (wrapped) {
7537 lp_build_endif(&wrap_if_state);
7538
7539 LLVMValueRef values[2] = {
7540 ret,
7541 original_ret
7542 };
7543 LLVMBasicBlockRef bbs[2] = {
7544 wrap_if_state.true_block,
7545 wrap_if_state.entry_block
7546 };
7547 ret = ac_build_phi(&ctx->ac, LLVMTypeOf(ret), 2, values, bbs);
7548 }
7549
7550 si_llvm_build_ret(ctx, ret);
7551 }
7552
7553 static bool si_get_vs_prolog(struct si_screen *sscreen,
7554 struct ac_llvm_compiler *compiler,
7555 struct si_shader *shader,
7556 struct pipe_debug_callback *debug,
7557 struct si_shader *main_part,
7558 const struct si_vs_prolog_bits *key)
7559 {
7560 struct si_shader_selector *vs = main_part->selector;
7561
7562 if (!si_vs_needs_prolog(vs, key))
7563 return true;
7564
7565 /* Get the prolog. */
7566 union si_shader_part_key prolog_key;
7567 si_get_vs_prolog_key(&vs->info, main_part->info.num_input_sgprs,
7568 key, shader, &prolog_key);
7569
7570 shader->prolog =
7571 si_get_shader_part(sscreen, &sscreen->vs_prologs,
7572 PIPE_SHADER_VERTEX, true, &prolog_key, compiler,
7573 debug, si_build_vs_prolog_function,
7574 "Vertex Shader Prolog");
7575 return shader->prolog != NULL;
7576 }
7577
7578 /**
7579 * Select and compile (or reuse) vertex shader parts (prolog & epilog).
7580 */
7581 static bool si_shader_select_vs_parts(struct si_screen *sscreen,
7582 struct ac_llvm_compiler *compiler,
7583 struct si_shader *shader,
7584 struct pipe_debug_callback *debug)
7585 {
7586 return si_get_vs_prolog(sscreen, compiler, shader, debug, shader,
7587 &shader->key.part.vs.prolog);
7588 }
7589
7590 /**
7591 * Compile the TCS epilog function. This writes tesselation factors to memory
7592 * based on the output primitive type of the tesselator (determined by TES).
7593 */
7594 static void si_build_tcs_epilog_function(struct si_shader_context *ctx,
7595 union si_shader_part_key *key)
7596 {
7597 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
7598 struct si_function_info fninfo;
7599 LLVMValueRef func;
7600
7601 si_init_function_info(&fninfo);
7602
7603 if (ctx->screen->info.chip_class >= GFX9) {
7604 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7605 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7606 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7607 add_arg(&fninfo, ARG_SGPR, ctx->i32); /* wave info */
7608 ctx->param_tcs_factor_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7609 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7610 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7611 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7612 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7613 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7614 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7615 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7616 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7617 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7618 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7619 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7620 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7621 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7622 ctx->param_tcs_out_lds_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7623 } else {
7624 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7625 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7626 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7627 add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
7628 ctx->param_tcs_offchip_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7629 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7630 ctx->param_tcs_out_lds_layout = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7631 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7632 ctx->param_tcs_offchip_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7633 ctx->param_tcs_factor_offset = add_arg(&fninfo, ARG_SGPR, ctx->i32);
7634 }
7635
7636 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* VGPR gap */
7637 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* VGPR gap */
7638 unsigned tess_factors_idx =
7639 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* patch index within the wave (REL_PATCH_ID) */
7640 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* invocation ID within the patch */
7641 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* LDS offset where tess factors should be loaded from */
7642
7643 for (unsigned i = 0; i < 6; i++)
7644 add_arg(&fninfo, ARG_VGPR, ctx->i32); /* tess factors */
7645
7646 /* Create the function. */
7647 si_create_function(ctx, "tcs_epilog", NULL, 0, &fninfo,
7648 ctx->screen->info.chip_class >= GFX7 ? 128 : 64);
7649 ac_declare_lds_as_pointer(&ctx->ac);
7650 func = ctx->main_fn;
7651
7652 LLVMValueRef invoc0_tess_factors[6];
7653 for (unsigned i = 0; i < 6; i++)
7654 invoc0_tess_factors[i] = LLVMGetParam(func, tess_factors_idx + 3 + i);
7655
7656 si_write_tess_factors(bld_base,
7657 LLVMGetParam(func, tess_factors_idx),
7658 LLVMGetParam(func, tess_factors_idx + 1),
7659 LLVMGetParam(func, tess_factors_idx + 2),
7660 invoc0_tess_factors, invoc0_tess_factors + 4);
7661
7662 LLVMBuildRetVoid(ctx->ac.builder);
7663 }
7664
7665 /**
7666 * Select and compile (or reuse) TCS parts (epilog).
7667 */
7668 static bool si_shader_select_tcs_parts(struct si_screen *sscreen,
7669 struct ac_llvm_compiler *compiler,
7670 struct si_shader *shader,
7671 struct pipe_debug_callback *debug)
7672 {
7673 if (sscreen->info.chip_class >= GFX9) {
7674 struct si_shader *ls_main_part =
7675 shader->key.part.tcs.ls->main_shader_part_ls;
7676
7677 if (!si_get_vs_prolog(sscreen, compiler, shader, debug, ls_main_part,
7678 &shader->key.part.tcs.ls_prolog))
7679 return false;
7680
7681 shader->previous_stage = ls_main_part;
7682 }
7683
7684 /* Get the epilog. */
7685 union si_shader_part_key epilog_key;
7686 memset(&epilog_key, 0, sizeof(epilog_key));
7687 epilog_key.tcs_epilog.states = shader->key.part.tcs.epilog;
7688
7689 shader->epilog = si_get_shader_part(sscreen, &sscreen->tcs_epilogs,
7690 PIPE_SHADER_TESS_CTRL, false,
7691 &epilog_key, compiler, debug,
7692 si_build_tcs_epilog_function,
7693 "Tessellation Control Shader Epilog");
7694 return shader->epilog != NULL;
7695 }
7696
7697 /**
7698 * Select and compile (or reuse) GS parts (prolog).
7699 */
7700 static bool si_shader_select_gs_parts(struct si_screen *sscreen,
7701 struct ac_llvm_compiler *compiler,
7702 struct si_shader *shader,
7703 struct pipe_debug_callback *debug)
7704 {
7705 if (sscreen->info.chip_class >= GFX9) {
7706 struct si_shader *es_main_part =
7707 shader->key.part.gs.es->main_shader_part_es;
7708
7709 if (shader->key.part.gs.es->type == PIPE_SHADER_VERTEX &&
7710 !si_get_vs_prolog(sscreen, compiler, shader, debug, es_main_part,
7711 &shader->key.part.gs.vs_prolog))
7712 return false;
7713
7714 shader->previous_stage = es_main_part;
7715 }
7716
7717 if (!shader->key.part.gs.prolog.tri_strip_adj_fix)
7718 return true;
7719
7720 union si_shader_part_key prolog_key;
7721 memset(&prolog_key, 0, sizeof(prolog_key));
7722 prolog_key.gs_prolog.states = shader->key.part.gs.prolog;
7723
7724 shader->prolog2 = si_get_shader_part(sscreen, &sscreen->gs_prologs,
7725 PIPE_SHADER_GEOMETRY, true,
7726 &prolog_key, compiler, debug,
7727 si_build_gs_prolog_function,
7728 "Geometry Shader Prolog");
7729 return shader->prolog2 != NULL;
7730 }
7731
7732 /**
7733 * Build the pixel shader prolog function. This handles:
7734 * - two-side color selection and interpolation
7735 * - overriding interpolation parameters for the API PS
7736 * - polygon stippling
7737 *
7738 * All preloaded SGPRs and VGPRs are passed through unmodified unless they are
7739 * overriden by other states. (e.g. per-sample interpolation)
7740 * Interpolated colors are stored after the preloaded VGPRs.
7741 */
7742 static void si_build_ps_prolog_function(struct si_shader_context *ctx,
7743 union si_shader_part_key *key)
7744 {
7745 struct si_function_info fninfo;
7746 LLVMValueRef ret, func;
7747 int num_returns, i, num_color_channels;
7748
7749 assert(si_need_ps_prolog(key));
7750
7751 si_init_function_info(&fninfo);
7752
7753 /* Declare inputs. */
7754 for (i = 0; i < key->ps_prolog.num_input_sgprs; i++)
7755 add_arg(&fninfo, ARG_SGPR, ctx->i32);
7756
7757 for (i = 0; i < key->ps_prolog.num_input_vgprs; i++)
7758 add_arg(&fninfo, ARG_VGPR, ctx->f32);
7759
7760 /* Declare outputs (same as inputs + add colors if needed) */
7761 num_returns = fninfo.num_params;
7762 num_color_channels = util_bitcount(key->ps_prolog.colors_read);
7763 for (i = 0; i < num_color_channels; i++)
7764 fninfo.types[num_returns++] = ctx->f32;
7765
7766 /* Create the function. */
7767 si_create_function(ctx, "ps_prolog", fninfo.types, num_returns,
7768 &fninfo, 0);
7769 func = ctx->main_fn;
7770
7771 /* Copy inputs to outputs. This should be no-op, as the registers match,
7772 * but it will prevent the compiler from overwriting them unintentionally.
7773 */
7774 ret = ctx->return_value;
7775 for (i = 0; i < fninfo.num_params; i++) {
7776 LLVMValueRef p = LLVMGetParam(func, i);
7777 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, p, i, "");
7778 }
7779
7780 /* Polygon stippling. */
7781 if (key->ps_prolog.states.poly_stipple) {
7782 /* POS_FIXED_PT is always last. */
7783 unsigned pos = key->ps_prolog.num_input_sgprs +
7784 key->ps_prolog.num_input_vgprs - 1;
7785 LLVMValueRef list = si_prolog_get_rw_buffers(ctx);
7786
7787 si_llvm_emit_polygon_stipple(ctx, list, pos);
7788 }
7789
7790 if (key->ps_prolog.states.bc_optimize_for_persp ||
7791 key->ps_prolog.states.bc_optimize_for_linear) {
7792 unsigned i, base = key->ps_prolog.num_input_sgprs;
7793 LLVMValueRef center[2], centroid[2], tmp, bc_optimize;
7794
7795 /* The shader should do: if (PRIM_MASK[31]) CENTROID = CENTER;
7796 * The hw doesn't compute CENTROID if the whole wave only
7797 * contains fully-covered quads.
7798 *
7799 * PRIM_MASK is after user SGPRs.
7800 */
7801 bc_optimize = LLVMGetParam(func, SI_PS_NUM_USER_SGPR);
7802 bc_optimize = LLVMBuildLShr(ctx->ac.builder, bc_optimize,
7803 LLVMConstInt(ctx->i32, 31, 0), "");
7804 bc_optimize = LLVMBuildTrunc(ctx->ac.builder, bc_optimize,
7805 ctx->i1, "");
7806
7807 if (key->ps_prolog.states.bc_optimize_for_persp) {
7808 /* Read PERSP_CENTER. */
7809 for (i = 0; i < 2; i++)
7810 center[i] = LLVMGetParam(func, base + 2 + i);
7811 /* Read PERSP_CENTROID. */
7812 for (i = 0; i < 2; i++)
7813 centroid[i] = LLVMGetParam(func, base + 4 + i);
7814 /* Select PERSP_CENTROID. */
7815 for (i = 0; i < 2; i++) {
7816 tmp = LLVMBuildSelect(ctx->ac.builder, bc_optimize,
7817 center[i], centroid[i], "");
7818 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7819 tmp, base + 4 + i, "");
7820 }
7821 }
7822 if (key->ps_prolog.states.bc_optimize_for_linear) {
7823 /* Read LINEAR_CENTER. */
7824 for (i = 0; i < 2; i++)
7825 center[i] = LLVMGetParam(func, base + 8 + i);
7826 /* Read LINEAR_CENTROID. */
7827 for (i = 0; i < 2; i++)
7828 centroid[i] = LLVMGetParam(func, base + 10 + i);
7829 /* Select LINEAR_CENTROID. */
7830 for (i = 0; i < 2; i++) {
7831 tmp = LLVMBuildSelect(ctx->ac.builder, bc_optimize,
7832 center[i], centroid[i], "");
7833 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7834 tmp, base + 10 + i, "");
7835 }
7836 }
7837 }
7838
7839 /* Force per-sample interpolation. */
7840 if (key->ps_prolog.states.force_persp_sample_interp) {
7841 unsigned i, base = key->ps_prolog.num_input_sgprs;
7842 LLVMValueRef persp_sample[2];
7843
7844 /* Read PERSP_SAMPLE. */
7845 for (i = 0; i < 2; i++)
7846 persp_sample[i] = LLVMGetParam(func, base + i);
7847 /* Overwrite PERSP_CENTER. */
7848 for (i = 0; i < 2; i++)
7849 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7850 persp_sample[i], base + 2 + i, "");
7851 /* Overwrite PERSP_CENTROID. */
7852 for (i = 0; i < 2; i++)
7853 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7854 persp_sample[i], base + 4 + i, "");
7855 }
7856 if (key->ps_prolog.states.force_linear_sample_interp) {
7857 unsigned i, base = key->ps_prolog.num_input_sgprs;
7858 LLVMValueRef linear_sample[2];
7859
7860 /* Read LINEAR_SAMPLE. */
7861 for (i = 0; i < 2; i++)
7862 linear_sample[i] = LLVMGetParam(func, base + 6 + i);
7863 /* Overwrite LINEAR_CENTER. */
7864 for (i = 0; i < 2; i++)
7865 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7866 linear_sample[i], base + 8 + i, "");
7867 /* Overwrite LINEAR_CENTROID. */
7868 for (i = 0; i < 2; i++)
7869 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7870 linear_sample[i], base + 10 + i, "");
7871 }
7872
7873 /* Force center interpolation. */
7874 if (key->ps_prolog.states.force_persp_center_interp) {
7875 unsigned i, base = key->ps_prolog.num_input_sgprs;
7876 LLVMValueRef persp_center[2];
7877
7878 /* Read PERSP_CENTER. */
7879 for (i = 0; i < 2; i++)
7880 persp_center[i] = LLVMGetParam(func, base + 2 + i);
7881 /* Overwrite PERSP_SAMPLE. */
7882 for (i = 0; i < 2; i++)
7883 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7884 persp_center[i], base + i, "");
7885 /* Overwrite PERSP_CENTROID. */
7886 for (i = 0; i < 2; i++)
7887 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7888 persp_center[i], base + 4 + i, "");
7889 }
7890 if (key->ps_prolog.states.force_linear_center_interp) {
7891 unsigned i, base = key->ps_prolog.num_input_sgprs;
7892 LLVMValueRef linear_center[2];
7893
7894 /* Read LINEAR_CENTER. */
7895 for (i = 0; i < 2; i++)
7896 linear_center[i] = LLVMGetParam(func, base + 8 + i);
7897 /* Overwrite LINEAR_SAMPLE. */
7898 for (i = 0; i < 2; i++)
7899 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7900 linear_center[i], base + 6 + i, "");
7901 /* Overwrite LINEAR_CENTROID. */
7902 for (i = 0; i < 2; i++)
7903 ret = LLVMBuildInsertValue(ctx->ac.builder, ret,
7904 linear_center[i], base + 10 + i, "");
7905 }
7906
7907 /* Interpolate colors. */
7908 unsigned color_out_idx = 0;
7909 for (i = 0; i < 2; i++) {
7910 unsigned writemask = (key->ps_prolog.colors_read >> (i * 4)) & 0xf;
7911 unsigned face_vgpr = key->ps_prolog.num_input_sgprs +
7912 key->ps_prolog.face_vgpr_index;
7913 LLVMValueRef interp[2], color[4];
7914 LLVMValueRef interp_ij = NULL, prim_mask = NULL, face = NULL;
7915
7916 if (!writemask)
7917 continue;
7918
7919 /* If the interpolation qualifier is not CONSTANT (-1). */
7920 if (key->ps_prolog.color_interp_vgpr_index[i] != -1) {
7921 unsigned interp_vgpr = key->ps_prolog.num_input_sgprs +
7922 key->ps_prolog.color_interp_vgpr_index[i];
7923
7924 /* Get the (i,j) updated by bc_optimize handling. */
7925 interp[0] = LLVMBuildExtractValue(ctx->ac.builder, ret,
7926 interp_vgpr, "");
7927 interp[1] = LLVMBuildExtractValue(ctx->ac.builder, ret,
7928 interp_vgpr + 1, "");
7929 interp_ij = ac_build_gather_values(&ctx->ac, interp, 2);
7930 }
7931
7932 /* Use the absolute location of the input. */
7933 prim_mask = LLVMGetParam(func, SI_PS_NUM_USER_SGPR);
7934
7935 if (key->ps_prolog.states.color_two_side) {
7936 face = LLVMGetParam(func, face_vgpr);
7937 face = ac_to_integer(&ctx->ac, face);
7938 }
7939
7940 interp_fs_input(ctx,
7941 key->ps_prolog.color_attr_index[i],
7942 TGSI_SEMANTIC_COLOR, i,
7943 key->ps_prolog.num_interp_inputs,
7944 key->ps_prolog.colors_read, interp_ij,
7945 prim_mask, face, color);
7946
7947 while (writemask) {
7948 unsigned chan = u_bit_scan(&writemask);
7949 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, color[chan],
7950 fninfo.num_params + color_out_idx++, "");
7951 }
7952 }
7953
7954 /* Section 15.2.2 (Shader Inputs) of the OpenGL 4.5 (Core Profile) spec
7955 * says:
7956 *
7957 * "When per-sample shading is active due to the use of a fragment
7958 * input qualified by sample or due to the use of the gl_SampleID
7959 * or gl_SamplePosition variables, only the bit for the current
7960 * sample is set in gl_SampleMaskIn. When state specifies multiple
7961 * fragment shader invocations for a given fragment, the sample
7962 * mask for any single fragment shader invocation may specify a
7963 * subset of the covered samples for the fragment. In this case,
7964 * the bit corresponding to each covered sample will be set in
7965 * exactly one fragment shader invocation."
7966 *
7967 * The samplemask loaded by hardware is always the coverage of the
7968 * entire pixel/fragment, so mask bits out based on the sample ID.
7969 */
7970 if (key->ps_prolog.states.samplemask_log_ps_iter) {
7971 /* The bit pattern matches that used by fixed function fragment
7972 * processing. */
7973 static const uint16_t ps_iter_masks[] = {
7974 0xffff, /* not used */
7975 0x5555,
7976 0x1111,
7977 0x0101,
7978 0x0001,
7979 };
7980 assert(key->ps_prolog.states.samplemask_log_ps_iter < ARRAY_SIZE(ps_iter_masks));
7981
7982 uint32_t ps_iter_mask = ps_iter_masks[key->ps_prolog.states.samplemask_log_ps_iter];
7983 unsigned ancillary_vgpr = key->ps_prolog.num_input_sgprs +
7984 key->ps_prolog.ancillary_vgpr_index;
7985 LLVMValueRef sampleid = si_unpack_param(ctx, ancillary_vgpr, 8, 4);
7986 LLVMValueRef samplemask = LLVMGetParam(func, ancillary_vgpr + 1);
7987
7988 samplemask = ac_to_integer(&ctx->ac, samplemask);
7989 samplemask = LLVMBuildAnd(
7990 ctx->ac.builder,
7991 samplemask,
7992 LLVMBuildShl(ctx->ac.builder,
7993 LLVMConstInt(ctx->i32, ps_iter_mask, false),
7994 sampleid, ""),
7995 "");
7996 samplemask = ac_to_float(&ctx->ac, samplemask);
7997
7998 ret = LLVMBuildInsertValue(ctx->ac.builder, ret, samplemask,
7999 ancillary_vgpr + 1, "");
8000 }
8001
8002 /* Tell LLVM to insert WQM instruction sequence when needed. */
8003 if (key->ps_prolog.wqm) {
8004 LLVMAddTargetDependentFunctionAttr(func,
8005 "amdgpu-ps-wqm-outputs", "");
8006 }
8007
8008 si_llvm_build_ret(ctx, ret);
8009 }
8010
8011 /**
8012 * Build the pixel shader epilog function. This handles everything that must be
8013 * emulated for pixel shader exports. (alpha-test, format conversions, etc)
8014 */
8015 static void si_build_ps_epilog_function(struct si_shader_context *ctx,
8016 union si_shader_part_key *key)
8017 {
8018 struct lp_build_tgsi_context *bld_base = &ctx->bld_base;
8019 struct si_function_info fninfo;
8020 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
8021 int i;
8022 struct si_ps_exports exp = {};
8023
8024 si_init_function_info(&fninfo);
8025
8026 /* Declare input SGPRs. */
8027 ctx->param_rw_buffers = add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
8028 ctx->param_bindless_samplers_and_images = add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
8029 ctx->param_const_and_shader_buffers = add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
8030 ctx->param_samplers_and_images = add_arg(&fninfo, ARG_SGPR, ctx->ac.intptr);
8031 add_arg_checked(&fninfo, ARG_SGPR, ctx->f32, SI_PARAM_ALPHA_REF);
8032
8033 /* Declare input VGPRs. */
8034 unsigned required_num_params =
8035 fninfo.num_sgpr_params +
8036 util_bitcount(key->ps_epilog.colors_written) * 4 +
8037 key->ps_epilog.writes_z +
8038 key->ps_epilog.writes_stencil +
8039 key->ps_epilog.writes_samplemask;
8040
8041 required_num_params = MAX2(required_num_params,
8042 fninfo.num_sgpr_params + PS_EPILOG_SAMPLEMASK_MIN_LOC + 1);
8043
8044 while (fninfo.num_params < required_num_params)
8045 add_arg(&fninfo, ARG_VGPR, ctx->f32);
8046
8047 /* Create the function. */
8048 si_create_function(ctx, "ps_epilog", NULL, 0, &fninfo, 0);
8049 /* Disable elimination of unused inputs. */
8050 ac_llvm_add_target_dep_function_attr(ctx->main_fn,
8051 "InitialPSInputAddr", 0xffffff);
8052
8053 /* Process colors. */
8054 unsigned vgpr = fninfo.num_sgpr_params;
8055 unsigned colors_written = key->ps_epilog.colors_written;
8056 int last_color_export = -1;
8057
8058 /* Find the last color export. */
8059 if (!key->ps_epilog.writes_z &&
8060 !key->ps_epilog.writes_stencil &&
8061 !key->ps_epilog.writes_samplemask) {
8062 unsigned spi_format = key->ps_epilog.states.spi_shader_col_format;
8063
8064 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
8065 if (colors_written == 0x1 && key->ps_epilog.states.last_cbuf > 0) {
8066 /* Just set this if any of the colorbuffers are enabled. */
8067 if (spi_format &
8068 ((1ull << (4 * (key->ps_epilog.states.last_cbuf + 1))) - 1))
8069 last_color_export = 0;
8070 } else {
8071 for (i = 0; i < 8; i++)
8072 if (colors_written & (1 << i) &&
8073 (spi_format >> (i * 4)) & 0xf)
8074 last_color_export = i;
8075 }
8076 }
8077
8078 while (colors_written) {
8079 LLVMValueRef color[4];
8080 int mrt = u_bit_scan(&colors_written);
8081
8082 for (i = 0; i < 4; i++)
8083 color[i] = LLVMGetParam(ctx->main_fn, vgpr++);
8084
8085 si_export_mrt_color(bld_base, color, mrt,
8086 fninfo.num_params - 1,
8087 mrt == last_color_export, &exp);
8088 }
8089
8090 /* Process depth, stencil, samplemask. */
8091 if (key->ps_epilog.writes_z)
8092 depth = LLVMGetParam(ctx->main_fn, vgpr++);
8093 if (key->ps_epilog.writes_stencil)
8094 stencil = LLVMGetParam(ctx->main_fn, vgpr++);
8095 if (key->ps_epilog.writes_samplemask)
8096 samplemask = LLVMGetParam(ctx->main_fn, vgpr++);
8097
8098 if (depth || stencil || samplemask)
8099 si_export_mrt_z(bld_base, depth, stencil, samplemask, &exp);
8100 else if (last_color_export == -1)
8101 ac_build_export_null(&ctx->ac);
8102
8103 if (exp.num)
8104 si_emit_ps_exports(ctx, &exp);
8105
8106 /* Compile. */
8107 LLVMBuildRetVoid(ctx->ac.builder);
8108 }
8109
8110 /**
8111 * Select and compile (or reuse) pixel shader parts (prolog & epilog).
8112 */
8113 static bool si_shader_select_ps_parts(struct si_screen *sscreen,
8114 struct ac_llvm_compiler *compiler,
8115 struct si_shader *shader,
8116 struct pipe_debug_callback *debug)
8117 {
8118 union si_shader_part_key prolog_key;
8119 union si_shader_part_key epilog_key;
8120
8121 /* Get the prolog. */
8122 si_get_ps_prolog_key(shader, &prolog_key, true);
8123
8124 /* The prolog is a no-op if these aren't set. */
8125 if (si_need_ps_prolog(&prolog_key)) {
8126 shader->prolog =
8127 si_get_shader_part(sscreen, &sscreen->ps_prologs,
8128 PIPE_SHADER_FRAGMENT, true,
8129 &prolog_key, compiler, debug,
8130 si_build_ps_prolog_function,
8131 "Fragment Shader Prolog");
8132 if (!shader->prolog)
8133 return false;
8134 }
8135
8136 /* Get the epilog. */
8137 si_get_ps_epilog_key(shader, &epilog_key);
8138
8139 shader->epilog =
8140 si_get_shader_part(sscreen, &sscreen->ps_epilogs,
8141 PIPE_SHADER_FRAGMENT, false,
8142 &epilog_key, compiler, debug,
8143 si_build_ps_epilog_function,
8144 "Fragment Shader Epilog");
8145 if (!shader->epilog)
8146 return false;
8147
8148 /* Enable POS_FIXED_PT if polygon stippling is enabled. */
8149 if (shader->key.part.ps.prolog.poly_stipple) {
8150 shader->config.spi_ps_input_ena |= S_0286CC_POS_FIXED_PT_ENA(1);
8151 assert(G_0286CC_POS_FIXED_PT_ENA(shader->config.spi_ps_input_addr));
8152 }
8153
8154 /* Set up the enable bits for per-sample shading if needed. */
8155 if (shader->key.part.ps.prolog.force_persp_sample_interp &&
8156 (G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_ena) ||
8157 G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8158 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTER_ENA;
8159 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTROID_ENA;
8160 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_SAMPLE_ENA(1);
8161 }
8162 if (shader->key.part.ps.prolog.force_linear_sample_interp &&
8163 (G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_ena) ||
8164 G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8165 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTER_ENA;
8166 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTROID_ENA;
8167 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_SAMPLE_ENA(1);
8168 }
8169 if (shader->key.part.ps.prolog.force_persp_center_interp &&
8170 (G_0286CC_PERSP_SAMPLE_ENA(shader->config.spi_ps_input_ena) ||
8171 G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8172 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_SAMPLE_ENA;
8173 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTROID_ENA;
8174 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_CENTER_ENA(1);
8175 }
8176 if (shader->key.part.ps.prolog.force_linear_center_interp &&
8177 (G_0286CC_LINEAR_SAMPLE_ENA(shader->config.spi_ps_input_ena) ||
8178 G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8179 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_SAMPLE_ENA;
8180 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTROID_ENA;
8181 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_CENTER_ENA(1);
8182 }
8183
8184 /* POW_W_FLOAT requires that one of the perspective weights is enabled. */
8185 if (G_0286CC_POS_W_FLOAT_ENA(shader->config.spi_ps_input_ena) &&
8186 !(shader->config.spi_ps_input_ena & 0xf)) {
8187 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_CENTER_ENA(1);
8188 assert(G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_addr));
8189 }
8190
8191 /* At least one pair of interpolation weights must be enabled. */
8192 if (!(shader->config.spi_ps_input_ena & 0x7f)) {
8193 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_CENTER_ENA(1);
8194 assert(G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_addr));
8195 }
8196
8197 /* Samplemask fixup requires the sample ID. */
8198 if (shader->key.part.ps.prolog.samplemask_log_ps_iter) {
8199 shader->config.spi_ps_input_ena |= S_0286CC_ANCILLARY_ENA(1);
8200 assert(G_0286CC_ANCILLARY_ENA(shader->config.spi_ps_input_addr));
8201 }
8202
8203 /* The sample mask input is always enabled, because the API shader always
8204 * passes it through to the epilog. Disable it here if it's unused.
8205 */
8206 if (!shader->key.part.ps.epilog.poly_line_smoothing &&
8207 !shader->selector->info.reads_samplemask)
8208 shader->config.spi_ps_input_ena &= C_0286CC_SAMPLE_COVERAGE_ENA;
8209
8210 return true;
8211 }
8212
8213 void si_multiwave_lds_size_workaround(struct si_screen *sscreen,
8214 unsigned *lds_size)
8215 {
8216 /* If tessellation is all offchip and on-chip GS isn't used, this
8217 * workaround is not needed.
8218 */
8219 return;
8220
8221 /* SPI barrier management bug:
8222 * Make sure we have at least 4k of LDS in use to avoid the bug.
8223 * It applies to workgroup sizes of more than one wavefront.
8224 */
8225 if (sscreen->info.family == CHIP_BONAIRE ||
8226 sscreen->info.family == CHIP_KABINI)
8227 *lds_size = MAX2(*lds_size, 8);
8228 }
8229
8230 static void si_fix_resource_usage(struct si_screen *sscreen,
8231 struct si_shader *shader)
8232 {
8233 unsigned min_sgprs = shader->info.num_input_sgprs + 2; /* VCC */
8234
8235 shader->config.num_sgprs = MAX2(shader->config.num_sgprs, min_sgprs);
8236
8237 if (shader->selector->type == PIPE_SHADER_COMPUTE &&
8238 si_get_max_workgroup_size(shader) > 64) {
8239 si_multiwave_lds_size_workaround(sscreen,
8240 &shader->config.lds_size);
8241 }
8242 }
8243
8244 bool si_shader_create(struct si_screen *sscreen, struct ac_llvm_compiler *compiler,
8245 struct si_shader *shader,
8246 struct pipe_debug_callback *debug)
8247 {
8248 struct si_shader_selector *sel = shader->selector;
8249 struct si_shader *mainp = *si_get_main_shader_part(sel, &shader->key);
8250 int r;
8251
8252 /* LS, ES, VS are compiled on demand if the main part hasn't been
8253 * compiled for that stage.
8254 *
8255 * GS are compiled on demand if the main part hasn't been compiled
8256 * for the chosen NGG-ness.
8257 *
8258 * Vertex shaders are compiled on demand when a vertex fetch
8259 * workaround must be applied.
8260 */
8261 if (shader->is_monolithic) {
8262 /* Monolithic shader (compiled as a whole, has many variants,
8263 * may take a long time to compile).
8264 */
8265 r = si_compile_tgsi_shader(sscreen, compiler, shader, debug);
8266 if (r)
8267 return false;
8268 } else {
8269 /* The shader consists of several parts:
8270 *
8271 * - the middle part is the user shader, it has 1 variant only
8272 * and it was compiled during the creation of the shader
8273 * selector
8274 * - the prolog part is inserted at the beginning
8275 * - the epilog part is inserted at the end
8276 *
8277 * The prolog and epilog have many (but simple) variants.
8278 *
8279 * Starting with gfx9, geometry and tessellation control
8280 * shaders also contain the prolog and user shader parts of
8281 * the previous shader stage.
8282 */
8283
8284 if (!mainp)
8285 return false;
8286
8287 /* Copy the compiled TGSI shader data over. */
8288 shader->is_binary_shared = true;
8289 shader->binary = mainp->binary;
8290 shader->config = mainp->config;
8291 shader->info.num_input_sgprs = mainp->info.num_input_sgprs;
8292 shader->info.num_input_vgprs = mainp->info.num_input_vgprs;
8293 shader->info.face_vgpr_index = mainp->info.face_vgpr_index;
8294 shader->info.ancillary_vgpr_index = mainp->info.ancillary_vgpr_index;
8295 memcpy(shader->info.vs_output_param_offset,
8296 mainp->info.vs_output_param_offset,
8297 sizeof(mainp->info.vs_output_param_offset));
8298 shader->info.uses_instanceid = mainp->info.uses_instanceid;
8299 shader->info.nr_pos_exports = mainp->info.nr_pos_exports;
8300 shader->info.nr_param_exports = mainp->info.nr_param_exports;
8301
8302 /* Select prologs and/or epilogs. */
8303 switch (sel->type) {
8304 case PIPE_SHADER_VERTEX:
8305 if (!si_shader_select_vs_parts(sscreen, compiler, shader, debug))
8306 return false;
8307 break;
8308 case PIPE_SHADER_TESS_CTRL:
8309 if (!si_shader_select_tcs_parts(sscreen, compiler, shader, debug))
8310 return false;
8311 break;
8312 case PIPE_SHADER_TESS_EVAL:
8313 break;
8314 case PIPE_SHADER_GEOMETRY:
8315 if (!si_shader_select_gs_parts(sscreen, compiler, shader, debug))
8316 return false;
8317 break;
8318 case PIPE_SHADER_FRAGMENT:
8319 if (!si_shader_select_ps_parts(sscreen, compiler, shader, debug))
8320 return false;
8321
8322 /* Make sure we have at least as many VGPRs as there
8323 * are allocated inputs.
8324 */
8325 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8326 shader->info.num_input_vgprs);
8327 break;
8328 default:;
8329 }
8330
8331 /* Update SGPR and VGPR counts. */
8332 if (shader->prolog) {
8333 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8334 shader->prolog->config.num_sgprs);
8335 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8336 shader->prolog->config.num_vgprs);
8337 }
8338 if (shader->previous_stage) {
8339 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8340 shader->previous_stage->config.num_sgprs);
8341 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8342 shader->previous_stage->config.num_vgprs);
8343 shader->config.spilled_sgprs =
8344 MAX2(shader->config.spilled_sgprs,
8345 shader->previous_stage->config.spilled_sgprs);
8346 shader->config.spilled_vgprs =
8347 MAX2(shader->config.spilled_vgprs,
8348 shader->previous_stage->config.spilled_vgprs);
8349 shader->info.private_mem_vgprs =
8350 MAX2(shader->info.private_mem_vgprs,
8351 shader->previous_stage->info.private_mem_vgprs);
8352 shader->config.scratch_bytes_per_wave =
8353 MAX2(shader->config.scratch_bytes_per_wave,
8354 shader->previous_stage->config.scratch_bytes_per_wave);
8355 shader->info.uses_instanceid |=
8356 shader->previous_stage->info.uses_instanceid;
8357 }
8358 if (shader->prolog2) {
8359 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8360 shader->prolog2->config.num_sgprs);
8361 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8362 shader->prolog2->config.num_vgprs);
8363 }
8364 if (shader->epilog) {
8365 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8366 shader->epilog->config.num_sgprs);
8367 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8368 shader->epilog->config.num_vgprs);
8369 }
8370 si_calculate_max_simd_waves(shader);
8371 }
8372
8373 if (shader->key.as_ngg) {
8374 assert(!shader->key.as_es && !shader->key.as_ls);
8375 gfx10_ngg_calculate_subgroup_info(shader);
8376 } else if (sscreen->info.chip_class >= GFX9 && sel->type == PIPE_SHADER_GEOMETRY) {
8377 gfx9_get_gs_info(shader->previous_stage_sel, sel, &shader->gs_info);
8378 }
8379
8380 si_fix_resource_usage(sscreen, shader);
8381 si_shader_dump(sscreen, shader, debug, stderr, true);
8382
8383 /* Upload. */
8384 if (!si_shader_binary_upload(sscreen, shader, 0)) {
8385 fprintf(stderr, "LLVM failed to upload shader\n");
8386 return false;
8387 }
8388
8389 return true;
8390 }
8391
8392 void si_shader_destroy(struct si_shader *shader)
8393 {
8394 if (shader->scratch_bo)
8395 si_resource_reference(&shader->scratch_bo, NULL);
8396
8397 si_resource_reference(&shader->bo, NULL);
8398
8399 if (!shader->is_binary_shared)
8400 si_shader_binary_clean(&shader->binary);
8401
8402 free(shader->shader_log);
8403 }