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