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