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