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