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