amd/common: unify cube map coordinate handling between radeonsi and radv
[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->soa.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->soa.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->soa.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->soa.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->soa.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->soa.bld_base);
374 struct gallivm_state *gallivm = radeon_bld->soa.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->soa.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->soa.bld_base.base.gallivm;
512 LLVMValueRef result;
513
514 result = ctx->soa.addr[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->soa.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->soa.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->soa.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->soa.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->soa.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->soa.bld_base.base;
1437 struct si_shader_context *ctx =
1438 si_shader_context(&radeon_bld->soa.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->soa.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->soa.bld_base);
1548 struct lp_build_context *uint_bld = &radeon_bld->soa.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->soa.bld_base);
1576 struct lp_build_context *bld = &radeon_bld->soa.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->soa.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->soa.bld_base,
1654 TGSI_OPCODE_FRC, pos[0]);
1655 pos[1] = lp_build_emit_llvm_unary(&radeon_bld->soa.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->soa.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->soa.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->soa.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->soa.addr[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 =
1922 &ctx->soa.bld_base.uint_bld;
1923 struct lp_build_context *base = &bld_base->base;
1924 struct gallivm_state *gallivm = base->gallivm;
1925 LLVMBuilderRef builder = base->gallivm->builder;
1926 LLVMValueRef val[4];
1927 unsigned spi_shader_col_format = V_028714_SPI_SHADER_32_ABGR;
1928 unsigned chan;
1929 bool is_int8;
1930
1931 /* Default is 0xf. Adjusted below depending on the format. */
1932 args[0] = lp_build_const_int32(base->gallivm, 0xf); /* writemask */
1933
1934 /* Specify whether the EXEC mask represents the valid mask */
1935 args[1] = uint->zero;
1936
1937 /* Specify whether this is the last export */
1938 args[2] = uint->zero;
1939
1940 /* Specify the target we are exporting */
1941 args[3] = lp_build_const_int32(base->gallivm, target);
1942
1943 if (ctx->type == PIPE_SHADER_FRAGMENT) {
1944 const struct si_shader_key *key = &ctx->shader->key;
1945 unsigned col_formats = key->part.ps.epilog.spi_shader_col_format;
1946 int cbuf = target - V_008DFC_SQ_EXP_MRT;
1947
1948 assert(cbuf >= 0 && cbuf < 8);
1949 spi_shader_col_format = (col_formats >> (cbuf * 4)) & 0xf;
1950 is_int8 = (key->part.ps.epilog.color_is_int8 >> cbuf) & 0x1;
1951 }
1952
1953 args[4] = uint->zero; /* COMPR flag */
1954 args[5] = base->undef;
1955 args[6] = base->undef;
1956 args[7] = base->undef;
1957 args[8] = base->undef;
1958
1959 switch (spi_shader_col_format) {
1960 case V_028714_SPI_SHADER_ZERO:
1961 args[0] = uint->zero; /* writemask */
1962 args[3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_NULL);
1963 break;
1964
1965 case V_028714_SPI_SHADER_32_R:
1966 args[0] = uint->one; /* writemask */
1967 args[5] = values[0];
1968 break;
1969
1970 case V_028714_SPI_SHADER_32_GR:
1971 args[0] = lp_build_const_int32(base->gallivm, 0x3); /* writemask */
1972 args[5] = values[0];
1973 args[6] = values[1];
1974 break;
1975
1976 case V_028714_SPI_SHADER_32_AR:
1977 args[0] = lp_build_const_int32(base->gallivm, 0x9); /* writemask */
1978 args[5] = values[0];
1979 args[8] = values[3];
1980 break;
1981
1982 case V_028714_SPI_SHADER_FP16_ABGR:
1983 args[4] = uint->one; /* COMPR flag */
1984
1985 for (chan = 0; chan < 2; chan++) {
1986 LLVMValueRef pack_args[2] = {
1987 values[2 * chan],
1988 values[2 * chan + 1]
1989 };
1990 LLVMValueRef packed;
1991
1992 packed = lp_build_intrinsic(base->gallivm->builder,
1993 "llvm.SI.packf16",
1994 ctx->i32, pack_args, 2,
1995 LP_FUNC_ATTR_READNONE);
1996 args[chan + 5] =
1997 LLVMBuildBitCast(base->gallivm->builder,
1998 packed, ctx->f32, "");
1999 }
2000 break;
2001
2002 case V_028714_SPI_SHADER_UNORM16_ABGR:
2003 for (chan = 0; chan < 4; chan++) {
2004 val[chan] = si_llvm_saturate(bld_base, values[chan]);
2005 val[chan] = LLVMBuildFMul(builder, val[chan],
2006 lp_build_const_float(gallivm, 65535), "");
2007 val[chan] = LLVMBuildFAdd(builder, val[chan],
2008 lp_build_const_float(gallivm, 0.5), "");
2009 val[chan] = LLVMBuildFPToUI(builder, val[chan],
2010 ctx->i32, "");
2011 }
2012
2013 args[4] = uint->one; /* COMPR flag */
2014 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2015 si_llvm_pack_two_int16(gallivm, val));
2016 args[6] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2017 si_llvm_pack_two_int16(gallivm, val+2));
2018 break;
2019
2020 case V_028714_SPI_SHADER_SNORM16_ABGR:
2021 for (chan = 0; chan < 4; chan++) {
2022 /* Clamp between [-1, 1]. */
2023 val[chan] = lp_build_emit_llvm_binary(bld_base, TGSI_OPCODE_MIN,
2024 values[chan],
2025 lp_build_const_float(gallivm, 1));
2026 val[chan] = lp_build_emit_llvm_binary(bld_base, TGSI_OPCODE_MAX,
2027 val[chan],
2028 lp_build_const_float(gallivm, -1));
2029 /* Convert to a signed integer in [-32767, 32767]. */
2030 val[chan] = LLVMBuildFMul(builder, val[chan],
2031 lp_build_const_float(gallivm, 32767), "");
2032 /* If positive, add 0.5, else add -0.5. */
2033 val[chan] = LLVMBuildFAdd(builder, val[chan],
2034 LLVMBuildSelect(builder,
2035 LLVMBuildFCmp(builder, LLVMRealOGE,
2036 val[chan], base->zero, ""),
2037 lp_build_const_float(gallivm, 0.5),
2038 lp_build_const_float(gallivm, -0.5), ""), "");
2039 val[chan] = LLVMBuildFPToSI(builder, val[chan], ctx->i32, "");
2040 }
2041
2042 args[4] = uint->one; /* COMPR flag */
2043 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2044 si_llvm_pack_two_int32_as_int16(gallivm, val));
2045 args[6] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2046 si_llvm_pack_two_int32_as_int16(gallivm, val+2));
2047 break;
2048
2049 case V_028714_SPI_SHADER_UINT16_ABGR: {
2050 LLVMValueRef max = lp_build_const_int32(gallivm, is_int8 ?
2051 255 : 65535);
2052 /* Clamp. */
2053 for (chan = 0; chan < 4; chan++) {
2054 val[chan] = bitcast(bld_base, TGSI_TYPE_UNSIGNED, values[chan]);
2055 val[chan] = lp_build_emit_llvm_binary(bld_base, TGSI_OPCODE_UMIN,
2056 val[chan], max);
2057 }
2058
2059 args[4] = uint->one; /* COMPR flag */
2060 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2061 si_llvm_pack_two_int16(gallivm, val));
2062 args[6] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2063 si_llvm_pack_two_int16(gallivm, val+2));
2064 break;
2065 }
2066
2067 case V_028714_SPI_SHADER_SINT16_ABGR: {
2068 LLVMValueRef max = lp_build_const_int32(gallivm, is_int8 ?
2069 127 : 32767);
2070 LLVMValueRef min = lp_build_const_int32(gallivm, is_int8 ?
2071 -128 : -32768);
2072 /* Clamp. */
2073 for (chan = 0; chan < 4; chan++) {
2074 val[chan] = bitcast(bld_base, TGSI_TYPE_UNSIGNED, values[chan]);
2075 val[chan] = lp_build_emit_llvm_binary(bld_base,
2076 TGSI_OPCODE_IMIN,
2077 val[chan], max);
2078 val[chan] = lp_build_emit_llvm_binary(bld_base,
2079 TGSI_OPCODE_IMAX,
2080 val[chan], min);
2081 }
2082
2083 args[4] = uint->one; /* COMPR flag */
2084 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2085 si_llvm_pack_two_int32_as_int16(gallivm, val));
2086 args[6] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2087 si_llvm_pack_two_int32_as_int16(gallivm, val+2));
2088 break;
2089 }
2090
2091 case V_028714_SPI_SHADER_32_ABGR:
2092 memcpy(&args[5], values, sizeof(values[0]) * 4);
2093 break;
2094 }
2095 }
2096
2097 static void si_alpha_test(struct lp_build_tgsi_context *bld_base,
2098 LLVMValueRef alpha)
2099 {
2100 struct si_shader_context *ctx = si_shader_context(bld_base);
2101 struct gallivm_state *gallivm = bld_base->base.gallivm;
2102
2103 if (ctx->shader->key.part.ps.epilog.alpha_func != PIPE_FUNC_NEVER) {
2104 LLVMValueRef alpha_ref = LLVMGetParam(ctx->main_fn,
2105 SI_PARAM_ALPHA_REF);
2106
2107 LLVMValueRef alpha_pass =
2108 lp_build_cmp(&bld_base->base,
2109 ctx->shader->key.part.ps.epilog.alpha_func,
2110 alpha, alpha_ref);
2111 LLVMValueRef arg =
2112 lp_build_select(&bld_base->base,
2113 alpha_pass,
2114 lp_build_const_float(gallivm, 1.0f),
2115 lp_build_const_float(gallivm, -1.0f));
2116
2117 lp_build_intrinsic(gallivm->builder, "llvm.AMDGPU.kill",
2118 ctx->voidt, &arg, 1, 0);
2119 } else {
2120 lp_build_intrinsic(gallivm->builder, "llvm.AMDGPU.kilp",
2121 ctx->voidt, NULL, 0, 0);
2122 }
2123 }
2124
2125 static LLVMValueRef si_scale_alpha_by_sample_mask(struct lp_build_tgsi_context *bld_base,
2126 LLVMValueRef alpha,
2127 unsigned samplemask_param)
2128 {
2129 struct si_shader_context *ctx = si_shader_context(bld_base);
2130 struct gallivm_state *gallivm = bld_base->base.gallivm;
2131 LLVMValueRef coverage;
2132
2133 /* alpha = alpha * popcount(coverage) / SI_NUM_SMOOTH_AA_SAMPLES */
2134 coverage = LLVMGetParam(ctx->main_fn,
2135 samplemask_param);
2136 coverage = bitcast(bld_base, TGSI_TYPE_SIGNED, coverage);
2137
2138 coverage = lp_build_intrinsic(gallivm->builder, "llvm.ctpop.i32",
2139 ctx->i32,
2140 &coverage, 1, LP_FUNC_ATTR_READNONE);
2141
2142 coverage = LLVMBuildUIToFP(gallivm->builder, coverage,
2143 ctx->f32, "");
2144
2145 coverage = LLVMBuildFMul(gallivm->builder, coverage,
2146 lp_build_const_float(gallivm,
2147 1.0 / SI_NUM_SMOOTH_AA_SAMPLES), "");
2148
2149 return LLVMBuildFMul(gallivm->builder, alpha, coverage, "");
2150 }
2151
2152 static void si_llvm_emit_clipvertex(struct lp_build_tgsi_context *bld_base,
2153 LLVMValueRef (*pos)[9], LLVMValueRef *out_elts)
2154 {
2155 struct si_shader_context *ctx = si_shader_context(bld_base);
2156 struct lp_build_context *base = &bld_base->base;
2157 struct lp_build_context *uint = &ctx->soa.bld_base.uint_bld;
2158 unsigned reg_index;
2159 unsigned chan;
2160 unsigned const_chan;
2161 LLVMValueRef base_elt;
2162 LLVMValueRef ptr = LLVMGetParam(ctx->main_fn, SI_PARAM_RW_BUFFERS);
2163 LLVMValueRef constbuf_index = lp_build_const_int32(base->gallivm,
2164 SI_VS_CONST_CLIP_PLANES);
2165 LLVMValueRef const_resource = build_indexed_load_const(ctx, ptr, constbuf_index);
2166
2167 for (reg_index = 0; reg_index < 2; reg_index ++) {
2168 LLVMValueRef *args = pos[2 + reg_index];
2169
2170 args[5] =
2171 args[6] =
2172 args[7] =
2173 args[8] = lp_build_const_float(base->gallivm, 0.0f);
2174
2175 /* Compute dot products of position and user clip plane vectors */
2176 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
2177 for (const_chan = 0; const_chan < TGSI_NUM_CHANNELS; const_chan++) {
2178 args[1] = lp_build_const_int32(base->gallivm,
2179 ((reg_index * 4 + chan) * 4 +
2180 const_chan) * 4);
2181 base_elt = buffer_load_const(ctx, const_resource,
2182 args[1]);
2183 args[5 + chan] =
2184 lp_build_add(base, args[5 + chan],
2185 lp_build_mul(base, base_elt,
2186 out_elts[const_chan]));
2187 }
2188 }
2189
2190 args[0] = lp_build_const_int32(base->gallivm, 0xf);
2191 args[1] = uint->zero;
2192 args[2] = uint->zero;
2193 args[3] = lp_build_const_int32(base->gallivm,
2194 V_008DFC_SQ_EXP_POS + 2 + reg_index);
2195 args[4] = uint->zero;
2196 }
2197 }
2198
2199 static void si_dump_streamout(struct pipe_stream_output_info *so)
2200 {
2201 unsigned i;
2202
2203 if (so->num_outputs)
2204 fprintf(stderr, "STREAMOUT\n");
2205
2206 for (i = 0; i < so->num_outputs; i++) {
2207 unsigned mask = ((1 << so->output[i].num_components) - 1) <<
2208 so->output[i].start_component;
2209 fprintf(stderr, " %i: BUF%i[%i..%i] <- OUT[%i].%s%s%s%s\n",
2210 i, so->output[i].output_buffer,
2211 so->output[i].dst_offset, so->output[i].dst_offset + so->output[i].num_components - 1,
2212 so->output[i].register_index,
2213 mask & 1 ? "x" : "",
2214 mask & 2 ? "y" : "",
2215 mask & 4 ? "z" : "",
2216 mask & 8 ? "w" : "");
2217 }
2218 }
2219
2220 static void emit_streamout_output(struct si_shader_context *ctx,
2221 LLVMValueRef const *so_buffers,
2222 LLVMValueRef const *so_write_offsets,
2223 struct pipe_stream_output *stream_out,
2224 struct si_shader_output_values *shader_out)
2225 {
2226 struct gallivm_state *gallivm = &ctx->gallivm;
2227 LLVMBuilderRef builder = gallivm->builder;
2228 unsigned buf_idx = stream_out->output_buffer;
2229 unsigned start = stream_out->start_component;
2230 unsigned num_comps = stream_out->num_components;
2231 LLVMValueRef out[4];
2232
2233 assert(num_comps && num_comps <= 4);
2234 if (!num_comps || num_comps > 4)
2235 return;
2236
2237 /* Load the output as int. */
2238 for (int j = 0; j < num_comps; j++) {
2239 assert(stream_out->stream == shader_out->vertex_stream[start + j]);
2240
2241 out[j] = LLVMBuildBitCast(builder,
2242 shader_out->values[start + j],
2243 ctx->i32, "");
2244 }
2245
2246 /* Pack the output. */
2247 LLVMValueRef vdata = NULL;
2248
2249 switch (num_comps) {
2250 case 1: /* as i32 */
2251 vdata = out[0];
2252 break;
2253 case 2: /* as v2i32 */
2254 case 3: /* as v4i32 (aligned to 4) */
2255 case 4: /* as v4i32 */
2256 vdata = LLVMGetUndef(LLVMVectorType(ctx->i32, util_next_power_of_two(num_comps)));
2257 for (int j = 0; j < num_comps; j++) {
2258 vdata = LLVMBuildInsertElement(builder, vdata, out[j],
2259 LLVMConstInt(ctx->i32, j, 0), "");
2260 }
2261 break;
2262 }
2263
2264 build_tbuffer_store_dwords(ctx, so_buffers[buf_idx],
2265 vdata, num_comps,
2266 so_write_offsets[buf_idx],
2267 LLVMConstInt(ctx->i32, 0, 0),
2268 stream_out->dst_offset * 4);
2269 }
2270
2271 /**
2272 * Write streamout data to buffers for vertex stream @p stream (different
2273 * vertex streams can occur for GS copy shaders).
2274 */
2275 static void si_llvm_emit_streamout(struct si_shader_context *ctx,
2276 struct si_shader_output_values *outputs,
2277 unsigned noutput, unsigned stream)
2278 {
2279 struct si_shader_selector *sel = ctx->shader->selector;
2280 struct pipe_stream_output_info *so = &sel->so;
2281 struct gallivm_state *gallivm = &ctx->gallivm;
2282 LLVMBuilderRef builder = gallivm->builder;
2283 int i;
2284 struct lp_build_if_state if_ctx;
2285
2286 /* Get bits [22:16], i.e. (so_param >> 16) & 127; */
2287 LLVMValueRef so_vtx_count =
2288 unpack_param(ctx, ctx->param_streamout_config, 16, 7);
2289
2290 LLVMValueRef tid = get_thread_id(ctx);
2291
2292 /* can_emit = tid < so_vtx_count; */
2293 LLVMValueRef can_emit =
2294 LLVMBuildICmp(builder, LLVMIntULT, tid, so_vtx_count, "");
2295
2296 /* Emit the streamout code conditionally. This actually avoids
2297 * out-of-bounds buffer access. The hw tells us via the SGPR
2298 * (so_vtx_count) which threads are allowed to emit streamout data. */
2299 lp_build_if(&if_ctx, gallivm, can_emit);
2300 {
2301 /* The buffer offset is computed as follows:
2302 * ByteOffset = streamout_offset[buffer_id]*4 +
2303 * (streamout_write_index + thread_id)*stride[buffer_id] +
2304 * attrib_offset
2305 */
2306
2307 LLVMValueRef so_write_index =
2308 LLVMGetParam(ctx->main_fn,
2309 ctx->param_streamout_write_index);
2310
2311 /* Compute (streamout_write_index + thread_id). */
2312 so_write_index = LLVMBuildAdd(builder, so_write_index, tid, "");
2313
2314 /* Load the descriptor and compute the write offset for each
2315 * enabled buffer. */
2316 LLVMValueRef so_write_offset[4] = {};
2317 LLVMValueRef so_buffers[4];
2318 LLVMValueRef buf_ptr = LLVMGetParam(ctx->main_fn,
2319 SI_PARAM_RW_BUFFERS);
2320
2321 for (i = 0; i < 4; i++) {
2322 if (!so->stride[i])
2323 continue;
2324
2325 LLVMValueRef offset = lp_build_const_int32(gallivm,
2326 SI_VS_STREAMOUT_BUF0 + i);
2327
2328 so_buffers[i] = build_indexed_load_const(ctx, buf_ptr, offset);
2329
2330 LLVMValueRef so_offset = LLVMGetParam(ctx->main_fn,
2331 ctx->param_streamout_offset[i]);
2332 so_offset = LLVMBuildMul(builder, so_offset, LLVMConstInt(ctx->i32, 4, 0), "");
2333
2334 so_write_offset[i] = LLVMBuildMul(builder, so_write_index,
2335 LLVMConstInt(ctx->i32, so->stride[i]*4, 0), "");
2336 so_write_offset[i] = LLVMBuildAdd(builder, so_write_offset[i], so_offset, "");
2337 }
2338
2339 /* Write streamout data. */
2340 for (i = 0; i < so->num_outputs; i++) {
2341 unsigned reg = so->output[i].register_index;
2342
2343 if (reg >= noutput)
2344 continue;
2345
2346 if (stream != so->output[i].stream)
2347 continue;
2348
2349 emit_streamout_output(ctx, so_buffers, so_write_offset,
2350 &so->output[i], &outputs[reg]);
2351 }
2352 }
2353 lp_build_endif(&if_ctx);
2354 }
2355
2356
2357 /* Generate export instructions for hardware VS shader stage */
2358 static void si_llvm_export_vs(struct lp_build_tgsi_context *bld_base,
2359 struct si_shader_output_values *outputs,
2360 unsigned noutput)
2361 {
2362 struct si_shader_context *ctx = si_shader_context(bld_base);
2363 struct si_shader *shader = ctx->shader;
2364 struct lp_build_context *base = &bld_base->base;
2365 struct lp_build_context *uint =
2366 &ctx->soa.bld_base.uint_bld;
2367 LLVMValueRef args[9];
2368 LLVMValueRef pos_args[4][9] = { { 0 } };
2369 LLVMValueRef psize_value = NULL, edgeflag_value = NULL, layer_value = NULL, viewport_index_value = NULL;
2370 unsigned semantic_name, semantic_index;
2371 unsigned target;
2372 unsigned param_count = 0;
2373 unsigned pos_idx;
2374 int i;
2375
2376 for (i = 0; i < noutput; i++) {
2377 semantic_name = outputs[i].semantic_name;
2378 semantic_index = outputs[i].semantic_index;
2379 bool export_param = true;
2380
2381 switch (semantic_name) {
2382 case TGSI_SEMANTIC_POSITION: /* ignore these */
2383 case TGSI_SEMANTIC_PSIZE:
2384 case TGSI_SEMANTIC_CLIPVERTEX:
2385 case TGSI_SEMANTIC_EDGEFLAG:
2386 break;
2387 case TGSI_SEMANTIC_GENERIC:
2388 case TGSI_SEMANTIC_CLIPDIST:
2389 if (shader->key.opt.hw_vs.kill_outputs &
2390 (1ull << si_shader_io_get_unique_index(semantic_name, semantic_index)))
2391 export_param = false;
2392 break;
2393 default:
2394 if (shader->key.opt.hw_vs.kill_outputs2 &
2395 (1u << si_shader_io_get_unique_index2(semantic_name, semantic_index)))
2396 export_param = false;
2397 break;
2398 }
2399
2400 if (outputs[i].vertex_stream[0] != 0 &&
2401 outputs[i].vertex_stream[1] != 0 &&
2402 outputs[i].vertex_stream[2] != 0 &&
2403 outputs[i].vertex_stream[3] != 0)
2404 export_param = false;
2405
2406 handle_semantic:
2407 /* Select the correct target */
2408 switch(semantic_name) {
2409 case TGSI_SEMANTIC_PSIZE:
2410 psize_value = outputs[i].values[0];
2411 continue;
2412 case TGSI_SEMANTIC_EDGEFLAG:
2413 edgeflag_value = outputs[i].values[0];
2414 continue;
2415 case TGSI_SEMANTIC_LAYER:
2416 layer_value = outputs[i].values[0];
2417 semantic_name = TGSI_SEMANTIC_GENERIC;
2418 goto handle_semantic;
2419 case TGSI_SEMANTIC_VIEWPORT_INDEX:
2420 viewport_index_value = outputs[i].values[0];
2421 semantic_name = TGSI_SEMANTIC_GENERIC;
2422 goto handle_semantic;
2423 case TGSI_SEMANTIC_POSITION:
2424 target = V_008DFC_SQ_EXP_POS;
2425 break;
2426 case TGSI_SEMANTIC_CLIPDIST:
2427 if (shader->key.opt.hw_vs.clip_disable) {
2428 semantic_name = TGSI_SEMANTIC_GENERIC;
2429 goto handle_semantic;
2430 }
2431 target = V_008DFC_SQ_EXP_POS + 2 + semantic_index;
2432 break;
2433 case TGSI_SEMANTIC_CLIPVERTEX:
2434 if (shader->key.opt.hw_vs.clip_disable)
2435 continue;
2436 si_llvm_emit_clipvertex(bld_base, pos_args, outputs[i].values);
2437 continue;
2438 case TGSI_SEMANTIC_COLOR:
2439 case TGSI_SEMANTIC_BCOLOR:
2440 case TGSI_SEMANTIC_PRIMID:
2441 case TGSI_SEMANTIC_FOG:
2442 case TGSI_SEMANTIC_TEXCOORD:
2443 case TGSI_SEMANTIC_GENERIC:
2444 if (!export_param)
2445 continue;
2446 target = V_008DFC_SQ_EXP_PARAM + param_count;
2447 assert(i < ARRAY_SIZE(shader->info.vs_output_param_offset));
2448 shader->info.vs_output_param_offset[i] = param_count;
2449 param_count++;
2450 break;
2451 default:
2452 target = 0;
2453 fprintf(stderr,
2454 "Warning: SI unhandled vs output type:%d\n",
2455 semantic_name);
2456 }
2457
2458 si_llvm_init_export_args(bld_base, outputs[i].values, target, args);
2459
2460 if (target >= V_008DFC_SQ_EXP_POS &&
2461 target <= (V_008DFC_SQ_EXP_POS + 3)) {
2462 memcpy(pos_args[target - V_008DFC_SQ_EXP_POS],
2463 args, sizeof(args));
2464 } else {
2465 lp_build_intrinsic(base->gallivm->builder,
2466 "llvm.SI.export", ctx->voidt,
2467 args, 9, 0);
2468 }
2469
2470 if (semantic_name == TGSI_SEMANTIC_CLIPDIST) {
2471 semantic_name = TGSI_SEMANTIC_GENERIC;
2472 goto handle_semantic;
2473 }
2474 }
2475
2476 shader->info.nr_param_exports = param_count;
2477
2478 /* We need to add the position output manually if it's missing. */
2479 if (!pos_args[0][0]) {
2480 pos_args[0][0] = lp_build_const_int32(base->gallivm, 0xf); /* writemask */
2481 pos_args[0][1] = uint->zero; /* EXEC mask */
2482 pos_args[0][2] = uint->zero; /* last export? */
2483 pos_args[0][3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_POS);
2484 pos_args[0][4] = uint->zero; /* COMPR flag */
2485 pos_args[0][5] = base->zero; /* X */
2486 pos_args[0][6] = base->zero; /* Y */
2487 pos_args[0][7] = base->zero; /* Z */
2488 pos_args[0][8] = base->one; /* W */
2489 }
2490
2491 /* Write the misc vector (point size, edgeflag, layer, viewport). */
2492 if (shader->selector->info.writes_psize ||
2493 shader->selector->info.writes_edgeflag ||
2494 shader->selector->info.writes_viewport_index ||
2495 shader->selector->info.writes_layer) {
2496 pos_args[1][0] = lp_build_const_int32(base->gallivm, /* writemask */
2497 shader->selector->info.writes_psize |
2498 (shader->selector->info.writes_edgeflag << 1) |
2499 (shader->selector->info.writes_layer << 2) |
2500 (shader->selector->info.writes_viewport_index << 3));
2501 pos_args[1][1] = uint->zero; /* EXEC mask */
2502 pos_args[1][2] = uint->zero; /* last export? */
2503 pos_args[1][3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_POS + 1);
2504 pos_args[1][4] = uint->zero; /* COMPR flag */
2505 pos_args[1][5] = base->zero; /* X */
2506 pos_args[1][6] = base->zero; /* Y */
2507 pos_args[1][7] = base->zero; /* Z */
2508 pos_args[1][8] = base->zero; /* W */
2509
2510 if (shader->selector->info.writes_psize)
2511 pos_args[1][5] = psize_value;
2512
2513 if (shader->selector->info.writes_edgeflag) {
2514 /* The output is a float, but the hw expects an integer
2515 * with the first bit containing the edge flag. */
2516 edgeflag_value = LLVMBuildFPToUI(base->gallivm->builder,
2517 edgeflag_value,
2518 ctx->i32, "");
2519 edgeflag_value = lp_build_min(&bld_base->int_bld,
2520 edgeflag_value,
2521 bld_base->int_bld.one);
2522
2523 /* The LLVM intrinsic expects a float. */
2524 pos_args[1][6] = LLVMBuildBitCast(base->gallivm->builder,
2525 edgeflag_value,
2526 ctx->f32, "");
2527 }
2528
2529 if (shader->selector->info.writes_layer)
2530 pos_args[1][7] = layer_value;
2531
2532 if (shader->selector->info.writes_viewport_index)
2533 pos_args[1][8] = viewport_index_value;
2534 }
2535
2536 for (i = 0; i < 4; i++)
2537 if (pos_args[i][0])
2538 shader->info.nr_pos_exports++;
2539
2540 pos_idx = 0;
2541 for (i = 0; i < 4; i++) {
2542 if (!pos_args[i][0])
2543 continue;
2544
2545 /* Specify the target we are exporting */
2546 pos_args[i][3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_POS + pos_idx++);
2547
2548 if (pos_idx == shader->info.nr_pos_exports)
2549 /* Specify that this is the last export */
2550 pos_args[i][2] = uint->one;
2551
2552 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
2553 ctx->voidt, pos_args[i], 9, 0);
2554 }
2555 }
2556
2557 /**
2558 * Forward all outputs from the vertex shader to the TES. This is only used
2559 * for the fixed function TCS.
2560 */
2561 static void si_copy_tcs_inputs(struct lp_build_tgsi_context *bld_base)
2562 {
2563 struct si_shader_context *ctx = si_shader_context(bld_base);
2564 struct gallivm_state *gallivm = bld_base->base.gallivm;
2565 LLVMValueRef invocation_id, rw_buffers, buffer, buffer_offset;
2566 LLVMValueRef lds_vertex_stride, lds_vertex_offset, lds_base;
2567 uint64_t inputs;
2568
2569 invocation_id = unpack_param(ctx, SI_PARAM_REL_IDS, 8, 5);
2570
2571 rw_buffers = LLVMGetParam(ctx->main_fn, SI_PARAM_RW_BUFFERS);
2572 buffer = build_indexed_load_const(ctx, rw_buffers,
2573 lp_build_const_int32(gallivm, SI_HS_RING_TESS_OFFCHIP));
2574
2575 buffer_offset = LLVMGetParam(ctx->main_fn, ctx->param_oc_lds);
2576
2577 lds_vertex_stride = unpack_param(ctx, SI_PARAM_TCS_IN_LAYOUT, 13, 8);
2578 lds_vertex_offset = LLVMBuildMul(gallivm->builder, invocation_id,
2579 lds_vertex_stride, "");
2580 lds_base = get_tcs_in_current_patch_offset(ctx);
2581 lds_base = LLVMBuildAdd(gallivm->builder, lds_base, lds_vertex_offset, "");
2582
2583 inputs = ctx->shader->key.mono.tcs.inputs_to_copy;
2584 while (inputs) {
2585 unsigned i = u_bit_scan64(&inputs);
2586
2587 LLVMValueRef lds_ptr = LLVMBuildAdd(gallivm->builder, lds_base,
2588 lp_build_const_int32(gallivm, 4 * i),
2589 "");
2590
2591 LLVMValueRef buffer_addr = get_tcs_tes_buffer_address(ctx,
2592 invocation_id,
2593 lp_build_const_int32(gallivm, i));
2594
2595 LLVMValueRef value = lds_load(bld_base, TGSI_TYPE_SIGNED, ~0,
2596 lds_ptr);
2597
2598 build_tbuffer_store_dwords(ctx, buffer, value, 4, buffer_addr,
2599 buffer_offset, 0);
2600 }
2601 }
2602
2603 static void si_write_tess_factors(struct lp_build_tgsi_context *bld_base,
2604 LLVMValueRef rel_patch_id,
2605 LLVMValueRef invocation_id,
2606 LLVMValueRef tcs_out_current_patch_data_offset)
2607 {
2608 struct si_shader_context *ctx = si_shader_context(bld_base);
2609 struct gallivm_state *gallivm = bld_base->base.gallivm;
2610 struct si_shader *shader = ctx->shader;
2611 unsigned tess_inner_index, tess_outer_index;
2612 LLVMValueRef lds_base, lds_inner, lds_outer, byteoffset, buffer;
2613 LLVMValueRef out[6], vec0, vec1, rw_buffers, tf_base;
2614 unsigned stride, outer_comps, inner_comps, i;
2615 struct lp_build_if_state if_ctx, inner_if_ctx;
2616
2617 si_llvm_emit_barrier(NULL, bld_base, NULL);
2618
2619 /* Do this only for invocation 0, because the tess levels are per-patch,
2620 * not per-vertex.
2621 *
2622 * This can't jump, because invocation 0 executes this. It should
2623 * at least mask out the loads and stores for other invocations.
2624 */
2625 lp_build_if(&if_ctx, gallivm,
2626 LLVMBuildICmp(gallivm->builder, LLVMIntEQ,
2627 invocation_id, bld_base->uint_bld.zero, ""));
2628
2629 /* Determine the layout of one tess factor element in the buffer. */
2630 switch (shader->key.part.tcs.epilog.prim_mode) {
2631 case PIPE_PRIM_LINES:
2632 stride = 2; /* 2 dwords, 1 vec2 store */
2633 outer_comps = 2;
2634 inner_comps = 0;
2635 break;
2636 case PIPE_PRIM_TRIANGLES:
2637 stride = 4; /* 4 dwords, 1 vec4 store */
2638 outer_comps = 3;
2639 inner_comps = 1;
2640 break;
2641 case PIPE_PRIM_QUADS:
2642 stride = 6; /* 6 dwords, 2 stores (vec4 + vec2) */
2643 outer_comps = 4;
2644 inner_comps = 2;
2645 break;
2646 default:
2647 assert(0);
2648 return;
2649 }
2650
2651 /* Load tess_inner and tess_outer from LDS.
2652 * Any invocation can write them, so we can't get them from a temporary.
2653 */
2654 tess_inner_index = si_shader_io_get_unique_index(TGSI_SEMANTIC_TESSINNER, 0);
2655 tess_outer_index = si_shader_io_get_unique_index(TGSI_SEMANTIC_TESSOUTER, 0);
2656
2657 lds_base = tcs_out_current_patch_data_offset;
2658 lds_inner = LLVMBuildAdd(gallivm->builder, lds_base,
2659 lp_build_const_int32(gallivm,
2660 tess_inner_index * 4), "");
2661 lds_outer = LLVMBuildAdd(gallivm->builder, lds_base,
2662 lp_build_const_int32(gallivm,
2663 tess_outer_index * 4), "");
2664
2665 if (shader->key.part.tcs.epilog.prim_mode == PIPE_PRIM_LINES) {
2666 /* For isolines, the hardware expects tess factors in the
2667 * reverse order from what GLSL / TGSI specify.
2668 */
2669 out[0] = lds_load(bld_base, TGSI_TYPE_SIGNED, 1, lds_outer);
2670 out[1] = lds_load(bld_base, TGSI_TYPE_SIGNED, 0, lds_outer);
2671 } else {
2672 for (i = 0; i < outer_comps; i++)
2673 out[i] = lds_load(bld_base, TGSI_TYPE_SIGNED, i, lds_outer);
2674 for (i = 0; i < inner_comps; i++)
2675 out[outer_comps+i] = lds_load(bld_base, TGSI_TYPE_SIGNED, i, lds_inner);
2676 }
2677
2678 /* Convert the outputs to vectors for stores. */
2679 vec0 = lp_build_gather_values(gallivm, out, MIN2(stride, 4));
2680 vec1 = NULL;
2681
2682 if (stride > 4)
2683 vec1 = lp_build_gather_values(gallivm, out+4, stride - 4);
2684
2685 /* Get the buffer. */
2686 rw_buffers = LLVMGetParam(ctx->main_fn,
2687 SI_PARAM_RW_BUFFERS);
2688 buffer = build_indexed_load_const(ctx, rw_buffers,
2689 lp_build_const_int32(gallivm, SI_HS_RING_TESS_FACTOR));
2690
2691 /* Get the offset. */
2692 tf_base = LLVMGetParam(ctx->main_fn,
2693 SI_PARAM_TESS_FACTOR_OFFSET);
2694 byteoffset = LLVMBuildMul(gallivm->builder, rel_patch_id,
2695 lp_build_const_int32(gallivm, 4 * stride), "");
2696
2697 lp_build_if(&inner_if_ctx, gallivm,
2698 LLVMBuildICmp(gallivm->builder, LLVMIntEQ,
2699 rel_patch_id, bld_base->uint_bld.zero, ""));
2700
2701 /* Store the dynamic HS control word. */
2702 build_tbuffer_store_dwords(ctx, buffer,
2703 lp_build_const_int32(gallivm, 0x80000000),
2704 1, lp_build_const_int32(gallivm, 0), tf_base, 0);
2705
2706 lp_build_endif(&inner_if_ctx);
2707
2708 /* Store the tessellation factors. */
2709 build_tbuffer_store_dwords(ctx, buffer, vec0,
2710 MIN2(stride, 4), byteoffset, tf_base, 4);
2711 if (vec1)
2712 build_tbuffer_store_dwords(ctx, buffer, vec1,
2713 stride - 4, byteoffset, tf_base, 20);
2714 lp_build_endif(&if_ctx);
2715 }
2716
2717 /* This only writes the tessellation factor levels. */
2718 static void si_llvm_emit_tcs_epilogue(struct lp_build_tgsi_context *bld_base)
2719 {
2720 struct si_shader_context *ctx = si_shader_context(bld_base);
2721 LLVMValueRef rel_patch_id, invocation_id, tf_lds_offset;
2722
2723 si_copy_tcs_inputs(bld_base);
2724
2725 rel_patch_id = get_rel_patch_id(ctx);
2726 invocation_id = unpack_param(ctx, SI_PARAM_REL_IDS, 8, 5);
2727 tf_lds_offset = get_tcs_out_current_patch_data_offset(ctx);
2728
2729 /* Return epilog parameters from this function. */
2730 LLVMBuilderRef builder = bld_base->base.gallivm->builder;
2731 LLVMValueRef ret = ctx->return_value;
2732 LLVMValueRef rw_buffers, rw0, rw1, tf_soffset;
2733 unsigned vgpr;
2734
2735 /* RW_BUFFERS pointer */
2736 rw_buffers = LLVMGetParam(ctx->main_fn,
2737 SI_PARAM_RW_BUFFERS);
2738 rw_buffers = LLVMBuildPtrToInt(builder, rw_buffers, ctx->i64, "");
2739 rw_buffers = LLVMBuildBitCast(builder, rw_buffers, ctx->v2i32, "");
2740 rw0 = LLVMBuildExtractElement(builder, rw_buffers,
2741 bld_base->uint_bld.zero, "");
2742 rw1 = LLVMBuildExtractElement(builder, rw_buffers,
2743 bld_base->uint_bld.one, "");
2744 ret = LLVMBuildInsertValue(builder, ret, rw0, 0, "");
2745 ret = LLVMBuildInsertValue(builder, ret, rw1, 1, "");
2746
2747 /* Tess factor buffer soffset is after user SGPRs. */
2748 tf_soffset = LLVMGetParam(ctx->main_fn,
2749 SI_PARAM_TESS_FACTOR_OFFSET);
2750 ret = LLVMBuildInsertValue(builder, ret, tf_soffset,
2751 SI_TCS_NUM_USER_SGPR + 1, "");
2752
2753 /* VGPRs */
2754 rel_patch_id = bitcast(bld_base, TGSI_TYPE_FLOAT, rel_patch_id);
2755 invocation_id = bitcast(bld_base, TGSI_TYPE_FLOAT, invocation_id);
2756 tf_lds_offset = bitcast(bld_base, TGSI_TYPE_FLOAT, tf_lds_offset);
2757
2758 vgpr = SI_TCS_NUM_USER_SGPR + 2;
2759 ret = LLVMBuildInsertValue(builder, ret, rel_patch_id, vgpr++, "");
2760 ret = LLVMBuildInsertValue(builder, ret, invocation_id, vgpr++, "");
2761 ret = LLVMBuildInsertValue(builder, ret, tf_lds_offset, vgpr++, "");
2762 ctx->return_value = ret;
2763 }
2764
2765 static void si_llvm_emit_ls_epilogue(struct lp_build_tgsi_context *bld_base)
2766 {
2767 struct si_shader_context *ctx = si_shader_context(bld_base);
2768 struct si_shader *shader = ctx->shader;
2769 struct tgsi_shader_info *info = &shader->selector->info;
2770 struct gallivm_state *gallivm = bld_base->base.gallivm;
2771 unsigned i, chan;
2772 LLVMValueRef vertex_id = LLVMGetParam(ctx->main_fn,
2773 ctx->param_rel_auto_id);
2774 LLVMValueRef vertex_dw_stride =
2775 unpack_param(ctx, SI_PARAM_LS_OUT_LAYOUT, 13, 8);
2776 LLVMValueRef base_dw_addr = LLVMBuildMul(gallivm->builder, vertex_id,
2777 vertex_dw_stride, "");
2778
2779 /* Write outputs to LDS. The next shader (TCS aka HS) will read
2780 * its inputs from it. */
2781 for (i = 0; i < info->num_outputs; i++) {
2782 LLVMValueRef *out_ptr = ctx->soa.outputs[i];
2783 unsigned name = info->output_semantic_name[i];
2784 unsigned index = info->output_semantic_index[i];
2785 int param = si_shader_io_get_unique_index(name, index);
2786 LLVMValueRef dw_addr = LLVMBuildAdd(gallivm->builder, base_dw_addr,
2787 lp_build_const_int32(gallivm, param * 4), "");
2788
2789 for (chan = 0; chan < 4; chan++) {
2790 lds_store(bld_base, chan, dw_addr,
2791 LLVMBuildLoad(gallivm->builder, out_ptr[chan], ""));
2792 }
2793 }
2794 }
2795
2796 static void si_llvm_emit_es_epilogue(struct lp_build_tgsi_context *bld_base)
2797 {
2798 struct si_shader_context *ctx = si_shader_context(bld_base);
2799 struct gallivm_state *gallivm = bld_base->base.gallivm;
2800 struct si_shader *es = ctx->shader;
2801 struct tgsi_shader_info *info = &es->selector->info;
2802 LLVMValueRef soffset = LLVMGetParam(ctx->main_fn,
2803 ctx->param_es2gs_offset);
2804 unsigned chan;
2805 int i;
2806
2807 for (i = 0; i < info->num_outputs; i++) {
2808 LLVMValueRef *out_ptr =
2809 ctx->soa.outputs[i];
2810 int param_index;
2811
2812 if (info->output_semantic_name[i] == TGSI_SEMANTIC_VIEWPORT_INDEX ||
2813 info->output_semantic_name[i] == TGSI_SEMANTIC_LAYER)
2814 continue;
2815
2816 param_index = si_shader_io_get_unique_index(info->output_semantic_name[i],
2817 info->output_semantic_index[i]);
2818
2819 for (chan = 0; chan < 4; chan++) {
2820 LLVMValueRef out_val = LLVMBuildLoad(gallivm->builder, out_ptr[chan], "");
2821 out_val = LLVMBuildBitCast(gallivm->builder, out_val, ctx->i32, "");
2822
2823 build_tbuffer_store(ctx,
2824 ctx->esgs_ring,
2825 out_val, 1,
2826 LLVMGetUndef(ctx->i32), soffset,
2827 (4 * param_index + chan) * 4,
2828 V_008F0C_BUF_DATA_FORMAT_32,
2829 V_008F0C_BUF_NUM_FORMAT_UINT,
2830 0, 0, 1, 1, 0);
2831 }
2832 }
2833 }
2834
2835 static void si_llvm_emit_gs_epilogue(struct lp_build_tgsi_context *bld_base)
2836 {
2837 struct si_shader_context *ctx = si_shader_context(bld_base);
2838 struct gallivm_state *gallivm = bld_base->base.gallivm;
2839 LLVMValueRef args[2];
2840
2841 args[0] = lp_build_const_int32(gallivm, SENDMSG_GS_OP_NOP | SENDMSG_GS_DONE);
2842 args[1] = LLVMGetParam(ctx->main_fn, SI_PARAM_GS_WAVE_ID);
2843 lp_build_intrinsic(gallivm->builder, "llvm.SI.sendmsg",
2844 ctx->voidt, args, 2, 0);
2845 }
2846
2847 static void si_llvm_emit_vs_epilogue(struct lp_build_tgsi_context *bld_base)
2848 {
2849 struct si_shader_context *ctx = si_shader_context(bld_base);
2850 struct gallivm_state *gallivm = bld_base->base.gallivm;
2851 struct tgsi_shader_info *info = &ctx->shader->selector->info;
2852 struct si_shader_output_values *outputs = NULL;
2853 int i,j;
2854
2855 assert(!ctx->shader->is_gs_copy_shader);
2856
2857 outputs = MALLOC((info->num_outputs + 1) * sizeof(outputs[0]));
2858
2859 /* Vertex color clamping.
2860 *
2861 * This uses a state constant loaded in a user data SGPR and
2862 * an IF statement is added that clamps all colors if the constant
2863 * is true.
2864 */
2865 if (ctx->type == PIPE_SHADER_VERTEX) {
2866 struct lp_build_if_state if_ctx;
2867 LLVMValueRef cond = NULL;
2868 LLVMValueRef addr, val;
2869
2870 for (i = 0; i < info->num_outputs; i++) {
2871 if (info->output_semantic_name[i] != TGSI_SEMANTIC_COLOR &&
2872 info->output_semantic_name[i] != TGSI_SEMANTIC_BCOLOR)
2873 continue;
2874
2875 /* We've found a color. */
2876 if (!cond) {
2877 /* The state is in the first bit of the user SGPR. */
2878 cond = LLVMGetParam(ctx->main_fn,
2879 SI_PARAM_VS_STATE_BITS);
2880 cond = LLVMBuildTrunc(gallivm->builder, cond,
2881 ctx->i1, "");
2882 lp_build_if(&if_ctx, gallivm, cond);
2883 }
2884
2885 for (j = 0; j < 4; j++) {
2886 addr = ctx->soa.outputs[i][j];
2887 val = LLVMBuildLoad(gallivm->builder, addr, "");
2888 val = si_llvm_saturate(bld_base, val);
2889 LLVMBuildStore(gallivm->builder, val, addr);
2890 }
2891 }
2892
2893 if (cond)
2894 lp_build_endif(&if_ctx);
2895 }
2896
2897 for (i = 0; i < info->num_outputs; i++) {
2898 outputs[i].semantic_name = info->output_semantic_name[i];
2899 outputs[i].semantic_index = info->output_semantic_index[i];
2900
2901 for (j = 0; j < 4; j++) {
2902 outputs[i].values[j] =
2903 LLVMBuildLoad(gallivm->builder,
2904 ctx->soa.outputs[i][j],
2905 "");
2906 outputs[i].vertex_stream[j] =
2907 (info->output_streams[i] >> (2 * j)) & 3;
2908 }
2909
2910 }
2911
2912 /* Return the primitive ID from the LLVM function. */
2913 ctx->return_value =
2914 LLVMBuildInsertValue(gallivm->builder,
2915 ctx->return_value,
2916 bitcast(bld_base, TGSI_TYPE_FLOAT,
2917 get_primitive_id(bld_base, 0)),
2918 VS_EPILOG_PRIMID_LOC, "");
2919
2920 if (ctx->shader->selector->so.num_outputs)
2921 si_llvm_emit_streamout(ctx, outputs, i, 0);
2922 si_llvm_export_vs(bld_base, outputs, i);
2923 FREE(outputs);
2924 }
2925
2926 struct si_ps_exports {
2927 unsigned num;
2928 LLVMValueRef args[10][9];
2929 };
2930
2931 unsigned si_get_spi_shader_z_format(bool writes_z, bool writes_stencil,
2932 bool writes_samplemask)
2933 {
2934 if (writes_z) {
2935 /* Z needs 32 bits. */
2936 if (writes_samplemask)
2937 return V_028710_SPI_SHADER_32_ABGR;
2938 else if (writes_stencil)
2939 return V_028710_SPI_SHADER_32_GR;
2940 else
2941 return V_028710_SPI_SHADER_32_R;
2942 } else if (writes_stencil || writes_samplemask) {
2943 /* Both stencil and sample mask need only 16 bits. */
2944 return V_028710_SPI_SHADER_UINT16_ABGR;
2945 } else {
2946 return V_028710_SPI_SHADER_ZERO;
2947 }
2948 }
2949
2950 static void si_export_mrt_z(struct lp_build_tgsi_context *bld_base,
2951 LLVMValueRef depth, LLVMValueRef stencil,
2952 LLVMValueRef samplemask, struct si_ps_exports *exp)
2953 {
2954 struct si_shader_context *ctx = si_shader_context(bld_base);
2955 struct lp_build_context *base = &bld_base->base;
2956 struct lp_build_context *uint = &bld_base->uint_bld;
2957 LLVMValueRef args[9];
2958 unsigned mask = 0;
2959 unsigned format = si_get_spi_shader_z_format(depth != NULL,
2960 stencil != NULL,
2961 samplemask != NULL);
2962
2963 assert(depth || stencil || samplemask);
2964
2965 args[1] = uint->one; /* whether the EXEC mask is valid */
2966 args[2] = uint->one; /* DONE bit */
2967
2968 /* Specify the target we are exporting */
2969 args[3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_MRTZ);
2970
2971 args[4] = uint->zero; /* COMP flag */
2972 args[5] = base->undef; /* R, depth */
2973 args[6] = base->undef; /* G, stencil test value[0:7], stencil op value[8:15] */
2974 args[7] = base->undef; /* B, sample mask */
2975 args[8] = base->undef; /* A, alpha to mask */
2976
2977 if (format == V_028710_SPI_SHADER_UINT16_ABGR) {
2978 assert(!depth);
2979 args[4] = uint->one; /* COMPR flag */
2980
2981 if (stencil) {
2982 /* Stencil should be in X[23:16]. */
2983 stencil = bitcast(bld_base, TGSI_TYPE_UNSIGNED, stencil);
2984 stencil = LLVMBuildShl(base->gallivm->builder, stencil,
2985 LLVMConstInt(ctx->i32, 16, 0), "");
2986 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT, stencil);
2987 mask |= 0x3;
2988 }
2989 if (samplemask) {
2990 /* SampleMask should be in Y[15:0]. */
2991 args[6] = samplemask;
2992 mask |= 0xc;
2993 }
2994 } else {
2995 if (depth) {
2996 args[5] = depth;
2997 mask |= 0x1;
2998 }
2999 if (stencil) {
3000 args[6] = stencil;
3001 mask |= 0x2;
3002 }
3003 if (samplemask) {
3004 args[7] = samplemask;
3005 mask |= 0x4;
3006 }
3007 }
3008
3009 /* SI (except OLAND and HAINAN) has a bug that it only looks
3010 * at the X writemask component. */
3011 if (ctx->screen->b.chip_class == SI &&
3012 ctx->screen->b.family != CHIP_OLAND &&
3013 ctx->screen->b.family != CHIP_HAINAN)
3014 mask |= 0x1;
3015
3016 /* Specify which components to enable */
3017 args[0] = lp_build_const_int32(base->gallivm, mask);
3018
3019 memcpy(exp->args[exp->num++], args, sizeof(args));
3020 }
3021
3022 static void si_export_mrt_color(struct lp_build_tgsi_context *bld_base,
3023 LLVMValueRef *color, unsigned index,
3024 unsigned samplemask_param,
3025 bool is_last, struct si_ps_exports *exp)
3026 {
3027 struct si_shader_context *ctx = si_shader_context(bld_base);
3028 struct lp_build_context *base = &bld_base->base;
3029 int i;
3030
3031 /* Clamp color */
3032 if (ctx->shader->key.part.ps.epilog.clamp_color)
3033 for (i = 0; i < 4; i++)
3034 color[i] = si_llvm_saturate(bld_base, color[i]);
3035
3036 /* Alpha to one */
3037 if (ctx->shader->key.part.ps.epilog.alpha_to_one)
3038 color[3] = base->one;
3039
3040 /* Alpha test */
3041 if (index == 0 &&
3042 ctx->shader->key.part.ps.epilog.alpha_func != PIPE_FUNC_ALWAYS)
3043 si_alpha_test(bld_base, color[3]);
3044
3045 /* Line & polygon smoothing */
3046 if (ctx->shader->key.part.ps.epilog.poly_line_smoothing)
3047 color[3] = si_scale_alpha_by_sample_mask(bld_base, color[3],
3048 samplemask_param);
3049
3050 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
3051 if (ctx->shader->key.part.ps.epilog.last_cbuf > 0) {
3052 LLVMValueRef args[8][9];
3053 int c, last = -1;
3054
3055 /* Get the export arguments, also find out what the last one is. */
3056 for (c = 0; c <= ctx->shader->key.part.ps.epilog.last_cbuf; c++) {
3057 si_llvm_init_export_args(bld_base, color,
3058 V_008DFC_SQ_EXP_MRT + c, args[c]);
3059 if (args[c][0] != bld_base->uint_bld.zero)
3060 last = c;
3061 }
3062
3063 /* Emit all exports. */
3064 for (c = 0; c <= ctx->shader->key.part.ps.epilog.last_cbuf; c++) {
3065 if (is_last && last == c) {
3066 args[c][1] = bld_base->uint_bld.one; /* whether the EXEC mask is valid */
3067 args[c][2] = bld_base->uint_bld.one; /* DONE bit */
3068 } else if (args[c][0] == bld_base->uint_bld.zero)
3069 continue; /* unnecessary NULL export */
3070
3071 memcpy(exp->args[exp->num++], args[c], sizeof(args[c]));
3072 }
3073 } else {
3074 LLVMValueRef args[9];
3075
3076 /* Export */
3077 si_llvm_init_export_args(bld_base, color, V_008DFC_SQ_EXP_MRT + index,
3078 args);
3079 if (is_last) {
3080 args[1] = bld_base->uint_bld.one; /* whether the EXEC mask is valid */
3081 args[2] = bld_base->uint_bld.one; /* DONE bit */
3082 } else if (args[0] == bld_base->uint_bld.zero)
3083 return; /* unnecessary NULL export */
3084
3085 memcpy(exp->args[exp->num++], args, sizeof(args));
3086 }
3087 }
3088
3089 static void si_emit_ps_exports(struct si_shader_context *ctx,
3090 struct si_ps_exports *exp)
3091 {
3092 for (unsigned i = 0; i < exp->num; i++)
3093 lp_build_intrinsic(ctx->gallivm.builder,
3094 "llvm.SI.export", ctx->voidt,
3095 exp->args[i], 9, 0);
3096 }
3097
3098 static void si_export_null(struct lp_build_tgsi_context *bld_base)
3099 {
3100 struct si_shader_context *ctx = si_shader_context(bld_base);
3101 struct lp_build_context *base = &bld_base->base;
3102 struct lp_build_context *uint = &bld_base->uint_bld;
3103 LLVMValueRef args[9];
3104
3105 args[0] = lp_build_const_int32(base->gallivm, 0x0); /* enabled channels */
3106 args[1] = uint->one; /* whether the EXEC mask is valid */
3107 args[2] = uint->one; /* DONE bit */
3108 args[3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_NULL);
3109 args[4] = uint->zero; /* COMPR flag (0 = 32-bit export) */
3110 args[5] = base->undef; /* R */
3111 args[6] = base->undef; /* G */
3112 args[7] = base->undef; /* B */
3113 args[8] = base->undef; /* A */
3114
3115 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
3116 ctx->voidt, args, 9, 0);
3117 }
3118
3119 /**
3120 * Return PS outputs in this order:
3121 *
3122 * v[0:3] = color0.xyzw
3123 * v[4:7] = color1.xyzw
3124 * ...
3125 * vN+0 = Depth
3126 * vN+1 = Stencil
3127 * vN+2 = SampleMask
3128 * vN+3 = SampleMaskIn (used for OpenGL smoothing)
3129 *
3130 * The alpha-ref SGPR is returned via its original location.
3131 */
3132 static void si_llvm_return_fs_outputs(struct lp_build_tgsi_context *bld_base)
3133 {
3134 struct si_shader_context *ctx = si_shader_context(bld_base);
3135 struct si_shader *shader = ctx->shader;
3136 struct lp_build_context *base = &bld_base->base;
3137 struct tgsi_shader_info *info = &shader->selector->info;
3138 LLVMBuilderRef builder = base->gallivm->builder;
3139 unsigned i, j, first_vgpr, vgpr;
3140
3141 LLVMValueRef color[8][4] = {};
3142 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
3143 LLVMValueRef ret;
3144
3145 /* Read the output values. */
3146 for (i = 0; i < info->num_outputs; i++) {
3147 unsigned semantic_name = info->output_semantic_name[i];
3148 unsigned semantic_index = info->output_semantic_index[i];
3149
3150 switch (semantic_name) {
3151 case TGSI_SEMANTIC_COLOR:
3152 assert(semantic_index < 8);
3153 for (j = 0; j < 4; j++) {
3154 LLVMValueRef ptr = ctx->soa.outputs[i][j];
3155 LLVMValueRef result = LLVMBuildLoad(builder, ptr, "");
3156 color[semantic_index][j] = result;
3157 }
3158 break;
3159 case TGSI_SEMANTIC_POSITION:
3160 depth = LLVMBuildLoad(builder,
3161 ctx->soa.outputs[i][2], "");
3162 break;
3163 case TGSI_SEMANTIC_STENCIL:
3164 stencil = LLVMBuildLoad(builder,
3165 ctx->soa.outputs[i][1], "");
3166 break;
3167 case TGSI_SEMANTIC_SAMPLEMASK:
3168 samplemask = LLVMBuildLoad(builder,
3169 ctx->soa.outputs[i][0], "");
3170 break;
3171 default:
3172 fprintf(stderr, "Warning: SI unhandled fs output type:%d\n",
3173 semantic_name);
3174 }
3175 }
3176
3177 /* Fill the return structure. */
3178 ret = ctx->return_value;
3179
3180 /* Set SGPRs. */
3181 ret = LLVMBuildInsertValue(builder, ret,
3182 bitcast(bld_base, TGSI_TYPE_SIGNED,
3183 LLVMGetParam(ctx->main_fn,
3184 SI_PARAM_ALPHA_REF)),
3185 SI_SGPR_ALPHA_REF, "");
3186
3187 /* Set VGPRs */
3188 first_vgpr = vgpr = SI_SGPR_ALPHA_REF + 1;
3189 for (i = 0; i < ARRAY_SIZE(color); i++) {
3190 if (!color[i][0])
3191 continue;
3192
3193 for (j = 0; j < 4; j++)
3194 ret = LLVMBuildInsertValue(builder, ret, color[i][j], vgpr++, "");
3195 }
3196 if (depth)
3197 ret = LLVMBuildInsertValue(builder, ret, depth, vgpr++, "");
3198 if (stencil)
3199 ret = LLVMBuildInsertValue(builder, ret, stencil, vgpr++, "");
3200 if (samplemask)
3201 ret = LLVMBuildInsertValue(builder, ret, samplemask, vgpr++, "");
3202
3203 /* Add the input sample mask for smoothing at the end. */
3204 if (vgpr < first_vgpr + PS_EPILOG_SAMPLEMASK_MIN_LOC)
3205 vgpr = first_vgpr + PS_EPILOG_SAMPLEMASK_MIN_LOC;
3206 ret = LLVMBuildInsertValue(builder, ret,
3207 LLVMGetParam(ctx->main_fn,
3208 SI_PARAM_SAMPLE_COVERAGE), vgpr++, "");
3209
3210 ctx->return_value = ret;
3211 }
3212
3213 /**
3214 * Given a v8i32 resource descriptor for a buffer, extract the size of the
3215 * buffer in number of elements and return it as an i32.
3216 */
3217 static LLVMValueRef get_buffer_size(
3218 struct lp_build_tgsi_context *bld_base,
3219 LLVMValueRef descriptor)
3220 {
3221 struct si_shader_context *ctx = si_shader_context(bld_base);
3222 struct gallivm_state *gallivm = bld_base->base.gallivm;
3223 LLVMBuilderRef builder = gallivm->builder;
3224 LLVMValueRef size =
3225 LLVMBuildExtractElement(builder, descriptor,
3226 lp_build_const_int32(gallivm, 2), "");
3227
3228 if (ctx->screen->b.chip_class >= VI) {
3229 /* On VI, the descriptor contains the size in bytes,
3230 * but TXQ must return the size in elements.
3231 * The stride is always non-zero for resources using TXQ.
3232 */
3233 LLVMValueRef stride =
3234 LLVMBuildExtractElement(builder, descriptor,
3235 lp_build_const_int32(gallivm, 1), "");
3236 stride = LLVMBuildLShr(builder, stride,
3237 lp_build_const_int32(gallivm, 16), "");
3238 stride = LLVMBuildAnd(builder, stride,
3239 lp_build_const_int32(gallivm, 0x3FFF), "");
3240
3241 size = LLVMBuildUDiv(builder, size, stride, "");
3242 }
3243
3244 return size;
3245 }
3246
3247 /**
3248 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
3249 * intrinsic names).
3250 */
3251 static void build_type_name_for_intr(
3252 LLVMTypeRef type,
3253 char *buf, unsigned bufsize)
3254 {
3255 LLVMTypeRef elem_type = type;
3256
3257 assert(bufsize >= 8);
3258
3259 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
3260 int ret = snprintf(buf, bufsize, "v%u",
3261 LLVMGetVectorSize(type));
3262 if (ret < 0) {
3263 char *type_name = LLVMPrintTypeToString(type);
3264 fprintf(stderr, "Error building type name for: %s\n",
3265 type_name);
3266 return;
3267 }
3268 elem_type = LLVMGetElementType(type);
3269 buf += ret;
3270 bufsize -= ret;
3271 }
3272 switch (LLVMGetTypeKind(elem_type)) {
3273 default: break;
3274 case LLVMIntegerTypeKind:
3275 snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
3276 break;
3277 case LLVMFloatTypeKind:
3278 snprintf(buf, bufsize, "f32");
3279 break;
3280 case LLVMDoubleTypeKind:
3281 snprintf(buf, bufsize, "f64");
3282 break;
3283 }
3284 }
3285
3286 static void build_tex_intrinsic(const struct lp_build_tgsi_action *action,
3287 struct lp_build_tgsi_context *bld_base,
3288 struct lp_build_emit_data *emit_data);
3289
3290 /* Prevent optimizations (at least of memory accesses) across the current
3291 * point in the program by emitting empty inline assembly that is marked as
3292 * having side effects.
3293 */
3294 #if 0 /* unused currently */
3295 static void emit_optimization_barrier(struct si_shader_context *ctx)
3296 {
3297 LLVMBuilderRef builder = ctx->gallivm.builder;
3298 LLVMTypeRef ftype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
3299 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, "", "", true, false);
3300 LLVMBuildCall(builder, inlineasm, NULL, 0, "");
3301 }
3302 #endif
3303
3304 /* Combine these with & instead of |. */
3305 #define NOOP_WAITCNT 0xf7f
3306 #define LGKM_CNT 0x07f
3307 #define VM_CNT 0xf70
3308
3309 static void emit_waitcnt(struct si_shader_context *ctx, unsigned simm16)
3310 {
3311 struct gallivm_state *gallivm = &ctx->gallivm;
3312 LLVMBuilderRef builder = gallivm->builder;
3313 LLVMValueRef args[1] = {
3314 lp_build_const_int32(gallivm, simm16)
3315 };
3316 lp_build_intrinsic(builder, "llvm.amdgcn.s.waitcnt",
3317 ctx->voidt, args, 1, 0);
3318 }
3319
3320 static void membar_emit(
3321 const struct lp_build_tgsi_action *action,
3322 struct lp_build_tgsi_context *bld_base,
3323 struct lp_build_emit_data *emit_data)
3324 {
3325 struct si_shader_context *ctx = si_shader_context(bld_base);
3326 LLVMValueRef src0 = lp_build_emit_fetch(bld_base, emit_data->inst, 0, 0);
3327 unsigned flags = LLVMConstIntGetZExtValue(src0);
3328 unsigned waitcnt = NOOP_WAITCNT;
3329
3330 if (flags & TGSI_MEMBAR_THREAD_GROUP)
3331 waitcnt &= VM_CNT & LGKM_CNT;
3332
3333 if (flags & (TGSI_MEMBAR_ATOMIC_BUFFER |
3334 TGSI_MEMBAR_SHADER_BUFFER |
3335 TGSI_MEMBAR_SHADER_IMAGE))
3336 waitcnt &= VM_CNT;
3337
3338 if (flags & TGSI_MEMBAR_SHARED)
3339 waitcnt &= LGKM_CNT;
3340
3341 if (waitcnt != NOOP_WAITCNT)
3342 emit_waitcnt(ctx, waitcnt);
3343 }
3344
3345 static LLVMValueRef
3346 shader_buffer_fetch_rsrc(struct si_shader_context *ctx,
3347 const struct tgsi_full_src_register *reg)
3348 {
3349 LLVMValueRef index;
3350 LLVMValueRef rsrc_ptr = LLVMGetParam(ctx->main_fn,
3351 SI_PARAM_SHADER_BUFFERS);
3352
3353 if (!reg->Register.Indirect)
3354 index = LLVMConstInt(ctx->i32, reg->Register.Index, 0);
3355 else
3356 index = get_bounded_indirect_index(ctx, &reg->Indirect,
3357 reg->Register.Index,
3358 SI_NUM_SHADER_BUFFERS);
3359
3360 return build_indexed_load_const(ctx, rsrc_ptr, index);
3361 }
3362
3363 static bool tgsi_is_array_sampler(unsigned target)
3364 {
3365 return target == TGSI_TEXTURE_1D_ARRAY ||
3366 target == TGSI_TEXTURE_SHADOW1D_ARRAY ||
3367 target == TGSI_TEXTURE_2D_ARRAY ||
3368 target == TGSI_TEXTURE_SHADOW2D_ARRAY ||
3369 target == TGSI_TEXTURE_CUBE_ARRAY ||
3370 target == TGSI_TEXTURE_SHADOWCUBE_ARRAY ||
3371 target == TGSI_TEXTURE_2D_ARRAY_MSAA;
3372 }
3373
3374 static bool tgsi_is_array_image(unsigned target)
3375 {
3376 return target == TGSI_TEXTURE_3D ||
3377 target == TGSI_TEXTURE_CUBE ||
3378 target == TGSI_TEXTURE_1D_ARRAY ||
3379 target == TGSI_TEXTURE_2D_ARRAY ||
3380 target == TGSI_TEXTURE_CUBE_ARRAY ||
3381 target == TGSI_TEXTURE_2D_ARRAY_MSAA;
3382 }
3383
3384 /**
3385 * Given a 256-bit resource descriptor, force the DCC enable bit to off.
3386 *
3387 * At least on Tonga, executing image stores on images with DCC enabled and
3388 * non-trivial can eventually lead to lockups. This can occur when an
3389 * application binds an image as read-only but then uses a shader that writes
3390 * to it. The OpenGL spec allows almost arbitrarily bad behavior (including
3391 * program termination) in this case, but it doesn't cost much to be a bit
3392 * nicer: disabling DCC in the shader still leads to undefined results but
3393 * avoids the lockup.
3394 */
3395 static LLVMValueRef force_dcc_off(struct si_shader_context *ctx,
3396 LLVMValueRef rsrc)
3397 {
3398 if (ctx->screen->b.chip_class <= CIK) {
3399 return rsrc;
3400 } else {
3401 LLVMBuilderRef builder = ctx->gallivm.builder;
3402 LLVMValueRef i32_6 = LLVMConstInt(ctx->i32, 6, 0);
3403 LLVMValueRef i32_C = LLVMConstInt(ctx->i32, C_008F28_COMPRESSION_EN, 0);
3404 LLVMValueRef tmp;
3405
3406 tmp = LLVMBuildExtractElement(builder, rsrc, i32_6, "");
3407 tmp = LLVMBuildAnd(builder, tmp, i32_C, "");
3408 return LLVMBuildInsertElement(builder, rsrc, tmp, i32_6, "");
3409 }
3410 }
3411
3412 static LLVMTypeRef const_array(LLVMTypeRef elem_type, int num_elements)
3413 {
3414 return LLVMPointerType(LLVMArrayType(elem_type, num_elements),
3415 CONST_ADDR_SPACE);
3416 }
3417
3418 /**
3419 * Load the resource descriptor for \p image.
3420 */
3421 static void
3422 image_fetch_rsrc(
3423 struct lp_build_tgsi_context *bld_base,
3424 const struct tgsi_full_src_register *image,
3425 bool is_store, unsigned target,
3426 LLVMValueRef *rsrc)
3427 {
3428 struct si_shader_context *ctx = si_shader_context(bld_base);
3429 LLVMValueRef rsrc_ptr = LLVMGetParam(ctx->main_fn,
3430 SI_PARAM_IMAGES);
3431 LLVMValueRef index, tmp;
3432 bool dcc_off = target != TGSI_TEXTURE_BUFFER && is_store;
3433
3434 assert(image->Register.File == TGSI_FILE_IMAGE);
3435
3436 if (!image->Register.Indirect) {
3437 const struct tgsi_shader_info *info = bld_base->info;
3438
3439 index = LLVMConstInt(ctx->i32, image->Register.Index, 0);
3440
3441 if (info->images_writemask & (1 << image->Register.Index) &&
3442 target != TGSI_TEXTURE_BUFFER)
3443 dcc_off = true;
3444 } else {
3445 /* From the GL_ARB_shader_image_load_store extension spec:
3446 *
3447 * If a shader performs an image load, store, or atomic
3448 * operation using an image variable declared as an array,
3449 * and if the index used to select an individual element is
3450 * negative or greater than or equal to the size of the
3451 * array, the results of the operation are undefined but may
3452 * not lead to termination.
3453 */
3454 index = get_bounded_indirect_index(ctx, &image->Indirect,
3455 image->Register.Index,
3456 SI_NUM_IMAGES);
3457 }
3458
3459 if (target == TGSI_TEXTURE_BUFFER) {
3460 LLVMBuilderRef builder = ctx->gallivm.builder;
3461
3462 rsrc_ptr = LLVMBuildPointerCast(builder, rsrc_ptr,
3463 const_array(ctx->v4i32, 0), "");
3464 index = LLVMBuildMul(builder, index,
3465 LLVMConstInt(ctx->i32, 2, 0), "");
3466 index = LLVMBuildAdd(builder, index,
3467 LLVMConstInt(ctx->i32, 1, 0), "");
3468 *rsrc = build_indexed_load_const(ctx, rsrc_ptr, index);
3469 return;
3470 }
3471
3472 tmp = build_indexed_load_const(ctx, rsrc_ptr, index);
3473 if (dcc_off)
3474 tmp = force_dcc_off(ctx, tmp);
3475 *rsrc = tmp;
3476 }
3477
3478 static LLVMValueRef image_fetch_coords(
3479 struct lp_build_tgsi_context *bld_base,
3480 const struct tgsi_full_instruction *inst,
3481 unsigned src)
3482 {
3483 struct gallivm_state *gallivm = bld_base->base.gallivm;
3484 LLVMBuilderRef builder = gallivm->builder;
3485 unsigned target = inst->Memory.Texture;
3486 unsigned num_coords = tgsi_util_get_texture_coord_dim(target);
3487 LLVMValueRef coords[4];
3488 LLVMValueRef tmp;
3489 int chan;
3490
3491 for (chan = 0; chan < num_coords; ++chan) {
3492 tmp = lp_build_emit_fetch(bld_base, inst, src, chan);
3493 tmp = LLVMBuildBitCast(builder, tmp, bld_base->uint_bld.elem_type, "");
3494 coords[chan] = tmp;
3495 }
3496
3497 if (num_coords == 1)
3498 return coords[0];
3499
3500 if (num_coords == 3) {
3501 /* LLVM has difficulties lowering 3-element vectors. */
3502 coords[3] = bld_base->uint_bld.undef;
3503 num_coords = 4;
3504 }
3505
3506 return lp_build_gather_values(gallivm, coords, num_coords);
3507 }
3508
3509 /**
3510 * Append the extra mode bits that are used by image load and store.
3511 */
3512 static void image_append_args(
3513 struct si_shader_context *ctx,
3514 struct lp_build_emit_data * emit_data,
3515 unsigned target,
3516 bool atomic,
3517 bool force_glc)
3518 {
3519 const struct tgsi_full_instruction *inst = emit_data->inst;
3520 LLVMValueRef i1false = LLVMConstInt(ctx->i1, 0, 0);
3521 LLVMValueRef i1true = LLVMConstInt(ctx->i1, 1, 0);
3522 LLVMValueRef r128 = i1false;
3523 LLVMValueRef da = tgsi_is_array_image(target) ? i1true : i1false;
3524 LLVMValueRef glc =
3525 force_glc ||
3526 inst->Memory.Qualifier & (TGSI_MEMORY_COHERENT | TGSI_MEMORY_VOLATILE) ?
3527 i1true : i1false;
3528 LLVMValueRef slc = i1false;
3529 LLVMValueRef lwe = i1false;
3530
3531 if (atomic || (HAVE_LLVM <= 0x0309)) {
3532 emit_data->args[emit_data->arg_count++] = r128;
3533 emit_data->args[emit_data->arg_count++] = da;
3534 if (!atomic) {
3535 emit_data->args[emit_data->arg_count++] = glc;
3536 }
3537 emit_data->args[emit_data->arg_count++] = slc;
3538 return;
3539 }
3540
3541 /* HAVE_LLVM >= 0x0400 */
3542 emit_data->args[emit_data->arg_count++] = glc;
3543 emit_data->args[emit_data->arg_count++] = slc;
3544 emit_data->args[emit_data->arg_count++] = lwe;
3545 emit_data->args[emit_data->arg_count++] = da;
3546 }
3547
3548 /**
3549 * Append the resource and indexing arguments for buffer intrinsics.
3550 *
3551 * \param rsrc the v4i32 buffer resource
3552 * \param index index into the buffer (stride-based)
3553 * \param offset byte offset into the buffer
3554 */
3555 static void buffer_append_args(
3556 struct si_shader_context *ctx,
3557 struct lp_build_emit_data *emit_data,
3558 LLVMValueRef rsrc,
3559 LLVMValueRef index,
3560 LLVMValueRef offset,
3561 bool atomic,
3562 bool force_glc)
3563 {
3564 const struct tgsi_full_instruction *inst = emit_data->inst;
3565 LLVMValueRef i1false = LLVMConstInt(ctx->i1, 0, 0);
3566 LLVMValueRef i1true = LLVMConstInt(ctx->i1, 1, 0);
3567
3568 emit_data->args[emit_data->arg_count++] = rsrc;
3569 emit_data->args[emit_data->arg_count++] = index; /* vindex */
3570 emit_data->args[emit_data->arg_count++] = offset; /* voffset */
3571 if (!atomic) {
3572 emit_data->args[emit_data->arg_count++] =
3573 force_glc ||
3574 inst->Memory.Qualifier & (TGSI_MEMORY_COHERENT | TGSI_MEMORY_VOLATILE) ?
3575 i1true : i1false; /* glc */
3576 }
3577 emit_data->args[emit_data->arg_count++] = i1false; /* slc */
3578 }
3579
3580 static void load_fetch_args(
3581 struct lp_build_tgsi_context * bld_base,
3582 struct lp_build_emit_data * emit_data)
3583 {
3584 struct si_shader_context *ctx = si_shader_context(bld_base);
3585 struct gallivm_state *gallivm = bld_base->base.gallivm;
3586 const struct tgsi_full_instruction * inst = emit_data->inst;
3587 unsigned target = inst->Memory.Texture;
3588 LLVMValueRef rsrc;
3589
3590 emit_data->dst_type = LLVMVectorType(bld_base->base.elem_type, 4);
3591
3592 if (inst->Src[0].Register.File == TGSI_FILE_BUFFER) {
3593 LLVMBuilderRef builder = gallivm->builder;
3594 LLVMValueRef offset;
3595 LLVMValueRef tmp;
3596
3597 rsrc = shader_buffer_fetch_rsrc(ctx, &inst->Src[0]);
3598
3599 tmp = lp_build_emit_fetch(bld_base, inst, 1, 0);
3600 offset = LLVMBuildBitCast(builder, tmp, bld_base->uint_bld.elem_type, "");
3601
3602 buffer_append_args(ctx, emit_data, rsrc, bld_base->uint_bld.zero,
3603 offset, false, false);
3604 } else if (inst->Src[0].Register.File == TGSI_FILE_IMAGE) {
3605 LLVMValueRef coords;
3606
3607 image_fetch_rsrc(bld_base, &inst->Src[0], false, target, &rsrc);
3608 coords = image_fetch_coords(bld_base, inst, 1);
3609
3610 if (target == TGSI_TEXTURE_BUFFER) {
3611 buffer_append_args(ctx, emit_data, rsrc, coords,
3612 bld_base->uint_bld.zero, false, false);
3613 } else {
3614 emit_data->args[0] = coords;
3615 emit_data->args[1] = rsrc;
3616 emit_data->args[2] = lp_build_const_int32(gallivm, 15); /* dmask */
3617 emit_data->arg_count = 3;
3618
3619 image_append_args(ctx, emit_data, target, false, false);
3620 }
3621 }
3622 }
3623
3624 static void load_emit_buffer(struct si_shader_context *ctx,
3625 struct lp_build_emit_data *emit_data)
3626 {
3627 const struct tgsi_full_instruction *inst = emit_data->inst;
3628 struct gallivm_state *gallivm = &ctx->gallivm;
3629 LLVMBuilderRef builder = gallivm->builder;
3630 uint writemask = inst->Dst[0].Register.WriteMask;
3631 uint count = util_last_bit(writemask);
3632 const char *intrinsic_name;
3633 LLVMTypeRef dst_type;
3634
3635 switch (count) {
3636 case 1:
3637 intrinsic_name = "llvm.amdgcn.buffer.load.f32";
3638 dst_type = ctx->f32;
3639 break;
3640 case 2:
3641 intrinsic_name = "llvm.amdgcn.buffer.load.v2f32";
3642 dst_type = LLVMVectorType(ctx->f32, 2);
3643 break;
3644 default: // 3 & 4
3645 intrinsic_name = "llvm.amdgcn.buffer.load.v4f32";
3646 dst_type = ctx->v4f32;
3647 count = 4;
3648 }
3649
3650 emit_data->output[emit_data->chan] = lp_build_intrinsic(
3651 builder, intrinsic_name, dst_type,
3652 emit_data->args, emit_data->arg_count,
3653 LP_FUNC_ATTR_READONLY);
3654 }
3655
3656 static LLVMValueRef get_memory_ptr(struct si_shader_context *ctx,
3657 const struct tgsi_full_instruction *inst,
3658 LLVMTypeRef type, int arg)
3659 {
3660 struct gallivm_state *gallivm = &ctx->gallivm;
3661 LLVMBuilderRef builder = gallivm->builder;
3662 LLVMValueRef offset, ptr;
3663 int addr_space;
3664
3665 offset = lp_build_emit_fetch(&ctx->soa.bld_base, inst, arg, 0);
3666 offset = LLVMBuildBitCast(builder, offset, ctx->i32, "");
3667
3668 ptr = ctx->shared_memory;
3669 ptr = LLVMBuildGEP(builder, ptr, &offset, 1, "");
3670 addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
3671 ptr = LLVMBuildBitCast(builder, ptr, LLVMPointerType(type, addr_space), "");
3672
3673 return ptr;
3674 }
3675
3676 static void load_emit_memory(
3677 struct si_shader_context *ctx,
3678 struct lp_build_emit_data *emit_data)
3679 {
3680 const struct tgsi_full_instruction *inst = emit_data->inst;
3681 struct lp_build_context *base = &ctx->soa.bld_base.base;
3682 struct gallivm_state *gallivm = &ctx->gallivm;
3683 LLVMBuilderRef builder = gallivm->builder;
3684 unsigned writemask = inst->Dst[0].Register.WriteMask;
3685 LLVMValueRef channels[4], ptr, derived_ptr, index;
3686 int chan;
3687
3688 ptr = get_memory_ptr(ctx, inst, base->elem_type, 1);
3689
3690 for (chan = 0; chan < 4; ++chan) {
3691 if (!(writemask & (1 << chan))) {
3692 channels[chan] = LLVMGetUndef(base->elem_type);
3693 continue;
3694 }
3695
3696 index = lp_build_const_int32(gallivm, chan);
3697 derived_ptr = LLVMBuildGEP(builder, ptr, &index, 1, "");
3698 channels[chan] = LLVMBuildLoad(builder, derived_ptr, "");
3699 }
3700 emit_data->output[emit_data->chan] = lp_build_gather_values(gallivm, channels, 4);
3701 }
3702
3703 static void get_image_intr_name(const char *base_name,
3704 LLVMTypeRef data_type,
3705 LLVMTypeRef coords_type,
3706 LLVMTypeRef rsrc_type,
3707 char *out_name, unsigned out_len)
3708 {
3709 char coords_type_name[8];
3710
3711 build_type_name_for_intr(coords_type, coords_type_name,
3712 sizeof(coords_type_name));
3713
3714 if (HAVE_LLVM <= 0x0309) {
3715 snprintf(out_name, out_len, "%s.%s", base_name, coords_type_name);
3716 } else {
3717 char data_type_name[8];
3718 char rsrc_type_name[8];
3719
3720 build_type_name_for_intr(data_type, data_type_name,
3721 sizeof(data_type_name));
3722 build_type_name_for_intr(rsrc_type, rsrc_type_name,
3723 sizeof(rsrc_type_name));
3724 snprintf(out_name, out_len, "%s.%s.%s.%s", base_name,
3725 data_type_name, coords_type_name, rsrc_type_name);
3726 }
3727 }
3728
3729 static void load_emit(
3730 const struct lp_build_tgsi_action *action,
3731 struct lp_build_tgsi_context *bld_base,
3732 struct lp_build_emit_data *emit_data)
3733 {
3734 struct si_shader_context *ctx = si_shader_context(bld_base);
3735 struct gallivm_state *gallivm = bld_base->base.gallivm;
3736 LLVMBuilderRef builder = gallivm->builder;
3737 const struct tgsi_full_instruction * inst = emit_data->inst;
3738 char intrinsic_name[64];
3739
3740 if (inst->Src[0].Register.File == TGSI_FILE_MEMORY) {
3741 load_emit_memory(ctx, emit_data);
3742 return;
3743 }
3744
3745 if (inst->Memory.Qualifier & TGSI_MEMORY_VOLATILE)
3746 emit_waitcnt(ctx, VM_CNT);
3747
3748 if (inst->Src[0].Register.File == TGSI_FILE_BUFFER) {
3749 load_emit_buffer(ctx, emit_data);
3750 return;
3751 }
3752
3753 if (inst->Memory.Texture == TGSI_TEXTURE_BUFFER) {
3754 emit_data->output[emit_data->chan] =
3755 lp_build_intrinsic(
3756 builder, "llvm.amdgcn.buffer.load.format.v4f32", emit_data->dst_type,
3757 emit_data->args, emit_data->arg_count,
3758 LP_FUNC_ATTR_READONLY);
3759 } else {
3760 get_image_intr_name("llvm.amdgcn.image.load",
3761 emit_data->dst_type, /* vdata */
3762 LLVMTypeOf(emit_data->args[0]), /* coords */
3763 LLVMTypeOf(emit_data->args[1]), /* rsrc */
3764 intrinsic_name, sizeof(intrinsic_name));
3765
3766 emit_data->output[emit_data->chan] =
3767 lp_build_intrinsic(
3768 builder, intrinsic_name, emit_data->dst_type,
3769 emit_data->args, emit_data->arg_count,
3770 LP_FUNC_ATTR_READONLY);
3771 }
3772 }
3773
3774 static void store_fetch_args(
3775 struct lp_build_tgsi_context * bld_base,
3776 struct lp_build_emit_data * emit_data)
3777 {
3778 struct si_shader_context *ctx = si_shader_context(bld_base);
3779 struct gallivm_state *gallivm = bld_base->base.gallivm;
3780 LLVMBuilderRef builder = gallivm->builder;
3781 const struct tgsi_full_instruction * inst = emit_data->inst;
3782 struct tgsi_full_src_register memory;
3783 LLVMValueRef chans[4];
3784 LLVMValueRef data;
3785 LLVMValueRef rsrc;
3786 unsigned chan;
3787
3788 emit_data->dst_type = LLVMVoidTypeInContext(gallivm->context);
3789
3790 for (chan = 0; chan < 4; ++chan) {
3791 chans[chan] = lp_build_emit_fetch(bld_base, inst, 1, chan);
3792 }
3793 data = lp_build_gather_values(gallivm, chans, 4);
3794
3795 emit_data->args[emit_data->arg_count++] = data;
3796
3797 memory = tgsi_full_src_register_from_dst(&inst->Dst[0]);
3798
3799 if (inst->Dst[0].Register.File == TGSI_FILE_BUFFER) {
3800 LLVMValueRef offset;
3801 LLVMValueRef tmp;
3802
3803 rsrc = shader_buffer_fetch_rsrc(ctx, &memory);
3804
3805 tmp = lp_build_emit_fetch(bld_base, inst, 0, 0);
3806 offset = LLVMBuildBitCast(builder, tmp, bld_base->uint_bld.elem_type, "");
3807
3808 buffer_append_args(ctx, emit_data, rsrc, bld_base->uint_bld.zero,
3809 offset, false, false);
3810 } else if (inst->Dst[0].Register.File == TGSI_FILE_IMAGE) {
3811 unsigned target = inst->Memory.Texture;
3812 LLVMValueRef coords;
3813
3814 /* 8bit/16bit TC L1 write corruption bug on SI.
3815 * All store opcodes not aligned to a dword are affected.
3816 *
3817 * The only way to get unaligned stores in radeonsi is through
3818 * shader images.
3819 */
3820 bool force_glc = ctx->screen->b.chip_class == SI;
3821
3822 coords = image_fetch_coords(bld_base, inst, 0);
3823
3824 if (target == TGSI_TEXTURE_BUFFER) {
3825 image_fetch_rsrc(bld_base, &memory, true, target, &rsrc);
3826 buffer_append_args(ctx, emit_data, rsrc, coords,
3827 bld_base->uint_bld.zero, false, force_glc);
3828 } else {
3829 emit_data->args[1] = coords;
3830 image_fetch_rsrc(bld_base, &memory, true, target,
3831 &emit_data->args[2]);
3832 emit_data->args[3] = lp_build_const_int32(gallivm, 15); /* dmask */
3833 emit_data->arg_count = 4;
3834
3835 image_append_args(ctx, emit_data, target, false, force_glc);
3836 }
3837 }
3838 }
3839
3840 static void store_emit_buffer(
3841 struct si_shader_context *ctx,
3842 struct lp_build_emit_data *emit_data)
3843 {
3844 const struct tgsi_full_instruction *inst = emit_data->inst;
3845 struct gallivm_state *gallivm = &ctx->gallivm;
3846 LLVMBuilderRef builder = gallivm->builder;
3847 struct lp_build_context *uint_bld = &ctx->soa.bld_base.uint_bld;
3848 LLVMValueRef base_data = emit_data->args[0];
3849 LLVMValueRef base_offset = emit_data->args[3];
3850 unsigned writemask = inst->Dst[0].Register.WriteMask;
3851
3852 while (writemask) {
3853 int start, count;
3854 const char *intrinsic_name;
3855 LLVMValueRef data;
3856 LLVMValueRef offset;
3857 LLVMValueRef tmp;
3858
3859 u_bit_scan_consecutive_range(&writemask, &start, &count);
3860
3861 /* Due to an LLVM limitation, split 3-element writes
3862 * into a 2-element and a 1-element write. */
3863 if (count == 3) {
3864 writemask |= 1 << (start + 2);
3865 count = 2;
3866 }
3867
3868 if (count == 4) {
3869 data = base_data;
3870 intrinsic_name = "llvm.amdgcn.buffer.store.v4f32";
3871 } else if (count == 2) {
3872 LLVMTypeRef v2f32 = LLVMVectorType(ctx->f32, 2);
3873
3874 tmp = LLVMBuildExtractElement(
3875 builder, base_data,
3876 lp_build_const_int32(gallivm, start), "");
3877 data = LLVMBuildInsertElement(
3878 builder, LLVMGetUndef(v2f32), tmp,
3879 uint_bld->zero, "");
3880
3881 tmp = LLVMBuildExtractElement(
3882 builder, base_data,
3883 lp_build_const_int32(gallivm, start + 1), "");
3884 data = LLVMBuildInsertElement(
3885 builder, data, tmp, uint_bld->one, "");
3886
3887 intrinsic_name = "llvm.amdgcn.buffer.store.v2f32";
3888 } else {
3889 assert(count == 1);
3890 data = LLVMBuildExtractElement(
3891 builder, base_data,
3892 lp_build_const_int32(gallivm, start), "");
3893 intrinsic_name = "llvm.amdgcn.buffer.store.f32";
3894 }
3895
3896 offset = base_offset;
3897 if (start != 0) {
3898 offset = LLVMBuildAdd(
3899 builder, offset,
3900 lp_build_const_int32(gallivm, start * 4), "");
3901 }
3902
3903 emit_data->args[0] = data;
3904 emit_data->args[3] = offset;
3905
3906 lp_build_intrinsic(
3907 builder, intrinsic_name, emit_data->dst_type,
3908 emit_data->args, emit_data->arg_count, 0);
3909 }
3910 }
3911
3912 static void store_emit_memory(
3913 struct si_shader_context *ctx,
3914 struct lp_build_emit_data *emit_data)
3915 {
3916 const struct tgsi_full_instruction *inst = emit_data->inst;
3917 struct gallivm_state *gallivm = &ctx->gallivm;
3918 struct lp_build_context *base = &ctx->soa.bld_base.base;
3919 LLVMBuilderRef builder = gallivm->builder;
3920 unsigned writemask = inst->Dst[0].Register.WriteMask;
3921 LLVMValueRef ptr, derived_ptr, data, index;
3922 int chan;
3923
3924 ptr = get_memory_ptr(ctx, inst, base->elem_type, 0);
3925
3926 for (chan = 0; chan < 4; ++chan) {
3927 if (!(writemask & (1 << chan))) {
3928 continue;
3929 }
3930 data = lp_build_emit_fetch(&ctx->soa.bld_base, inst, 1, chan);
3931 index = lp_build_const_int32(gallivm, chan);
3932 derived_ptr = LLVMBuildGEP(builder, ptr, &index, 1, "");
3933 LLVMBuildStore(builder, data, derived_ptr);
3934 }
3935 }
3936
3937 static void store_emit(
3938 const struct lp_build_tgsi_action *action,
3939 struct lp_build_tgsi_context *bld_base,
3940 struct lp_build_emit_data *emit_data)
3941 {
3942 struct si_shader_context *ctx = si_shader_context(bld_base);
3943 struct gallivm_state *gallivm = bld_base->base.gallivm;
3944 LLVMBuilderRef builder = gallivm->builder;
3945 const struct tgsi_full_instruction * inst = emit_data->inst;
3946 unsigned target = inst->Memory.Texture;
3947 char intrinsic_name[64];
3948
3949 if (inst->Dst[0].Register.File == TGSI_FILE_MEMORY) {
3950 store_emit_memory(ctx, emit_data);
3951 return;
3952 }
3953
3954 if (inst->Memory.Qualifier & TGSI_MEMORY_VOLATILE)
3955 emit_waitcnt(ctx, VM_CNT);
3956
3957 if (inst->Dst[0].Register.File == TGSI_FILE_BUFFER) {
3958 store_emit_buffer(ctx, emit_data);
3959 return;
3960 }
3961
3962 if (target == TGSI_TEXTURE_BUFFER) {
3963 emit_data->output[emit_data->chan] = lp_build_intrinsic(
3964 builder, "llvm.amdgcn.buffer.store.format.v4f32",
3965 emit_data->dst_type, emit_data->args,
3966 emit_data->arg_count, 0);
3967 } else {
3968 get_image_intr_name("llvm.amdgcn.image.store",
3969 LLVMTypeOf(emit_data->args[0]), /* vdata */
3970 LLVMTypeOf(emit_data->args[1]), /* coords */
3971 LLVMTypeOf(emit_data->args[2]), /* rsrc */
3972 intrinsic_name, sizeof(intrinsic_name));
3973
3974 emit_data->output[emit_data->chan] =
3975 lp_build_intrinsic(
3976 builder, intrinsic_name, emit_data->dst_type,
3977 emit_data->args, emit_data->arg_count, 0);
3978 }
3979 }
3980
3981 static void atomic_fetch_args(
3982 struct lp_build_tgsi_context * bld_base,
3983 struct lp_build_emit_data * emit_data)
3984 {
3985 struct si_shader_context *ctx = si_shader_context(bld_base);
3986 struct gallivm_state *gallivm = bld_base->base.gallivm;
3987 LLVMBuilderRef builder = gallivm->builder;
3988 const struct tgsi_full_instruction * inst = emit_data->inst;
3989 LLVMValueRef data1, data2;
3990 LLVMValueRef rsrc;
3991 LLVMValueRef tmp;
3992
3993 emit_data->dst_type = bld_base->base.elem_type;
3994
3995 tmp = lp_build_emit_fetch(bld_base, inst, 2, 0);
3996 data1 = LLVMBuildBitCast(builder, tmp, bld_base->uint_bld.elem_type, "");
3997
3998 if (inst->Instruction.Opcode == TGSI_OPCODE_ATOMCAS) {
3999 tmp = lp_build_emit_fetch(bld_base, inst, 3, 0);
4000 data2 = LLVMBuildBitCast(builder, tmp, bld_base->uint_bld.elem_type, "");
4001 }
4002
4003 /* llvm.amdgcn.image/buffer.atomic.cmpswap reflect the hardware order
4004 * of arguments, which is reversed relative to TGSI (and GLSL)
4005 */
4006 if (inst->Instruction.Opcode == TGSI_OPCODE_ATOMCAS)
4007 emit_data->args[emit_data->arg_count++] = data2;
4008 emit_data->args[emit_data->arg_count++] = data1;
4009
4010 if (inst->Src[0].Register.File == TGSI_FILE_BUFFER) {
4011 LLVMValueRef offset;
4012
4013 rsrc = shader_buffer_fetch_rsrc(ctx, &inst->Src[0]);
4014
4015 tmp = lp_build_emit_fetch(bld_base, inst, 1, 0);
4016 offset = LLVMBuildBitCast(builder, tmp, bld_base->uint_bld.elem_type, "");
4017
4018 buffer_append_args(ctx, emit_data, rsrc, bld_base->uint_bld.zero,
4019 offset, true, false);
4020 } else if (inst->Src[0].Register.File == TGSI_FILE_IMAGE) {
4021 unsigned target = inst->Memory.Texture;
4022 LLVMValueRef coords;
4023
4024 image_fetch_rsrc(bld_base, &inst->Src[0], true, target, &rsrc);
4025 coords = image_fetch_coords(bld_base, inst, 1);
4026
4027 if (target == TGSI_TEXTURE_BUFFER) {
4028 buffer_append_args(ctx, emit_data, rsrc, coords,
4029 bld_base->uint_bld.zero, true, false);
4030 } else {
4031 emit_data->args[emit_data->arg_count++] = coords;
4032 emit_data->args[emit_data->arg_count++] = rsrc;
4033
4034 image_append_args(ctx, emit_data, target, true, false);
4035 }
4036 }
4037 }
4038
4039 static void atomic_emit_memory(struct si_shader_context *ctx,
4040 struct lp_build_emit_data *emit_data) {
4041 struct gallivm_state *gallivm = &ctx->gallivm;
4042 LLVMBuilderRef builder = gallivm->builder;
4043 const struct tgsi_full_instruction * inst = emit_data->inst;
4044 LLVMValueRef ptr, result, arg;
4045
4046 ptr = get_memory_ptr(ctx, inst, ctx->i32, 1);
4047
4048 arg = lp_build_emit_fetch(&ctx->soa.bld_base, inst, 2, 0);
4049 arg = LLVMBuildBitCast(builder, arg, ctx->i32, "");
4050
4051 if (inst->Instruction.Opcode == TGSI_OPCODE_ATOMCAS) {
4052 LLVMValueRef new_data;
4053 new_data = lp_build_emit_fetch(&ctx->soa.bld_base,
4054 inst, 3, 0);
4055
4056 new_data = LLVMBuildBitCast(builder, new_data, ctx->i32, "");
4057
4058 #if HAVE_LLVM >= 0x309
4059 result = LLVMBuildAtomicCmpXchg(builder, ptr, arg, new_data,
4060 LLVMAtomicOrderingSequentiallyConsistent,
4061 LLVMAtomicOrderingSequentiallyConsistent,
4062 false);
4063 #endif
4064
4065 result = LLVMBuildExtractValue(builder, result, 0, "");
4066 } else {
4067 LLVMAtomicRMWBinOp op;
4068
4069 switch(inst->Instruction.Opcode) {
4070 case TGSI_OPCODE_ATOMUADD:
4071 op = LLVMAtomicRMWBinOpAdd;
4072 break;
4073 case TGSI_OPCODE_ATOMXCHG:
4074 op = LLVMAtomicRMWBinOpXchg;
4075 break;
4076 case TGSI_OPCODE_ATOMAND:
4077 op = LLVMAtomicRMWBinOpAnd;
4078 break;
4079 case TGSI_OPCODE_ATOMOR:
4080 op = LLVMAtomicRMWBinOpOr;
4081 break;
4082 case TGSI_OPCODE_ATOMXOR:
4083 op = LLVMAtomicRMWBinOpXor;
4084 break;
4085 case TGSI_OPCODE_ATOMUMIN:
4086 op = LLVMAtomicRMWBinOpUMin;
4087 break;
4088 case TGSI_OPCODE_ATOMUMAX:
4089 op = LLVMAtomicRMWBinOpUMax;
4090 break;
4091 case TGSI_OPCODE_ATOMIMIN:
4092 op = LLVMAtomicRMWBinOpMin;
4093 break;
4094 case TGSI_OPCODE_ATOMIMAX:
4095 op = LLVMAtomicRMWBinOpMax;
4096 break;
4097 default:
4098 unreachable("unknown atomic opcode");
4099 }
4100
4101 result = LLVMBuildAtomicRMW(builder, op, ptr, arg,
4102 LLVMAtomicOrderingSequentiallyConsistent,
4103 false);
4104 }
4105 emit_data->output[emit_data->chan] = LLVMBuildBitCast(builder, result, emit_data->dst_type, "");
4106 }
4107
4108 static void atomic_emit(
4109 const struct lp_build_tgsi_action *action,
4110 struct lp_build_tgsi_context *bld_base,
4111 struct lp_build_emit_data *emit_data)
4112 {
4113 struct si_shader_context *ctx = si_shader_context(bld_base);
4114 struct gallivm_state *gallivm = bld_base->base.gallivm;
4115 LLVMBuilderRef builder = gallivm->builder;
4116 const struct tgsi_full_instruction * inst = emit_data->inst;
4117 char intrinsic_name[40];
4118 LLVMValueRef tmp;
4119
4120 if (inst->Src[0].Register.File == TGSI_FILE_MEMORY) {
4121 atomic_emit_memory(ctx, emit_data);
4122 return;
4123 }
4124
4125 if (inst->Src[0].Register.File == TGSI_FILE_BUFFER ||
4126 inst->Memory.Texture == TGSI_TEXTURE_BUFFER) {
4127 snprintf(intrinsic_name, sizeof(intrinsic_name),
4128 "llvm.amdgcn.buffer.atomic.%s", action->intr_name);
4129 } else {
4130 LLVMValueRef coords;
4131 char coords_type[8];
4132
4133 if (inst->Instruction.Opcode == TGSI_OPCODE_ATOMCAS)
4134 coords = emit_data->args[2];
4135 else
4136 coords = emit_data->args[1];
4137
4138 build_type_name_for_intr(LLVMTypeOf(coords), coords_type, sizeof(coords_type));
4139 snprintf(intrinsic_name, sizeof(intrinsic_name),
4140 "llvm.amdgcn.image.atomic.%s.%s",
4141 action->intr_name, coords_type);
4142 }
4143
4144 tmp = lp_build_intrinsic(
4145 builder, intrinsic_name, bld_base->uint_bld.elem_type,
4146 emit_data->args, emit_data->arg_count, 0);
4147 emit_data->output[emit_data->chan] =
4148 LLVMBuildBitCast(builder, tmp, bld_base->base.elem_type, "");
4149 }
4150
4151 static void resq_fetch_args(
4152 struct lp_build_tgsi_context * bld_base,
4153 struct lp_build_emit_data * emit_data)
4154 {
4155 struct si_shader_context *ctx = si_shader_context(bld_base);
4156 struct gallivm_state *gallivm = bld_base->base.gallivm;
4157 const struct tgsi_full_instruction *inst = emit_data->inst;
4158 const struct tgsi_full_src_register *reg = &inst->Src[0];
4159
4160 emit_data->dst_type = ctx->v4i32;
4161
4162 if (reg->Register.File == TGSI_FILE_BUFFER) {
4163 emit_data->args[0] = shader_buffer_fetch_rsrc(ctx, reg);
4164 emit_data->arg_count = 1;
4165 } else if (inst->Memory.Texture == TGSI_TEXTURE_BUFFER) {
4166 image_fetch_rsrc(bld_base, reg, false, inst->Memory.Texture,
4167 &emit_data->args[0]);
4168 emit_data->arg_count = 1;
4169 } else {
4170 emit_data->args[0] = bld_base->uint_bld.zero; /* mip level */
4171 image_fetch_rsrc(bld_base, reg, false, inst->Memory.Texture,
4172 &emit_data->args[1]);
4173 emit_data->args[2] = lp_build_const_int32(gallivm, 15); /* dmask */
4174 emit_data->args[3] = bld_base->uint_bld.zero; /* unorm */
4175 emit_data->args[4] = bld_base->uint_bld.zero; /* r128 */
4176 emit_data->args[5] = tgsi_is_array_image(inst->Memory.Texture) ?
4177 bld_base->uint_bld.one : bld_base->uint_bld.zero; /* da */
4178 emit_data->args[6] = bld_base->uint_bld.zero; /* glc */
4179 emit_data->args[7] = bld_base->uint_bld.zero; /* slc */
4180 emit_data->args[8] = bld_base->uint_bld.zero; /* tfe */
4181 emit_data->args[9] = bld_base->uint_bld.zero; /* lwe */
4182 emit_data->arg_count = 10;
4183 }
4184 }
4185
4186 static void resq_emit(
4187 const struct lp_build_tgsi_action *action,
4188 struct lp_build_tgsi_context *bld_base,
4189 struct lp_build_emit_data *emit_data)
4190 {
4191 struct gallivm_state *gallivm = bld_base->base.gallivm;
4192 LLVMBuilderRef builder = gallivm->builder;
4193 const struct tgsi_full_instruction *inst = emit_data->inst;
4194 LLVMValueRef out;
4195
4196 if (inst->Src[0].Register.File == TGSI_FILE_BUFFER) {
4197 out = LLVMBuildExtractElement(builder, emit_data->args[0],
4198 lp_build_const_int32(gallivm, 2), "");
4199 } else if (inst->Memory.Texture == TGSI_TEXTURE_BUFFER) {
4200 out = get_buffer_size(bld_base, emit_data->args[0]);
4201 } else {
4202 out = lp_build_intrinsic(
4203 builder, "llvm.SI.getresinfo.i32", emit_data->dst_type,
4204 emit_data->args, emit_data->arg_count,
4205 LP_FUNC_ATTR_READNONE);
4206
4207 /* Divide the number of layers by 6 to get the number of cubes. */
4208 if (inst->Memory.Texture == TGSI_TEXTURE_CUBE_ARRAY) {
4209 LLVMValueRef imm2 = lp_build_const_int32(gallivm, 2);
4210 LLVMValueRef imm6 = lp_build_const_int32(gallivm, 6);
4211
4212 LLVMValueRef z = LLVMBuildExtractElement(builder, out, imm2, "");
4213 z = LLVMBuildSDiv(builder, z, imm6, "");
4214 out = LLVMBuildInsertElement(builder, out, z, imm2, "");
4215 }
4216 }
4217
4218 emit_data->output[emit_data->chan] = out;
4219 }
4220
4221 static void set_tex_fetch_args(struct si_shader_context *ctx,
4222 struct lp_build_emit_data *emit_data,
4223 unsigned opcode, unsigned target,
4224 LLVMValueRef res_ptr, LLVMValueRef samp_ptr,
4225 LLVMValueRef *param, unsigned count,
4226 unsigned dmask)
4227 {
4228 struct gallivm_state *gallivm = &ctx->gallivm;
4229 unsigned num_args;
4230 unsigned is_rect = target == TGSI_TEXTURE_RECT;
4231
4232 /* Pad to power of two vector */
4233 while (count < util_next_power_of_two(count))
4234 param[count++] = LLVMGetUndef(ctx->i32);
4235
4236 /* Texture coordinates. */
4237 if (count > 1)
4238 emit_data->args[0] = lp_build_gather_values(gallivm, param, count);
4239 else
4240 emit_data->args[0] = param[0];
4241
4242 /* Resource. */
4243 emit_data->args[1] = res_ptr;
4244 num_args = 2;
4245
4246 if (opcode == TGSI_OPCODE_TXF || opcode == TGSI_OPCODE_TXQ)
4247 emit_data->dst_type = ctx->v4i32;
4248 else {
4249 emit_data->dst_type = ctx->v4f32;
4250
4251 emit_data->args[num_args++] = samp_ptr;
4252 }
4253
4254 emit_data->args[num_args++] = lp_build_const_int32(gallivm, dmask);
4255 emit_data->args[num_args++] = lp_build_const_int32(gallivm, is_rect); /* unorm */
4256 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* r128 */
4257 emit_data->args[num_args++] = lp_build_const_int32(gallivm,
4258 tgsi_is_array_sampler(target)); /* da */
4259 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* glc */
4260 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* slc */
4261 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* tfe */
4262 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* lwe */
4263
4264 emit_data->arg_count = num_args;
4265 }
4266
4267 static const struct lp_build_tgsi_action tex_action;
4268
4269 enum desc_type {
4270 DESC_IMAGE,
4271 DESC_BUFFER,
4272 DESC_FMASK,
4273 DESC_SAMPLER,
4274 };
4275
4276 /**
4277 * Load an image view, fmask view. or sampler state descriptor.
4278 */
4279 static LLVMValueRef load_sampler_desc_custom(struct si_shader_context *ctx,
4280 LLVMValueRef list, LLVMValueRef index,
4281 enum desc_type type)
4282 {
4283 struct gallivm_state *gallivm = &ctx->gallivm;
4284 LLVMBuilderRef builder = gallivm->builder;
4285
4286 switch (type) {
4287 case DESC_IMAGE:
4288 /* The image is at [0:7]. */
4289 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 2, 0), "");
4290 break;
4291 case DESC_BUFFER:
4292 /* The buffer is in [4:7]. */
4293 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
4294 index = LLVMBuildAdd(builder, index, LLVMConstInt(ctx->i32, 1, 0), "");
4295 list = LLVMBuildPointerCast(builder, list,
4296 const_array(ctx->v4i32, 0), "");
4297 break;
4298 case DESC_FMASK:
4299 /* The FMASK is at [8:15]. */
4300 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 2, 0), "");
4301 index = LLVMBuildAdd(builder, index, LLVMConstInt(ctx->i32, 1, 0), "");
4302 break;
4303 case DESC_SAMPLER:
4304 /* The sampler state is at [12:15]. */
4305 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
4306 index = LLVMBuildAdd(builder, index, LLVMConstInt(ctx->i32, 3, 0), "");
4307 list = LLVMBuildPointerCast(builder, list,
4308 const_array(ctx->v4i32, 0), "");
4309 break;
4310 }
4311
4312 return build_indexed_load_const(ctx, list, index);
4313 }
4314
4315 static LLVMValueRef load_sampler_desc(struct si_shader_context *ctx,
4316 LLVMValueRef index, enum desc_type type)
4317 {
4318 LLVMValueRef list = LLVMGetParam(ctx->main_fn,
4319 SI_PARAM_SAMPLERS);
4320
4321 return load_sampler_desc_custom(ctx, list, index, type);
4322 }
4323
4324 /* Disable anisotropic filtering if BASE_LEVEL == LAST_LEVEL.
4325 *
4326 * SI-CI:
4327 * If BASE_LEVEL == LAST_LEVEL, the shader must disable anisotropic
4328 * filtering manually. The driver sets img7 to a mask clearing
4329 * MAX_ANISO_RATIO if BASE_LEVEL == LAST_LEVEL. The shader must do:
4330 * s_and_b32 samp0, samp0, img7
4331 *
4332 * VI:
4333 * The ANISO_OVERRIDE sampler field enables this fix in TA.
4334 */
4335 static LLVMValueRef sici_fix_sampler_aniso(struct si_shader_context *ctx,
4336 LLVMValueRef res, LLVMValueRef samp)
4337 {
4338 LLVMBuilderRef builder = ctx->gallivm.builder;
4339 LLVMValueRef img7, samp0;
4340
4341 if (ctx->screen->b.chip_class >= VI)
4342 return samp;
4343
4344 img7 = LLVMBuildExtractElement(builder, res,
4345 LLVMConstInt(ctx->i32, 7, 0), "");
4346 samp0 = LLVMBuildExtractElement(builder, samp,
4347 LLVMConstInt(ctx->i32, 0, 0), "");
4348 samp0 = LLVMBuildAnd(builder, samp0, img7, "");
4349 return LLVMBuildInsertElement(builder, samp, samp0,
4350 LLVMConstInt(ctx->i32, 0, 0), "");
4351 }
4352
4353 static void tex_fetch_ptrs(
4354 struct lp_build_tgsi_context *bld_base,
4355 struct lp_build_emit_data *emit_data,
4356 LLVMValueRef *res_ptr, LLVMValueRef *samp_ptr, LLVMValueRef *fmask_ptr)
4357 {
4358 struct si_shader_context *ctx = si_shader_context(bld_base);
4359 const struct tgsi_full_instruction *inst = emit_data->inst;
4360 unsigned target = inst->Texture.Texture;
4361 unsigned sampler_src;
4362 unsigned sampler_index;
4363 LLVMValueRef index;
4364
4365 sampler_src = emit_data->inst->Instruction.NumSrcRegs - 1;
4366 sampler_index = emit_data->inst->Src[sampler_src].Register.Index;
4367
4368 if (emit_data->inst->Src[sampler_src].Register.Indirect) {
4369 const struct tgsi_full_src_register *reg = &emit_data->inst->Src[sampler_src];
4370
4371 index = get_bounded_indirect_index(ctx,
4372 &reg->Indirect,
4373 reg->Register.Index,
4374 SI_NUM_SAMPLERS);
4375 } else {
4376 index = LLVMConstInt(ctx->i32, sampler_index, 0);
4377 }
4378
4379 if (target == TGSI_TEXTURE_BUFFER)
4380 *res_ptr = load_sampler_desc(ctx, index, DESC_BUFFER);
4381 else
4382 *res_ptr = load_sampler_desc(ctx, index, DESC_IMAGE);
4383
4384 if (samp_ptr)
4385 *samp_ptr = NULL;
4386 if (fmask_ptr)
4387 *fmask_ptr = NULL;
4388
4389 if (target == TGSI_TEXTURE_2D_MSAA ||
4390 target == TGSI_TEXTURE_2D_ARRAY_MSAA) {
4391 if (fmask_ptr)
4392 *fmask_ptr = load_sampler_desc(ctx, index, DESC_FMASK);
4393 } else if (target != TGSI_TEXTURE_BUFFER) {
4394 if (samp_ptr) {
4395 *samp_ptr = load_sampler_desc(ctx, index, DESC_SAMPLER);
4396 *samp_ptr = sici_fix_sampler_aniso(ctx, *res_ptr, *samp_ptr);
4397 }
4398 }
4399 }
4400
4401 static void txq_fetch_args(
4402 struct lp_build_tgsi_context *bld_base,
4403 struct lp_build_emit_data *emit_data)
4404 {
4405 struct si_shader_context *ctx = si_shader_context(bld_base);
4406 const struct tgsi_full_instruction *inst = emit_data->inst;
4407 unsigned target = inst->Texture.Texture;
4408 LLVMValueRef res_ptr;
4409 LLVMValueRef address;
4410
4411 tex_fetch_ptrs(bld_base, emit_data, &res_ptr, NULL, NULL);
4412
4413 if (target == TGSI_TEXTURE_BUFFER) {
4414 /* Read the size from the buffer descriptor directly. */
4415 emit_data->args[0] = get_buffer_size(bld_base, res_ptr);
4416 return;
4417 }
4418
4419 /* Textures - set the mip level. */
4420 address = lp_build_emit_fetch(bld_base, inst, 0, TGSI_CHAN_X);
4421
4422 set_tex_fetch_args(ctx, emit_data, TGSI_OPCODE_TXQ, target, res_ptr,
4423 NULL, &address, 1, 0xf);
4424 }
4425
4426 static void txq_emit(const struct lp_build_tgsi_action *action,
4427 struct lp_build_tgsi_context *bld_base,
4428 struct lp_build_emit_data *emit_data)
4429 {
4430 struct lp_build_context *base = &bld_base->base;
4431 unsigned target = emit_data->inst->Texture.Texture;
4432
4433 if (target == TGSI_TEXTURE_BUFFER) {
4434 /* Just return the buffer size. */
4435 emit_data->output[emit_data->chan] = emit_data->args[0];
4436 return;
4437 }
4438
4439 emit_data->output[emit_data->chan] = lp_build_intrinsic(
4440 base->gallivm->builder, "llvm.SI.getresinfo.i32",
4441 emit_data->dst_type, emit_data->args, emit_data->arg_count,
4442 LP_FUNC_ATTR_READNONE);
4443
4444 /* Divide the number of layers by 6 to get the number of cubes. */
4445 if (target == TGSI_TEXTURE_CUBE_ARRAY ||
4446 target == TGSI_TEXTURE_SHADOWCUBE_ARRAY) {
4447 LLVMBuilderRef builder = bld_base->base.gallivm->builder;
4448 LLVMValueRef two = lp_build_const_int32(bld_base->base.gallivm, 2);
4449 LLVMValueRef six = lp_build_const_int32(bld_base->base.gallivm, 6);
4450
4451 LLVMValueRef v4 = emit_data->output[emit_data->chan];
4452 LLVMValueRef z = LLVMBuildExtractElement(builder, v4, two, "");
4453 z = LLVMBuildSDiv(builder, z, six, "");
4454
4455 emit_data->output[emit_data->chan] =
4456 LLVMBuildInsertElement(builder, v4, z, two, "");
4457 }
4458 }
4459
4460 static void tex_fetch_args(
4461 struct lp_build_tgsi_context *bld_base,
4462 struct lp_build_emit_data *emit_data)
4463 {
4464 struct si_shader_context *ctx = si_shader_context(bld_base);
4465 struct gallivm_state *gallivm = bld_base->base.gallivm;
4466 const struct tgsi_full_instruction *inst = emit_data->inst;
4467 unsigned opcode = inst->Instruction.Opcode;
4468 unsigned target = inst->Texture.Texture;
4469 LLVMValueRef coords[5], derivs[6];
4470 LLVMValueRef address[16];
4471 unsigned num_coords = tgsi_util_get_texture_coord_dim(target);
4472 int ref_pos = tgsi_util_get_shadow_ref_src_index(target);
4473 unsigned count = 0;
4474 unsigned chan;
4475 unsigned num_deriv_channels = 0;
4476 bool has_offset = inst->Texture.NumOffsets > 0;
4477 LLVMValueRef res_ptr, samp_ptr, fmask_ptr = NULL;
4478 unsigned dmask = 0xf;
4479
4480 tex_fetch_ptrs(bld_base, emit_data, &res_ptr, &samp_ptr, &fmask_ptr);
4481
4482 if (target == TGSI_TEXTURE_BUFFER) {
4483 emit_data->dst_type = ctx->v4f32;
4484 emit_data->args[0] = LLVMBuildBitCast(gallivm->builder, res_ptr,
4485 ctx->v16i8, "");
4486 emit_data->args[1] = bld_base->uint_bld.zero;
4487 emit_data->args[2] = lp_build_emit_fetch(bld_base, emit_data->inst, 0, TGSI_CHAN_X);
4488 emit_data->arg_count = 3;
4489 return;
4490 }
4491
4492 /* Fetch and project texture coordinates */
4493 coords[3] = lp_build_emit_fetch(bld_base, emit_data->inst, 0, TGSI_CHAN_W);
4494 for (chan = 0; chan < 3; chan++ ) {
4495 coords[chan] = lp_build_emit_fetch(bld_base,
4496 emit_data->inst, 0,
4497 chan);
4498 if (opcode == TGSI_OPCODE_TXP)
4499 coords[chan] = lp_build_emit_llvm_binary(bld_base,
4500 TGSI_OPCODE_DIV,
4501 coords[chan],
4502 coords[3]);
4503 }
4504
4505 if (opcode == TGSI_OPCODE_TXP)
4506 coords[3] = bld_base->base.one;
4507
4508 /* Pack offsets. */
4509 if (has_offset && opcode != TGSI_OPCODE_TXF) {
4510 /* The offsets are six-bit signed integers packed like this:
4511 * X=[5:0], Y=[13:8], and Z=[21:16].
4512 */
4513 LLVMValueRef offset[3], pack;
4514
4515 assert(inst->Texture.NumOffsets == 1);
4516
4517 for (chan = 0; chan < 3; chan++) {
4518 offset[chan] = lp_build_emit_fetch_texoffset(bld_base,
4519 emit_data->inst, 0, chan);
4520 offset[chan] = LLVMBuildAnd(gallivm->builder, offset[chan],
4521 lp_build_const_int32(gallivm, 0x3f), "");
4522 if (chan)
4523 offset[chan] = LLVMBuildShl(gallivm->builder, offset[chan],
4524 lp_build_const_int32(gallivm, chan*8), "");
4525 }
4526
4527 pack = LLVMBuildOr(gallivm->builder, offset[0], offset[1], "");
4528 pack = LLVMBuildOr(gallivm->builder, pack, offset[2], "");
4529 address[count++] = pack;
4530 }
4531
4532 /* Pack LOD bias value */
4533 if (opcode == TGSI_OPCODE_TXB)
4534 address[count++] = coords[3];
4535 if (opcode == TGSI_OPCODE_TXB2)
4536 address[count++] = lp_build_emit_fetch(bld_base, inst, 1, TGSI_CHAN_X);
4537
4538 /* Pack depth comparison value */
4539 if (tgsi_is_shadow_target(target) && opcode != TGSI_OPCODE_LODQ) {
4540 LLVMValueRef z;
4541
4542 if (target == TGSI_TEXTURE_SHADOWCUBE_ARRAY) {
4543 z = lp_build_emit_fetch(bld_base, inst, 1, TGSI_CHAN_X);
4544 } else {
4545 assert(ref_pos >= 0);
4546 z = coords[ref_pos];
4547 }
4548
4549 /* TC-compatible HTILE promotes Z16 and Z24 to Z32_FLOAT,
4550 * so the depth comparison value isn't clamped for Z16 and
4551 * Z24 anymore. Do it manually here.
4552 *
4553 * It's unnecessary if the original texture format was
4554 * Z32_FLOAT, but we don't know that here.
4555 */
4556 if (ctx->screen->b.chip_class == VI)
4557 z = si_llvm_saturate(bld_base, z);
4558
4559 address[count++] = z;
4560 }
4561
4562 /* Pack user derivatives */
4563 if (opcode == TGSI_OPCODE_TXD) {
4564 int param, num_src_deriv_channels;
4565
4566 switch (target) {
4567 case TGSI_TEXTURE_3D:
4568 num_src_deriv_channels = 3;
4569 num_deriv_channels = 3;
4570 break;
4571 case TGSI_TEXTURE_2D:
4572 case TGSI_TEXTURE_SHADOW2D:
4573 case TGSI_TEXTURE_RECT:
4574 case TGSI_TEXTURE_SHADOWRECT:
4575 case TGSI_TEXTURE_2D_ARRAY:
4576 case TGSI_TEXTURE_SHADOW2D_ARRAY:
4577 num_src_deriv_channels = 2;
4578 num_deriv_channels = 2;
4579 break;
4580 case TGSI_TEXTURE_CUBE:
4581 case TGSI_TEXTURE_SHADOWCUBE:
4582 case TGSI_TEXTURE_CUBE_ARRAY:
4583 case TGSI_TEXTURE_SHADOWCUBE_ARRAY:
4584 /* Cube derivatives will be converted to 2D. */
4585 num_src_deriv_channels = 3;
4586 num_deriv_channels = 2;
4587 break;
4588 case TGSI_TEXTURE_1D:
4589 case TGSI_TEXTURE_SHADOW1D:
4590 case TGSI_TEXTURE_1D_ARRAY:
4591 case TGSI_TEXTURE_SHADOW1D_ARRAY:
4592 num_src_deriv_channels = 1;
4593 num_deriv_channels = 1;
4594 break;
4595 default:
4596 unreachable("invalid target");
4597 }
4598
4599 for (param = 0; param < 2; param++)
4600 for (chan = 0; chan < num_src_deriv_channels; chan++)
4601 derivs[param * num_src_deriv_channels + chan] =
4602 lp_build_emit_fetch(bld_base, inst, param+1, chan);
4603 }
4604
4605 if (target == TGSI_TEXTURE_CUBE ||
4606 target == TGSI_TEXTURE_CUBE_ARRAY ||
4607 target == TGSI_TEXTURE_SHADOWCUBE ||
4608 target == TGSI_TEXTURE_SHADOWCUBE_ARRAY)
4609 ac_prepare_cube_coords(&ctx->ac,
4610 opcode == TGSI_OPCODE_TXD,
4611 target == TGSI_TEXTURE_CUBE_ARRAY ||
4612 target == TGSI_TEXTURE_SHADOWCUBE_ARRAY,
4613 coords, derivs);
4614
4615 if (opcode == TGSI_OPCODE_TXD)
4616 for (int i = 0; i < num_deriv_channels * 2; i++)
4617 address[count++] = derivs[i];
4618
4619 /* Pack texture coordinates */
4620 address[count++] = coords[0];
4621 if (num_coords > 1)
4622 address[count++] = coords[1];
4623 if (num_coords > 2)
4624 address[count++] = coords[2];
4625
4626 /* Pack LOD or sample index */
4627 if (opcode == TGSI_OPCODE_TXL || opcode == TGSI_OPCODE_TXF)
4628 address[count++] = coords[3];
4629 else if (opcode == TGSI_OPCODE_TXL2)
4630 address[count++] = lp_build_emit_fetch(bld_base, inst, 1, TGSI_CHAN_X);
4631
4632 if (count > 16) {
4633 assert(!"Cannot handle more than 16 texture address parameters");
4634 count = 16;
4635 }
4636
4637 for (chan = 0; chan < count; chan++ ) {
4638 address[chan] = LLVMBuildBitCast(gallivm->builder,
4639 address[chan], ctx->i32, "");
4640 }
4641
4642 /* Adjust the sample index according to FMASK.
4643 *
4644 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
4645 * which is the identity mapping. Each nibble says which physical sample
4646 * should be fetched to get that sample.
4647 *
4648 * For example, 0x11111100 means there are only 2 samples stored and
4649 * the second sample covers 3/4 of the pixel. When reading samples 0
4650 * and 1, return physical sample 0 (determined by the first two 0s
4651 * in FMASK), otherwise return physical sample 1.
4652 *
4653 * The sample index should be adjusted as follows:
4654 * sample_index = (fmask >> (sample_index * 4)) & 0xF;
4655 */
4656 if (target == TGSI_TEXTURE_2D_MSAA ||
4657 target == TGSI_TEXTURE_2D_ARRAY_MSAA) {
4658 struct lp_build_context *uint_bld = &bld_base->uint_bld;
4659 struct lp_build_emit_data txf_emit_data = *emit_data;
4660 LLVMValueRef txf_address[4];
4661 unsigned txf_count = count;
4662 struct tgsi_full_instruction inst = {};
4663
4664 memcpy(txf_address, address, sizeof(txf_address));
4665
4666 if (target == TGSI_TEXTURE_2D_MSAA) {
4667 txf_address[2] = bld_base->uint_bld.zero;
4668 }
4669 txf_address[3] = bld_base->uint_bld.zero;
4670
4671 /* Read FMASK using TXF. */
4672 inst.Instruction.Opcode = TGSI_OPCODE_TXF;
4673 inst.Texture.Texture = target;
4674 txf_emit_data.inst = &inst;
4675 txf_emit_data.chan = 0;
4676 set_tex_fetch_args(ctx, &txf_emit_data, TGSI_OPCODE_TXF,
4677 target, fmask_ptr, NULL,
4678 txf_address, txf_count, 0xf);
4679 build_tex_intrinsic(&tex_action, bld_base, &txf_emit_data);
4680
4681 /* Initialize some constants. */
4682 LLVMValueRef four = LLVMConstInt(ctx->i32, 4, 0);
4683 LLVMValueRef F = LLVMConstInt(ctx->i32, 0xF, 0);
4684
4685 /* Apply the formula. */
4686 LLVMValueRef fmask =
4687 LLVMBuildExtractElement(gallivm->builder,
4688 txf_emit_data.output[0],
4689 uint_bld->zero, "");
4690
4691 unsigned sample_chan = target == TGSI_TEXTURE_2D_MSAA ? 2 : 3;
4692
4693 LLVMValueRef sample_index4 =
4694 LLVMBuildMul(gallivm->builder, address[sample_chan], four, "");
4695
4696 LLVMValueRef shifted_fmask =
4697 LLVMBuildLShr(gallivm->builder, fmask, sample_index4, "");
4698
4699 LLVMValueRef final_sample =
4700 LLVMBuildAnd(gallivm->builder, shifted_fmask, F, "");
4701
4702 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
4703 * resource descriptor is 0 (invalid),
4704 */
4705 LLVMValueRef fmask_desc =
4706 LLVMBuildBitCast(gallivm->builder, fmask_ptr,
4707 ctx->v8i32, "");
4708
4709 LLVMValueRef fmask_word1 =
4710 LLVMBuildExtractElement(gallivm->builder, fmask_desc,
4711 uint_bld->one, "");
4712
4713 LLVMValueRef word1_is_nonzero =
4714 LLVMBuildICmp(gallivm->builder, LLVMIntNE,
4715 fmask_word1, uint_bld->zero, "");
4716
4717 /* Replace the MSAA sample index. */
4718 address[sample_chan] =
4719 LLVMBuildSelect(gallivm->builder, word1_is_nonzero,
4720 final_sample, address[sample_chan], "");
4721 }
4722
4723 if (opcode == TGSI_OPCODE_TXF) {
4724 /* add tex offsets */
4725 if (inst->Texture.NumOffsets) {
4726 struct lp_build_context *uint_bld = &bld_base->uint_bld;
4727 struct lp_build_tgsi_soa_context *bld = lp_soa_context(bld_base);
4728 const struct tgsi_texture_offset *off = inst->TexOffsets;
4729
4730 assert(inst->Texture.NumOffsets == 1);
4731
4732 switch (target) {
4733 case TGSI_TEXTURE_3D:
4734 address[2] = lp_build_add(uint_bld, address[2],
4735 bld->immediates[off->Index][off->SwizzleZ]);
4736 /* fall through */
4737 case TGSI_TEXTURE_2D:
4738 case TGSI_TEXTURE_SHADOW2D:
4739 case TGSI_TEXTURE_RECT:
4740 case TGSI_TEXTURE_SHADOWRECT:
4741 case TGSI_TEXTURE_2D_ARRAY:
4742 case TGSI_TEXTURE_SHADOW2D_ARRAY:
4743 address[1] =
4744 lp_build_add(uint_bld, address[1],
4745 bld->immediates[off->Index][off->SwizzleY]);
4746 /* fall through */
4747 case TGSI_TEXTURE_1D:
4748 case TGSI_TEXTURE_SHADOW1D:
4749 case TGSI_TEXTURE_1D_ARRAY:
4750 case TGSI_TEXTURE_SHADOW1D_ARRAY:
4751 address[0] =
4752 lp_build_add(uint_bld, address[0],
4753 bld->immediates[off->Index][off->SwizzleX]);
4754 break;
4755 /* texture offsets do not apply to other texture targets */
4756 }
4757 }
4758 }
4759
4760 if (opcode == TGSI_OPCODE_TG4) {
4761 unsigned gather_comp = 0;
4762
4763 /* DMASK was repurposed for GATHER4. 4 components are always
4764 * returned and DMASK works like a swizzle - it selects
4765 * the component to fetch. The only valid DMASK values are
4766 * 1=red, 2=green, 4=blue, 8=alpha. (e.g. 1 returns
4767 * (red,red,red,red) etc.) The ISA document doesn't mention
4768 * this.
4769 */
4770
4771 /* Get the component index from src1.x for Gather4. */
4772 if (!tgsi_is_shadow_target(target)) {
4773 LLVMValueRef (*imms)[4] = lp_soa_context(bld_base)->immediates;
4774 LLVMValueRef comp_imm;
4775 struct tgsi_src_register src1 = inst->Src[1].Register;
4776
4777 assert(src1.File == TGSI_FILE_IMMEDIATE);
4778
4779 comp_imm = imms[src1.Index][src1.SwizzleX];
4780 gather_comp = LLVMConstIntGetZExtValue(comp_imm);
4781 gather_comp = CLAMP(gather_comp, 0, 3);
4782 }
4783
4784 dmask = 1 << gather_comp;
4785 }
4786
4787 set_tex_fetch_args(ctx, emit_data, opcode, target, res_ptr,
4788 samp_ptr, address, count, dmask);
4789 }
4790
4791 /* Gather4 should follow the same rules as bilinear filtering, but the hardware
4792 * incorrectly forces nearest filtering if the texture format is integer.
4793 * The only effect it has on Gather4, which always returns 4 texels for
4794 * bilinear filtering, is that the final coordinates are off by 0.5 of
4795 * the texel size.
4796 *
4797 * The workaround is to subtract 0.5 from the unnormalized coordinates,
4798 * or (0.5 / size) from the normalized coordinates.
4799 */
4800 static void si_lower_gather4_integer(struct si_shader_context *ctx,
4801 struct lp_build_emit_data *emit_data,
4802 const char *intr_name,
4803 unsigned coord_vgpr_index)
4804 {
4805 LLVMBuilderRef builder = ctx->gallivm.builder;
4806 LLVMValueRef coord = emit_data->args[0];
4807 LLVMValueRef half_texel[2];
4808 int c;
4809
4810 if (emit_data->inst->Texture.Texture == TGSI_TEXTURE_RECT ||
4811 emit_data->inst->Texture.Texture == TGSI_TEXTURE_SHADOWRECT) {
4812 half_texel[0] = half_texel[1] = LLVMConstReal(ctx->f32, -0.5);
4813 } else {
4814 struct tgsi_full_instruction txq_inst = {};
4815 struct lp_build_emit_data txq_emit_data = {};
4816
4817 /* Query the texture size. */
4818 txq_inst.Texture.Texture = emit_data->inst->Texture.Texture;
4819 txq_emit_data.inst = &txq_inst;
4820 txq_emit_data.dst_type = ctx->v4i32;
4821 set_tex_fetch_args(ctx, &txq_emit_data, TGSI_OPCODE_TXQ,
4822 txq_inst.Texture.Texture,
4823 emit_data->args[1], NULL,
4824 &ctx->soa.bld_base.uint_bld.zero,
4825 1, 0xf);
4826 txq_emit(NULL, &ctx->soa.bld_base, &txq_emit_data);
4827
4828 /* Compute -0.5 / size. */
4829 for (c = 0; c < 2; c++) {
4830 half_texel[c] =
4831 LLVMBuildExtractElement(builder, txq_emit_data.output[0],
4832 LLVMConstInt(ctx->i32, c, 0), "");
4833 half_texel[c] = LLVMBuildUIToFP(builder, half_texel[c], ctx->f32, "");
4834 half_texel[c] =
4835 lp_build_emit_llvm_unary(&ctx->soa.bld_base,
4836 TGSI_OPCODE_RCP, half_texel[c]);
4837 half_texel[c] = LLVMBuildFMul(builder, half_texel[c],
4838 LLVMConstReal(ctx->f32, -0.5), "");
4839 }
4840 }
4841
4842 for (c = 0; c < 2; c++) {
4843 LLVMValueRef tmp;
4844 LLVMValueRef index = LLVMConstInt(ctx->i32, coord_vgpr_index + c, 0);
4845
4846 tmp = LLVMBuildExtractElement(builder, coord, index, "");
4847 tmp = LLVMBuildBitCast(builder, tmp, ctx->f32, "");
4848 tmp = LLVMBuildFAdd(builder, tmp, half_texel[c], "");
4849 tmp = LLVMBuildBitCast(builder, tmp, ctx->i32, "");
4850 coord = LLVMBuildInsertElement(builder, coord, tmp, index, "");
4851 }
4852
4853 emit_data->args[0] = coord;
4854 emit_data->output[emit_data->chan] =
4855 lp_build_intrinsic(builder, intr_name, emit_data->dst_type,
4856 emit_data->args, emit_data->arg_count,
4857 LP_FUNC_ATTR_READNONE);
4858 }
4859
4860 static void build_tex_intrinsic(const struct lp_build_tgsi_action *action,
4861 struct lp_build_tgsi_context *bld_base,
4862 struct lp_build_emit_data *emit_data)
4863 {
4864 struct si_shader_context *ctx = si_shader_context(bld_base);
4865 struct lp_build_context *base = &bld_base->base;
4866 const struct tgsi_full_instruction *inst = emit_data->inst;
4867 unsigned opcode = inst->Instruction.Opcode;
4868 unsigned target = inst->Texture.Texture;
4869 char intr_name[127];
4870 bool has_offset = inst->Texture.NumOffsets > 0;
4871 bool is_shadow = tgsi_is_shadow_target(target);
4872 char type[64];
4873 const char *name = "llvm.SI.image.sample";
4874 const char *infix = "";
4875
4876 if (target == TGSI_TEXTURE_BUFFER) {
4877 emit_data->output[emit_data->chan] = lp_build_intrinsic(
4878 base->gallivm->builder,
4879 "llvm.SI.vs.load.input", emit_data->dst_type,
4880 emit_data->args, emit_data->arg_count,
4881 LP_FUNC_ATTR_READNONE);
4882 return;
4883 }
4884
4885 switch (opcode) {
4886 case TGSI_OPCODE_TXF:
4887 name = target == TGSI_TEXTURE_2D_MSAA ||
4888 target == TGSI_TEXTURE_2D_ARRAY_MSAA ?
4889 "llvm.SI.image.load" :
4890 "llvm.SI.image.load.mip";
4891 is_shadow = false;
4892 has_offset = false;
4893 break;
4894 case TGSI_OPCODE_LODQ:
4895 name = "llvm.SI.getlod";
4896 is_shadow = false;
4897 has_offset = false;
4898 break;
4899 case TGSI_OPCODE_TEX:
4900 case TGSI_OPCODE_TEX2:
4901 case TGSI_OPCODE_TXP:
4902 if (ctx->type != PIPE_SHADER_FRAGMENT)
4903 infix = ".lz";
4904 break;
4905 case TGSI_OPCODE_TXB:
4906 case TGSI_OPCODE_TXB2:
4907 assert(ctx->type == PIPE_SHADER_FRAGMENT);
4908 infix = ".b";
4909 break;
4910 case TGSI_OPCODE_TXL:
4911 case TGSI_OPCODE_TXL2:
4912 infix = ".l";
4913 break;
4914 case TGSI_OPCODE_TXD:
4915 infix = ".d";
4916 break;
4917 case TGSI_OPCODE_TG4:
4918 name = "llvm.SI.gather4";
4919 infix = ".lz";
4920 break;
4921 default:
4922 assert(0);
4923 return;
4924 }
4925
4926 /* Add the type and suffixes .c, .o if needed. */
4927 build_type_name_for_intr(LLVMTypeOf(emit_data->args[0]), type, sizeof(type));
4928 sprintf(intr_name, "%s%s%s%s.%s",
4929 name, is_shadow ? ".c" : "", infix,
4930 has_offset ? ".o" : "", type);
4931
4932 /* The hardware needs special lowering for Gather4 with integer formats. */
4933 if (opcode == TGSI_OPCODE_TG4) {
4934 struct tgsi_shader_info *info = &ctx->shader->selector->info;
4935 /* This will also work with non-constant indexing because of how
4936 * glsl_to_tgsi works and we intent to preserve that behavior.
4937 */
4938 const unsigned src_idx = 2;
4939 unsigned sampler = inst->Src[src_idx].Register.Index;
4940
4941 assert(inst->Src[src_idx].Register.File == TGSI_FILE_SAMPLER);
4942
4943 if (info->sampler_type[sampler] == TGSI_RETURN_TYPE_SINT ||
4944 info->sampler_type[sampler] == TGSI_RETURN_TYPE_UINT) {
4945 /* Texture coordinates start after:
4946 * {offset, bias, z-compare, derivatives}
4947 * Only the offset and z-compare can occur here.
4948 */
4949 si_lower_gather4_integer(ctx, emit_data, intr_name,
4950 (int)has_offset + (int)is_shadow);
4951 return;
4952 }
4953 }
4954
4955 emit_data->output[emit_data->chan] = lp_build_intrinsic(
4956 base->gallivm->builder, intr_name, emit_data->dst_type,
4957 emit_data->args, emit_data->arg_count,
4958 LP_FUNC_ATTR_READNONE);
4959 }
4960
4961 static void si_llvm_emit_txqs(
4962 const struct lp_build_tgsi_action *action,
4963 struct lp_build_tgsi_context *bld_base,
4964 struct lp_build_emit_data *emit_data)
4965 {
4966 struct si_shader_context *ctx = si_shader_context(bld_base);
4967 struct gallivm_state *gallivm = bld_base->base.gallivm;
4968 LLVMBuilderRef builder = gallivm->builder;
4969 LLVMValueRef res, samples;
4970 LLVMValueRef res_ptr, samp_ptr, fmask_ptr = NULL;
4971
4972 tex_fetch_ptrs(bld_base, emit_data, &res_ptr, &samp_ptr, &fmask_ptr);
4973
4974
4975 /* Read the samples from the descriptor directly. */
4976 res = LLVMBuildBitCast(builder, res_ptr, ctx->v8i32, "");
4977 samples = LLVMBuildExtractElement(
4978 builder, res,
4979 lp_build_const_int32(gallivm, 3), "");
4980 samples = LLVMBuildLShr(builder, samples,
4981 lp_build_const_int32(gallivm, 16), "");
4982 samples = LLVMBuildAnd(builder, samples,
4983 lp_build_const_int32(gallivm, 0xf), "");
4984 samples = LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1),
4985 samples, "");
4986
4987 emit_data->output[emit_data->chan] = samples;
4988 }
4989
4990 /*
4991 * SI implements derivatives using the local data store (LDS)
4992 * All writes to the LDS happen in all executing threads at
4993 * the same time. TID is the Thread ID for the current
4994 * thread and is a value between 0 and 63, representing
4995 * the thread's position in the wavefront.
4996 *
4997 * For the pixel shader threads are grouped into quads of four pixels.
4998 * The TIDs of the pixels of a quad are:
4999 *
5000 * +------+------+
5001 * |4n + 0|4n + 1|
5002 * +------+------+
5003 * |4n + 2|4n + 3|
5004 * +------+------+
5005 *
5006 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
5007 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
5008 * the current pixel's column, and masking with 0xfffffffe yields the TID
5009 * of the left pixel of the current pixel's row.
5010 *
5011 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
5012 * adding 2 yields the TID of the pixel below the top pixel.
5013 */
5014 /* masks for thread ID. */
5015 #define TID_MASK_TOP_LEFT 0xfffffffc
5016 #define TID_MASK_TOP 0xfffffffd
5017 #define TID_MASK_LEFT 0xfffffffe
5018
5019 static void si_llvm_emit_ddxy(
5020 const struct lp_build_tgsi_action *action,
5021 struct lp_build_tgsi_context *bld_base,
5022 struct lp_build_emit_data *emit_data)
5023 {
5024 struct si_shader_context *ctx = si_shader_context(bld_base);
5025 struct gallivm_state *gallivm = bld_base->base.gallivm;
5026 unsigned opcode = emit_data->info->opcode;
5027 LLVMValueRef thread_id, tl, trbl, tl_tid, trbl_tid, val, args[2];
5028 int idx;
5029 unsigned mask;
5030
5031 thread_id = get_thread_id(ctx);
5032
5033 if (opcode == TGSI_OPCODE_DDX_FINE)
5034 mask = TID_MASK_LEFT;
5035 else if (opcode == TGSI_OPCODE_DDY_FINE)
5036 mask = TID_MASK_TOP;
5037 else
5038 mask = TID_MASK_TOP_LEFT;
5039
5040 tl_tid = LLVMBuildAnd(gallivm->builder, thread_id,
5041 lp_build_const_int32(gallivm, mask), "");
5042
5043 /* for DDX we want to next X pixel, DDY next Y pixel. */
5044 idx = (opcode == TGSI_OPCODE_DDX || opcode == TGSI_OPCODE_DDX_FINE) ? 1 : 2;
5045 trbl_tid = LLVMBuildAdd(gallivm->builder, tl_tid,
5046 lp_build_const_int32(gallivm, idx), "");
5047
5048 val = LLVMBuildBitCast(gallivm->builder, emit_data->args[0], ctx->i32, "");
5049
5050 if (ctx->screen->has_ds_bpermute) {
5051 args[0] = LLVMBuildMul(gallivm->builder, tl_tid,
5052 lp_build_const_int32(gallivm, 4), "");
5053 args[1] = val;
5054 tl = lp_build_intrinsic(gallivm->builder,
5055 "llvm.amdgcn.ds.bpermute", ctx->i32,
5056 args, 2, LP_FUNC_ATTR_READNONE);
5057
5058 args[0] = LLVMBuildMul(gallivm->builder, trbl_tid,
5059 lp_build_const_int32(gallivm, 4), "");
5060 trbl = lp_build_intrinsic(gallivm->builder,
5061 "llvm.amdgcn.ds.bpermute", ctx->i32,
5062 args, 2, LP_FUNC_ATTR_READNONE);
5063 } else {
5064 LLVMValueRef store_ptr, load_ptr0, load_ptr1;
5065
5066 store_ptr = build_gep0(ctx, ctx->lds, thread_id);
5067 load_ptr0 = build_gep0(ctx, ctx->lds, tl_tid);
5068 load_ptr1 = build_gep0(ctx, ctx->lds, trbl_tid);
5069
5070 LLVMBuildStore(gallivm->builder, val, store_ptr);
5071 tl = LLVMBuildLoad(gallivm->builder, load_ptr0, "");
5072 trbl = LLVMBuildLoad(gallivm->builder, load_ptr1, "");
5073 }
5074
5075 tl = LLVMBuildBitCast(gallivm->builder, tl, ctx->f32, "");
5076 trbl = LLVMBuildBitCast(gallivm->builder, trbl, ctx->f32, "");
5077
5078 emit_data->output[emit_data->chan] =
5079 LLVMBuildFSub(gallivm->builder, trbl, tl, "");
5080 }
5081
5082 /*
5083 * this takes an I,J coordinate pair,
5084 * and works out the X and Y derivatives.
5085 * it returns DDX(I), DDX(J), DDY(I), DDY(J).
5086 */
5087 static LLVMValueRef si_llvm_emit_ddxy_interp(
5088 struct lp_build_tgsi_context *bld_base,
5089 LLVMValueRef interp_ij)
5090 {
5091 struct si_shader_context *ctx = si_shader_context(bld_base);
5092 struct gallivm_state *gallivm = bld_base->base.gallivm;
5093 LLVMValueRef result[4], a;
5094 unsigned i;
5095
5096 for (i = 0; i < 2; i++) {
5097 a = LLVMBuildExtractElement(gallivm->builder, interp_ij,
5098 LLVMConstInt(ctx->i32, i, 0), "");
5099 result[i] = lp_build_emit_llvm_unary(bld_base, TGSI_OPCODE_DDX, a);
5100 result[2+i] = lp_build_emit_llvm_unary(bld_base, TGSI_OPCODE_DDY, a);
5101 }
5102
5103 return lp_build_gather_values(gallivm, result, 4);
5104 }
5105
5106 static void interp_fetch_args(
5107 struct lp_build_tgsi_context *bld_base,
5108 struct lp_build_emit_data *emit_data)
5109 {
5110 struct si_shader_context *ctx = si_shader_context(bld_base);
5111 struct gallivm_state *gallivm = bld_base->base.gallivm;
5112 const struct tgsi_full_instruction *inst = emit_data->inst;
5113
5114 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET) {
5115 /* offset is in second src, first two channels */
5116 emit_data->args[0] = lp_build_emit_fetch(bld_base,
5117 emit_data->inst, 1,
5118 TGSI_CHAN_X);
5119 emit_data->args[1] = lp_build_emit_fetch(bld_base,
5120 emit_data->inst, 1,
5121 TGSI_CHAN_Y);
5122 emit_data->arg_count = 2;
5123 } else if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE) {
5124 LLVMValueRef sample_position;
5125 LLVMValueRef sample_id;
5126 LLVMValueRef halfval = lp_build_const_float(gallivm, 0.5f);
5127
5128 /* fetch sample ID, then fetch its sample position,
5129 * and place into first two channels.
5130 */
5131 sample_id = lp_build_emit_fetch(bld_base,
5132 emit_data->inst, 1, TGSI_CHAN_X);
5133 sample_id = LLVMBuildBitCast(gallivm->builder, sample_id,
5134 ctx->i32, "");
5135 sample_position = load_sample_position(ctx, sample_id);
5136
5137 emit_data->args[0] = LLVMBuildExtractElement(gallivm->builder,
5138 sample_position,
5139 lp_build_const_int32(gallivm, 0), "");
5140
5141 emit_data->args[0] = LLVMBuildFSub(gallivm->builder, emit_data->args[0], halfval, "");
5142 emit_data->args[1] = LLVMBuildExtractElement(gallivm->builder,
5143 sample_position,
5144 lp_build_const_int32(gallivm, 1), "");
5145 emit_data->args[1] = LLVMBuildFSub(gallivm->builder, emit_data->args[1], halfval, "");
5146 emit_data->arg_count = 2;
5147 }
5148 }
5149
5150 static void build_interp_intrinsic(const struct lp_build_tgsi_action *action,
5151 struct lp_build_tgsi_context *bld_base,
5152 struct lp_build_emit_data *emit_data)
5153 {
5154 struct si_shader_context *ctx = si_shader_context(bld_base);
5155 struct si_shader *shader = ctx->shader;
5156 struct gallivm_state *gallivm = bld_base->base.gallivm;
5157 struct lp_build_context *uint = &bld_base->uint_bld;
5158 LLVMValueRef interp_param;
5159 const struct tgsi_full_instruction *inst = emit_data->inst;
5160 int input_index = inst->Src[0].Register.Index;
5161 int chan;
5162 int i;
5163 LLVMValueRef attr_number;
5164 LLVMValueRef params = LLVMGetParam(ctx->main_fn, SI_PARAM_PRIM_MASK);
5165 int interp_param_idx;
5166 unsigned interp = shader->selector->info.input_interpolate[input_index];
5167 unsigned location;
5168
5169 assert(inst->Src[0].Register.File == TGSI_FILE_INPUT);
5170
5171 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET ||
5172 inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE)
5173 location = TGSI_INTERPOLATE_LOC_CENTER;
5174 else
5175 location = TGSI_INTERPOLATE_LOC_CENTROID;
5176
5177 interp_param_idx = lookup_interp_param_index(interp, location);
5178 if (interp_param_idx == -1)
5179 return;
5180 else if (interp_param_idx)
5181 interp_param = LLVMGetParam(ctx->main_fn, interp_param_idx);
5182 else
5183 interp_param = NULL;
5184
5185 attr_number = lp_build_const_int32(gallivm, input_index);
5186
5187 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET ||
5188 inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE) {
5189 LLVMValueRef ij_out[2];
5190 LLVMValueRef ddxy_out = si_llvm_emit_ddxy_interp(bld_base, interp_param);
5191
5192 /*
5193 * take the I then J parameters, and the DDX/Y for it, and
5194 * calculate the IJ inputs for the interpolator.
5195 * temp1 = ddx * offset/sample.x + I;
5196 * interp_param.I = ddy * offset/sample.y + temp1;
5197 * temp1 = ddx * offset/sample.x + J;
5198 * interp_param.J = ddy * offset/sample.y + temp1;
5199 */
5200 for (i = 0; i < 2; i++) {
5201 LLVMValueRef ix_ll = lp_build_const_int32(gallivm, i);
5202 LLVMValueRef iy_ll = lp_build_const_int32(gallivm, i + 2);
5203 LLVMValueRef ddx_el = LLVMBuildExtractElement(gallivm->builder,
5204 ddxy_out, ix_ll, "");
5205 LLVMValueRef ddy_el = LLVMBuildExtractElement(gallivm->builder,
5206 ddxy_out, iy_ll, "");
5207 LLVMValueRef interp_el = LLVMBuildExtractElement(gallivm->builder,
5208 interp_param, ix_ll, "");
5209 LLVMValueRef temp1, temp2;
5210
5211 interp_el = LLVMBuildBitCast(gallivm->builder, interp_el,
5212 ctx->f32, "");
5213
5214 temp1 = LLVMBuildFMul(gallivm->builder, ddx_el, emit_data->args[0], "");
5215
5216 temp1 = LLVMBuildFAdd(gallivm->builder, temp1, interp_el, "");
5217
5218 temp2 = LLVMBuildFMul(gallivm->builder, ddy_el, emit_data->args[1], "");
5219
5220 ij_out[i] = LLVMBuildFAdd(gallivm->builder, temp2, temp1, "");
5221 }
5222 interp_param = lp_build_gather_values(bld_base->base.gallivm, ij_out, 2);
5223 }
5224
5225 for (chan = 0; chan < 4; chan++) {
5226 LLVMValueRef llvm_chan;
5227 unsigned schan;
5228
5229 schan = tgsi_util_get_full_src_register_swizzle(&inst->Src[0], chan);
5230 llvm_chan = lp_build_const_int32(gallivm, schan);
5231
5232 if (interp_param) {
5233 interp_param = LLVMBuildBitCast(gallivm->builder,
5234 interp_param, LLVMVectorType(ctx->f32, 2), "");
5235 LLVMValueRef i = LLVMBuildExtractElement(
5236 gallivm->builder, interp_param, uint->zero, "");
5237 LLVMValueRef j = LLVMBuildExtractElement(
5238 gallivm->builder, interp_param, uint->one, "");
5239 emit_data->output[chan] = build_fs_interp(bld_base,
5240 llvm_chan, attr_number, params,
5241 i, j);
5242 } else {
5243 emit_data->output[chan] = build_fs_interp_mov(bld_base,
5244 lp_build_const_int32(gallivm, 2), /* P0 */
5245 llvm_chan, attr_number, params);
5246 }
5247 }
5248 }
5249
5250 static unsigned si_llvm_get_stream(struct lp_build_tgsi_context *bld_base,
5251 struct lp_build_emit_data *emit_data)
5252 {
5253 LLVMValueRef (*imms)[4] = lp_soa_context(bld_base)->immediates;
5254 struct tgsi_src_register src0 = emit_data->inst->Src[0].Register;
5255 unsigned stream;
5256
5257 assert(src0.File == TGSI_FILE_IMMEDIATE);
5258
5259 stream = LLVMConstIntGetZExtValue(imms[src0.Index][src0.SwizzleX]) & 0x3;
5260 return stream;
5261 }
5262
5263 /* Emit one vertex from the geometry shader */
5264 static void si_llvm_emit_vertex(
5265 const struct lp_build_tgsi_action *action,
5266 struct lp_build_tgsi_context *bld_base,
5267 struct lp_build_emit_data *emit_data)
5268 {
5269 struct si_shader_context *ctx = si_shader_context(bld_base);
5270 struct lp_build_context *uint = &bld_base->uint_bld;
5271 struct si_shader *shader = ctx->shader;
5272 struct tgsi_shader_info *info = &shader->selector->info;
5273 struct gallivm_state *gallivm = bld_base->base.gallivm;
5274 struct lp_build_if_state if_state;
5275 LLVMValueRef soffset = LLVMGetParam(ctx->main_fn,
5276 SI_PARAM_GS2VS_OFFSET);
5277 LLVMValueRef gs_next_vertex;
5278 LLVMValueRef can_emit, kill;
5279 LLVMValueRef args[2];
5280 unsigned chan, offset;
5281 int i;
5282 unsigned stream;
5283
5284 stream = si_llvm_get_stream(bld_base, emit_data);
5285
5286 /* Write vertex attribute values to GSVS ring */
5287 gs_next_vertex = LLVMBuildLoad(gallivm->builder,
5288 ctx->gs_next_vertex[stream],
5289 "");
5290
5291 /* If this thread has already emitted the declared maximum number of
5292 * vertices, skip the write: excessive vertex emissions are not
5293 * supposed to have any effect.
5294 *
5295 * If the shader has no writes to memory, kill it instead. This skips
5296 * further memory loads and may allow LLVM to skip to the end
5297 * altogether.
5298 */
5299 can_emit = LLVMBuildICmp(gallivm->builder, LLVMIntULT, gs_next_vertex,
5300 lp_build_const_int32(gallivm,
5301 shader->selector->gs_max_out_vertices), "");
5302
5303 bool use_kill = !info->writes_memory;
5304 if (use_kill) {
5305 kill = lp_build_select(&bld_base->base, can_emit,
5306 lp_build_const_float(gallivm, 1.0f),
5307 lp_build_const_float(gallivm, -1.0f));
5308
5309 lp_build_intrinsic(gallivm->builder, "llvm.AMDGPU.kill",
5310 ctx->voidt, &kill, 1, 0);
5311 } else {
5312 lp_build_if(&if_state, gallivm, can_emit);
5313 }
5314
5315 offset = 0;
5316 for (i = 0; i < info->num_outputs; i++) {
5317 LLVMValueRef *out_ptr =
5318 ctx->soa.outputs[i];
5319
5320 for (chan = 0; chan < 4; chan++) {
5321 if (!(info->output_usagemask[i] & (1 << chan)) ||
5322 ((info->output_streams[i] >> (2 * chan)) & 3) != stream)
5323 continue;
5324
5325 LLVMValueRef out_val = LLVMBuildLoad(gallivm->builder, out_ptr[chan], "");
5326 LLVMValueRef voffset =
5327 lp_build_const_int32(gallivm, offset *
5328 shader->selector->gs_max_out_vertices);
5329 offset++;
5330
5331 voffset = lp_build_add(uint, voffset, gs_next_vertex);
5332 voffset = lp_build_mul_imm(uint, voffset, 4);
5333
5334 out_val = LLVMBuildBitCast(gallivm->builder, out_val, ctx->i32, "");
5335
5336 build_tbuffer_store(ctx,
5337 ctx->gsvs_ring[stream],
5338 out_val, 1,
5339 voffset, soffset, 0,
5340 V_008F0C_BUF_DATA_FORMAT_32,
5341 V_008F0C_BUF_NUM_FORMAT_UINT,
5342 1, 0, 1, 1, 0);
5343 }
5344 }
5345
5346 gs_next_vertex = lp_build_add(uint, gs_next_vertex,
5347 lp_build_const_int32(gallivm, 1));
5348
5349 LLVMBuildStore(gallivm->builder, gs_next_vertex, ctx->gs_next_vertex[stream]);
5350
5351 /* Signal vertex emission */
5352 args[0] = lp_build_const_int32(gallivm, SENDMSG_GS_OP_EMIT | SENDMSG_GS | (stream << 8));
5353 args[1] = LLVMGetParam(ctx->main_fn, SI_PARAM_GS_WAVE_ID);
5354 lp_build_intrinsic(gallivm->builder, "llvm.SI.sendmsg",
5355 ctx->voidt, args, 2, 0);
5356
5357 if (!use_kill)
5358 lp_build_endif(&if_state);
5359 }
5360
5361 /* Cut one primitive from the geometry shader */
5362 static void si_llvm_emit_primitive(
5363 const struct lp_build_tgsi_action *action,
5364 struct lp_build_tgsi_context *bld_base,
5365 struct lp_build_emit_data *emit_data)
5366 {
5367 struct si_shader_context *ctx = si_shader_context(bld_base);
5368 struct gallivm_state *gallivm = bld_base->base.gallivm;
5369 LLVMValueRef args[2];
5370 unsigned stream;
5371
5372 /* Signal primitive cut */
5373 stream = si_llvm_get_stream(bld_base, emit_data);
5374 args[0] = lp_build_const_int32(gallivm, SENDMSG_GS_OP_CUT | SENDMSG_GS | (stream << 8));
5375 args[1] = LLVMGetParam(ctx->main_fn, SI_PARAM_GS_WAVE_ID);
5376 lp_build_intrinsic(gallivm->builder, "llvm.SI.sendmsg",
5377 ctx->voidt, args, 2, 0);
5378 }
5379
5380 static void si_llvm_emit_barrier(const struct lp_build_tgsi_action *action,
5381 struct lp_build_tgsi_context *bld_base,
5382 struct lp_build_emit_data *emit_data)
5383 {
5384 struct si_shader_context *ctx = si_shader_context(bld_base);
5385 struct gallivm_state *gallivm = bld_base->base.gallivm;
5386
5387 /* The real barrier instruction isn’t needed, because an entire patch
5388 * always fits into a single wave.
5389 */
5390 if (ctx->type == PIPE_SHADER_TESS_CTRL) {
5391 emit_waitcnt(ctx, LGKM_CNT & VM_CNT);
5392 return;
5393 }
5394
5395 lp_build_intrinsic(gallivm->builder,
5396 HAVE_LLVM >= 0x0309 ? "llvm.amdgcn.s.barrier"
5397 : "llvm.AMDGPU.barrier.local",
5398 ctx->voidt, NULL, 0, 0);
5399 }
5400
5401 static const struct lp_build_tgsi_action tex_action = {
5402 .fetch_args = tex_fetch_args,
5403 .emit = build_tex_intrinsic,
5404 };
5405
5406 static const struct lp_build_tgsi_action interp_action = {
5407 .fetch_args = interp_fetch_args,
5408 .emit = build_interp_intrinsic,
5409 };
5410
5411 static void si_create_function(struct si_shader_context *ctx,
5412 const char *name,
5413 LLVMTypeRef *returns, unsigned num_returns,
5414 LLVMTypeRef *params, unsigned num_params,
5415 int last_sgpr)
5416 {
5417 int i;
5418
5419 si_llvm_create_func(ctx, name, returns, num_returns,
5420 params, num_params);
5421 si_llvm_shader_type(ctx->main_fn, ctx->type);
5422 ctx->return_value = LLVMGetUndef(ctx->return_type);
5423
5424 for (i = 0; i <= last_sgpr; ++i) {
5425 LLVMValueRef P = LLVMGetParam(ctx->main_fn, i);
5426
5427 /* The combination of:
5428 * - ByVal
5429 * - dereferenceable
5430 * - invariant.load
5431 * allows the optimization passes to move loads and reduces
5432 * SGPR spilling significantly.
5433 */
5434 if (LLVMGetTypeKind(LLVMTypeOf(P)) == LLVMPointerTypeKind) {
5435 lp_add_function_attr(ctx->main_fn, i + 1, LP_FUNC_ATTR_BYVAL);
5436 lp_add_attr_dereferenceable(P, UINT64_MAX);
5437 } else
5438 lp_add_function_attr(ctx->main_fn, i + 1, LP_FUNC_ATTR_INREG);
5439 }
5440
5441 if (ctx->screen->b.debug_flags & DBG_UNSAFE_MATH) {
5442 /* These were copied from some LLVM test. */
5443 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
5444 "less-precise-fpmad",
5445 "true");
5446 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
5447 "no-infs-fp-math",
5448 "true");
5449 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
5450 "no-nans-fp-math",
5451 "true");
5452 LLVMAddTargetDependentFunctionAttr(ctx->main_fn,
5453 "unsafe-fp-math",
5454 "true");
5455 }
5456 }
5457
5458 static void create_meta_data(struct si_shader_context *ctx)
5459 {
5460 struct gallivm_state *gallivm = ctx->soa.bld_base.base.gallivm;
5461
5462 ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(gallivm->context,
5463 "invariant.load", 14);
5464 ctx->range_md_kind = LLVMGetMDKindIDInContext(gallivm->context,
5465 "range", 5);
5466 ctx->uniform_md_kind = LLVMGetMDKindIDInContext(gallivm->context,
5467 "amdgpu.uniform", 14);
5468
5469 ctx->empty_md = LLVMMDNodeInContext(gallivm->context, NULL, 0);
5470 }
5471
5472 static void declare_streamout_params(struct si_shader_context *ctx,
5473 struct pipe_stream_output_info *so,
5474 LLVMTypeRef *params, LLVMTypeRef i32,
5475 unsigned *num_params)
5476 {
5477 int i;
5478
5479 /* Streamout SGPRs. */
5480 if (so->num_outputs) {
5481 if (ctx->type != PIPE_SHADER_TESS_EVAL)
5482 params[ctx->param_streamout_config = (*num_params)++] = i32;
5483 else
5484 ctx->param_streamout_config = ctx->param_tess_offchip;
5485
5486 params[ctx->param_streamout_write_index = (*num_params)++] = i32;
5487 }
5488 /* A streamout buffer offset is loaded if the stride is non-zero. */
5489 for (i = 0; i < 4; i++) {
5490 if (!so->stride[i])
5491 continue;
5492
5493 params[ctx->param_streamout_offset[i] = (*num_params)++] = i32;
5494 }
5495 }
5496
5497 static unsigned llvm_get_type_size(LLVMTypeRef type)
5498 {
5499 LLVMTypeKind kind = LLVMGetTypeKind(type);
5500
5501 switch (kind) {
5502 case LLVMIntegerTypeKind:
5503 return LLVMGetIntTypeWidth(type) / 8;
5504 case LLVMFloatTypeKind:
5505 return 4;
5506 case LLVMPointerTypeKind:
5507 return 8;
5508 case LLVMVectorTypeKind:
5509 return LLVMGetVectorSize(type) *
5510 llvm_get_type_size(LLVMGetElementType(type));
5511 case LLVMArrayTypeKind:
5512 return LLVMGetArrayLength(type) *
5513 llvm_get_type_size(LLVMGetElementType(type));
5514 default:
5515 assert(0);
5516 return 0;
5517 }
5518 }
5519
5520 static void declare_tess_lds(struct si_shader_context *ctx)
5521 {
5522 struct gallivm_state *gallivm = &ctx->gallivm;
5523 struct lp_build_tgsi_context *bld_base = &ctx->soa.bld_base;
5524 struct lp_build_context *uint = &bld_base->uint_bld;
5525
5526 unsigned lds_size = ctx->screen->b.chip_class >= CIK ? 65536 : 32768;
5527 ctx->lds = LLVMBuildIntToPtr(gallivm->builder, uint->zero,
5528 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), LOCAL_ADDR_SPACE),
5529 "tess_lds");
5530 }
5531
5532 static unsigned si_get_max_workgroup_size(struct si_shader *shader)
5533 {
5534 const unsigned *properties = shader->selector->info.properties;
5535 unsigned max_work_group_size =
5536 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_WIDTH] *
5537 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_HEIGHT] *
5538 properties[TGSI_PROPERTY_CS_FIXED_BLOCK_DEPTH];
5539
5540 if (!max_work_group_size) {
5541 /* This is a variable group size compute shader,
5542 * compile it for the maximum possible group size.
5543 */
5544 max_work_group_size = SI_MAX_VARIABLE_THREADS_PER_BLOCK;
5545 }
5546 return max_work_group_size;
5547 }
5548
5549 static void create_function(struct si_shader_context *ctx)
5550 {
5551 struct lp_build_tgsi_context *bld_base = &ctx->soa.bld_base;
5552 struct gallivm_state *gallivm = bld_base->base.gallivm;
5553 struct si_shader *shader = ctx->shader;
5554 LLVMTypeRef params[SI_NUM_PARAMS + SI_NUM_VERTEX_BUFFERS], v3i32;
5555 LLVMTypeRef returns[16+32*4];
5556 unsigned i, last_sgpr, num_params, num_return_sgprs;
5557 unsigned num_returns = 0;
5558 unsigned num_prolog_vgprs = 0;
5559
5560 v3i32 = LLVMVectorType(ctx->i32, 3);
5561
5562 params[SI_PARAM_RW_BUFFERS] = const_array(ctx->v16i8, SI_NUM_RW_BUFFERS);
5563 params[SI_PARAM_CONST_BUFFERS] = const_array(ctx->v16i8, SI_NUM_CONST_BUFFERS);
5564 params[SI_PARAM_SAMPLERS] = const_array(ctx->v8i32, SI_NUM_SAMPLERS);
5565 params[SI_PARAM_IMAGES] = const_array(ctx->v8i32, SI_NUM_IMAGES);
5566 params[SI_PARAM_SHADER_BUFFERS] = const_array(ctx->v4i32, SI_NUM_SHADER_BUFFERS);
5567
5568 switch (ctx->type) {
5569 case PIPE_SHADER_VERTEX:
5570 params[SI_PARAM_VERTEX_BUFFERS] = const_array(ctx->v16i8, SI_NUM_VERTEX_BUFFERS);
5571 params[SI_PARAM_BASE_VERTEX] = ctx->i32;
5572 params[SI_PARAM_START_INSTANCE] = ctx->i32;
5573 params[SI_PARAM_DRAWID] = ctx->i32;
5574 num_params = SI_PARAM_DRAWID+1;
5575
5576 if (shader->key.as_es) {
5577 params[ctx->param_es2gs_offset = num_params++] = ctx->i32;
5578 } else if (shader->key.as_ls) {
5579 params[SI_PARAM_LS_OUT_LAYOUT] = ctx->i32;
5580 num_params = SI_PARAM_LS_OUT_LAYOUT+1;
5581 } else {
5582 if (shader->is_gs_copy_shader) {
5583 num_params = SI_PARAM_RW_BUFFERS+1;
5584 } else {
5585 params[SI_PARAM_VS_STATE_BITS] = ctx->i32;
5586 num_params = SI_PARAM_VS_STATE_BITS+1;
5587 }
5588
5589 /* The locations of the other parameters are assigned dynamically. */
5590 declare_streamout_params(ctx, &shader->selector->so,
5591 params, ctx->i32, &num_params);
5592 }
5593
5594 last_sgpr = num_params-1;
5595
5596 /* VGPRs */
5597 params[ctx->param_vertex_id = num_params++] = ctx->i32;
5598 params[ctx->param_rel_auto_id = num_params++] = ctx->i32;
5599 params[ctx->param_vs_prim_id = num_params++] = ctx->i32;
5600 params[ctx->param_instance_id = num_params++] = ctx->i32;
5601
5602 if (!shader->is_gs_copy_shader) {
5603 /* Vertex load indices. */
5604 ctx->param_vertex_index0 = num_params;
5605
5606 for (i = 0; i < shader->selector->info.num_inputs; i++)
5607 params[num_params++] = ctx->i32;
5608
5609 num_prolog_vgprs += shader->selector->info.num_inputs;
5610
5611 /* PrimitiveID output. */
5612 if (!shader->key.as_es && !shader->key.as_ls)
5613 for (i = 0; i <= VS_EPILOG_PRIMID_LOC; i++)
5614 returns[num_returns++] = ctx->f32;
5615 }
5616 break;
5617
5618 case PIPE_SHADER_TESS_CTRL:
5619 params[SI_PARAM_TCS_OFFCHIP_LAYOUT] = ctx->i32;
5620 params[SI_PARAM_TCS_OUT_OFFSETS] = ctx->i32;
5621 params[SI_PARAM_TCS_OUT_LAYOUT] = ctx->i32;
5622 params[SI_PARAM_TCS_IN_LAYOUT] = ctx->i32;
5623 params[ctx->param_oc_lds = SI_PARAM_TCS_OC_LDS] = ctx->i32;
5624 params[SI_PARAM_TESS_FACTOR_OFFSET] = ctx->i32;
5625 last_sgpr = SI_PARAM_TESS_FACTOR_OFFSET;
5626
5627 /* VGPRs */
5628 params[SI_PARAM_PATCH_ID] = ctx->i32;
5629 params[SI_PARAM_REL_IDS] = ctx->i32;
5630 num_params = SI_PARAM_REL_IDS+1;
5631
5632 /* SI_PARAM_TCS_OC_LDS and PARAM_TESS_FACTOR_OFFSET are
5633 * placed after the user SGPRs.
5634 */
5635 for (i = 0; i < SI_TCS_NUM_USER_SGPR + 2; i++)
5636 returns[num_returns++] = ctx->i32; /* SGPRs */
5637
5638 for (i = 0; i < 3; i++)
5639 returns[num_returns++] = ctx->f32; /* VGPRs */
5640 break;
5641
5642 case PIPE_SHADER_TESS_EVAL:
5643 params[SI_PARAM_TCS_OFFCHIP_LAYOUT] = ctx->i32;
5644 num_params = SI_PARAM_TCS_OFFCHIP_LAYOUT+1;
5645
5646 if (shader->key.as_es) {
5647 params[ctx->param_oc_lds = num_params++] = ctx->i32;
5648 params[ctx->param_tess_offchip = num_params++] = ctx->i32;
5649 params[ctx->param_es2gs_offset = num_params++] = ctx->i32;
5650 } else {
5651 params[ctx->param_tess_offchip = num_params++] = ctx->i32;
5652 declare_streamout_params(ctx, &shader->selector->so,
5653 params, ctx->i32, &num_params);
5654 params[ctx->param_oc_lds = num_params++] = ctx->i32;
5655 }
5656 last_sgpr = num_params - 1;
5657
5658 /* VGPRs */
5659 params[ctx->param_tes_u = num_params++] = ctx->f32;
5660 params[ctx->param_tes_v = num_params++] = ctx->f32;
5661 params[ctx->param_tes_rel_patch_id = num_params++] = ctx->i32;
5662 params[ctx->param_tes_patch_id = num_params++] = ctx->i32;
5663
5664 /* PrimitiveID output. */
5665 if (!shader->key.as_es)
5666 for (i = 0; i <= VS_EPILOG_PRIMID_LOC; i++)
5667 returns[num_returns++] = ctx->f32;
5668 break;
5669
5670 case PIPE_SHADER_GEOMETRY:
5671 params[SI_PARAM_GS2VS_OFFSET] = ctx->i32;
5672 params[SI_PARAM_GS_WAVE_ID] = ctx->i32;
5673 last_sgpr = SI_PARAM_GS_WAVE_ID;
5674
5675 /* VGPRs */
5676 params[SI_PARAM_VTX0_OFFSET] = ctx->i32;
5677 params[SI_PARAM_VTX1_OFFSET] = ctx->i32;
5678 params[SI_PARAM_PRIMITIVE_ID] = ctx->i32;
5679 params[SI_PARAM_VTX2_OFFSET] = ctx->i32;
5680 params[SI_PARAM_VTX3_OFFSET] = ctx->i32;
5681 params[SI_PARAM_VTX4_OFFSET] = ctx->i32;
5682 params[SI_PARAM_VTX5_OFFSET] = ctx->i32;
5683 params[SI_PARAM_GS_INSTANCE_ID] = ctx->i32;
5684 num_params = SI_PARAM_GS_INSTANCE_ID+1;
5685 break;
5686
5687 case PIPE_SHADER_FRAGMENT:
5688 params[SI_PARAM_ALPHA_REF] = ctx->f32;
5689 params[SI_PARAM_PRIM_MASK] = ctx->i32;
5690 last_sgpr = SI_PARAM_PRIM_MASK;
5691 params[SI_PARAM_PERSP_SAMPLE] = ctx->v2i32;
5692 params[SI_PARAM_PERSP_CENTER] = ctx->v2i32;
5693 params[SI_PARAM_PERSP_CENTROID] = ctx->v2i32;
5694 params[SI_PARAM_PERSP_PULL_MODEL] = v3i32;
5695 params[SI_PARAM_LINEAR_SAMPLE] = ctx->v2i32;
5696 params[SI_PARAM_LINEAR_CENTER] = ctx->v2i32;
5697 params[SI_PARAM_LINEAR_CENTROID] = ctx->v2i32;
5698 params[SI_PARAM_LINE_STIPPLE_TEX] = ctx->f32;
5699 params[SI_PARAM_POS_X_FLOAT] = ctx->f32;
5700 params[SI_PARAM_POS_Y_FLOAT] = ctx->f32;
5701 params[SI_PARAM_POS_Z_FLOAT] = ctx->f32;
5702 params[SI_PARAM_POS_W_FLOAT] = ctx->f32;
5703 params[SI_PARAM_FRONT_FACE] = ctx->i32;
5704 shader->info.face_vgpr_index = 20;
5705 params[SI_PARAM_ANCILLARY] = ctx->i32;
5706 params[SI_PARAM_SAMPLE_COVERAGE] = ctx->f32;
5707 params[SI_PARAM_POS_FIXED_PT] = ctx->i32;
5708 num_params = SI_PARAM_POS_FIXED_PT+1;
5709
5710 /* Color inputs from the prolog. */
5711 if (shader->selector->info.colors_read) {
5712 unsigned num_color_elements =
5713 util_bitcount(shader->selector->info.colors_read);
5714
5715 assert(num_params + num_color_elements <= ARRAY_SIZE(params));
5716 for (i = 0; i < num_color_elements; i++)
5717 params[num_params++] = ctx->f32;
5718
5719 num_prolog_vgprs += num_color_elements;
5720 }
5721
5722 /* Outputs for the epilog. */
5723 num_return_sgprs = SI_SGPR_ALPHA_REF + 1;
5724 num_returns =
5725 num_return_sgprs +
5726 util_bitcount(shader->selector->info.colors_written) * 4 +
5727 shader->selector->info.writes_z +
5728 shader->selector->info.writes_stencil +
5729 shader->selector->info.writes_samplemask +
5730 1 /* SampleMaskIn */;
5731
5732 num_returns = MAX2(num_returns,
5733 num_return_sgprs +
5734 PS_EPILOG_SAMPLEMASK_MIN_LOC + 1);
5735
5736 for (i = 0; i < num_return_sgprs; i++)
5737 returns[i] = ctx->i32;
5738 for (; i < num_returns; i++)
5739 returns[i] = ctx->f32;
5740 break;
5741
5742 case PIPE_SHADER_COMPUTE:
5743 params[SI_PARAM_GRID_SIZE] = v3i32;
5744 params[SI_PARAM_BLOCK_SIZE] = v3i32;
5745 params[SI_PARAM_BLOCK_ID] = v3i32;
5746 last_sgpr = SI_PARAM_BLOCK_ID;
5747
5748 params[SI_PARAM_THREAD_ID] = v3i32;
5749 num_params = SI_PARAM_THREAD_ID + 1;
5750 break;
5751 default:
5752 assert(0 && "unimplemented shader");
5753 return;
5754 }
5755
5756 assert(num_params <= ARRAY_SIZE(params));
5757
5758 si_create_function(ctx, "main", returns, num_returns, params,
5759 num_params, last_sgpr);
5760
5761 /* Reserve register locations for VGPR inputs the PS prolog may need. */
5762 if (ctx->type == PIPE_SHADER_FRAGMENT &&
5763 ctx->separate_prolog) {
5764 si_llvm_add_attribute(ctx->main_fn,
5765 "InitialPSInputAddr",
5766 S_0286D0_PERSP_SAMPLE_ENA(1) |
5767 S_0286D0_PERSP_CENTER_ENA(1) |
5768 S_0286D0_PERSP_CENTROID_ENA(1) |
5769 S_0286D0_LINEAR_SAMPLE_ENA(1) |
5770 S_0286D0_LINEAR_CENTER_ENA(1) |
5771 S_0286D0_LINEAR_CENTROID_ENA(1) |
5772 S_0286D0_FRONT_FACE_ENA(1) |
5773 S_0286D0_POS_FIXED_PT_ENA(1));
5774 } else if (ctx->type == PIPE_SHADER_COMPUTE) {
5775 si_llvm_add_attribute(ctx->main_fn,
5776 "amdgpu-max-work-group-size",
5777 si_get_max_workgroup_size(shader));
5778 }
5779
5780 shader->info.num_input_sgprs = 0;
5781 shader->info.num_input_vgprs = 0;
5782
5783 for (i = 0; i <= last_sgpr; ++i)
5784 shader->info.num_input_sgprs += llvm_get_type_size(params[i]) / 4;
5785
5786 for (; i < num_params; ++i)
5787 shader->info.num_input_vgprs += llvm_get_type_size(params[i]) / 4;
5788
5789 assert(shader->info.num_input_vgprs >= num_prolog_vgprs);
5790 shader->info.num_input_vgprs -= num_prolog_vgprs;
5791
5792 if (!ctx->screen->has_ds_bpermute &&
5793 bld_base->info &&
5794 (bld_base->info->opcode_count[TGSI_OPCODE_DDX] > 0 ||
5795 bld_base->info->opcode_count[TGSI_OPCODE_DDY] > 0 ||
5796 bld_base->info->opcode_count[TGSI_OPCODE_DDX_FINE] > 0 ||
5797 bld_base->info->opcode_count[TGSI_OPCODE_DDY_FINE] > 0 ||
5798 bld_base->info->opcode_count[TGSI_OPCODE_INTERP_OFFSET] > 0 ||
5799 bld_base->info->opcode_count[TGSI_OPCODE_INTERP_SAMPLE] > 0))
5800 ctx->lds =
5801 LLVMAddGlobalInAddressSpace(gallivm->module,
5802 LLVMArrayType(ctx->i32, 64),
5803 "ddxy_lds",
5804 LOCAL_ADDR_SPACE);
5805
5806 if ((ctx->type == PIPE_SHADER_VERTEX && shader->key.as_ls) ||
5807 ctx->type == PIPE_SHADER_TESS_CTRL ||
5808 ctx->type == PIPE_SHADER_TESS_EVAL)
5809 declare_tess_lds(ctx);
5810 }
5811
5812 /**
5813 * Load ESGS and GSVS ring buffer resource descriptors and save the variables
5814 * for later use.
5815 */
5816 static void preload_ring_buffers(struct si_shader_context *ctx)
5817 {
5818 struct gallivm_state *gallivm =
5819 ctx->soa.bld_base.base.gallivm;
5820 LLVMBuilderRef builder = gallivm->builder;
5821
5822 LLVMValueRef buf_ptr = LLVMGetParam(ctx->main_fn,
5823 SI_PARAM_RW_BUFFERS);
5824
5825 if ((ctx->type == PIPE_SHADER_VERTEX &&
5826 ctx->shader->key.as_es) ||
5827 (ctx->type == PIPE_SHADER_TESS_EVAL &&
5828 ctx->shader->key.as_es) ||
5829 ctx->type == PIPE_SHADER_GEOMETRY) {
5830 unsigned ring =
5831 ctx->type == PIPE_SHADER_GEOMETRY ? SI_GS_RING_ESGS
5832 : SI_ES_RING_ESGS;
5833 LLVMValueRef offset = lp_build_const_int32(gallivm, ring);
5834
5835 ctx->esgs_ring =
5836 build_indexed_load_const(ctx, buf_ptr, offset);
5837 }
5838
5839 if (ctx->shader->is_gs_copy_shader) {
5840 LLVMValueRef offset = lp_build_const_int32(gallivm, SI_RING_GSVS);
5841
5842 ctx->gsvs_ring[0] =
5843 build_indexed_load_const(ctx, buf_ptr, offset);
5844 } else if (ctx->type == PIPE_SHADER_GEOMETRY) {
5845 const struct si_shader_selector *sel = ctx->shader->selector;
5846 struct lp_build_context *uint = &ctx->soa.bld_base.uint_bld;
5847 LLVMValueRef offset = lp_build_const_int32(gallivm, SI_RING_GSVS);
5848 LLVMValueRef base_ring;
5849
5850 base_ring = build_indexed_load_const(ctx, buf_ptr, offset);
5851
5852 /* The conceptual layout of the GSVS ring is
5853 * v0c0 .. vLv0 v0c1 .. vLc1 ..
5854 * but the real memory layout is swizzled across
5855 * threads:
5856 * t0v0c0 .. t15v0c0 t0v1c0 .. t15v1c0 ... t15vLcL
5857 * t16v0c0 ..
5858 * Override the buffer descriptor accordingly.
5859 */
5860 LLVMTypeRef v2i64 = LLVMVectorType(ctx->i64, 2);
5861 uint64_t stream_offset = 0;
5862
5863 for (unsigned stream = 0; stream < 4; ++stream) {
5864 unsigned num_components;
5865 unsigned stride;
5866 unsigned num_records;
5867 LLVMValueRef ring, tmp;
5868
5869 num_components = sel->info.num_stream_output_components[stream];
5870 if (!num_components)
5871 continue;
5872
5873 stride = 4 * num_components * sel->gs_max_out_vertices;
5874
5875 /* Limit on the stride field for <= CIK. */
5876 assert(stride < (1 << 14));
5877
5878 num_records = 64;
5879
5880 ring = LLVMBuildBitCast(builder, base_ring, v2i64, "");
5881 tmp = LLVMBuildExtractElement(builder, ring, uint->zero, "");
5882 tmp = LLVMBuildAdd(builder, tmp,
5883 LLVMConstInt(ctx->i64,
5884 stream_offset, 0), "");
5885 stream_offset += stride * 64;
5886
5887 ring = LLVMBuildInsertElement(builder, ring, tmp, uint->zero, "");
5888 ring = LLVMBuildBitCast(builder, ring, ctx->v4i32, "");
5889 tmp = LLVMBuildExtractElement(builder, ring, uint->one, "");
5890 tmp = LLVMBuildOr(builder, tmp,
5891 LLVMConstInt(ctx->i32,
5892 S_008F04_STRIDE(stride) |
5893 S_008F04_SWIZZLE_ENABLE(1), 0), "");
5894 ring = LLVMBuildInsertElement(builder, ring, tmp, uint->one, "");
5895 ring = LLVMBuildInsertElement(builder, ring,
5896 LLVMConstInt(ctx->i32, num_records, 0),
5897 LLVMConstInt(ctx->i32, 2, 0), "");
5898 ring = LLVMBuildInsertElement(builder, ring,
5899 LLVMConstInt(ctx->i32,
5900 S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
5901 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
5902 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
5903 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
5904 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
5905 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
5906 S_008F0C_ELEMENT_SIZE(1) | /* element_size = 4 (bytes) */
5907 S_008F0C_INDEX_STRIDE(1) | /* index_stride = 16 (elements) */
5908 S_008F0C_ADD_TID_ENABLE(1),
5909 0),
5910 LLVMConstInt(ctx->i32, 3, 0), "");
5911 ring = LLVMBuildBitCast(builder, ring, ctx->v16i8, "");
5912
5913 ctx->gsvs_ring[stream] = ring;
5914 }
5915 }
5916 }
5917
5918 static void si_llvm_emit_polygon_stipple(struct si_shader_context *ctx,
5919 LLVMValueRef param_rw_buffers,
5920 unsigned param_pos_fixed_pt)
5921 {
5922 struct lp_build_tgsi_context *bld_base =
5923 &ctx->soa.bld_base;
5924 struct gallivm_state *gallivm = bld_base->base.gallivm;
5925 LLVMBuilderRef builder = gallivm->builder;
5926 LLVMValueRef slot, desc, offset, row, bit, address[2];
5927
5928 /* Use the fixed-point gl_FragCoord input.
5929 * Since the stipple pattern is 32x32 and it repeats, just get 5 bits
5930 * per coordinate to get the repeating effect.
5931 */
5932 address[0] = unpack_param(ctx, param_pos_fixed_pt, 0, 5);
5933 address[1] = unpack_param(ctx, param_pos_fixed_pt, 16, 5);
5934
5935 /* Load the buffer descriptor. */
5936 slot = lp_build_const_int32(gallivm, SI_PS_CONST_POLY_STIPPLE);
5937 desc = build_indexed_load_const(ctx, param_rw_buffers, slot);
5938
5939 /* The stipple pattern is 32x32, each row has 32 bits. */
5940 offset = LLVMBuildMul(builder, address[1],
5941 LLVMConstInt(ctx->i32, 4, 0), "");
5942 row = buffer_load_const(ctx, desc, offset);
5943 row = LLVMBuildBitCast(builder, row, ctx->i32, "");
5944 bit = LLVMBuildLShr(builder, row, address[0], "");
5945 bit = LLVMBuildTrunc(builder, bit, ctx->i1, "");
5946
5947 /* The intrinsic kills the thread if arg < 0. */
5948 bit = LLVMBuildSelect(builder, bit, LLVMConstReal(ctx->f32, 0),
5949 LLVMConstReal(ctx->f32, -1), "");
5950 lp_build_intrinsic(builder, "llvm.AMDGPU.kill", ctx->voidt, &bit, 1, 0);
5951 }
5952
5953 void si_shader_binary_read_config(struct radeon_shader_binary *binary,
5954 struct si_shader_config *conf,
5955 unsigned symbol_offset)
5956 {
5957 unsigned i;
5958 const unsigned char *config =
5959 radeon_shader_binary_config_start(binary, symbol_offset);
5960 bool really_needs_scratch = false;
5961
5962 /* LLVM adds SGPR spills to the scratch size.
5963 * Find out if we really need the scratch buffer.
5964 */
5965 for (i = 0; i < binary->reloc_count; i++) {
5966 const struct radeon_shader_reloc *reloc = &binary->relocs[i];
5967
5968 if (!strcmp(scratch_rsrc_dword0_symbol, reloc->name) ||
5969 !strcmp(scratch_rsrc_dword1_symbol, reloc->name)) {
5970 really_needs_scratch = true;
5971 break;
5972 }
5973 }
5974
5975 /* XXX: We may be able to emit some of these values directly rather than
5976 * extracting fields to be emitted later.
5977 */
5978
5979 for (i = 0; i < binary->config_size_per_symbol; i+= 8) {
5980 unsigned reg = util_le32_to_cpu(*(uint32_t*)(config + i));
5981 unsigned value = util_le32_to_cpu(*(uint32_t*)(config + i + 4));
5982 switch (reg) {
5983 case R_00B028_SPI_SHADER_PGM_RSRC1_PS:
5984 case R_00B128_SPI_SHADER_PGM_RSRC1_VS:
5985 case R_00B228_SPI_SHADER_PGM_RSRC1_GS:
5986 case R_00B848_COMPUTE_PGM_RSRC1:
5987 conf->num_sgprs = MAX2(conf->num_sgprs, (G_00B028_SGPRS(value) + 1) * 8);
5988 conf->num_vgprs = MAX2(conf->num_vgprs, (G_00B028_VGPRS(value) + 1) * 4);
5989 conf->float_mode = G_00B028_FLOAT_MODE(value);
5990 conf->rsrc1 = value;
5991 break;
5992 case R_00B02C_SPI_SHADER_PGM_RSRC2_PS:
5993 conf->lds_size = MAX2(conf->lds_size, G_00B02C_EXTRA_LDS_SIZE(value));
5994 break;
5995 case R_00B84C_COMPUTE_PGM_RSRC2:
5996 conf->lds_size = MAX2(conf->lds_size, G_00B84C_LDS_SIZE(value));
5997 conf->rsrc2 = value;
5998 break;
5999 case R_0286CC_SPI_PS_INPUT_ENA:
6000 conf->spi_ps_input_ena = value;
6001 break;
6002 case R_0286D0_SPI_PS_INPUT_ADDR:
6003 conf->spi_ps_input_addr = value;
6004 break;
6005 case R_0286E8_SPI_TMPRING_SIZE:
6006 case R_00B860_COMPUTE_TMPRING_SIZE:
6007 /* WAVESIZE is in units of 256 dwords. */
6008 if (really_needs_scratch)
6009 conf->scratch_bytes_per_wave =
6010 G_00B860_WAVESIZE(value) * 256 * 4;
6011 break;
6012 case 0x4: /* SPILLED_SGPRS */
6013 conf->spilled_sgprs = value;
6014 break;
6015 case 0x8: /* SPILLED_VGPRS */
6016 conf->spilled_vgprs = value;
6017 break;
6018 default:
6019 {
6020 static bool printed;
6021
6022 if (!printed) {
6023 fprintf(stderr, "Warning: LLVM emitted unknown "
6024 "config register: 0x%x\n", reg);
6025 printed = true;
6026 }
6027 }
6028 break;
6029 }
6030 }
6031
6032 if (!conf->spi_ps_input_addr)
6033 conf->spi_ps_input_addr = conf->spi_ps_input_ena;
6034 }
6035
6036 void si_shader_apply_scratch_relocs(struct si_context *sctx,
6037 struct si_shader *shader,
6038 struct si_shader_config *config,
6039 uint64_t scratch_va)
6040 {
6041 unsigned i;
6042 uint32_t scratch_rsrc_dword0 = scratch_va;
6043 uint32_t scratch_rsrc_dword1 =
6044 S_008F04_BASE_ADDRESS_HI(scratch_va >> 32);
6045
6046 /* Enable scratch coalescing if LLVM sets ELEMENT_SIZE & INDEX_STRIDE
6047 * correctly.
6048 */
6049 if (HAVE_LLVM >= 0x0309)
6050 scratch_rsrc_dword1 |= S_008F04_SWIZZLE_ENABLE(1);
6051 else
6052 scratch_rsrc_dword1 |=
6053 S_008F04_STRIDE(config->scratch_bytes_per_wave / 64);
6054
6055 for (i = 0 ; i < shader->binary.reloc_count; i++) {
6056 const struct radeon_shader_reloc *reloc =
6057 &shader->binary.relocs[i];
6058 if (!strcmp(scratch_rsrc_dword0_symbol, reloc->name)) {
6059 util_memcpy_cpu_to_le32(shader->binary.code + reloc->offset,
6060 &scratch_rsrc_dword0, 4);
6061 } else if (!strcmp(scratch_rsrc_dword1_symbol, reloc->name)) {
6062 util_memcpy_cpu_to_le32(shader->binary.code + reloc->offset,
6063 &scratch_rsrc_dword1, 4);
6064 }
6065 }
6066 }
6067
6068 static unsigned si_get_shader_binary_size(struct si_shader *shader)
6069 {
6070 unsigned size = shader->binary.code_size;
6071
6072 if (shader->prolog)
6073 size += shader->prolog->binary.code_size;
6074 if (shader->epilog)
6075 size += shader->epilog->binary.code_size;
6076 return size;
6077 }
6078
6079 int si_shader_binary_upload(struct si_screen *sscreen, struct si_shader *shader)
6080 {
6081 const struct radeon_shader_binary *prolog =
6082 shader->prolog ? &shader->prolog->binary : NULL;
6083 const struct radeon_shader_binary *epilog =
6084 shader->epilog ? &shader->epilog->binary : NULL;
6085 const struct radeon_shader_binary *mainb = &shader->binary;
6086 unsigned bo_size = si_get_shader_binary_size(shader) +
6087 (!epilog ? mainb->rodata_size : 0);
6088 unsigned char *ptr;
6089
6090 assert(!prolog || !prolog->rodata_size);
6091 assert((!prolog && !epilog) || !mainb->rodata_size);
6092 assert(!epilog || !epilog->rodata_size);
6093
6094 r600_resource_reference(&shader->bo, NULL);
6095 shader->bo = (struct r600_resource*)
6096 pipe_buffer_create(&sscreen->b.b, 0,
6097 PIPE_USAGE_IMMUTABLE, bo_size);
6098 if (!shader->bo)
6099 return -ENOMEM;
6100
6101 /* Upload. */
6102 ptr = sscreen->b.ws->buffer_map(shader->bo->buf, NULL,
6103 PIPE_TRANSFER_READ_WRITE);
6104
6105 if (prolog) {
6106 util_memcpy_cpu_to_le32(ptr, prolog->code, prolog->code_size);
6107 ptr += prolog->code_size;
6108 }
6109
6110 util_memcpy_cpu_to_le32(ptr, mainb->code, mainb->code_size);
6111 ptr += mainb->code_size;
6112
6113 if (epilog)
6114 util_memcpy_cpu_to_le32(ptr, epilog->code, epilog->code_size);
6115 else if (mainb->rodata_size > 0)
6116 util_memcpy_cpu_to_le32(ptr, mainb->rodata, mainb->rodata_size);
6117
6118 sscreen->b.ws->buffer_unmap(shader->bo->buf);
6119 return 0;
6120 }
6121
6122 static void si_shader_dump_disassembly(const struct radeon_shader_binary *binary,
6123 struct pipe_debug_callback *debug,
6124 const char *name, FILE *file)
6125 {
6126 char *line, *p;
6127 unsigned i, count;
6128
6129 if (binary->disasm_string) {
6130 fprintf(file, "Shader %s disassembly:\n", name);
6131 fprintf(file, "%s", binary->disasm_string);
6132
6133 if (debug && debug->debug_message) {
6134 /* Very long debug messages are cut off, so send the
6135 * disassembly one line at a time. This causes more
6136 * overhead, but on the plus side it simplifies
6137 * parsing of resulting logs.
6138 */
6139 pipe_debug_message(debug, SHADER_INFO,
6140 "Shader Disassembly Begin");
6141
6142 line = binary->disasm_string;
6143 while (*line) {
6144 p = util_strchrnul(line, '\n');
6145 count = p - line;
6146
6147 if (count) {
6148 pipe_debug_message(debug, SHADER_INFO,
6149 "%.*s", count, line);
6150 }
6151
6152 if (!*p)
6153 break;
6154 line = p + 1;
6155 }
6156
6157 pipe_debug_message(debug, SHADER_INFO,
6158 "Shader Disassembly End");
6159 }
6160 } else {
6161 fprintf(file, "Shader %s binary:\n", name);
6162 for (i = 0; i < binary->code_size; i += 4) {
6163 fprintf(file, "@0x%x: %02x%02x%02x%02x\n", i,
6164 binary->code[i + 3], binary->code[i + 2],
6165 binary->code[i + 1], binary->code[i]);
6166 }
6167 }
6168 }
6169
6170 static void si_shader_dump_stats(struct si_screen *sscreen,
6171 struct si_shader *shader,
6172 struct pipe_debug_callback *debug,
6173 unsigned processor,
6174 FILE *file,
6175 bool check_debug_option)
6176 {
6177 struct si_shader_config *conf = &shader->config;
6178 unsigned num_inputs = shader->selector ? shader->selector->info.num_inputs : 0;
6179 unsigned code_size = si_get_shader_binary_size(shader);
6180 unsigned lds_increment = sscreen->b.chip_class >= CIK ? 512 : 256;
6181 unsigned lds_per_wave = 0;
6182 unsigned max_simd_waves = 10;
6183
6184 /* Compute LDS usage for PS. */
6185 switch (processor) {
6186 case PIPE_SHADER_FRAGMENT:
6187 /* The minimum usage per wave is (num_inputs * 48). The maximum
6188 * usage is (num_inputs * 48 * 16).
6189 * We can get anything in between and it varies between waves.
6190 *
6191 * The 48 bytes per input for a single primitive is equal to
6192 * 4 bytes/component * 4 components/input * 3 points.
6193 *
6194 * Other stages don't know the size at compile time or don't
6195 * allocate LDS per wave, but instead they do it per thread group.
6196 */
6197 lds_per_wave = conf->lds_size * lds_increment +
6198 align(num_inputs * 48, lds_increment);
6199 break;
6200 case PIPE_SHADER_COMPUTE:
6201 if (shader->selector) {
6202 unsigned max_workgroup_size =
6203 si_get_max_workgroup_size(shader);
6204 lds_per_wave = (conf->lds_size * lds_increment) /
6205 DIV_ROUND_UP(max_workgroup_size, 64);
6206 }
6207 break;
6208 }
6209
6210 /* Compute the per-SIMD wave counts. */
6211 if (conf->num_sgprs) {
6212 if (sscreen->b.chip_class >= VI)
6213 max_simd_waves = MIN2(max_simd_waves, 800 / conf->num_sgprs);
6214 else
6215 max_simd_waves = MIN2(max_simd_waves, 512 / conf->num_sgprs);
6216 }
6217
6218 if (conf->num_vgprs)
6219 max_simd_waves = MIN2(max_simd_waves, 256 / conf->num_vgprs);
6220
6221 /* LDS is 64KB per CU (4 SIMDs), which is 16KB per SIMD (usage above
6222 * 16KB makes some SIMDs unoccupied). */
6223 if (lds_per_wave)
6224 max_simd_waves = MIN2(max_simd_waves, 16384 / lds_per_wave);
6225
6226 if (!check_debug_option ||
6227 r600_can_dump_shader(&sscreen->b, processor)) {
6228 if (processor == PIPE_SHADER_FRAGMENT) {
6229 fprintf(file, "*** SHADER CONFIG ***\n"
6230 "SPI_PS_INPUT_ADDR = 0x%04x\n"
6231 "SPI_PS_INPUT_ENA = 0x%04x\n",
6232 conf->spi_ps_input_addr, conf->spi_ps_input_ena);
6233 }
6234
6235 fprintf(file, "*** SHADER STATS ***\n"
6236 "SGPRS: %d\n"
6237 "VGPRS: %d\n"
6238 "Spilled SGPRs: %d\n"
6239 "Spilled VGPRs: %d\n"
6240 "Private memory VGPRs: %d\n"
6241 "Code Size: %d bytes\n"
6242 "LDS: %d blocks\n"
6243 "Scratch: %d bytes per wave\n"
6244 "Max Waves: %d\n"
6245 "********************\n\n\n",
6246 conf->num_sgprs, conf->num_vgprs,
6247 conf->spilled_sgprs, conf->spilled_vgprs,
6248 conf->private_mem_vgprs, code_size,
6249 conf->lds_size, conf->scratch_bytes_per_wave,
6250 max_simd_waves);
6251 }
6252
6253 pipe_debug_message(debug, SHADER_INFO,
6254 "Shader Stats: SGPRS: %d VGPRS: %d Code Size: %d "
6255 "LDS: %d Scratch: %d Max Waves: %d Spilled SGPRs: %d "
6256 "Spilled VGPRs: %d PrivMem VGPRs: %d",
6257 conf->num_sgprs, conf->num_vgprs, code_size,
6258 conf->lds_size, conf->scratch_bytes_per_wave,
6259 max_simd_waves, conf->spilled_sgprs,
6260 conf->spilled_vgprs, conf->private_mem_vgprs);
6261 }
6262
6263 static const char *si_get_shader_name(struct si_shader *shader,
6264 unsigned processor)
6265 {
6266 switch (processor) {
6267 case PIPE_SHADER_VERTEX:
6268 if (shader->key.as_es)
6269 return "Vertex Shader as ES";
6270 else if (shader->key.as_ls)
6271 return "Vertex Shader as LS";
6272 else
6273 return "Vertex Shader as VS";
6274 case PIPE_SHADER_TESS_CTRL:
6275 return "Tessellation Control Shader";
6276 case PIPE_SHADER_TESS_EVAL:
6277 if (shader->key.as_es)
6278 return "Tessellation Evaluation Shader as ES";
6279 else
6280 return "Tessellation Evaluation Shader as VS";
6281 case PIPE_SHADER_GEOMETRY:
6282 if (shader->is_gs_copy_shader)
6283 return "GS Copy Shader as VS";
6284 else
6285 return "Geometry Shader";
6286 case PIPE_SHADER_FRAGMENT:
6287 return "Pixel Shader";
6288 case PIPE_SHADER_COMPUTE:
6289 return "Compute Shader";
6290 default:
6291 return "Unknown Shader";
6292 }
6293 }
6294
6295 void si_shader_dump(struct si_screen *sscreen, struct si_shader *shader,
6296 struct pipe_debug_callback *debug, unsigned processor,
6297 FILE *file, bool check_debug_option)
6298 {
6299 if (!check_debug_option ||
6300 r600_can_dump_shader(&sscreen->b, processor))
6301 si_dump_shader_key(processor, &shader->key, file);
6302
6303 if (!check_debug_option && shader->binary.llvm_ir_string) {
6304 fprintf(file, "\n%s - main shader part - LLVM IR:\n\n",
6305 si_get_shader_name(shader, processor));
6306 fprintf(file, "%s\n", shader->binary.llvm_ir_string);
6307 }
6308
6309 if (!check_debug_option ||
6310 (r600_can_dump_shader(&sscreen->b, processor) &&
6311 !(sscreen->b.debug_flags & DBG_NO_ASM))) {
6312 fprintf(file, "\n%s:\n", si_get_shader_name(shader, processor));
6313
6314 if (shader->prolog)
6315 si_shader_dump_disassembly(&shader->prolog->binary,
6316 debug, "prolog", file);
6317
6318 si_shader_dump_disassembly(&shader->binary, debug, "main", file);
6319
6320 if (shader->epilog)
6321 si_shader_dump_disassembly(&shader->epilog->binary,
6322 debug, "epilog", file);
6323 fprintf(file, "\n");
6324 }
6325
6326 si_shader_dump_stats(sscreen, shader, debug, processor, file,
6327 check_debug_option);
6328 }
6329
6330 int si_compile_llvm(struct si_screen *sscreen,
6331 struct radeon_shader_binary *binary,
6332 struct si_shader_config *conf,
6333 LLVMTargetMachineRef tm,
6334 LLVMModuleRef mod,
6335 struct pipe_debug_callback *debug,
6336 unsigned processor,
6337 const char *name)
6338 {
6339 int r = 0;
6340 unsigned count = p_atomic_inc_return(&sscreen->b.num_compilations);
6341
6342 if (r600_can_dump_shader(&sscreen->b, processor)) {
6343 fprintf(stderr, "radeonsi: Compiling shader %d\n", count);
6344
6345 if (!(sscreen->b.debug_flags & (DBG_NO_IR | DBG_PREOPT_IR))) {
6346 fprintf(stderr, "%s LLVM IR:\n\n", name);
6347 LLVMDumpModule(mod);
6348 fprintf(stderr, "\n");
6349 }
6350 }
6351
6352 if (sscreen->record_llvm_ir) {
6353 char *ir = LLVMPrintModuleToString(mod);
6354 binary->llvm_ir_string = strdup(ir);
6355 LLVMDisposeMessage(ir);
6356 }
6357
6358 if (!si_replace_shader(count, binary)) {
6359 r = si_llvm_compile(mod, binary, tm, debug);
6360 if (r)
6361 return r;
6362 }
6363
6364 si_shader_binary_read_config(binary, conf, 0);
6365
6366 /* Enable 64-bit and 16-bit denormals, because there is no performance
6367 * cost.
6368 *
6369 * If denormals are enabled, all floating-point output modifiers are
6370 * ignored.
6371 *
6372 * Don't enable denormals for 32-bit floats, because:
6373 * - Floating-point output modifiers would be ignored by the hw.
6374 * - Some opcodes don't support denormals, such as v_mad_f32. We would
6375 * have to stop using those.
6376 * - SI & CI would be very slow.
6377 */
6378 conf->float_mode |= V_00B028_FP_64_DENORMS;
6379
6380 FREE(binary->config);
6381 FREE(binary->global_symbol_offsets);
6382 binary->config = NULL;
6383 binary->global_symbol_offsets = NULL;
6384
6385 /* Some shaders can't have rodata because their binaries can be
6386 * concatenated.
6387 */
6388 if (binary->rodata_size &&
6389 (processor == PIPE_SHADER_VERTEX ||
6390 processor == PIPE_SHADER_TESS_CTRL ||
6391 processor == PIPE_SHADER_TESS_EVAL ||
6392 processor == PIPE_SHADER_FRAGMENT)) {
6393 fprintf(stderr, "radeonsi: The shader can't have rodata.");
6394 return -EINVAL;
6395 }
6396
6397 return r;
6398 }
6399
6400 static void si_llvm_build_ret(struct si_shader_context *ctx, LLVMValueRef ret)
6401 {
6402 if (LLVMGetTypeKind(LLVMTypeOf(ret)) == LLVMVoidTypeKind)
6403 LLVMBuildRetVoid(ctx->gallivm.builder);
6404 else
6405 LLVMBuildRet(ctx->gallivm.builder, ret);
6406 }
6407
6408 /* Generate code for the hardware VS shader stage to go with a geometry shader */
6409 struct si_shader *
6410 si_generate_gs_copy_shader(struct si_screen *sscreen,
6411 LLVMTargetMachineRef tm,
6412 struct si_shader_selector *gs_selector,
6413 struct pipe_debug_callback *debug)
6414 {
6415 struct si_shader_context ctx;
6416 struct si_shader *shader;
6417 struct gallivm_state *gallivm = &ctx.gallivm;
6418 LLVMBuilderRef builder;
6419 struct lp_build_tgsi_context *bld_base = &ctx.soa.bld_base;
6420 struct lp_build_context *uint = &bld_base->uint_bld;
6421 struct si_shader_output_values *outputs;
6422 struct tgsi_shader_info *gsinfo = &gs_selector->info;
6423 LLVMValueRef args[9];
6424 int i, r;
6425
6426 outputs = MALLOC(gsinfo->num_outputs * sizeof(outputs[0]));
6427
6428 if (!outputs)
6429 return NULL;
6430
6431 shader = CALLOC_STRUCT(si_shader);
6432 if (!shader) {
6433 FREE(outputs);
6434 return NULL;
6435 }
6436
6437
6438 shader->selector = gs_selector;
6439 shader->is_gs_copy_shader = true;
6440
6441 si_init_shader_ctx(&ctx, sscreen, shader, tm);
6442 ctx.type = PIPE_SHADER_VERTEX;
6443
6444 builder = gallivm->builder;
6445
6446 create_meta_data(&ctx);
6447 create_function(&ctx);
6448 preload_ring_buffers(&ctx);
6449
6450 args[0] = ctx.gsvs_ring[0];
6451 args[1] = lp_build_mul_imm(uint,
6452 LLVMGetParam(ctx.main_fn,
6453 ctx.param_vertex_id),
6454 4);
6455 args[3] = uint->zero;
6456 args[4] = uint->one; /* OFFEN */
6457 args[5] = uint->zero; /* IDXEN */
6458 args[6] = uint->one; /* GLC */
6459 args[7] = uint->one; /* SLC */
6460 args[8] = uint->zero; /* TFE */
6461
6462 /* Fetch the vertex stream ID.*/
6463 LLVMValueRef stream_id;
6464
6465 if (gs_selector->so.num_outputs)
6466 stream_id = unpack_param(&ctx, ctx.param_streamout_config, 24, 2);
6467 else
6468 stream_id = uint->zero;
6469
6470 /* Fill in output information. */
6471 for (i = 0; i < gsinfo->num_outputs; ++i) {
6472 outputs[i].semantic_name = gsinfo->output_semantic_name[i];
6473 outputs[i].semantic_index = gsinfo->output_semantic_index[i];
6474
6475 for (int chan = 0; chan < 4; chan++) {
6476 outputs[i].vertex_stream[chan] =
6477 (gsinfo->output_streams[i] >> (2 * chan)) & 3;
6478 }
6479 }
6480
6481 LLVMBasicBlockRef end_bb;
6482 LLVMValueRef switch_inst;
6483
6484 end_bb = LLVMAppendBasicBlockInContext(gallivm->context, ctx.main_fn, "end");
6485 switch_inst = LLVMBuildSwitch(builder, stream_id, end_bb, 4);
6486
6487 for (int stream = 0; stream < 4; stream++) {
6488 LLVMBasicBlockRef bb;
6489 unsigned offset;
6490
6491 if (!gsinfo->num_stream_output_components[stream])
6492 continue;
6493
6494 if (stream > 0 && !gs_selector->so.num_outputs)
6495 continue;
6496
6497 bb = LLVMInsertBasicBlockInContext(gallivm->context, end_bb, "out");
6498 LLVMAddCase(switch_inst, lp_build_const_int32(gallivm, stream), bb);
6499 LLVMPositionBuilderAtEnd(builder, bb);
6500
6501 /* Fetch vertex data from GSVS ring */
6502 offset = 0;
6503 for (i = 0; i < gsinfo->num_outputs; ++i) {
6504 for (unsigned chan = 0; chan < 4; chan++) {
6505 if (!(gsinfo->output_usagemask[i] & (1 << chan)) ||
6506 outputs[i].vertex_stream[chan] != stream) {
6507 outputs[i].values[chan] = ctx.soa.bld_base.base.undef;
6508 continue;
6509 }
6510
6511 args[2] = lp_build_const_int32(
6512 gallivm,
6513 offset * gs_selector->gs_max_out_vertices * 16 * 4);
6514 offset++;
6515
6516 outputs[i].values[chan] =
6517 LLVMBuildBitCast(gallivm->builder,
6518 lp_build_intrinsic(gallivm->builder,
6519 "llvm.SI.buffer.load.dword.i32.i32",
6520 ctx.i32, args, 9,
6521 LP_FUNC_ATTR_READONLY),
6522 ctx.f32, "");
6523 }
6524 }
6525
6526 /* Streamout and exports. */
6527 if (gs_selector->so.num_outputs) {
6528 si_llvm_emit_streamout(&ctx, outputs,
6529 gsinfo->num_outputs,
6530 stream);
6531 }
6532
6533 if (stream == 0)
6534 si_llvm_export_vs(bld_base, outputs, gsinfo->num_outputs);
6535
6536 LLVMBuildBr(builder, end_bb);
6537 }
6538
6539 LLVMPositionBuilderAtEnd(builder, end_bb);
6540
6541 LLVMBuildRetVoid(gallivm->builder);
6542
6543 /* Dump LLVM IR before any optimization passes */
6544 if (sscreen->b.debug_flags & DBG_PREOPT_IR &&
6545 r600_can_dump_shader(&sscreen->b, PIPE_SHADER_GEOMETRY))
6546 LLVMDumpModule(bld_base->base.gallivm->module);
6547
6548 si_llvm_finalize_module(&ctx,
6549 r600_extra_shader_checks(&sscreen->b, PIPE_SHADER_GEOMETRY));
6550
6551 r = si_compile_llvm(sscreen, &ctx.shader->binary,
6552 &ctx.shader->config, ctx.tm,
6553 bld_base->base.gallivm->module,
6554 debug, PIPE_SHADER_GEOMETRY,
6555 "GS Copy Shader");
6556 if (!r) {
6557 if (r600_can_dump_shader(&sscreen->b, PIPE_SHADER_GEOMETRY))
6558 fprintf(stderr, "GS Copy Shader:\n");
6559 si_shader_dump(sscreen, ctx.shader, debug,
6560 PIPE_SHADER_GEOMETRY, stderr, true);
6561 r = si_shader_binary_upload(sscreen, ctx.shader);
6562 }
6563
6564 si_llvm_dispose(&ctx);
6565
6566 FREE(outputs);
6567
6568 if (r != 0) {
6569 FREE(shader);
6570 shader = NULL;
6571 }
6572 return shader;
6573 }
6574
6575 static void si_dump_shader_key(unsigned shader, struct si_shader_key *key,
6576 FILE *f)
6577 {
6578 int i;
6579
6580 fprintf(f, "SHADER KEY\n");
6581
6582 switch (shader) {
6583 case PIPE_SHADER_VERTEX:
6584 fprintf(f, " part.vs.prolog.instance_divisors = {");
6585 for (i = 0; i < ARRAY_SIZE(key->part.vs.prolog.instance_divisors); i++)
6586 fprintf(f, !i ? "%u" : ", %u",
6587 key->part.vs.prolog.instance_divisors[i]);
6588 fprintf(f, "}\n");
6589 fprintf(f, " part.vs.epilog.export_prim_id = %u\n", key->part.vs.epilog.export_prim_id);
6590 fprintf(f, " as_es = %u\n", key->as_es);
6591 fprintf(f, " as_ls = %u\n", key->as_ls);
6592 fprintf(f, " mono.vs.fix_fetch = 0x%x\n", key->mono.vs.fix_fetch);
6593 break;
6594
6595 case PIPE_SHADER_TESS_CTRL:
6596 fprintf(f, " part.tcs.epilog.prim_mode = %u\n", key->part.tcs.epilog.prim_mode);
6597 fprintf(f, " mono.tcs.inputs_to_copy = 0x%"PRIx64"\n", key->mono.tcs.inputs_to_copy);
6598 break;
6599
6600 case PIPE_SHADER_TESS_EVAL:
6601 fprintf(f, " part.tes.epilog.export_prim_id = %u\n", key->part.tes.epilog.export_prim_id);
6602 fprintf(f, " as_es = %u\n", key->as_es);
6603 break;
6604
6605 case PIPE_SHADER_GEOMETRY:
6606 fprintf(f, " part.gs.prolog.tri_strip_adj_fix = %u\n", key->part.gs.prolog.tri_strip_adj_fix);
6607 break;
6608
6609 case PIPE_SHADER_COMPUTE:
6610 break;
6611
6612 case PIPE_SHADER_FRAGMENT:
6613 fprintf(f, " part.ps.prolog.color_two_side = %u\n", key->part.ps.prolog.color_two_side);
6614 fprintf(f, " part.ps.prolog.flatshade_colors = %u\n", key->part.ps.prolog.flatshade_colors);
6615 fprintf(f, " part.ps.prolog.poly_stipple = %u\n", key->part.ps.prolog.poly_stipple);
6616 fprintf(f, " part.ps.prolog.force_persp_sample_interp = %u\n", key->part.ps.prolog.force_persp_sample_interp);
6617 fprintf(f, " part.ps.prolog.force_linear_sample_interp = %u\n", key->part.ps.prolog.force_linear_sample_interp);
6618 fprintf(f, " part.ps.prolog.force_persp_center_interp = %u\n", key->part.ps.prolog.force_persp_center_interp);
6619 fprintf(f, " part.ps.prolog.force_linear_center_interp = %u\n", key->part.ps.prolog.force_linear_center_interp);
6620 fprintf(f, " part.ps.prolog.bc_optimize_for_persp = %u\n", key->part.ps.prolog.bc_optimize_for_persp);
6621 fprintf(f, " part.ps.prolog.bc_optimize_for_linear = %u\n", key->part.ps.prolog.bc_optimize_for_linear);
6622 fprintf(f, " part.ps.epilog.spi_shader_col_format = 0x%x\n", key->part.ps.epilog.spi_shader_col_format);
6623 fprintf(f, " part.ps.epilog.color_is_int8 = 0x%X\n", key->part.ps.epilog.color_is_int8);
6624 fprintf(f, " part.ps.epilog.last_cbuf = %u\n", key->part.ps.epilog.last_cbuf);
6625 fprintf(f, " part.ps.epilog.alpha_func = %u\n", key->part.ps.epilog.alpha_func);
6626 fprintf(f, " part.ps.epilog.alpha_to_one = %u\n", key->part.ps.epilog.alpha_to_one);
6627 fprintf(f, " part.ps.epilog.poly_line_smoothing = %u\n", key->part.ps.epilog.poly_line_smoothing);
6628 fprintf(f, " part.ps.epilog.clamp_color = %u\n", key->part.ps.epilog.clamp_color);
6629 break;
6630
6631 default:
6632 assert(0);
6633 }
6634
6635 if ((shader == PIPE_SHADER_GEOMETRY ||
6636 shader == PIPE_SHADER_TESS_EVAL ||
6637 shader == PIPE_SHADER_VERTEX) &&
6638 !key->as_es && !key->as_ls) {
6639 fprintf(f, " opt.hw_vs.kill_outputs = 0x%"PRIx64"\n", key->opt.hw_vs.kill_outputs);
6640 fprintf(f, " opt.hw_vs.kill_outputs2 = 0x%x\n", key->opt.hw_vs.kill_outputs2);
6641 fprintf(f, " opt.hw_vs.clip_disable = %u\n", key->opt.hw_vs.clip_disable);
6642 }
6643 }
6644
6645 static void si_init_shader_ctx(struct si_shader_context *ctx,
6646 struct si_screen *sscreen,
6647 struct si_shader *shader,
6648 LLVMTargetMachineRef tm)
6649 {
6650 struct lp_build_tgsi_context *bld_base;
6651 struct lp_build_tgsi_action tmpl = {};
6652
6653 si_llvm_context_init(ctx, sscreen, shader, tm,
6654 (shader && shader->selector) ? &shader->selector->info : NULL,
6655 (shader && shader->selector) ? shader->selector->tokens : NULL);
6656
6657 bld_base = &ctx->soa.bld_base;
6658 bld_base->emit_fetch_funcs[TGSI_FILE_CONSTANT] = fetch_constant;
6659
6660 bld_base->op_actions[TGSI_OPCODE_INTERP_CENTROID] = interp_action;
6661 bld_base->op_actions[TGSI_OPCODE_INTERP_SAMPLE] = interp_action;
6662 bld_base->op_actions[TGSI_OPCODE_INTERP_OFFSET] = interp_action;
6663
6664 bld_base->op_actions[TGSI_OPCODE_TEX] = tex_action;
6665 bld_base->op_actions[TGSI_OPCODE_TEX2] = tex_action;
6666 bld_base->op_actions[TGSI_OPCODE_TXB] = tex_action;
6667 bld_base->op_actions[TGSI_OPCODE_TXB2] = tex_action;
6668 bld_base->op_actions[TGSI_OPCODE_TXD] = tex_action;
6669 bld_base->op_actions[TGSI_OPCODE_TXF] = tex_action;
6670 bld_base->op_actions[TGSI_OPCODE_TXL] = tex_action;
6671 bld_base->op_actions[TGSI_OPCODE_TXL2] = tex_action;
6672 bld_base->op_actions[TGSI_OPCODE_TXP] = tex_action;
6673 bld_base->op_actions[TGSI_OPCODE_TXQ].fetch_args = txq_fetch_args;
6674 bld_base->op_actions[TGSI_OPCODE_TXQ].emit = txq_emit;
6675 bld_base->op_actions[TGSI_OPCODE_TG4] = tex_action;
6676 bld_base->op_actions[TGSI_OPCODE_LODQ] = tex_action;
6677 bld_base->op_actions[TGSI_OPCODE_TXQS].emit = si_llvm_emit_txqs;
6678
6679 bld_base->op_actions[TGSI_OPCODE_LOAD].fetch_args = load_fetch_args;
6680 bld_base->op_actions[TGSI_OPCODE_LOAD].emit = load_emit;
6681 bld_base->op_actions[TGSI_OPCODE_STORE].fetch_args = store_fetch_args;
6682 bld_base->op_actions[TGSI_OPCODE_STORE].emit = store_emit;
6683 bld_base->op_actions[TGSI_OPCODE_RESQ].fetch_args = resq_fetch_args;
6684 bld_base->op_actions[TGSI_OPCODE_RESQ].emit = resq_emit;
6685
6686 tmpl.fetch_args = atomic_fetch_args;
6687 tmpl.emit = atomic_emit;
6688 bld_base->op_actions[TGSI_OPCODE_ATOMUADD] = tmpl;
6689 bld_base->op_actions[TGSI_OPCODE_ATOMUADD].intr_name = "add";
6690 bld_base->op_actions[TGSI_OPCODE_ATOMXCHG] = tmpl;
6691 bld_base->op_actions[TGSI_OPCODE_ATOMXCHG].intr_name = "swap";
6692 bld_base->op_actions[TGSI_OPCODE_ATOMCAS] = tmpl;
6693 bld_base->op_actions[TGSI_OPCODE_ATOMCAS].intr_name = "cmpswap";
6694 bld_base->op_actions[TGSI_OPCODE_ATOMAND] = tmpl;
6695 bld_base->op_actions[TGSI_OPCODE_ATOMAND].intr_name = "and";
6696 bld_base->op_actions[TGSI_OPCODE_ATOMOR] = tmpl;
6697 bld_base->op_actions[TGSI_OPCODE_ATOMOR].intr_name = "or";
6698 bld_base->op_actions[TGSI_OPCODE_ATOMXOR] = tmpl;
6699 bld_base->op_actions[TGSI_OPCODE_ATOMXOR].intr_name = "xor";
6700 bld_base->op_actions[TGSI_OPCODE_ATOMUMIN] = tmpl;
6701 bld_base->op_actions[TGSI_OPCODE_ATOMUMIN].intr_name = "umin";
6702 bld_base->op_actions[TGSI_OPCODE_ATOMUMAX] = tmpl;
6703 bld_base->op_actions[TGSI_OPCODE_ATOMUMAX].intr_name = "umax";
6704 bld_base->op_actions[TGSI_OPCODE_ATOMIMIN] = tmpl;
6705 bld_base->op_actions[TGSI_OPCODE_ATOMIMIN].intr_name = "smin";
6706 bld_base->op_actions[TGSI_OPCODE_ATOMIMAX] = tmpl;
6707 bld_base->op_actions[TGSI_OPCODE_ATOMIMAX].intr_name = "smax";
6708
6709 bld_base->op_actions[TGSI_OPCODE_MEMBAR].emit = membar_emit;
6710
6711 bld_base->op_actions[TGSI_OPCODE_DDX].emit = si_llvm_emit_ddxy;
6712 bld_base->op_actions[TGSI_OPCODE_DDY].emit = si_llvm_emit_ddxy;
6713 bld_base->op_actions[TGSI_OPCODE_DDX_FINE].emit = si_llvm_emit_ddxy;
6714 bld_base->op_actions[TGSI_OPCODE_DDY_FINE].emit = si_llvm_emit_ddxy;
6715
6716 bld_base->op_actions[TGSI_OPCODE_EMIT].emit = si_llvm_emit_vertex;
6717 bld_base->op_actions[TGSI_OPCODE_ENDPRIM].emit = si_llvm_emit_primitive;
6718 bld_base->op_actions[TGSI_OPCODE_BARRIER].emit = si_llvm_emit_barrier;
6719 }
6720
6721 /* Return true if the PARAM export has been eliminated. */
6722 static bool si_eliminate_const_output(struct si_shader_context *ctx,
6723 LLVMValueRef inst, unsigned offset)
6724 {
6725 struct si_shader *shader = ctx->shader;
6726 unsigned num_outputs = shader->selector->info.num_outputs;
6727 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
6728 bool is_zero[4] = {}, is_one[4] = {};
6729
6730 for (i = 0; i < 4; i++) {
6731 LLVMBool loses_info;
6732 LLVMValueRef p = LLVMGetOperand(inst, 5 + i);
6733
6734 /* It's a constant expression. Undef outputs are eliminated too. */
6735 if (LLVMIsUndef(p)) {
6736 is_zero[i] = true;
6737 is_one[i] = true;
6738 } else if (LLVMIsAConstantFP(p)) {
6739 double a = LLVMConstRealGetDouble(p, &loses_info);
6740
6741 if (a == 0)
6742 is_zero[i] = true;
6743 else if (a == 1)
6744 is_one[i] = true;
6745 else
6746 return false; /* other constant */
6747 } else
6748 return false;
6749 }
6750
6751 /* Only certain combinations of 0 and 1 can be eliminated. */
6752 if (is_zero[0] && is_zero[1] && is_zero[2])
6753 default_val = is_zero[3] ? 0 : 1;
6754 else if (is_one[0] && is_one[1] && is_one[2])
6755 default_val = is_zero[3] ? 2 : 3;
6756 else
6757 return false;
6758
6759 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
6760 LLVMInstructionEraseFromParent(inst);
6761
6762 /* Change OFFSET to DEFAULT_VAL. */
6763 for (i = 0; i < num_outputs; i++) {
6764 if (shader->info.vs_output_param_offset[i] == offset) {
6765 shader->info.vs_output_param_offset[i] =
6766 EXP_PARAM_DEFAULT_VAL_0000 + default_val;
6767 break;
6768 }
6769 }
6770 return true;
6771 }
6772
6773 struct si_vs_exports {
6774 unsigned num;
6775 unsigned offset[SI_MAX_VS_OUTPUTS];
6776 LLVMValueRef inst[SI_MAX_VS_OUTPUTS];
6777 };
6778
6779 static void si_eliminate_const_vs_outputs(struct si_shader_context *ctx)
6780 {
6781 struct si_shader *shader = ctx->shader;
6782 struct tgsi_shader_info *info = &shader->selector->info;
6783 LLVMBasicBlockRef bb;
6784 struct si_vs_exports exports;
6785 bool removed_any = false;
6786
6787 exports.num = 0;
6788
6789 if (ctx->type == PIPE_SHADER_FRAGMENT ||
6790 ctx->type == PIPE_SHADER_COMPUTE ||
6791 shader->key.as_es ||
6792 shader->key.as_ls)
6793 return;
6794
6795 /* Process all LLVM instructions. */
6796 bb = LLVMGetFirstBasicBlock(ctx->main_fn);
6797 while (bb) {
6798 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
6799
6800 while (inst) {
6801 LLVMValueRef cur = inst;
6802 inst = LLVMGetNextInstruction(inst);
6803
6804 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
6805 continue;
6806
6807 LLVMValueRef callee = lp_get_called_value(cur);
6808
6809 if (!lp_is_function(callee))
6810 continue;
6811
6812 const char *name = LLVMGetValueName(callee);
6813 unsigned num_args = LLVMCountParams(callee);
6814
6815 /* Check if this is an export instruction. */
6816 if (num_args != 9 || strcmp(name, "llvm.SI.export"))
6817 continue;
6818
6819 LLVMValueRef arg = LLVMGetOperand(cur, 3);
6820 unsigned target = LLVMConstIntGetZExtValue(arg);
6821
6822 if (target < V_008DFC_SQ_EXP_PARAM)
6823 continue;
6824
6825 target -= V_008DFC_SQ_EXP_PARAM;
6826
6827 /* Eliminate constant value PARAM exports. */
6828 if (si_eliminate_const_output(ctx, cur, target)) {
6829 removed_any = true;
6830 } else {
6831 exports.offset[exports.num] = target;
6832 exports.inst[exports.num] = cur;
6833 exports.num++;
6834 }
6835 }
6836 bb = LLVMGetNextBasicBlock(bb);
6837 }
6838
6839 /* Remove holes in export memory due to removed PARAM exports.
6840 * This is done by renumbering all PARAM exports.
6841 */
6842 if (removed_any) {
6843 ubyte current_offset[SI_MAX_VS_OUTPUTS];
6844 unsigned new_count = 0;
6845 unsigned out, i;
6846
6847 /* Make a copy of the offsets. We need the old version while
6848 * we are modifying some of them. */
6849 assert(sizeof(current_offset) ==
6850 sizeof(shader->info.vs_output_param_offset));
6851 memcpy(current_offset, shader->info.vs_output_param_offset,
6852 sizeof(current_offset));
6853
6854 for (i = 0; i < exports.num; i++) {
6855 unsigned offset = exports.offset[i];
6856
6857 for (out = 0; out < info->num_outputs; out++) {
6858 if (current_offset[out] != offset)
6859 continue;
6860
6861 LLVMSetOperand(exports.inst[i], 3,
6862 LLVMConstInt(ctx->i32,
6863 V_008DFC_SQ_EXP_PARAM + new_count, 0));
6864 shader->info.vs_output_param_offset[out] = new_count;
6865 new_count++;
6866 break;
6867 }
6868 }
6869 shader->info.nr_param_exports = new_count;
6870 }
6871 }
6872
6873 static void si_count_scratch_private_memory(struct si_shader_context *ctx)
6874 {
6875 ctx->shader->config.private_mem_vgprs = 0;
6876
6877 /* Process all LLVM instructions. */
6878 LLVMBasicBlockRef bb = LLVMGetFirstBasicBlock(ctx->main_fn);
6879 while (bb) {
6880 LLVMValueRef next = LLVMGetFirstInstruction(bb);
6881
6882 while (next) {
6883 LLVMValueRef inst = next;
6884 next = LLVMGetNextInstruction(next);
6885
6886 if (LLVMGetInstructionOpcode(inst) != LLVMAlloca)
6887 continue;
6888
6889 LLVMTypeRef type = LLVMGetElementType(LLVMTypeOf(inst));
6890 /* No idea why LLVM aligns allocas to 4 elements. */
6891 unsigned alignment = LLVMGetAlignment(inst);
6892 unsigned dw_size = align(llvm_get_type_size(type) / 4, alignment);
6893 ctx->shader->config.private_mem_vgprs += dw_size;
6894 }
6895 bb = LLVMGetNextBasicBlock(bb);
6896 }
6897 }
6898
6899 static bool si_compile_tgsi_main(struct si_shader_context *ctx,
6900 struct si_shader *shader)
6901 {
6902 struct si_shader_selector *sel = shader->selector;
6903 struct lp_build_tgsi_context *bld_base = &ctx->soa.bld_base;
6904
6905 switch (ctx->type) {
6906 case PIPE_SHADER_VERTEX:
6907 ctx->load_input = declare_input_vs;
6908 if (shader->key.as_ls)
6909 bld_base->emit_epilogue = si_llvm_emit_ls_epilogue;
6910 else if (shader->key.as_es)
6911 bld_base->emit_epilogue = si_llvm_emit_es_epilogue;
6912 else
6913 bld_base->emit_epilogue = si_llvm_emit_vs_epilogue;
6914 break;
6915 case PIPE_SHADER_TESS_CTRL:
6916 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_tcs;
6917 bld_base->emit_fetch_funcs[TGSI_FILE_OUTPUT] = fetch_output_tcs;
6918 bld_base->emit_store = store_output_tcs;
6919 bld_base->emit_epilogue = si_llvm_emit_tcs_epilogue;
6920 break;
6921 case PIPE_SHADER_TESS_EVAL:
6922 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_tes;
6923 if (shader->key.as_es)
6924 bld_base->emit_epilogue = si_llvm_emit_es_epilogue;
6925 else
6926 bld_base->emit_epilogue = si_llvm_emit_vs_epilogue;
6927 break;
6928 case PIPE_SHADER_GEOMETRY:
6929 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_gs;
6930 bld_base->emit_epilogue = si_llvm_emit_gs_epilogue;
6931 break;
6932 case PIPE_SHADER_FRAGMENT:
6933 ctx->load_input = declare_input_fs;
6934 bld_base->emit_epilogue = si_llvm_return_fs_outputs;
6935 break;
6936 case PIPE_SHADER_COMPUTE:
6937 ctx->declare_memory_region = declare_compute_memory;
6938 break;
6939 default:
6940 assert(!"Unsupported shader type");
6941 return false;
6942 }
6943
6944 create_meta_data(ctx);
6945 create_function(ctx);
6946 preload_ring_buffers(ctx);
6947
6948 if (ctx->type == PIPE_SHADER_GEOMETRY) {
6949 int i;
6950 for (i = 0; i < 4; i++) {
6951 ctx->gs_next_vertex[i] =
6952 lp_build_alloca(bld_base->base.gallivm,
6953 ctx->i32, "");
6954 }
6955 }
6956
6957 if (!lp_build_tgsi_llvm(bld_base, sel->tokens)) {
6958 fprintf(stderr, "Failed to translate shader from TGSI to LLVM\n");
6959 return false;
6960 }
6961
6962 si_llvm_build_ret(ctx, ctx->return_value);
6963 return true;
6964 }
6965
6966 /**
6967 * Compute the VS prolog key, which contains all the information needed to
6968 * build the VS prolog function, and set shader->info bits where needed.
6969 */
6970 static void si_get_vs_prolog_key(struct si_shader *shader,
6971 union si_shader_part_key *key)
6972 {
6973 struct tgsi_shader_info *info = &shader->selector->info;
6974
6975 memset(key, 0, sizeof(*key));
6976 key->vs_prolog.states = shader->key.part.vs.prolog;
6977 key->vs_prolog.num_input_sgprs = shader->info.num_input_sgprs;
6978 key->vs_prolog.last_input = MAX2(1, info->num_inputs) - 1;
6979
6980 /* Set the instanceID flag. */
6981 for (unsigned i = 0; i < info->num_inputs; i++)
6982 if (key->vs_prolog.states.instance_divisors[i])
6983 shader->info.uses_instanceid = true;
6984 }
6985
6986 /**
6987 * Compute the VS epilog key, which contains all the information needed to
6988 * build the VS epilog function, and set the PrimitiveID output offset.
6989 */
6990 static void si_get_vs_epilog_key(struct si_shader *shader,
6991 struct si_vs_epilog_bits *states,
6992 union si_shader_part_key *key)
6993 {
6994 memset(key, 0, sizeof(*key));
6995 key->vs_epilog.states = *states;
6996
6997 /* Set up the PrimitiveID output. */
6998 if (shader->key.part.vs.epilog.export_prim_id) {
6999 unsigned index = shader->selector->info.num_outputs;
7000 unsigned offset = shader->info.nr_param_exports++;
7001
7002 key->vs_epilog.prim_id_param_offset = offset;
7003 assert(index < ARRAY_SIZE(shader->info.vs_output_param_offset));
7004 shader->info.vs_output_param_offset[index] = offset;
7005 }
7006 }
7007
7008 /**
7009 * Compute the PS prolog key, which contains all the information needed to
7010 * build the PS prolog function, and set related bits in shader->config.
7011 */
7012 static void si_get_ps_prolog_key(struct si_shader *shader,
7013 union si_shader_part_key *key,
7014 bool separate_prolog)
7015 {
7016 struct tgsi_shader_info *info = &shader->selector->info;
7017
7018 memset(key, 0, sizeof(*key));
7019 key->ps_prolog.states = shader->key.part.ps.prolog;
7020 key->ps_prolog.colors_read = info->colors_read;
7021 key->ps_prolog.num_input_sgprs = shader->info.num_input_sgprs;
7022 key->ps_prolog.num_input_vgprs = shader->info.num_input_vgprs;
7023 key->ps_prolog.wqm = info->uses_derivatives &&
7024 (key->ps_prolog.colors_read ||
7025 key->ps_prolog.states.force_persp_sample_interp ||
7026 key->ps_prolog.states.force_linear_sample_interp ||
7027 key->ps_prolog.states.force_persp_center_interp ||
7028 key->ps_prolog.states.force_linear_center_interp ||
7029 key->ps_prolog.states.bc_optimize_for_persp ||
7030 key->ps_prolog.states.bc_optimize_for_linear);
7031
7032 if (info->colors_read) {
7033 unsigned *color = shader->selector->color_attr_index;
7034
7035 if (shader->key.part.ps.prolog.color_two_side) {
7036 /* BCOLORs are stored after the last input. */
7037 key->ps_prolog.num_interp_inputs = info->num_inputs;
7038 key->ps_prolog.face_vgpr_index = shader->info.face_vgpr_index;
7039 shader->config.spi_ps_input_ena |= S_0286CC_FRONT_FACE_ENA(1);
7040 }
7041
7042 for (unsigned i = 0; i < 2; i++) {
7043 unsigned interp = info->input_interpolate[color[i]];
7044 unsigned location = info->input_interpolate_loc[color[i]];
7045
7046 if (!(info->colors_read & (0xf << i*4)))
7047 continue;
7048
7049 key->ps_prolog.color_attr_index[i] = color[i];
7050
7051 if (shader->key.part.ps.prolog.flatshade_colors &&
7052 interp == TGSI_INTERPOLATE_COLOR)
7053 interp = TGSI_INTERPOLATE_CONSTANT;
7054
7055 switch (interp) {
7056 case TGSI_INTERPOLATE_CONSTANT:
7057 key->ps_prolog.color_interp_vgpr_index[i] = -1;
7058 break;
7059 case TGSI_INTERPOLATE_PERSPECTIVE:
7060 case TGSI_INTERPOLATE_COLOR:
7061 /* Force the interpolation location for colors here. */
7062 if (shader->key.part.ps.prolog.force_persp_sample_interp)
7063 location = TGSI_INTERPOLATE_LOC_SAMPLE;
7064 if (shader->key.part.ps.prolog.force_persp_center_interp)
7065 location = TGSI_INTERPOLATE_LOC_CENTER;
7066
7067 switch (location) {
7068 case TGSI_INTERPOLATE_LOC_SAMPLE:
7069 key->ps_prolog.color_interp_vgpr_index[i] = 0;
7070 shader->config.spi_ps_input_ena |=
7071 S_0286CC_PERSP_SAMPLE_ENA(1);
7072 break;
7073 case TGSI_INTERPOLATE_LOC_CENTER:
7074 key->ps_prolog.color_interp_vgpr_index[i] = 2;
7075 shader->config.spi_ps_input_ena |=
7076 S_0286CC_PERSP_CENTER_ENA(1);
7077 break;
7078 case TGSI_INTERPOLATE_LOC_CENTROID:
7079 key->ps_prolog.color_interp_vgpr_index[i] = 4;
7080 shader->config.spi_ps_input_ena |=
7081 S_0286CC_PERSP_CENTROID_ENA(1);
7082 break;
7083 default:
7084 assert(0);
7085 }
7086 break;
7087 case TGSI_INTERPOLATE_LINEAR:
7088 /* Force the interpolation location for colors here. */
7089 if (shader->key.part.ps.prolog.force_linear_sample_interp)
7090 location = TGSI_INTERPOLATE_LOC_SAMPLE;
7091 if (shader->key.part.ps.prolog.force_linear_center_interp)
7092 location = TGSI_INTERPOLATE_LOC_CENTER;
7093
7094 /* The VGPR assignment for non-monolithic shaders
7095 * works because InitialPSInputAddr is set on the
7096 * main shader and PERSP_PULL_MODEL is never used.
7097 */
7098 switch (location) {
7099 case TGSI_INTERPOLATE_LOC_SAMPLE:
7100 key->ps_prolog.color_interp_vgpr_index[i] =
7101 separate_prolog ? 6 : 9;
7102 shader->config.spi_ps_input_ena |=
7103 S_0286CC_LINEAR_SAMPLE_ENA(1);
7104 break;
7105 case TGSI_INTERPOLATE_LOC_CENTER:
7106 key->ps_prolog.color_interp_vgpr_index[i] =
7107 separate_prolog ? 8 : 11;
7108 shader->config.spi_ps_input_ena |=
7109 S_0286CC_LINEAR_CENTER_ENA(1);
7110 break;
7111 case TGSI_INTERPOLATE_LOC_CENTROID:
7112 key->ps_prolog.color_interp_vgpr_index[i] =
7113 separate_prolog ? 10 : 13;
7114 shader->config.spi_ps_input_ena |=
7115 S_0286CC_LINEAR_CENTROID_ENA(1);
7116 break;
7117 default:
7118 assert(0);
7119 }
7120 break;
7121 default:
7122 assert(0);
7123 }
7124 }
7125 }
7126 }
7127
7128 /**
7129 * Check whether a PS prolog is required based on the key.
7130 */
7131 static bool si_need_ps_prolog(const union si_shader_part_key *key)
7132 {
7133 return key->ps_prolog.colors_read ||
7134 key->ps_prolog.states.force_persp_sample_interp ||
7135 key->ps_prolog.states.force_linear_sample_interp ||
7136 key->ps_prolog.states.force_persp_center_interp ||
7137 key->ps_prolog.states.force_linear_center_interp ||
7138 key->ps_prolog.states.bc_optimize_for_persp ||
7139 key->ps_prolog.states.bc_optimize_for_linear ||
7140 key->ps_prolog.states.poly_stipple;
7141 }
7142
7143 /**
7144 * Compute the PS epilog key, which contains all the information needed to
7145 * build the PS epilog function.
7146 */
7147 static void si_get_ps_epilog_key(struct si_shader *shader,
7148 union si_shader_part_key *key)
7149 {
7150 struct tgsi_shader_info *info = &shader->selector->info;
7151 memset(key, 0, sizeof(*key));
7152 key->ps_epilog.colors_written = info->colors_written;
7153 key->ps_epilog.writes_z = info->writes_z;
7154 key->ps_epilog.writes_stencil = info->writes_stencil;
7155 key->ps_epilog.writes_samplemask = info->writes_samplemask;
7156 key->ps_epilog.states = shader->key.part.ps.epilog;
7157 }
7158
7159 /**
7160 * Build the GS prolog function. Rotate the input vertices for triangle strips
7161 * with adjacency.
7162 */
7163 static void si_build_gs_prolog_function(struct si_shader_context *ctx,
7164 union si_shader_part_key *key)
7165 {
7166 const unsigned num_sgprs = SI_GS_NUM_USER_SGPR + 2;
7167 const unsigned num_vgprs = 8;
7168 struct gallivm_state *gallivm = &ctx->gallivm;
7169 LLVMBuilderRef builder = gallivm->builder;
7170 LLVMTypeRef params[32];
7171 LLVMTypeRef returns[32];
7172 LLVMValueRef func, ret;
7173
7174 for (unsigned i = 0; i < num_sgprs; ++i) {
7175 params[i] = ctx->i32;
7176 returns[i] = ctx->i32;
7177 }
7178
7179 for (unsigned i = 0; i < num_vgprs; ++i) {
7180 params[num_sgprs + i] = ctx->i32;
7181 returns[num_sgprs + i] = ctx->f32;
7182 }
7183
7184 /* Create the function. */
7185 si_create_function(ctx, "gs_prolog", returns, num_sgprs + num_vgprs,
7186 params, num_sgprs + num_vgprs, num_sgprs - 1);
7187 func = ctx->main_fn;
7188
7189 /* Copy inputs to outputs. This should be no-op, as the registers match,
7190 * but it will prevent the compiler from overwriting them unintentionally.
7191 */
7192 ret = ctx->return_value;
7193 for (unsigned i = 0; i < num_sgprs; i++) {
7194 LLVMValueRef p = LLVMGetParam(func, i);
7195 ret = LLVMBuildInsertValue(builder, ret, p, i, "");
7196 }
7197 for (unsigned i = 0; i < num_vgprs; i++) {
7198 LLVMValueRef p = LLVMGetParam(func, num_sgprs + i);
7199 p = LLVMBuildBitCast(builder, p, ctx->f32, "");
7200 ret = LLVMBuildInsertValue(builder, ret, p, num_sgprs + i, "");
7201 }
7202
7203 if (key->gs_prolog.states.tri_strip_adj_fix) {
7204 /* Remap the input vertices for every other primitive. */
7205 const unsigned vtx_params[6] = {
7206 num_sgprs,
7207 num_sgprs + 1,
7208 num_sgprs + 3,
7209 num_sgprs + 4,
7210 num_sgprs + 5,
7211 num_sgprs + 6
7212 };
7213 LLVMValueRef prim_id, rotate;
7214
7215 prim_id = LLVMGetParam(func, num_sgprs + 2);
7216 rotate = LLVMBuildTrunc(builder, prim_id, ctx->i1, "");
7217
7218 for (unsigned i = 0; i < 6; ++i) {
7219 LLVMValueRef base, rotated, actual;
7220 base = LLVMGetParam(func, vtx_params[i]);
7221 rotated = LLVMGetParam(func, vtx_params[(i + 4) % 6]);
7222 actual = LLVMBuildSelect(builder, rotate, rotated, base, "");
7223 actual = LLVMBuildBitCast(builder, actual, ctx->f32, "");
7224 ret = LLVMBuildInsertValue(builder, ret, actual, vtx_params[i], "");
7225 }
7226 }
7227
7228 LLVMBuildRet(builder, ret);
7229 }
7230
7231 /**
7232 * Given a list of shader part functions, build a wrapper function that
7233 * runs them in sequence to form a monolithic shader.
7234 */
7235 static void si_build_wrapper_function(struct si_shader_context *ctx,
7236 LLVMValueRef *parts,
7237 unsigned num_parts,
7238 unsigned main_part)
7239 {
7240 struct gallivm_state *gallivm = &ctx->gallivm;
7241 LLVMBuilderRef builder = ctx->gallivm.builder;
7242 /* PS epilog has one arg per color component */
7243 LLVMTypeRef param_types[48];
7244 LLVMValueRef out[48];
7245 LLVMTypeRef function_type;
7246 unsigned num_params;
7247 unsigned num_out;
7248 MAYBE_UNUSED unsigned num_out_sgpr; /* used in debug checks */
7249 unsigned num_sgprs, num_vgprs;
7250 unsigned last_sgpr_param;
7251 unsigned gprs;
7252
7253 for (unsigned i = 0; i < num_parts; ++i) {
7254 lp_add_function_attr(parts[i], -1, LP_FUNC_ATTR_ALWAYSINLINE);
7255 LLVMSetLinkage(parts[i], LLVMPrivateLinkage);
7256 }
7257
7258 /* The parameters of the wrapper function correspond to those of the
7259 * first part in terms of SGPRs and VGPRs, but we use the types of the
7260 * main part to get the right types. This is relevant for the
7261 * dereferenceable attribute on descriptor table pointers.
7262 */
7263 num_sgprs = 0;
7264 num_vgprs = 0;
7265
7266 function_type = LLVMGetElementType(LLVMTypeOf(parts[0]));
7267 num_params = LLVMCountParamTypes(function_type);
7268
7269 for (unsigned i = 0; i < num_params; ++i) {
7270 LLVMValueRef param = LLVMGetParam(parts[0], i);
7271
7272 if (ac_is_sgpr_param(param)) {
7273 assert(num_vgprs == 0);
7274 num_sgprs += llvm_get_type_size(LLVMTypeOf(param)) / 4;
7275 } else {
7276 num_vgprs += llvm_get_type_size(LLVMTypeOf(param)) / 4;
7277 }
7278 }
7279 assert(num_vgprs + num_sgprs <= ARRAY_SIZE(param_types));
7280
7281 num_params = 0;
7282 last_sgpr_param = 0;
7283 gprs = 0;
7284 while (gprs < num_sgprs + num_vgprs) {
7285 LLVMValueRef param = LLVMGetParam(parts[main_part], num_params);
7286 unsigned size;
7287
7288 param_types[num_params] = LLVMTypeOf(param);
7289 if (gprs < num_sgprs)
7290 last_sgpr_param = num_params;
7291 size = llvm_get_type_size(param_types[num_params]) / 4;
7292 num_params++;
7293
7294 assert(ac_is_sgpr_param(param) == (gprs < num_sgprs));
7295 assert(gprs + size <= num_sgprs + num_vgprs &&
7296 (gprs >= num_sgprs || gprs + size <= num_sgprs));
7297
7298 gprs += size;
7299 }
7300
7301 si_create_function(ctx, "wrapper", NULL, 0, param_types, num_params, last_sgpr_param);
7302
7303 /* Record the arguments of the function as if they were an output of
7304 * a previous part.
7305 */
7306 num_out = 0;
7307 num_out_sgpr = 0;
7308
7309 for (unsigned i = 0; i < num_params; ++i) {
7310 LLVMValueRef param = LLVMGetParam(ctx->main_fn, i);
7311 LLVMTypeRef param_type = LLVMTypeOf(param);
7312 LLVMTypeRef out_type = i <= last_sgpr_param ? ctx->i32 : ctx->f32;
7313 unsigned size = llvm_get_type_size(param_type) / 4;
7314
7315 if (size == 1) {
7316 if (param_type != out_type)
7317 param = LLVMBuildBitCast(builder, param, out_type, "");
7318 out[num_out++] = param;
7319 } else {
7320 LLVMTypeRef vector_type = LLVMVectorType(out_type, size);
7321
7322 if (LLVMGetTypeKind(param_type) == LLVMPointerTypeKind) {
7323 param = LLVMBuildPtrToInt(builder, param, ctx->i64, "");
7324 param_type = ctx->i64;
7325 }
7326
7327 if (param_type != vector_type)
7328 param = LLVMBuildBitCast(builder, param, vector_type, "");
7329
7330 for (unsigned j = 0; j < size; ++j)
7331 out[num_out++] = LLVMBuildExtractElement(
7332 builder, param, LLVMConstInt(ctx->i32, j, 0), "");
7333 }
7334
7335 if (i <= last_sgpr_param)
7336 num_out_sgpr = num_out;
7337 }
7338
7339 /* Now chain the parts. */
7340 for (unsigned part = 0; part < num_parts; ++part) {
7341 LLVMValueRef in[48];
7342 LLVMValueRef ret;
7343 LLVMTypeRef ret_type;
7344 unsigned out_idx = 0;
7345
7346 num_params = LLVMCountParams(parts[part]);
7347 assert(num_params <= ARRAY_SIZE(param_types));
7348
7349 /* Derive arguments for the next part from outputs of the
7350 * previous one.
7351 */
7352 for (unsigned param_idx = 0; param_idx < num_params; ++param_idx) {
7353 LLVMValueRef param;
7354 LLVMTypeRef param_type;
7355 bool is_sgpr;
7356 unsigned param_size;
7357 LLVMValueRef arg = NULL;
7358
7359 param = LLVMGetParam(parts[part], param_idx);
7360 param_type = LLVMTypeOf(param);
7361 param_size = llvm_get_type_size(param_type) / 4;
7362 is_sgpr = ac_is_sgpr_param(param);
7363
7364 if (is_sgpr) {
7365 #if HAVE_LLVM < 0x0400
7366 LLVMRemoveAttribute(param, LLVMByValAttribute);
7367 #else
7368 unsigned kind_id = LLVMGetEnumAttributeKindForName("byval", 5);
7369 LLVMRemoveEnumAttributeAtIndex(parts[part], param_idx + 1, kind_id);
7370 #endif
7371 lp_add_function_attr(parts[part], param_idx + 1, LP_FUNC_ATTR_INREG);
7372 }
7373
7374 assert(out_idx + param_size <= (is_sgpr ? num_out_sgpr : num_out));
7375 assert(is_sgpr || out_idx >= num_out_sgpr);
7376
7377 if (param_size == 1)
7378 arg = out[out_idx];
7379 else
7380 arg = lp_build_gather_values(gallivm, &out[out_idx], param_size);
7381
7382 if (LLVMTypeOf(arg) != param_type) {
7383 if (LLVMGetTypeKind(param_type) == LLVMPointerTypeKind) {
7384 arg = LLVMBuildBitCast(builder, arg, ctx->i64, "");
7385 arg = LLVMBuildIntToPtr(builder, arg, param_type, "");
7386 } else {
7387 arg = LLVMBuildBitCast(builder, arg, param_type, "");
7388 }
7389 }
7390
7391 in[param_idx] = arg;
7392 out_idx += param_size;
7393 }
7394
7395 ret = LLVMBuildCall(builder, parts[part], in, num_params, "");
7396 ret_type = LLVMTypeOf(ret);
7397
7398 /* Extract the returned GPRs. */
7399 num_out = 0;
7400 num_out_sgpr = 0;
7401
7402 if (LLVMGetTypeKind(ret_type) != LLVMVoidTypeKind) {
7403 assert(LLVMGetTypeKind(ret_type) == LLVMStructTypeKind);
7404
7405 unsigned ret_size = LLVMCountStructElementTypes(ret_type);
7406
7407 for (unsigned i = 0; i < ret_size; ++i) {
7408 LLVMValueRef val =
7409 LLVMBuildExtractValue(builder, ret, i, "");
7410
7411 out[num_out++] = val;
7412
7413 if (LLVMTypeOf(val) == ctx->i32) {
7414 assert(num_out_sgpr + 1 == num_out);
7415 num_out_sgpr = num_out;
7416 }
7417 }
7418 }
7419 }
7420
7421 LLVMBuildRetVoid(builder);
7422 }
7423
7424 int si_compile_tgsi_shader(struct si_screen *sscreen,
7425 LLVMTargetMachineRef tm,
7426 struct si_shader *shader,
7427 bool is_monolithic,
7428 struct pipe_debug_callback *debug)
7429 {
7430 struct si_shader_selector *sel = shader->selector;
7431 struct si_shader_context ctx;
7432 struct lp_build_tgsi_context *bld_base;
7433 LLVMModuleRef mod;
7434 int r = -1;
7435
7436 /* Dump TGSI code before doing TGSI->LLVM conversion in case the
7437 * conversion fails. */
7438 if (r600_can_dump_shader(&sscreen->b, sel->info.processor) &&
7439 !(sscreen->b.debug_flags & DBG_NO_TGSI)) {
7440 tgsi_dump(sel->tokens, 0);
7441 si_dump_streamout(&sel->so);
7442 }
7443
7444 si_init_shader_ctx(&ctx, sscreen, shader, tm);
7445 ctx.separate_prolog = !is_monolithic;
7446
7447 memset(shader->info.vs_output_param_offset, EXP_PARAM_UNDEFINED,
7448 sizeof(shader->info.vs_output_param_offset));
7449
7450 shader->info.uses_instanceid = sel->info.uses_instanceid;
7451
7452 bld_base = &ctx.soa.bld_base;
7453 ctx.load_system_value = declare_system_value;
7454
7455 if (!si_compile_tgsi_main(&ctx, shader)) {
7456 si_llvm_dispose(&ctx);
7457 return -1;
7458 }
7459
7460 if (is_monolithic && ctx.type == PIPE_SHADER_VERTEX) {
7461 LLVMValueRef parts[3];
7462 bool need_prolog;
7463 bool need_epilog;
7464
7465 need_prolog = sel->info.num_inputs;
7466 need_epilog = !shader->key.as_es && !shader->key.as_ls;
7467
7468 parts[need_prolog ? 1 : 0] = ctx.main_fn;
7469
7470 if (need_prolog) {
7471 union si_shader_part_key prolog_key;
7472 si_get_vs_prolog_key(shader, &prolog_key);
7473 si_build_vs_prolog_function(&ctx, &prolog_key);
7474 parts[0] = ctx.main_fn;
7475 }
7476
7477 if (need_epilog) {
7478 union si_shader_part_key epilog_key;
7479 si_get_vs_epilog_key(shader, &shader->key.part.vs.epilog, &epilog_key);
7480 si_build_vs_epilog_function(&ctx, &epilog_key);
7481 parts[need_prolog ? 2 : 1] = ctx.main_fn;
7482 }
7483
7484 si_build_wrapper_function(&ctx, parts, 1 + need_prolog + need_epilog,
7485 need_prolog ? 1 : 0);
7486 } else if (is_monolithic && ctx.type == PIPE_SHADER_TESS_CTRL) {
7487 LLVMValueRef parts[2];
7488 union si_shader_part_key epilog_key;
7489
7490 parts[0] = ctx.main_fn;
7491
7492 memset(&epilog_key, 0, sizeof(epilog_key));
7493 epilog_key.tcs_epilog.states = shader->key.part.tcs.epilog;
7494 si_build_tcs_epilog_function(&ctx, &epilog_key);
7495 parts[1] = ctx.main_fn;
7496
7497 si_build_wrapper_function(&ctx, parts, 2, 0);
7498 } else if (is_monolithic && ctx.type == PIPE_SHADER_TESS_EVAL &&
7499 !shader->key.as_es) {
7500 LLVMValueRef parts[2];
7501 union si_shader_part_key epilog_key;
7502
7503 parts[0] = ctx.main_fn;
7504
7505 si_get_vs_epilog_key(shader, &shader->key.part.tes.epilog, &epilog_key);
7506 si_build_vs_epilog_function(&ctx, &epilog_key);
7507 parts[1] = ctx.main_fn;
7508
7509 si_build_wrapper_function(&ctx, parts, 2, 0);
7510 } else if (is_monolithic && ctx.type == PIPE_SHADER_GEOMETRY) {
7511 LLVMValueRef parts[2];
7512 union si_shader_part_key prolog_key;
7513
7514 parts[1] = ctx.main_fn;
7515
7516 memset(&prolog_key, 0, sizeof(prolog_key));
7517 prolog_key.gs_prolog.states = shader->key.part.gs.prolog;
7518 si_build_gs_prolog_function(&ctx, &prolog_key);
7519 parts[0] = ctx.main_fn;
7520
7521 si_build_wrapper_function(&ctx, parts, 2, 1);
7522 } else if (is_monolithic && ctx.type == PIPE_SHADER_FRAGMENT) {
7523 LLVMValueRef parts[3];
7524 union si_shader_part_key prolog_key;
7525 union si_shader_part_key epilog_key;
7526 bool need_prolog;
7527
7528 si_get_ps_prolog_key(shader, &prolog_key, false);
7529 need_prolog = si_need_ps_prolog(&prolog_key);
7530
7531 parts[need_prolog ? 1 : 0] = ctx.main_fn;
7532
7533 if (need_prolog) {
7534 si_build_ps_prolog_function(&ctx, &prolog_key);
7535 parts[0] = ctx.main_fn;
7536 }
7537
7538 si_get_ps_epilog_key(shader, &epilog_key);
7539 si_build_ps_epilog_function(&ctx, &epilog_key);
7540 parts[need_prolog ? 2 : 1] = ctx.main_fn;
7541
7542 si_build_wrapper_function(&ctx, parts, need_prolog ? 3 : 2, need_prolog ? 1 : 0);
7543 }
7544
7545 mod = bld_base->base.gallivm->module;
7546
7547 /* Dump LLVM IR before any optimization passes */
7548 if (sscreen->b.debug_flags & DBG_PREOPT_IR &&
7549 r600_can_dump_shader(&sscreen->b, ctx.type))
7550 LLVMDumpModule(mod);
7551
7552 si_llvm_finalize_module(&ctx,
7553 r600_extra_shader_checks(&sscreen->b, ctx.type));
7554
7555 /* Post-optimization transformations and analysis. */
7556 si_eliminate_const_vs_outputs(&ctx);
7557
7558 if ((debug && debug->debug_message) ||
7559 r600_can_dump_shader(&sscreen->b, ctx.type))
7560 si_count_scratch_private_memory(&ctx);
7561
7562 /* Compile to bytecode. */
7563 r = si_compile_llvm(sscreen, &shader->binary, &shader->config, tm,
7564 mod, debug, ctx.type, "TGSI shader");
7565 si_llvm_dispose(&ctx);
7566 if (r) {
7567 fprintf(stderr, "LLVM failed to compile shader\n");
7568 return r;
7569 }
7570
7571 /* Validate SGPR and VGPR usage for compute to detect compiler bugs.
7572 * LLVM 3.9svn has this bug.
7573 */
7574 if (sel->type == PIPE_SHADER_COMPUTE) {
7575 unsigned wave_size = 64;
7576 unsigned max_vgprs = 256;
7577 unsigned max_sgprs = sscreen->b.chip_class >= VI ? 800 : 512;
7578 unsigned max_sgprs_per_wave = 128;
7579 unsigned max_block_threads = si_get_max_workgroup_size(shader);
7580 unsigned min_waves_per_cu = DIV_ROUND_UP(max_block_threads, wave_size);
7581 unsigned min_waves_per_simd = DIV_ROUND_UP(min_waves_per_cu, 4);
7582
7583 max_vgprs = max_vgprs / min_waves_per_simd;
7584 max_sgprs = MIN2(max_sgprs / min_waves_per_simd, max_sgprs_per_wave);
7585
7586 if (shader->config.num_sgprs > max_sgprs ||
7587 shader->config.num_vgprs > max_vgprs) {
7588 fprintf(stderr, "LLVM failed to compile a shader correctly: "
7589 "SGPR:VGPR usage is %u:%u, but the hw limit is %u:%u\n",
7590 shader->config.num_sgprs, shader->config.num_vgprs,
7591 max_sgprs, max_vgprs);
7592
7593 /* Just terminate the process, because dependent
7594 * shaders can hang due to bad input data, but use
7595 * the env var to allow shader-db to work.
7596 */
7597 if (!debug_get_bool_option("SI_PASS_BAD_SHADERS", false))
7598 abort();
7599 }
7600 }
7601
7602 /* Add the scratch offset to input SGPRs. */
7603 if (shader->config.scratch_bytes_per_wave)
7604 shader->info.num_input_sgprs += 1; /* scratch byte offset */
7605
7606 /* Calculate the number of fragment input VGPRs. */
7607 if (ctx.type == PIPE_SHADER_FRAGMENT) {
7608 shader->info.num_input_vgprs = 0;
7609 shader->info.face_vgpr_index = -1;
7610
7611 if (G_0286CC_PERSP_SAMPLE_ENA(shader->config.spi_ps_input_addr))
7612 shader->info.num_input_vgprs += 2;
7613 if (G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_addr))
7614 shader->info.num_input_vgprs += 2;
7615 if (G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_addr))
7616 shader->info.num_input_vgprs += 2;
7617 if (G_0286CC_PERSP_PULL_MODEL_ENA(shader->config.spi_ps_input_addr))
7618 shader->info.num_input_vgprs += 3;
7619 if (G_0286CC_LINEAR_SAMPLE_ENA(shader->config.spi_ps_input_addr))
7620 shader->info.num_input_vgprs += 2;
7621 if (G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_addr))
7622 shader->info.num_input_vgprs += 2;
7623 if (G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_addr))
7624 shader->info.num_input_vgprs += 2;
7625 if (G_0286CC_LINE_STIPPLE_TEX_ENA(shader->config.spi_ps_input_addr))
7626 shader->info.num_input_vgprs += 1;
7627 if (G_0286CC_POS_X_FLOAT_ENA(shader->config.spi_ps_input_addr))
7628 shader->info.num_input_vgprs += 1;
7629 if (G_0286CC_POS_Y_FLOAT_ENA(shader->config.spi_ps_input_addr))
7630 shader->info.num_input_vgprs += 1;
7631 if (G_0286CC_POS_Z_FLOAT_ENA(shader->config.spi_ps_input_addr))
7632 shader->info.num_input_vgprs += 1;
7633 if (G_0286CC_POS_W_FLOAT_ENA(shader->config.spi_ps_input_addr))
7634 shader->info.num_input_vgprs += 1;
7635 if (G_0286CC_FRONT_FACE_ENA(shader->config.spi_ps_input_addr)) {
7636 shader->info.face_vgpr_index = shader->info.num_input_vgprs;
7637 shader->info.num_input_vgprs += 1;
7638 }
7639 if (G_0286CC_ANCILLARY_ENA(shader->config.spi_ps_input_addr))
7640 shader->info.num_input_vgprs += 1;
7641 if (G_0286CC_SAMPLE_COVERAGE_ENA(shader->config.spi_ps_input_addr))
7642 shader->info.num_input_vgprs += 1;
7643 if (G_0286CC_POS_FIXED_PT_ENA(shader->config.spi_ps_input_addr))
7644 shader->info.num_input_vgprs += 1;
7645 }
7646
7647 return 0;
7648 }
7649
7650 /**
7651 * Create, compile and return a shader part (prolog or epilog).
7652 *
7653 * \param sscreen screen
7654 * \param list list of shader parts of the same category
7655 * \param type shader type
7656 * \param key shader part key
7657 * \param prolog whether the part being requested is a prolog
7658 * \param tm LLVM target machine
7659 * \param debug debug callback
7660 * \param build the callback responsible for building the main function
7661 * \return non-NULL on success
7662 */
7663 static struct si_shader_part *
7664 si_get_shader_part(struct si_screen *sscreen,
7665 struct si_shader_part **list,
7666 enum pipe_shader_type type,
7667 bool prolog,
7668 union si_shader_part_key *key,
7669 LLVMTargetMachineRef tm,
7670 struct pipe_debug_callback *debug,
7671 void (*build)(struct si_shader_context *,
7672 union si_shader_part_key *),
7673 const char *name)
7674 {
7675 struct si_shader_part *result;
7676
7677 pipe_mutex_lock(sscreen->shader_parts_mutex);
7678
7679 /* Find existing. */
7680 for (result = *list; result; result = result->next) {
7681 if (memcmp(&result->key, key, sizeof(*key)) == 0) {
7682 pipe_mutex_unlock(sscreen->shader_parts_mutex);
7683 return result;
7684 }
7685 }
7686
7687 /* Compile a new one. */
7688 result = CALLOC_STRUCT(si_shader_part);
7689 result->key = *key;
7690
7691 struct si_shader shader = {};
7692 struct si_shader_context ctx;
7693 struct gallivm_state *gallivm = &ctx.gallivm;
7694
7695 si_init_shader_ctx(&ctx, sscreen, &shader, tm);
7696 ctx.type = type;
7697
7698 switch (type) {
7699 case PIPE_SHADER_VERTEX:
7700 break;
7701 case PIPE_SHADER_TESS_CTRL:
7702 assert(!prolog);
7703 shader.key.part.tcs.epilog = key->tcs_epilog.states;
7704 break;
7705 case PIPE_SHADER_GEOMETRY:
7706 assert(prolog);
7707 break;
7708 case PIPE_SHADER_FRAGMENT:
7709 if (prolog)
7710 shader.key.part.ps.prolog = key->ps_prolog.states;
7711 else
7712 shader.key.part.ps.epilog = key->ps_epilog.states;
7713 break;
7714 default:
7715 unreachable("bad shader part");
7716 }
7717
7718 build(&ctx, key);
7719
7720 /* Compile. */
7721 si_llvm_finalize_module(&ctx,
7722 r600_extra_shader_checks(&sscreen->b, PIPE_SHADER_FRAGMENT));
7723
7724 if (si_compile_llvm(sscreen, &result->binary, &result->config, tm,
7725 gallivm->module, debug, ctx.type, name)) {
7726 FREE(result);
7727 result = NULL;
7728 goto out;
7729 }
7730
7731 result->next = *list;
7732 *list = result;
7733
7734 out:
7735 si_llvm_dispose(&ctx);
7736 pipe_mutex_unlock(sscreen->shader_parts_mutex);
7737 return result;
7738 }
7739
7740 /**
7741 * Build the vertex shader prolog function.
7742 *
7743 * The inputs are the same as VS (a lot of SGPRs and 4 VGPR system values).
7744 * All inputs are returned unmodified. The vertex load indices are
7745 * stored after them, which will be used by the API VS for fetching inputs.
7746 *
7747 * For example, the expected outputs for instance_divisors[] = {0, 1, 2} are:
7748 * input_v0,
7749 * input_v1,
7750 * input_v2,
7751 * input_v3,
7752 * (VertexID + BaseVertex),
7753 * (InstanceID + StartInstance),
7754 * (InstanceID / 2 + StartInstance)
7755 */
7756 static void si_build_vs_prolog_function(struct si_shader_context *ctx,
7757 union si_shader_part_key *key)
7758 {
7759 struct gallivm_state *gallivm = &ctx->gallivm;
7760 LLVMTypeRef *params, *returns;
7761 LLVMValueRef ret, func;
7762 int last_sgpr, num_params, num_returns, i;
7763
7764 ctx->param_vertex_id = key->vs_prolog.num_input_sgprs;
7765 ctx->param_instance_id = key->vs_prolog.num_input_sgprs + 3;
7766
7767 /* 4 preloaded VGPRs + vertex load indices as prolog outputs */
7768 params = alloca((key->vs_prolog.num_input_sgprs + 4) *
7769 sizeof(LLVMTypeRef));
7770 returns = alloca((key->vs_prolog.num_input_sgprs + 4 +
7771 key->vs_prolog.last_input + 1) *
7772 sizeof(LLVMTypeRef));
7773 num_params = 0;
7774 num_returns = 0;
7775
7776 /* Declare input and output SGPRs. */
7777 num_params = 0;
7778 for (i = 0; i < key->vs_prolog.num_input_sgprs; i++) {
7779 params[num_params++] = ctx->i32;
7780 returns[num_returns++] = ctx->i32;
7781 }
7782 last_sgpr = num_params - 1;
7783
7784 /* 4 preloaded VGPRs (outputs must be floats) */
7785 for (i = 0; i < 4; i++) {
7786 params[num_params++] = ctx->i32;
7787 returns[num_returns++] = ctx->f32;
7788 }
7789
7790 /* Vertex load indices. */
7791 for (i = 0; i <= key->vs_prolog.last_input; i++)
7792 returns[num_returns++] = ctx->f32;
7793
7794 /* Create the function. */
7795 si_create_function(ctx, "vs_prolog", returns, num_returns, params,
7796 num_params, last_sgpr);
7797 func = ctx->main_fn;
7798
7799 /* Copy inputs to outputs. This should be no-op, as the registers match,
7800 * but it will prevent the compiler from overwriting them unintentionally.
7801 */
7802 ret = ctx->return_value;
7803 for (i = 0; i < key->vs_prolog.num_input_sgprs; i++) {
7804 LLVMValueRef p = LLVMGetParam(func, i);
7805 ret = LLVMBuildInsertValue(gallivm->builder, ret, p, i, "");
7806 }
7807 for (i = num_params - 4; i < num_params; i++) {
7808 LLVMValueRef p = LLVMGetParam(func, i);
7809 p = LLVMBuildBitCast(gallivm->builder, p, ctx->f32, "");
7810 ret = LLVMBuildInsertValue(gallivm->builder, ret, p, i, "");
7811 }
7812
7813 /* Compute vertex load indices from instance divisors. */
7814 for (i = 0; i <= key->vs_prolog.last_input; i++) {
7815 unsigned divisor = key->vs_prolog.states.instance_divisors[i];
7816 LLVMValueRef index;
7817
7818 if (divisor) {
7819 /* InstanceID / Divisor + StartInstance */
7820 index = get_instance_index_for_fetch(ctx,
7821 SI_SGPR_START_INSTANCE,
7822 divisor);
7823 } else {
7824 /* VertexID + BaseVertex */
7825 index = LLVMBuildAdd(gallivm->builder,
7826 LLVMGetParam(func, ctx->param_vertex_id),
7827 LLVMGetParam(func, SI_SGPR_BASE_VERTEX), "");
7828 }
7829
7830 index = LLVMBuildBitCast(gallivm->builder, index, ctx->f32, "");
7831 ret = LLVMBuildInsertValue(gallivm->builder, ret, index,
7832 num_params++, "");
7833 }
7834
7835 si_llvm_build_ret(ctx, ret);
7836 }
7837
7838 /**
7839 * Build the vertex shader epilog function. This is also used by the tessellation
7840 * evaluation shader compiled as VS.
7841 *
7842 * The input is PrimitiveID.
7843 *
7844 * If PrimitiveID is required by the pixel shader, export it.
7845 * Otherwise, do nothing.
7846 */
7847 static void si_build_vs_epilog_function(struct si_shader_context *ctx,
7848 union si_shader_part_key *key)
7849 {
7850 struct gallivm_state *gallivm = &ctx->gallivm;
7851 struct lp_build_tgsi_context *bld_base = &ctx->soa.bld_base;
7852 LLVMTypeRef params[5];
7853 int num_params, i;
7854
7855 /* Declare input VGPRs. */
7856 num_params = key->vs_epilog.states.export_prim_id ?
7857 (VS_EPILOG_PRIMID_LOC + 1) : 0;
7858 assert(num_params <= ARRAY_SIZE(params));
7859
7860 for (i = 0; i < num_params; i++)
7861 params[i] = ctx->f32;
7862
7863 /* Create the function. */
7864 si_create_function(ctx, "vs_epilog", NULL, 0, params, num_params, -1);
7865
7866 /* Emit exports. */
7867 if (key->vs_epilog.states.export_prim_id) {
7868 struct lp_build_context *base = &bld_base->base;
7869 struct lp_build_context *uint = &bld_base->uint_bld;
7870 LLVMValueRef args[9];
7871
7872 args[0] = lp_build_const_int32(base->gallivm, 0x0); /* enabled channels */
7873 args[1] = uint->zero; /* whether the EXEC mask is valid */
7874 args[2] = uint->zero; /* DONE bit */
7875 args[3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_PARAM +
7876 key->vs_epilog.prim_id_param_offset);
7877 args[4] = uint->zero; /* COMPR flag (0 = 32-bit export) */
7878 args[5] = LLVMGetParam(ctx->main_fn,
7879 VS_EPILOG_PRIMID_LOC); /* X */
7880 args[6] = base->undef; /* Y */
7881 args[7] = base->undef; /* Z */
7882 args[8] = base->undef; /* W */
7883
7884 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
7885 LLVMVoidTypeInContext(base->gallivm->context),
7886 args, 9, 0);
7887 }
7888
7889 LLVMBuildRetVoid(gallivm->builder);
7890 }
7891
7892 /**
7893 * Create & compile a vertex shader epilog. This a helper used by VS and TES.
7894 */
7895 static bool si_get_vs_epilog(struct si_screen *sscreen,
7896 LLVMTargetMachineRef tm,
7897 struct si_shader *shader,
7898 struct pipe_debug_callback *debug,
7899 struct si_vs_epilog_bits *states)
7900 {
7901 union si_shader_part_key epilog_key;
7902
7903 si_get_vs_epilog_key(shader, states, &epilog_key);
7904
7905 shader->epilog = si_get_shader_part(sscreen, &sscreen->vs_epilogs,
7906 PIPE_SHADER_VERTEX, true,
7907 &epilog_key, tm, debug,
7908 si_build_vs_epilog_function,
7909 "Vertex Shader Epilog");
7910 return shader->epilog != NULL;
7911 }
7912
7913 /**
7914 * Select and compile (or reuse) vertex shader parts (prolog & epilog).
7915 */
7916 static bool si_shader_select_vs_parts(struct si_screen *sscreen,
7917 LLVMTargetMachineRef tm,
7918 struct si_shader *shader,
7919 struct pipe_debug_callback *debug)
7920 {
7921 struct tgsi_shader_info *info = &shader->selector->info;
7922 union si_shader_part_key prolog_key;
7923
7924 /* Get the prolog. */
7925 si_get_vs_prolog_key(shader, &prolog_key);
7926
7927 /* The prolog is a no-op if there are no inputs. */
7928 if (info->num_inputs) {
7929 shader->prolog =
7930 si_get_shader_part(sscreen, &sscreen->vs_prologs,
7931 PIPE_SHADER_VERTEX, true,
7932 &prolog_key, tm, debug,
7933 si_build_vs_prolog_function,
7934 "Vertex Shader Prolog");
7935 if (!shader->prolog)
7936 return false;
7937 }
7938
7939 /* Get the epilog. */
7940 if (!shader->key.as_es && !shader->key.as_ls &&
7941 !si_get_vs_epilog(sscreen, tm, shader, debug,
7942 &shader->key.part.vs.epilog))
7943 return false;
7944
7945 return true;
7946 }
7947
7948 /**
7949 * Select and compile (or reuse) TES parts (epilog).
7950 */
7951 static bool si_shader_select_tes_parts(struct si_screen *sscreen,
7952 LLVMTargetMachineRef tm,
7953 struct si_shader *shader,
7954 struct pipe_debug_callback *debug)
7955 {
7956 if (shader->key.as_es)
7957 return true;
7958
7959 /* TES compiled as VS. */
7960 return si_get_vs_epilog(sscreen, tm, shader, debug,
7961 &shader->key.part.tes.epilog);
7962 }
7963
7964 /**
7965 * Compile the TCS epilog function. This writes tesselation factors to memory
7966 * based on the output primitive type of the tesselator (determined by TES).
7967 */
7968 static void si_build_tcs_epilog_function(struct si_shader_context *ctx,
7969 union si_shader_part_key *key)
7970 {
7971 struct gallivm_state *gallivm = &ctx->gallivm;
7972 struct lp_build_tgsi_context *bld_base = &ctx->soa.bld_base;
7973 LLVMTypeRef params[16];
7974 LLVMValueRef func;
7975 int last_sgpr, num_params;
7976
7977 /* Declare inputs. Only RW_BUFFERS and TESS_FACTOR_OFFSET are used. */
7978 params[SI_PARAM_RW_BUFFERS] = const_array(ctx->v16i8, SI_NUM_RW_BUFFERS);
7979 params[SI_PARAM_CONST_BUFFERS] = ctx->i64;
7980 params[SI_PARAM_SAMPLERS] = ctx->i64;
7981 params[SI_PARAM_IMAGES] = ctx->i64;
7982 params[SI_PARAM_SHADER_BUFFERS] = ctx->i64;
7983 params[SI_PARAM_TCS_OFFCHIP_LAYOUT] = ctx->i32;
7984 params[SI_PARAM_TCS_OUT_OFFSETS] = ctx->i32;
7985 params[SI_PARAM_TCS_OUT_LAYOUT] = ctx->i32;
7986 params[SI_PARAM_TCS_IN_LAYOUT] = ctx->i32;
7987 params[ctx->param_oc_lds = SI_PARAM_TCS_OC_LDS] = ctx->i32;
7988 params[SI_PARAM_TESS_FACTOR_OFFSET] = ctx->i32;
7989 last_sgpr = SI_PARAM_TESS_FACTOR_OFFSET;
7990 num_params = last_sgpr + 1;
7991
7992 params[num_params++] = ctx->i32; /* patch index within the wave (REL_PATCH_ID) */
7993 params[num_params++] = ctx->i32; /* invocation ID within the patch */
7994 params[num_params++] = ctx->i32; /* LDS offset where tess factors should be loaded from */
7995
7996 /* Create the function. */
7997 si_create_function(ctx, "tcs_epilog", NULL, 0, params, num_params, last_sgpr);
7998 declare_tess_lds(ctx);
7999 func = ctx->main_fn;
8000
8001 si_write_tess_factors(bld_base,
8002 LLVMGetParam(func, last_sgpr + 1),
8003 LLVMGetParam(func, last_sgpr + 2),
8004 LLVMGetParam(func, last_sgpr + 3));
8005
8006 LLVMBuildRetVoid(gallivm->builder);
8007 }
8008
8009 /**
8010 * Select and compile (or reuse) TCS parts (epilog).
8011 */
8012 static bool si_shader_select_tcs_parts(struct si_screen *sscreen,
8013 LLVMTargetMachineRef tm,
8014 struct si_shader *shader,
8015 struct pipe_debug_callback *debug)
8016 {
8017 union si_shader_part_key epilog_key;
8018
8019 /* Get the epilog. */
8020 memset(&epilog_key, 0, sizeof(epilog_key));
8021 epilog_key.tcs_epilog.states = shader->key.part.tcs.epilog;
8022
8023 shader->epilog = si_get_shader_part(sscreen, &sscreen->tcs_epilogs,
8024 PIPE_SHADER_TESS_CTRL, false,
8025 &epilog_key, tm, debug,
8026 si_build_tcs_epilog_function,
8027 "Tessellation Control Shader Epilog");
8028 return shader->epilog != NULL;
8029 }
8030
8031 /**
8032 * Select and compile (or reuse) GS parts (prolog).
8033 */
8034 static bool si_shader_select_gs_parts(struct si_screen *sscreen,
8035 LLVMTargetMachineRef tm,
8036 struct si_shader *shader,
8037 struct pipe_debug_callback *debug)
8038 {
8039 union si_shader_part_key prolog_key;
8040
8041 if (!shader->key.part.gs.prolog.tri_strip_adj_fix)
8042 return true;
8043
8044 memset(&prolog_key, 0, sizeof(prolog_key));
8045 prolog_key.gs_prolog.states = shader->key.part.gs.prolog;
8046
8047 shader->prolog = si_get_shader_part(sscreen, &sscreen->gs_prologs,
8048 PIPE_SHADER_GEOMETRY, true,
8049 &prolog_key, tm, debug,
8050 si_build_gs_prolog_function,
8051 "Geometry Shader Prolog");
8052 return shader->prolog != NULL;
8053 }
8054
8055 /**
8056 * Build the pixel shader prolog function. This handles:
8057 * - two-side color selection and interpolation
8058 * - overriding interpolation parameters for the API PS
8059 * - polygon stippling
8060 *
8061 * All preloaded SGPRs and VGPRs are passed through unmodified unless they are
8062 * overriden by other states. (e.g. per-sample interpolation)
8063 * Interpolated colors are stored after the preloaded VGPRs.
8064 */
8065 static void si_build_ps_prolog_function(struct si_shader_context *ctx,
8066 union si_shader_part_key *key)
8067 {
8068 struct gallivm_state *gallivm = &ctx->gallivm;
8069 LLVMTypeRef *params;
8070 LLVMValueRef ret, func;
8071 int last_sgpr, num_params, num_returns, i, num_color_channels;
8072
8073 assert(si_need_ps_prolog(key));
8074
8075 /* Number of inputs + 8 color elements. */
8076 params = alloca((key->ps_prolog.num_input_sgprs +
8077 key->ps_prolog.num_input_vgprs + 8) *
8078 sizeof(LLVMTypeRef));
8079
8080 /* Declare inputs. */
8081 num_params = 0;
8082 for (i = 0; i < key->ps_prolog.num_input_sgprs; i++)
8083 params[num_params++] = ctx->i32;
8084 last_sgpr = num_params - 1;
8085
8086 for (i = 0; i < key->ps_prolog.num_input_vgprs; i++)
8087 params[num_params++] = ctx->f32;
8088
8089 /* Declare outputs (same as inputs + add colors if needed) */
8090 num_returns = num_params;
8091 num_color_channels = util_bitcount(key->ps_prolog.colors_read);
8092 for (i = 0; i < num_color_channels; i++)
8093 params[num_returns++] = ctx->f32;
8094
8095 /* Create the function. */
8096 si_create_function(ctx, "ps_prolog", params, num_returns, params,
8097 num_params, last_sgpr);
8098 func = ctx->main_fn;
8099
8100 /* Copy inputs to outputs. This should be no-op, as the registers match,
8101 * but it will prevent the compiler from overwriting them unintentionally.
8102 */
8103 ret = ctx->return_value;
8104 for (i = 0; i < num_params; i++) {
8105 LLVMValueRef p = LLVMGetParam(func, i);
8106 ret = LLVMBuildInsertValue(gallivm->builder, ret, p, i, "");
8107 }
8108
8109 /* Polygon stippling. */
8110 if (key->ps_prolog.states.poly_stipple) {
8111 /* POS_FIXED_PT is always last. */
8112 unsigned pos = key->ps_prolog.num_input_sgprs +
8113 key->ps_prolog.num_input_vgprs - 1;
8114 LLVMValueRef ptr[2], list;
8115
8116 /* Get the pointer to rw buffers. */
8117 ptr[0] = LLVMGetParam(func, SI_SGPR_RW_BUFFERS);
8118 ptr[1] = LLVMGetParam(func, SI_SGPR_RW_BUFFERS_HI);
8119 list = lp_build_gather_values(gallivm, ptr, 2);
8120 list = LLVMBuildBitCast(gallivm->builder, list, ctx->i64, "");
8121 list = LLVMBuildIntToPtr(gallivm->builder, list,
8122 const_array(ctx->v16i8, SI_NUM_RW_BUFFERS), "");
8123
8124 si_llvm_emit_polygon_stipple(ctx, list, pos);
8125 }
8126
8127 if (key->ps_prolog.states.bc_optimize_for_persp ||
8128 key->ps_prolog.states.bc_optimize_for_linear) {
8129 unsigned i, base = key->ps_prolog.num_input_sgprs;
8130 LLVMValueRef center[2], centroid[2], tmp, bc_optimize;
8131
8132 /* The shader should do: if (PRIM_MASK[31]) CENTROID = CENTER;
8133 * The hw doesn't compute CENTROID if the whole wave only
8134 * contains fully-covered quads.
8135 *
8136 * PRIM_MASK is after user SGPRs.
8137 */
8138 bc_optimize = LLVMGetParam(func, SI_PS_NUM_USER_SGPR);
8139 bc_optimize = LLVMBuildLShr(gallivm->builder, bc_optimize,
8140 LLVMConstInt(ctx->i32, 31, 0), "");
8141 bc_optimize = LLVMBuildTrunc(gallivm->builder, bc_optimize,
8142 ctx->i1, "");
8143
8144 if (key->ps_prolog.states.bc_optimize_for_persp) {
8145 /* Read PERSP_CENTER. */
8146 for (i = 0; i < 2; i++)
8147 center[i] = LLVMGetParam(func, base + 2 + i);
8148 /* Read PERSP_CENTROID. */
8149 for (i = 0; i < 2; i++)
8150 centroid[i] = LLVMGetParam(func, base + 4 + i);
8151 /* Select PERSP_CENTROID. */
8152 for (i = 0; i < 2; i++) {
8153 tmp = LLVMBuildSelect(gallivm->builder, bc_optimize,
8154 center[i], centroid[i], "");
8155 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8156 tmp, base + 4 + i, "");
8157 }
8158 }
8159 if (key->ps_prolog.states.bc_optimize_for_linear) {
8160 /* Read LINEAR_CENTER. */
8161 for (i = 0; i < 2; i++)
8162 center[i] = LLVMGetParam(func, base + 8 + i);
8163 /* Read LINEAR_CENTROID. */
8164 for (i = 0; i < 2; i++)
8165 centroid[i] = LLVMGetParam(func, base + 10 + i);
8166 /* Select LINEAR_CENTROID. */
8167 for (i = 0; i < 2; i++) {
8168 tmp = LLVMBuildSelect(gallivm->builder, bc_optimize,
8169 center[i], centroid[i], "");
8170 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8171 tmp, base + 10 + i, "");
8172 }
8173 }
8174 }
8175
8176 /* Force per-sample interpolation. */
8177 if (key->ps_prolog.states.force_persp_sample_interp) {
8178 unsigned i, base = key->ps_prolog.num_input_sgprs;
8179 LLVMValueRef persp_sample[2];
8180
8181 /* Read PERSP_SAMPLE. */
8182 for (i = 0; i < 2; i++)
8183 persp_sample[i] = LLVMGetParam(func, base + i);
8184 /* Overwrite PERSP_CENTER. */
8185 for (i = 0; i < 2; i++)
8186 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8187 persp_sample[i], base + 2 + i, "");
8188 /* Overwrite PERSP_CENTROID. */
8189 for (i = 0; i < 2; i++)
8190 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8191 persp_sample[i], base + 4 + i, "");
8192 }
8193 if (key->ps_prolog.states.force_linear_sample_interp) {
8194 unsigned i, base = key->ps_prolog.num_input_sgprs;
8195 LLVMValueRef linear_sample[2];
8196
8197 /* Read LINEAR_SAMPLE. */
8198 for (i = 0; i < 2; i++)
8199 linear_sample[i] = LLVMGetParam(func, base + 6 + i);
8200 /* Overwrite LINEAR_CENTER. */
8201 for (i = 0; i < 2; i++)
8202 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8203 linear_sample[i], base + 8 + i, "");
8204 /* Overwrite LINEAR_CENTROID. */
8205 for (i = 0; i < 2; i++)
8206 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8207 linear_sample[i], base + 10 + i, "");
8208 }
8209
8210 /* Force center interpolation. */
8211 if (key->ps_prolog.states.force_persp_center_interp) {
8212 unsigned i, base = key->ps_prolog.num_input_sgprs;
8213 LLVMValueRef persp_center[2];
8214
8215 /* Read PERSP_CENTER. */
8216 for (i = 0; i < 2; i++)
8217 persp_center[i] = LLVMGetParam(func, base + 2 + i);
8218 /* Overwrite PERSP_SAMPLE. */
8219 for (i = 0; i < 2; i++)
8220 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8221 persp_center[i], base + i, "");
8222 /* Overwrite PERSP_CENTROID. */
8223 for (i = 0; i < 2; i++)
8224 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8225 persp_center[i], base + 4 + i, "");
8226 }
8227 if (key->ps_prolog.states.force_linear_center_interp) {
8228 unsigned i, base = key->ps_prolog.num_input_sgprs;
8229 LLVMValueRef linear_center[2];
8230
8231 /* Read LINEAR_CENTER. */
8232 for (i = 0; i < 2; i++)
8233 linear_center[i] = LLVMGetParam(func, base + 8 + i);
8234 /* Overwrite LINEAR_SAMPLE. */
8235 for (i = 0; i < 2; i++)
8236 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8237 linear_center[i], base + 6 + i, "");
8238 /* Overwrite LINEAR_CENTROID. */
8239 for (i = 0; i < 2; i++)
8240 ret = LLVMBuildInsertValue(gallivm->builder, ret,
8241 linear_center[i], base + 10 + i, "");
8242 }
8243
8244 /* Interpolate colors. */
8245 for (i = 0; i < 2; i++) {
8246 unsigned writemask = (key->ps_prolog.colors_read >> (i * 4)) & 0xf;
8247 unsigned face_vgpr = key->ps_prolog.num_input_sgprs +
8248 key->ps_prolog.face_vgpr_index;
8249 LLVMValueRef interp[2], color[4];
8250 LLVMValueRef interp_ij = NULL, prim_mask = NULL, face = NULL;
8251
8252 if (!writemask)
8253 continue;
8254
8255 /* If the interpolation qualifier is not CONSTANT (-1). */
8256 if (key->ps_prolog.color_interp_vgpr_index[i] != -1) {
8257 unsigned interp_vgpr = key->ps_prolog.num_input_sgprs +
8258 key->ps_prolog.color_interp_vgpr_index[i];
8259
8260 /* Get the (i,j) updated by bc_optimize handling. */
8261 interp[0] = LLVMBuildExtractValue(gallivm->builder, ret,
8262 interp_vgpr, "");
8263 interp[1] = LLVMBuildExtractValue(gallivm->builder, ret,
8264 interp_vgpr + 1, "");
8265 interp_ij = lp_build_gather_values(gallivm, interp, 2);
8266 }
8267
8268 /* Use the absolute location of the input. */
8269 prim_mask = LLVMGetParam(func, SI_PS_NUM_USER_SGPR);
8270
8271 if (key->ps_prolog.states.color_two_side) {
8272 face = LLVMGetParam(func, face_vgpr);
8273 face = LLVMBuildBitCast(gallivm->builder, face, ctx->i32, "");
8274 }
8275
8276 interp_fs_input(ctx,
8277 key->ps_prolog.color_attr_index[i],
8278 TGSI_SEMANTIC_COLOR, i,
8279 key->ps_prolog.num_interp_inputs,
8280 key->ps_prolog.colors_read, interp_ij,
8281 prim_mask, face, color);
8282
8283 while (writemask) {
8284 unsigned chan = u_bit_scan(&writemask);
8285 ret = LLVMBuildInsertValue(gallivm->builder, ret, color[chan],
8286 num_params++, "");
8287 }
8288 }
8289
8290 /* Tell LLVM to insert WQM instruction sequence when needed. */
8291 if (key->ps_prolog.wqm) {
8292 LLVMAddTargetDependentFunctionAttr(func,
8293 "amdgpu-ps-wqm-outputs", "");
8294 }
8295
8296 si_llvm_build_ret(ctx, ret);
8297 }
8298
8299 /**
8300 * Build the pixel shader epilog function. This handles everything that must be
8301 * emulated for pixel shader exports. (alpha-test, format conversions, etc)
8302 */
8303 static void si_build_ps_epilog_function(struct si_shader_context *ctx,
8304 union si_shader_part_key *key)
8305 {
8306 struct gallivm_state *gallivm = &ctx->gallivm;
8307 struct lp_build_tgsi_context *bld_base = &ctx->soa.bld_base;
8308 LLVMTypeRef params[16+8*4+3];
8309 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
8310 int last_sgpr, num_params, i;
8311 struct si_ps_exports exp = {};
8312
8313 /* Declare input SGPRs. */
8314 params[SI_PARAM_RW_BUFFERS] = ctx->i64;
8315 params[SI_PARAM_CONST_BUFFERS] = ctx->i64;
8316 params[SI_PARAM_SAMPLERS] = ctx->i64;
8317 params[SI_PARAM_IMAGES] = ctx->i64;
8318 params[SI_PARAM_SHADER_BUFFERS] = ctx->i64;
8319 params[SI_PARAM_ALPHA_REF] = ctx->f32;
8320 last_sgpr = SI_PARAM_ALPHA_REF;
8321
8322 /* Declare input VGPRs. */
8323 num_params = (last_sgpr + 1) +
8324 util_bitcount(key->ps_epilog.colors_written) * 4 +
8325 key->ps_epilog.writes_z +
8326 key->ps_epilog.writes_stencil +
8327 key->ps_epilog.writes_samplemask;
8328
8329 num_params = MAX2(num_params,
8330 last_sgpr + 1 + PS_EPILOG_SAMPLEMASK_MIN_LOC + 1);
8331
8332 assert(num_params <= ARRAY_SIZE(params));
8333
8334 for (i = last_sgpr + 1; i < num_params; i++)
8335 params[i] = ctx->f32;
8336
8337 /* Create the function. */
8338 si_create_function(ctx, "ps_epilog", NULL, 0, params, num_params, last_sgpr);
8339 /* Disable elimination of unused inputs. */
8340 si_llvm_add_attribute(ctx->main_fn,
8341 "InitialPSInputAddr", 0xffffff);
8342
8343 /* Process colors. */
8344 unsigned vgpr = last_sgpr + 1;
8345 unsigned colors_written = key->ps_epilog.colors_written;
8346 int last_color_export = -1;
8347
8348 /* Find the last color export. */
8349 if (!key->ps_epilog.writes_z &&
8350 !key->ps_epilog.writes_stencil &&
8351 !key->ps_epilog.writes_samplemask) {
8352 unsigned spi_format = key->ps_epilog.states.spi_shader_col_format;
8353
8354 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
8355 if (colors_written == 0x1 && key->ps_epilog.states.last_cbuf > 0) {
8356 /* Just set this if any of the colorbuffers are enabled. */
8357 if (spi_format &
8358 ((1llu << (4 * (key->ps_epilog.states.last_cbuf + 1))) - 1))
8359 last_color_export = 0;
8360 } else {
8361 for (i = 0; i < 8; i++)
8362 if (colors_written & (1 << i) &&
8363 (spi_format >> (i * 4)) & 0xf)
8364 last_color_export = i;
8365 }
8366 }
8367
8368 while (colors_written) {
8369 LLVMValueRef color[4];
8370 int mrt = u_bit_scan(&colors_written);
8371
8372 for (i = 0; i < 4; i++)
8373 color[i] = LLVMGetParam(ctx->main_fn, vgpr++);
8374
8375 si_export_mrt_color(bld_base, color, mrt,
8376 num_params - 1,
8377 mrt == last_color_export, &exp);
8378 }
8379
8380 /* Process depth, stencil, samplemask. */
8381 if (key->ps_epilog.writes_z)
8382 depth = LLVMGetParam(ctx->main_fn, vgpr++);
8383 if (key->ps_epilog.writes_stencil)
8384 stencil = LLVMGetParam(ctx->main_fn, vgpr++);
8385 if (key->ps_epilog.writes_samplemask)
8386 samplemask = LLVMGetParam(ctx->main_fn, vgpr++);
8387
8388 if (depth || stencil || samplemask)
8389 si_export_mrt_z(bld_base, depth, stencil, samplemask, &exp);
8390 else if (last_color_export == -1)
8391 si_export_null(bld_base);
8392
8393 if (exp.num)
8394 si_emit_ps_exports(ctx, &exp);
8395
8396 /* Compile. */
8397 LLVMBuildRetVoid(gallivm->builder);
8398 }
8399
8400 /**
8401 * Select and compile (or reuse) pixel shader parts (prolog & epilog).
8402 */
8403 static bool si_shader_select_ps_parts(struct si_screen *sscreen,
8404 LLVMTargetMachineRef tm,
8405 struct si_shader *shader,
8406 struct pipe_debug_callback *debug)
8407 {
8408 union si_shader_part_key prolog_key;
8409 union si_shader_part_key epilog_key;
8410
8411 /* Get the prolog. */
8412 si_get_ps_prolog_key(shader, &prolog_key, true);
8413
8414 /* The prolog is a no-op if these aren't set. */
8415 if (si_need_ps_prolog(&prolog_key)) {
8416 shader->prolog =
8417 si_get_shader_part(sscreen, &sscreen->ps_prologs,
8418 PIPE_SHADER_FRAGMENT, true,
8419 &prolog_key, tm, debug,
8420 si_build_ps_prolog_function,
8421 "Fragment Shader Prolog");
8422 if (!shader->prolog)
8423 return false;
8424 }
8425
8426 /* Get the epilog. */
8427 si_get_ps_epilog_key(shader, &epilog_key);
8428
8429 shader->epilog =
8430 si_get_shader_part(sscreen, &sscreen->ps_epilogs,
8431 PIPE_SHADER_FRAGMENT, false,
8432 &epilog_key, tm, debug,
8433 si_build_ps_epilog_function,
8434 "Fragment Shader Epilog");
8435 if (!shader->epilog)
8436 return false;
8437
8438 /* Enable POS_FIXED_PT if polygon stippling is enabled. */
8439 if (shader->key.part.ps.prolog.poly_stipple) {
8440 shader->config.spi_ps_input_ena |= S_0286CC_POS_FIXED_PT_ENA(1);
8441 assert(G_0286CC_POS_FIXED_PT_ENA(shader->config.spi_ps_input_addr));
8442 }
8443
8444 /* Set up the enable bits for per-sample shading if needed. */
8445 if (shader->key.part.ps.prolog.force_persp_sample_interp &&
8446 (G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_ena) ||
8447 G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8448 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTER_ENA;
8449 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTROID_ENA;
8450 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_SAMPLE_ENA(1);
8451 }
8452 if (shader->key.part.ps.prolog.force_linear_sample_interp &&
8453 (G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_ena) ||
8454 G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8455 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTER_ENA;
8456 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTROID_ENA;
8457 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_SAMPLE_ENA(1);
8458 }
8459 if (shader->key.part.ps.prolog.force_persp_center_interp &&
8460 (G_0286CC_PERSP_SAMPLE_ENA(shader->config.spi_ps_input_ena) ||
8461 G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8462 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_SAMPLE_ENA;
8463 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTROID_ENA;
8464 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_CENTER_ENA(1);
8465 }
8466 if (shader->key.part.ps.prolog.force_linear_center_interp &&
8467 (G_0286CC_LINEAR_SAMPLE_ENA(shader->config.spi_ps_input_ena) ||
8468 G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_ena))) {
8469 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_SAMPLE_ENA;
8470 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTROID_ENA;
8471 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_CENTER_ENA(1);
8472 }
8473
8474 /* POW_W_FLOAT requires that one of the perspective weights is enabled. */
8475 if (G_0286CC_POS_W_FLOAT_ENA(shader->config.spi_ps_input_ena) &&
8476 !(shader->config.spi_ps_input_ena & 0xf)) {
8477 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_CENTER_ENA(1);
8478 assert(G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_addr));
8479 }
8480
8481 /* At least one pair of interpolation weights must be enabled. */
8482 if (!(shader->config.spi_ps_input_ena & 0x7f)) {
8483 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_CENTER_ENA(1);
8484 assert(G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_addr));
8485 }
8486
8487 /* The sample mask input is always enabled, because the API shader always
8488 * passes it through to the epilog. Disable it here if it's unused.
8489 */
8490 if (!shader->key.part.ps.epilog.poly_line_smoothing &&
8491 !shader->selector->info.reads_samplemask)
8492 shader->config.spi_ps_input_ena &= C_0286CC_SAMPLE_COVERAGE_ENA;
8493
8494 return true;
8495 }
8496
8497 void si_multiwave_lds_size_workaround(struct si_screen *sscreen,
8498 unsigned *lds_size)
8499 {
8500 /* SPI barrier management bug:
8501 * Make sure we have at least 4k of LDS in use to avoid the bug.
8502 * It applies to workgroup sizes of more than one wavefront.
8503 */
8504 if (sscreen->b.family == CHIP_BONAIRE ||
8505 sscreen->b.family == CHIP_KABINI ||
8506 sscreen->b.family == CHIP_MULLINS)
8507 *lds_size = MAX2(*lds_size, 8);
8508 }
8509
8510 static void si_fix_resource_usage(struct si_screen *sscreen,
8511 struct si_shader *shader)
8512 {
8513 unsigned min_sgprs = shader->info.num_input_sgprs + 2; /* VCC */
8514
8515 shader->config.num_sgprs = MAX2(shader->config.num_sgprs, min_sgprs);
8516
8517 if (shader->selector->type == PIPE_SHADER_COMPUTE &&
8518 si_get_max_workgroup_size(shader) > 64) {
8519 si_multiwave_lds_size_workaround(sscreen,
8520 &shader->config.lds_size);
8521 }
8522 }
8523
8524 int si_shader_create(struct si_screen *sscreen, LLVMTargetMachineRef tm,
8525 struct si_shader *shader,
8526 struct pipe_debug_callback *debug)
8527 {
8528 struct si_shader_selector *sel = shader->selector;
8529 struct si_shader *mainp = sel->main_shader_part;
8530 int r;
8531
8532 /* LS, ES, VS are compiled on demand if the main part hasn't been
8533 * compiled for that stage.
8534 *
8535 * Vertex shaders are compiled on demand when a vertex fetch
8536 * workaround must be applied.
8537 */
8538 if (shader->is_monolithic) {
8539 /* Monolithic shader (compiled as a whole, has many variants,
8540 * may take a long time to compile).
8541 */
8542 r = si_compile_tgsi_shader(sscreen, tm, shader, true, debug);
8543 if (r)
8544 return r;
8545 } else {
8546 /* The shader consists of 2-3 parts:
8547 *
8548 * - the middle part is the user shader, it has 1 variant only
8549 * and it was compiled during the creation of the shader
8550 * selector
8551 * - the prolog part is inserted at the beginning
8552 * - the epilog part is inserted at the end
8553 *
8554 * The prolog and epilog have many (but simple) variants.
8555 */
8556
8557 /* Copy the compiled TGSI shader data over. */
8558 shader->is_binary_shared = true;
8559 shader->binary = mainp->binary;
8560 shader->config = mainp->config;
8561 shader->info.num_input_sgprs = mainp->info.num_input_sgprs;
8562 shader->info.num_input_vgprs = mainp->info.num_input_vgprs;
8563 shader->info.face_vgpr_index = mainp->info.face_vgpr_index;
8564 memcpy(shader->info.vs_output_param_offset,
8565 mainp->info.vs_output_param_offset,
8566 sizeof(mainp->info.vs_output_param_offset));
8567 shader->info.uses_instanceid = mainp->info.uses_instanceid;
8568 shader->info.nr_pos_exports = mainp->info.nr_pos_exports;
8569 shader->info.nr_param_exports = mainp->info.nr_param_exports;
8570
8571 /* Select prologs and/or epilogs. */
8572 switch (sel->type) {
8573 case PIPE_SHADER_VERTEX:
8574 if (!si_shader_select_vs_parts(sscreen, tm, shader, debug))
8575 return -1;
8576 break;
8577 case PIPE_SHADER_TESS_CTRL:
8578 if (!si_shader_select_tcs_parts(sscreen, tm, shader, debug))
8579 return -1;
8580 break;
8581 case PIPE_SHADER_TESS_EVAL:
8582 if (!si_shader_select_tes_parts(sscreen, tm, shader, debug))
8583 return -1;
8584 break;
8585 case PIPE_SHADER_GEOMETRY:
8586 if (!si_shader_select_gs_parts(sscreen, tm, shader, debug))
8587 return -1;
8588 break;
8589 case PIPE_SHADER_FRAGMENT:
8590 if (!si_shader_select_ps_parts(sscreen, tm, shader, debug))
8591 return -1;
8592
8593 /* Make sure we have at least as many VGPRs as there
8594 * are allocated inputs.
8595 */
8596 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8597 shader->info.num_input_vgprs);
8598 break;
8599 }
8600
8601 /* Update SGPR and VGPR counts. */
8602 if (shader->prolog) {
8603 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8604 shader->prolog->config.num_sgprs);
8605 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8606 shader->prolog->config.num_vgprs);
8607 }
8608 if (shader->epilog) {
8609 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
8610 shader->epilog->config.num_sgprs);
8611 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
8612 shader->epilog->config.num_vgprs);
8613 }
8614 }
8615
8616 si_fix_resource_usage(sscreen, shader);
8617 si_shader_dump(sscreen, shader, debug, sel->info.processor,
8618 stderr, true);
8619
8620 /* Upload. */
8621 r = si_shader_binary_upload(sscreen, shader);
8622 if (r) {
8623 fprintf(stderr, "LLVM failed to upload shader\n");
8624 return r;
8625 }
8626
8627 return 0;
8628 }
8629
8630 void si_shader_destroy(struct si_shader *shader)
8631 {
8632 if (shader->scratch_bo)
8633 r600_resource_reference(&shader->scratch_bo, NULL);
8634
8635 r600_resource_reference(&shader->bo, NULL);
8636
8637 if (!shader->is_binary_shared)
8638 radeon_shader_binary_clean(&shader->binary);
8639
8640 free(shader->shader_log);
8641 }