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