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