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