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