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