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