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