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