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