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