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