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