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