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