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