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