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