radeonsi: add PS prolog
[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_bitarit.h"
35 #include "gallivm/lp_bld_flow.h"
36 #include "radeon/r600_cs.h"
37 #include "radeon/radeon_llvm.h"
38 #include "radeon/radeon_elf_util.h"
39 #include "radeon/radeon_llvm_emit.h"
40 #include "util/u_memory.h"
41 #include "util/u_pstipple.h"
42 #include "tgsi/tgsi_parse.h"
43 #include "tgsi/tgsi_util.h"
44 #include "tgsi/tgsi_dump.h"
45
46 #include "si_pipe.h"
47 #include "si_shader.h"
48 #include "sid.h"
49
50 #include <errno.h>
51
52 static const char *scratch_rsrc_dword0_symbol =
53 "SCRATCH_RSRC_DWORD0";
54
55 static const char *scratch_rsrc_dword1_symbol =
56 "SCRATCH_RSRC_DWORD1";
57
58 struct si_shader_output_values
59 {
60 LLVMValueRef values[4];
61 unsigned name;
62 unsigned sid;
63 };
64
65 struct si_shader_context
66 {
67 struct radeon_llvm_context radeon_bld;
68 struct si_shader *shader;
69 struct si_screen *screen;
70
71 unsigned type; /* TGSI_PROCESSOR_* specifies the type of shader. */
72 bool is_gs_copy_shader;
73
74 /* Whether to generate the optimized shader variant compiled as a whole
75 * (without a prolog and epilog)
76 */
77 bool is_monolithic;
78
79 int param_streamout_config;
80 int param_streamout_write_index;
81 int param_streamout_offset[4];
82 int param_vertex_id;
83 int param_rel_auto_id;
84 int param_vs_prim_id;
85 int param_instance_id;
86 int param_vertex_index0;
87 int param_tes_u;
88 int param_tes_v;
89 int param_tes_rel_patch_id;
90 int param_tes_patch_id;
91 int param_es2gs_offset;
92
93 LLVMTargetMachineRef tm;
94
95 LLVMValueRef const_md;
96 LLVMValueRef const_buffers[SI_NUM_CONST_BUFFERS];
97 LLVMValueRef lds;
98 LLVMValueRef *constants[SI_NUM_CONST_BUFFERS];
99 LLVMValueRef sampler_views[SI_NUM_SAMPLERS];
100 LLVMValueRef sampler_states[SI_NUM_SAMPLERS];
101 LLVMValueRef fmasks[SI_NUM_USER_SAMPLERS];
102 LLVMValueRef so_buffers[4];
103 LLVMValueRef esgs_ring;
104 LLVMValueRef gsvs_ring[4];
105 LLVMValueRef gs_next_vertex[4];
106 LLVMValueRef return_value;
107
108 LLVMTypeRef voidt;
109 LLVMTypeRef i1;
110 LLVMTypeRef i8;
111 LLVMTypeRef i32;
112 LLVMTypeRef i64;
113 LLVMTypeRef i128;
114 LLVMTypeRef f32;
115 LLVMTypeRef v16i8;
116 LLVMTypeRef v2i32;
117 LLVMTypeRef v4i32;
118 LLVMTypeRef v4f32;
119 LLVMTypeRef v8i32;
120 };
121
122 static struct si_shader_context *si_shader_context(
123 struct lp_build_tgsi_context *bld_base)
124 {
125 return (struct si_shader_context *)bld_base;
126 }
127
128 static void si_init_shader_ctx(struct si_shader_context *ctx,
129 struct si_screen *sscreen,
130 struct si_shader *shader,
131 LLVMTargetMachineRef tm,
132 struct tgsi_shader_info *info);
133
134 /* Ideally pass the sample mask input to the PS epilog as v13, which
135 * is its usual location, so that the shader doesn't have to add v_mov.
136 */
137 #define PS_EPILOG_SAMPLEMASK_MIN_LOC 13
138
139 /* The VS location of the PrimitiveID input is the same in the epilog,
140 * so that the main shader part doesn't have to move it.
141 */
142 #define VS_EPILOG_PRIMID_LOC 2
143
144 #define PERSPECTIVE_BASE 0
145 #define LINEAR_BASE 9
146
147 #define SAMPLE_OFFSET 0
148 #define CENTER_OFFSET 2
149 #define CENTROID_OFSET 4
150
151 #define USE_SGPR_MAX_SUFFIX_LEN 5
152 #define CONST_ADDR_SPACE 2
153 #define LOCAL_ADDR_SPACE 3
154 #define USER_SGPR_ADDR_SPACE 8
155
156
157 #define SENDMSG_GS 2
158 #define SENDMSG_GS_DONE 3
159
160 #define SENDMSG_GS_OP_NOP (0 << 4)
161 #define SENDMSG_GS_OP_CUT (1 << 4)
162 #define SENDMSG_GS_OP_EMIT (2 << 4)
163 #define SENDMSG_GS_OP_EMIT_CUT (3 << 4)
164
165 /**
166 * Returns a unique index for a semantic name and index. The index must be
167 * less than 64, so that a 64-bit bitmask of used inputs or outputs can be
168 * calculated.
169 */
170 unsigned si_shader_io_get_unique_index(unsigned semantic_name, unsigned index)
171 {
172 switch (semantic_name) {
173 case TGSI_SEMANTIC_POSITION:
174 return 0;
175 case TGSI_SEMANTIC_PSIZE:
176 return 1;
177 case TGSI_SEMANTIC_CLIPDIST:
178 assert(index <= 1);
179 return 2 + index;
180 case TGSI_SEMANTIC_GENERIC:
181 if (index <= 63-4)
182 return 4 + index;
183 else
184 /* same explanation as in the default statement,
185 * the only user hitting this is st/nine.
186 */
187 return 0;
188
189 /* patch indices are completely separate and thus start from 0 */
190 case TGSI_SEMANTIC_TESSOUTER:
191 return 0;
192 case TGSI_SEMANTIC_TESSINNER:
193 return 1;
194 case TGSI_SEMANTIC_PATCH:
195 return 2 + index;
196
197 default:
198 /* Don't fail here. The result of this function is only used
199 * for LS, TCS, TES, and GS, where legacy GL semantics can't
200 * occur, but this function is called for all vertex shaders
201 * before it's known whether LS will be compiled or not.
202 */
203 return 0;
204 }
205 }
206
207 /**
208 * Get the value of a shader input parameter and extract a bitfield.
209 */
210 static LLVMValueRef unpack_param(struct si_shader_context *ctx,
211 unsigned param, unsigned rshift,
212 unsigned bitwidth)
213 {
214 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
215 LLVMValueRef value = LLVMGetParam(ctx->radeon_bld.main_fn,
216 param);
217
218 if (rshift)
219 value = LLVMBuildLShr(gallivm->builder, value,
220 lp_build_const_int32(gallivm, rshift), "");
221
222 if (rshift + bitwidth < 32) {
223 unsigned mask = (1 << bitwidth) - 1;
224 value = LLVMBuildAnd(gallivm->builder, value,
225 lp_build_const_int32(gallivm, mask), "");
226 }
227
228 return value;
229 }
230
231 static LLVMValueRef get_rel_patch_id(struct si_shader_context *ctx)
232 {
233 switch (ctx->type) {
234 case TGSI_PROCESSOR_TESS_CTRL:
235 return unpack_param(ctx, SI_PARAM_REL_IDS, 0, 8);
236
237 case TGSI_PROCESSOR_TESS_EVAL:
238 return LLVMGetParam(ctx->radeon_bld.main_fn,
239 ctx->param_tes_rel_patch_id);
240
241 default:
242 assert(0);
243 return NULL;
244 }
245 }
246
247 /* Tessellation shaders pass outputs to the next shader using LDS.
248 *
249 * LS outputs = TCS inputs
250 * TCS outputs = TES inputs
251 *
252 * The LDS layout is:
253 * - TCS inputs for patch 0
254 * - TCS inputs for patch 1
255 * - TCS inputs for patch 2 = get_tcs_in_current_patch_offset (if RelPatchID==2)
256 * - ...
257 * - TCS outputs for patch 0 = get_tcs_out_patch0_offset
258 * - Per-patch TCS outputs for patch 0 = get_tcs_out_patch0_patch_data_offset
259 * - TCS outputs for patch 1
260 * - Per-patch TCS outputs for patch 1
261 * - TCS outputs for patch 2 = get_tcs_out_current_patch_offset (if RelPatchID==2)
262 * - Per-patch TCS outputs for patch 2 = get_tcs_out_current_patch_data_offset (if RelPatchID==2)
263 * - ...
264 *
265 * All three shaders VS(LS), TCS, TES share the same LDS space.
266 */
267
268 static LLVMValueRef
269 get_tcs_in_patch_stride(struct si_shader_context *ctx)
270 {
271 if (ctx->type == TGSI_PROCESSOR_VERTEX)
272 return unpack_param(ctx, SI_PARAM_LS_OUT_LAYOUT, 0, 13);
273 else if (ctx->type == TGSI_PROCESSOR_TESS_CTRL)
274 return unpack_param(ctx, SI_PARAM_TCS_IN_LAYOUT, 0, 13);
275 else {
276 assert(0);
277 return NULL;
278 }
279 }
280
281 static LLVMValueRef
282 get_tcs_out_patch_stride(struct si_shader_context *ctx)
283 {
284 return unpack_param(ctx, SI_PARAM_TCS_OUT_LAYOUT, 0, 13);
285 }
286
287 static LLVMValueRef
288 get_tcs_out_patch0_offset(struct si_shader_context *ctx)
289 {
290 return lp_build_mul_imm(&ctx->radeon_bld.soa.bld_base.uint_bld,
291 unpack_param(ctx,
292 SI_PARAM_TCS_OUT_OFFSETS,
293 0, 16),
294 4);
295 }
296
297 static LLVMValueRef
298 get_tcs_out_patch0_patch_data_offset(struct si_shader_context *ctx)
299 {
300 return lp_build_mul_imm(&ctx->radeon_bld.soa.bld_base.uint_bld,
301 unpack_param(ctx,
302 SI_PARAM_TCS_OUT_OFFSETS,
303 16, 16),
304 4);
305 }
306
307 static LLVMValueRef
308 get_tcs_in_current_patch_offset(struct si_shader_context *ctx)
309 {
310 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
311 LLVMValueRef patch_stride = get_tcs_in_patch_stride(ctx);
312 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
313
314 return LLVMBuildMul(gallivm->builder, patch_stride, rel_patch_id, "");
315 }
316
317 static LLVMValueRef
318 get_tcs_out_current_patch_offset(struct si_shader_context *ctx)
319 {
320 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
321 LLVMValueRef patch0_offset = get_tcs_out_patch0_offset(ctx);
322 LLVMValueRef patch_stride = get_tcs_out_patch_stride(ctx);
323 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
324
325 return LLVMBuildAdd(gallivm->builder, patch0_offset,
326 LLVMBuildMul(gallivm->builder, patch_stride,
327 rel_patch_id, ""),
328 "");
329 }
330
331 static LLVMValueRef
332 get_tcs_out_current_patch_data_offset(struct si_shader_context *ctx)
333 {
334 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
335 LLVMValueRef patch0_patch_data_offset =
336 get_tcs_out_patch0_patch_data_offset(ctx);
337 LLVMValueRef patch_stride = get_tcs_out_patch_stride(ctx);
338 LLVMValueRef rel_patch_id = get_rel_patch_id(ctx);
339
340 return LLVMBuildAdd(gallivm->builder, patch0_patch_data_offset,
341 LLVMBuildMul(gallivm->builder, patch_stride,
342 rel_patch_id, ""),
343 "");
344 }
345
346 static void build_indexed_store(struct si_shader_context *ctx,
347 LLVMValueRef base_ptr, LLVMValueRef index,
348 LLVMValueRef value)
349 {
350 struct lp_build_tgsi_context *bld_base = &ctx->radeon_bld.soa.bld_base;
351 struct gallivm_state *gallivm = bld_base->base.gallivm;
352 LLVMValueRef indices[2], pointer;
353
354 indices[0] = bld_base->uint_bld.zero;
355 indices[1] = index;
356
357 pointer = LLVMBuildGEP(gallivm->builder, base_ptr, indices, 2, "");
358 LLVMBuildStore(gallivm->builder, value, pointer);
359 }
360
361 /**
362 * Build an LLVM bytecode indexed load using LLVMBuildGEP + LLVMBuildLoad.
363 * It's equivalent to doing a load from &base_ptr[index].
364 *
365 * \param base_ptr Where the array starts.
366 * \param index The element index into the array.
367 */
368 static LLVMValueRef build_indexed_load(struct si_shader_context *ctx,
369 LLVMValueRef base_ptr, LLVMValueRef index)
370 {
371 struct lp_build_tgsi_context *bld_base = &ctx->radeon_bld.soa.bld_base;
372 struct gallivm_state *gallivm = bld_base->base.gallivm;
373 LLVMValueRef indices[2], pointer;
374
375 indices[0] = bld_base->uint_bld.zero;
376 indices[1] = index;
377
378 pointer = LLVMBuildGEP(gallivm->builder, base_ptr, indices, 2, "");
379 return LLVMBuildLoad(gallivm->builder, pointer, "");
380 }
381
382 /**
383 * Do a load from &base_ptr[index], but also add a flag that it's loading
384 * a constant.
385 */
386 static LLVMValueRef build_indexed_load_const(
387 struct si_shader_context *ctx,
388 LLVMValueRef base_ptr, LLVMValueRef index)
389 {
390 LLVMValueRef result = build_indexed_load(ctx, base_ptr, index);
391 LLVMSetMetadata(result, 1, ctx->const_md);
392 return result;
393 }
394
395 static LLVMValueRef get_instance_index_for_fetch(
396 struct radeon_llvm_context *radeon_bld,
397 unsigned param_start_instance, unsigned divisor)
398 {
399 struct si_shader_context *ctx =
400 si_shader_context(&radeon_bld->soa.bld_base);
401 struct gallivm_state *gallivm = radeon_bld->soa.bld_base.base.gallivm;
402
403 LLVMValueRef result = LLVMGetParam(radeon_bld->main_fn,
404 ctx->param_instance_id);
405
406 /* The division must be done before START_INSTANCE is added. */
407 if (divisor > 1)
408 result = LLVMBuildUDiv(gallivm->builder, result,
409 lp_build_const_int32(gallivm, divisor), "");
410
411 return LLVMBuildAdd(gallivm->builder, result,
412 LLVMGetParam(radeon_bld->main_fn, param_start_instance), "");
413 }
414
415 static void declare_input_vs(
416 struct radeon_llvm_context *radeon_bld,
417 unsigned input_index,
418 const struct tgsi_full_declaration *decl)
419 {
420 struct lp_build_context *base = &radeon_bld->soa.bld_base.base;
421 struct gallivm_state *gallivm = base->gallivm;
422 struct si_shader_context *ctx =
423 si_shader_context(&radeon_bld->soa.bld_base);
424 unsigned divisor =
425 ctx->shader->key.vs.prolog.instance_divisors[input_index];
426
427 unsigned chan;
428
429 LLVMValueRef t_list_ptr;
430 LLVMValueRef t_offset;
431 LLVMValueRef t_list;
432 LLVMValueRef attribute_offset;
433 LLVMValueRef buffer_index;
434 LLVMValueRef args[3];
435 LLVMValueRef input;
436
437 /* Load the T list */
438 t_list_ptr = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_VERTEX_BUFFERS);
439
440 t_offset = lp_build_const_int32(gallivm, input_index);
441
442 t_list = build_indexed_load_const(ctx, t_list_ptr, t_offset);
443
444 /* Build the attribute offset */
445 attribute_offset = lp_build_const_int32(gallivm, 0);
446
447 if (!ctx->is_monolithic) {
448 buffer_index = LLVMGetParam(radeon_bld->main_fn,
449 ctx->param_vertex_index0 +
450 input_index);
451 } else if (divisor) {
452 /* Build index from instance ID, start instance and divisor */
453 ctx->shader->uses_instanceid = true;
454 buffer_index = get_instance_index_for_fetch(&ctx->radeon_bld,
455 SI_PARAM_START_INSTANCE,
456 divisor);
457 } else {
458 /* Load the buffer index for vertices. */
459 LLVMValueRef vertex_id = LLVMGetParam(ctx->radeon_bld.main_fn,
460 ctx->param_vertex_id);
461 LLVMValueRef base_vertex = LLVMGetParam(radeon_bld->main_fn,
462 SI_PARAM_BASE_VERTEX);
463 buffer_index = LLVMBuildAdd(gallivm->builder, base_vertex, vertex_id, "");
464 }
465
466 args[0] = t_list;
467 args[1] = attribute_offset;
468 args[2] = buffer_index;
469 input = lp_build_intrinsic(gallivm->builder,
470 "llvm.SI.vs.load.input", ctx->v4f32, args, 3,
471 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
472
473 /* Break up the vec4 into individual components */
474 for (chan = 0; chan < 4; chan++) {
475 LLVMValueRef llvm_chan = lp_build_const_int32(gallivm, chan);
476 /* XXX: Use a helper function for this. There is one in
477 * tgsi_llvm.c. */
478 ctx->radeon_bld.inputs[radeon_llvm_reg_index_soa(input_index, chan)] =
479 LLVMBuildExtractElement(gallivm->builder,
480 input, llvm_chan, "");
481 }
482 }
483
484 static LLVMValueRef get_primitive_id(struct lp_build_tgsi_context *bld_base,
485 unsigned swizzle)
486 {
487 struct si_shader_context *ctx = si_shader_context(bld_base);
488
489 if (swizzle > 0)
490 return bld_base->uint_bld.zero;
491
492 switch (ctx->type) {
493 case TGSI_PROCESSOR_VERTEX:
494 return LLVMGetParam(ctx->radeon_bld.main_fn,
495 ctx->param_vs_prim_id);
496 case TGSI_PROCESSOR_TESS_CTRL:
497 return LLVMGetParam(ctx->radeon_bld.main_fn,
498 SI_PARAM_PATCH_ID);
499 case TGSI_PROCESSOR_TESS_EVAL:
500 return LLVMGetParam(ctx->radeon_bld.main_fn,
501 ctx->param_tes_patch_id);
502 case TGSI_PROCESSOR_GEOMETRY:
503 return LLVMGetParam(ctx->radeon_bld.main_fn,
504 SI_PARAM_PRIMITIVE_ID);
505 default:
506 assert(0);
507 return bld_base->uint_bld.zero;
508 }
509 }
510
511 /**
512 * Return the value of tgsi_ind_register for indexing.
513 * This is the indirect index with the constant offset added to it.
514 */
515 static LLVMValueRef get_indirect_index(struct si_shader_context *ctx,
516 const struct tgsi_ind_register *ind,
517 int rel_index)
518 {
519 struct gallivm_state *gallivm = ctx->radeon_bld.soa.bld_base.base.gallivm;
520 LLVMValueRef result;
521
522 result = ctx->radeon_bld.soa.addr[ind->Index][ind->Swizzle];
523 result = LLVMBuildLoad(gallivm->builder, result, "");
524 result = LLVMBuildAdd(gallivm->builder, result,
525 lp_build_const_int32(gallivm, rel_index), "");
526 return result;
527 }
528
529 /**
530 * Calculate a dword address given an input or output register and a stride.
531 */
532 static LLVMValueRef get_dw_address(struct si_shader_context *ctx,
533 const struct tgsi_full_dst_register *dst,
534 const struct tgsi_full_src_register *src,
535 LLVMValueRef vertex_dw_stride,
536 LLVMValueRef base_addr)
537 {
538 struct gallivm_state *gallivm = ctx->radeon_bld.soa.bld_base.base.gallivm;
539 struct tgsi_shader_info *info = &ctx->shader->selector->info;
540 ubyte *name, *index, *array_first;
541 int first, param;
542 struct tgsi_full_dst_register reg;
543
544 /* Set the register description. The address computation is the same
545 * for sources and destinations. */
546 if (src) {
547 reg.Register.File = src->Register.File;
548 reg.Register.Index = src->Register.Index;
549 reg.Register.Indirect = src->Register.Indirect;
550 reg.Register.Dimension = src->Register.Dimension;
551 reg.Indirect = src->Indirect;
552 reg.Dimension = src->Dimension;
553 reg.DimIndirect = src->DimIndirect;
554 } else
555 reg = *dst;
556
557 /* If the register is 2-dimensional (e.g. an array of vertices
558 * in a primitive), calculate the base address of the vertex. */
559 if (reg.Register.Dimension) {
560 LLVMValueRef index;
561
562 if (reg.Dimension.Indirect)
563 index = get_indirect_index(ctx, &reg.DimIndirect,
564 reg.Dimension.Index);
565 else
566 index = lp_build_const_int32(gallivm, reg.Dimension.Index);
567
568 base_addr = LLVMBuildAdd(gallivm->builder, base_addr,
569 LLVMBuildMul(gallivm->builder, index,
570 vertex_dw_stride, ""), "");
571 }
572
573 /* Get information about the register. */
574 if (reg.Register.File == TGSI_FILE_INPUT) {
575 name = info->input_semantic_name;
576 index = info->input_semantic_index;
577 array_first = info->input_array_first;
578 } else if (reg.Register.File == TGSI_FILE_OUTPUT) {
579 name = info->output_semantic_name;
580 index = info->output_semantic_index;
581 array_first = info->output_array_first;
582 } else {
583 assert(0);
584 return NULL;
585 }
586
587 if (reg.Register.Indirect) {
588 /* Add the relative address of the element. */
589 LLVMValueRef ind_index;
590
591 if (reg.Indirect.ArrayID)
592 first = array_first[reg.Indirect.ArrayID];
593 else
594 first = reg.Register.Index;
595
596 ind_index = get_indirect_index(ctx, &reg.Indirect,
597 reg.Register.Index - first);
598
599 base_addr = LLVMBuildAdd(gallivm->builder, base_addr,
600 LLVMBuildMul(gallivm->builder, ind_index,
601 lp_build_const_int32(gallivm, 4), ""), "");
602
603 param = si_shader_io_get_unique_index(name[first], index[first]);
604 } else {
605 param = si_shader_io_get_unique_index(name[reg.Register.Index],
606 index[reg.Register.Index]);
607 }
608
609 /* Add the base address of the element. */
610 return LLVMBuildAdd(gallivm->builder, base_addr,
611 lp_build_const_int32(gallivm, param * 4), "");
612 }
613
614 /**
615 * Load from LDS.
616 *
617 * \param type output value type
618 * \param swizzle offset (typically 0..3); it can be ~0, which loads a vec4
619 * \param dw_addr address in dwords
620 */
621 static LLVMValueRef lds_load(struct lp_build_tgsi_context *bld_base,
622 enum tgsi_opcode_type type, unsigned swizzle,
623 LLVMValueRef dw_addr)
624 {
625 struct si_shader_context *ctx = si_shader_context(bld_base);
626 struct gallivm_state *gallivm = bld_base->base.gallivm;
627 LLVMValueRef value;
628
629 if (swizzle == ~0) {
630 LLVMValueRef values[TGSI_NUM_CHANNELS];
631
632 for (unsigned chan = 0; chan < TGSI_NUM_CHANNELS; chan++)
633 values[chan] = lds_load(bld_base, type, chan, dw_addr);
634
635 return lp_build_gather_values(bld_base->base.gallivm, values,
636 TGSI_NUM_CHANNELS);
637 }
638
639 dw_addr = lp_build_add(&bld_base->uint_bld, dw_addr,
640 lp_build_const_int32(gallivm, swizzle));
641
642 value = build_indexed_load(ctx, ctx->lds, dw_addr);
643 if (type == TGSI_TYPE_DOUBLE) {
644 LLVMValueRef value2;
645 dw_addr = lp_build_add(&bld_base->uint_bld, dw_addr,
646 lp_build_const_int32(gallivm, swizzle + 1));
647 value2 = build_indexed_load(ctx, ctx->lds, dw_addr);
648 return radeon_llvm_emit_fetch_double(bld_base, value, value2);
649 }
650
651 return LLVMBuildBitCast(gallivm->builder, value,
652 tgsi2llvmtype(bld_base, type), "");
653 }
654
655 /**
656 * Store to LDS.
657 *
658 * \param swizzle offset (typically 0..3)
659 * \param dw_addr address in dwords
660 * \param value value to store
661 */
662 static void lds_store(struct lp_build_tgsi_context *bld_base,
663 unsigned swizzle, LLVMValueRef dw_addr,
664 LLVMValueRef value)
665 {
666 struct si_shader_context *ctx = si_shader_context(bld_base);
667 struct gallivm_state *gallivm = bld_base->base.gallivm;
668
669 dw_addr = lp_build_add(&bld_base->uint_bld, dw_addr,
670 lp_build_const_int32(gallivm, swizzle));
671
672 value = LLVMBuildBitCast(gallivm->builder, value, ctx->i32, "");
673 build_indexed_store(ctx, ctx->lds,
674 dw_addr, value);
675 }
676
677 static LLVMValueRef fetch_input_tcs(
678 struct lp_build_tgsi_context *bld_base,
679 const struct tgsi_full_src_register *reg,
680 enum tgsi_opcode_type type, unsigned swizzle)
681 {
682 struct si_shader_context *ctx = si_shader_context(bld_base);
683 LLVMValueRef dw_addr, stride;
684
685 stride = unpack_param(ctx, SI_PARAM_TCS_IN_LAYOUT, 13, 8);
686 dw_addr = get_tcs_in_current_patch_offset(ctx);
687 dw_addr = get_dw_address(ctx, NULL, reg, stride, dw_addr);
688
689 return lds_load(bld_base, type, swizzle, dw_addr);
690 }
691
692 static LLVMValueRef fetch_output_tcs(
693 struct lp_build_tgsi_context *bld_base,
694 const struct tgsi_full_src_register *reg,
695 enum tgsi_opcode_type type, unsigned swizzle)
696 {
697 struct si_shader_context *ctx = si_shader_context(bld_base);
698 LLVMValueRef dw_addr, stride;
699
700 if (reg->Register.Dimension) {
701 stride = unpack_param(ctx, SI_PARAM_TCS_OUT_LAYOUT, 13, 8);
702 dw_addr = get_tcs_out_current_patch_offset(ctx);
703 dw_addr = get_dw_address(ctx, NULL, reg, stride, dw_addr);
704 } else {
705 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
706 dw_addr = get_dw_address(ctx, NULL, reg, NULL, dw_addr);
707 }
708
709 return lds_load(bld_base, type, swizzle, dw_addr);
710 }
711
712 static LLVMValueRef fetch_input_tes(
713 struct lp_build_tgsi_context *bld_base,
714 const struct tgsi_full_src_register *reg,
715 enum tgsi_opcode_type type, unsigned swizzle)
716 {
717 struct si_shader_context *ctx = si_shader_context(bld_base);
718 LLVMValueRef dw_addr, stride;
719
720 if (reg->Register.Dimension) {
721 stride = unpack_param(ctx, SI_PARAM_TCS_OUT_LAYOUT, 13, 8);
722 dw_addr = get_tcs_out_current_patch_offset(ctx);
723 dw_addr = get_dw_address(ctx, NULL, reg, stride, dw_addr);
724 } else {
725 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
726 dw_addr = get_dw_address(ctx, NULL, reg, NULL, dw_addr);
727 }
728
729 return lds_load(bld_base, type, swizzle, dw_addr);
730 }
731
732 static void store_output_tcs(struct lp_build_tgsi_context *bld_base,
733 const struct tgsi_full_instruction *inst,
734 const struct tgsi_opcode_info *info,
735 LLVMValueRef dst[4])
736 {
737 struct si_shader_context *ctx = si_shader_context(bld_base);
738 const struct tgsi_full_dst_register *reg = &inst->Dst[0];
739 unsigned chan_index;
740 LLVMValueRef dw_addr, stride;
741
742 /* Only handle per-patch and per-vertex outputs here.
743 * Vectors will be lowered to scalars and this function will be called again.
744 */
745 if (reg->Register.File != TGSI_FILE_OUTPUT ||
746 (dst[0] && LLVMGetTypeKind(LLVMTypeOf(dst[0])) == LLVMVectorTypeKind)) {
747 radeon_llvm_emit_store(bld_base, inst, info, dst);
748 return;
749 }
750
751 if (reg->Register.Dimension) {
752 stride = unpack_param(ctx, SI_PARAM_TCS_OUT_LAYOUT, 13, 8);
753 dw_addr = get_tcs_out_current_patch_offset(ctx);
754 dw_addr = get_dw_address(ctx, reg, NULL, stride, dw_addr);
755 } else {
756 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
757 dw_addr = get_dw_address(ctx, reg, NULL, NULL, dw_addr);
758 }
759
760 TGSI_FOR_EACH_DST0_ENABLED_CHANNEL(inst, chan_index) {
761 LLVMValueRef value = dst[chan_index];
762
763 if (inst->Instruction.Saturate)
764 value = radeon_llvm_saturate(bld_base, value);
765
766 lds_store(bld_base, chan_index, dw_addr, value);
767 }
768 }
769
770 static LLVMValueRef fetch_input_gs(
771 struct lp_build_tgsi_context *bld_base,
772 const struct tgsi_full_src_register *reg,
773 enum tgsi_opcode_type type,
774 unsigned swizzle)
775 {
776 struct lp_build_context *base = &bld_base->base;
777 struct si_shader_context *ctx = si_shader_context(bld_base);
778 struct si_shader *shader = ctx->shader;
779 struct lp_build_context *uint = &ctx->radeon_bld.soa.bld_base.uint_bld;
780 struct gallivm_state *gallivm = base->gallivm;
781 LLVMValueRef vtx_offset;
782 LLVMValueRef args[9];
783 unsigned vtx_offset_param;
784 struct tgsi_shader_info *info = &shader->selector->info;
785 unsigned semantic_name = info->input_semantic_name[reg->Register.Index];
786 unsigned semantic_index = info->input_semantic_index[reg->Register.Index];
787 unsigned param;
788 LLVMValueRef value;
789
790 if (swizzle != ~0 && semantic_name == TGSI_SEMANTIC_PRIMID)
791 return get_primitive_id(bld_base, swizzle);
792
793 if (!reg->Register.Dimension)
794 return NULL;
795
796 if (swizzle == ~0) {
797 LLVMValueRef values[TGSI_NUM_CHANNELS];
798 unsigned chan;
799 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
800 values[chan] = fetch_input_gs(bld_base, reg, type, chan);
801 }
802 return lp_build_gather_values(bld_base->base.gallivm, values,
803 TGSI_NUM_CHANNELS);
804 }
805
806 /* Get the vertex offset parameter */
807 vtx_offset_param = reg->Dimension.Index;
808 if (vtx_offset_param < 2) {
809 vtx_offset_param += SI_PARAM_VTX0_OFFSET;
810 } else {
811 assert(vtx_offset_param < 6);
812 vtx_offset_param += SI_PARAM_VTX2_OFFSET - 2;
813 }
814 vtx_offset = lp_build_mul_imm(uint,
815 LLVMGetParam(ctx->radeon_bld.main_fn,
816 vtx_offset_param),
817 4);
818
819 param = si_shader_io_get_unique_index(semantic_name, semantic_index);
820 args[0] = ctx->esgs_ring;
821 args[1] = vtx_offset;
822 args[2] = lp_build_const_int32(gallivm, (param * 4 + swizzle) * 256);
823 args[3] = uint->zero;
824 args[4] = uint->one; /* OFFEN */
825 args[5] = uint->zero; /* IDXEN */
826 args[6] = uint->one; /* GLC */
827 args[7] = uint->zero; /* SLC */
828 args[8] = uint->zero; /* TFE */
829
830 value = lp_build_intrinsic(gallivm->builder,
831 "llvm.SI.buffer.load.dword.i32.i32",
832 ctx->i32, args, 9,
833 LLVMReadOnlyAttribute | LLVMNoUnwindAttribute);
834 if (type == TGSI_TYPE_DOUBLE) {
835 LLVMValueRef value2;
836 args[2] = lp_build_const_int32(gallivm, (param * 4 + swizzle + 1) * 256);
837 value2 = lp_build_intrinsic(gallivm->builder,
838 "llvm.SI.buffer.load.dword.i32.i32",
839 ctx->i32, args, 9,
840 LLVMReadOnlyAttribute | LLVMNoUnwindAttribute);
841 return radeon_llvm_emit_fetch_double(bld_base,
842 value, value2);
843 }
844 return LLVMBuildBitCast(gallivm->builder,
845 value,
846 tgsi2llvmtype(bld_base, type), "");
847 }
848
849 static int lookup_interp_param_index(unsigned interpolate, unsigned location)
850 {
851 switch (interpolate) {
852 case TGSI_INTERPOLATE_CONSTANT:
853 return 0;
854
855 case TGSI_INTERPOLATE_LINEAR:
856 if (location == TGSI_INTERPOLATE_LOC_SAMPLE)
857 return SI_PARAM_LINEAR_SAMPLE;
858 else if (location == TGSI_INTERPOLATE_LOC_CENTROID)
859 return SI_PARAM_LINEAR_CENTROID;
860 else
861 return SI_PARAM_LINEAR_CENTER;
862 break;
863 case TGSI_INTERPOLATE_COLOR:
864 case TGSI_INTERPOLATE_PERSPECTIVE:
865 if (location == TGSI_INTERPOLATE_LOC_SAMPLE)
866 return SI_PARAM_PERSP_SAMPLE;
867 else if (location == TGSI_INTERPOLATE_LOC_CENTROID)
868 return SI_PARAM_PERSP_CENTROID;
869 else
870 return SI_PARAM_PERSP_CENTER;
871 break;
872 default:
873 fprintf(stderr, "Warning: Unhandled interpolation mode.\n");
874 return -1;
875 }
876 }
877
878 /* This shouldn't be used by explicit INTERP opcodes. */
879 static unsigned select_interp_param(struct si_shader_context *ctx,
880 unsigned param)
881 {
882 if (!ctx->shader->key.ps.prolog.force_persample_interp ||
883 !ctx->is_monolithic)
884 return param;
885
886 /* If the shader doesn't use center/centroid, just return the parameter.
887 *
888 * If the shader only uses one set of (i,j), "si_emit_spi_ps_input" can
889 * switch between center/centroid and sample without shader changes.
890 */
891 switch (param) {
892 case SI_PARAM_PERSP_CENTROID:
893 case SI_PARAM_PERSP_CENTER:
894 return SI_PARAM_PERSP_SAMPLE;
895
896 case SI_PARAM_LINEAR_CENTROID:
897 case SI_PARAM_LINEAR_CENTER:
898 return SI_PARAM_LINEAR_SAMPLE;
899
900 default:
901 return param;
902 }
903 }
904
905 /**
906 * Interpolate a fragment shader input.
907 *
908 * @param ctx context
909 * @param input_index index of the input in hardware
910 * @param semantic_name TGSI_SEMANTIC_*
911 * @param semantic_index semantic index
912 * @param num_interp_inputs number of all interpolated inputs (= BCOLOR offset)
913 * @param colors_read_mask color components read (4 bits for each color, 8 bits in total)
914 * @param interp_param interpolation weights (i,j)
915 * @param prim_mask SI_PARAM_PRIM_MASK
916 * @param face SI_PARAM_FRONT_FACE
917 * @param result the return value (4 components)
918 */
919 static void interp_fs_input(struct si_shader_context *ctx,
920 unsigned input_index,
921 unsigned semantic_name,
922 unsigned semantic_index,
923 unsigned num_interp_inputs,
924 unsigned colors_read_mask,
925 LLVMValueRef interp_param,
926 LLVMValueRef prim_mask,
927 LLVMValueRef face,
928 LLVMValueRef result[4])
929 {
930 struct lp_build_context *base = &ctx->radeon_bld.soa.bld_base.base;
931 struct lp_build_context *uint = &ctx->radeon_bld.soa.bld_base.uint_bld;
932 struct gallivm_state *gallivm = base->gallivm;
933 const char *intr_name;
934 LLVMValueRef attr_number;
935
936 unsigned chan;
937
938 attr_number = lp_build_const_int32(gallivm, input_index);
939
940 /* fs.constant returns the param from the middle vertex, so it's not
941 * really useful for flat shading. It's meant to be used for custom
942 * interpolation (but the intrinsic can't fetch from the other two
943 * vertices).
944 *
945 * Luckily, it doesn't matter, because we rely on the FLAT_SHADE state
946 * to do the right thing. The only reason we use fs.constant is that
947 * fs.interp cannot be used on integers, because they can be equal
948 * to NaN.
949 */
950 intr_name = interp_param ? "llvm.SI.fs.interp" : "llvm.SI.fs.constant";
951
952 if (semantic_name == TGSI_SEMANTIC_COLOR &&
953 ctx->shader->key.ps.prolog.color_two_side) {
954 LLVMValueRef args[4];
955 LLVMValueRef is_face_positive;
956 LLVMValueRef back_attr_number;
957
958 /* If BCOLOR0 is used, BCOLOR1 is at offset "num_inputs + 1",
959 * otherwise it's at offset "num_inputs".
960 */
961 unsigned back_attr_offset = num_interp_inputs;
962 if (semantic_index == 1 && colors_read_mask & 0xf)
963 back_attr_offset += 1;
964
965 back_attr_number = lp_build_const_int32(gallivm, back_attr_offset);
966
967 is_face_positive = LLVMBuildICmp(gallivm->builder, LLVMIntNE,
968 face, uint->zero, "");
969
970 args[2] = prim_mask;
971 args[3] = interp_param;
972 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
973 LLVMValueRef llvm_chan = lp_build_const_int32(gallivm, chan);
974 LLVMValueRef front, back;
975
976 args[0] = llvm_chan;
977 args[1] = attr_number;
978 front = lp_build_intrinsic(gallivm->builder, intr_name,
979 ctx->f32, args, args[3] ? 4 : 3,
980 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
981
982 args[1] = back_attr_number;
983 back = lp_build_intrinsic(gallivm->builder, intr_name,
984 ctx->f32, args, args[3] ? 4 : 3,
985 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
986
987 result[chan] = LLVMBuildSelect(gallivm->builder,
988 is_face_positive,
989 front,
990 back,
991 "");
992 }
993 } else if (semantic_name == TGSI_SEMANTIC_FOG) {
994 LLVMValueRef args[4];
995
996 args[0] = uint->zero;
997 args[1] = attr_number;
998 args[2] = prim_mask;
999 args[3] = interp_param;
1000 result[0] = lp_build_intrinsic(gallivm->builder, intr_name,
1001 ctx->f32, args, args[3] ? 4 : 3,
1002 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
1003 result[1] =
1004 result[2] = lp_build_const_float(gallivm, 0.0f);
1005 result[3] = lp_build_const_float(gallivm, 1.0f);
1006 } else {
1007 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
1008 LLVMValueRef args[4];
1009 LLVMValueRef llvm_chan = lp_build_const_int32(gallivm, chan);
1010
1011 args[0] = llvm_chan;
1012 args[1] = attr_number;
1013 args[2] = prim_mask;
1014 args[3] = interp_param;
1015 result[chan] = lp_build_intrinsic(gallivm->builder, intr_name,
1016 ctx->f32, args, args[3] ? 4 : 3,
1017 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
1018 }
1019 }
1020 }
1021
1022 static void declare_input_fs(
1023 struct radeon_llvm_context *radeon_bld,
1024 unsigned input_index,
1025 const struct tgsi_full_declaration *decl)
1026 {
1027 struct lp_build_context *base = &radeon_bld->soa.bld_base.base;
1028 struct si_shader_context *ctx =
1029 si_shader_context(&radeon_bld->soa.bld_base);
1030 struct si_shader *shader = ctx->shader;
1031 LLVMValueRef main_fn = radeon_bld->main_fn;
1032 LLVMValueRef interp_param = NULL;
1033 int interp_param_idx;
1034
1035 /* Get colors from input VGPRs (set by the prolog). */
1036 if (!ctx->is_monolithic &&
1037 decl->Semantic.Name == TGSI_SEMANTIC_COLOR) {
1038 unsigned i = decl->Semantic.Index;
1039 unsigned colors_read = shader->selector->info.colors_read;
1040 unsigned mask = colors_read >> (i * 4);
1041 unsigned offset = SI_PARAM_POS_FIXED_PT + 1 +
1042 (i ? util_bitcount(colors_read & 0xf) : 0);
1043
1044 radeon_bld->inputs[radeon_llvm_reg_index_soa(input_index, 0)] =
1045 mask & 0x1 ? LLVMGetParam(main_fn, offset++) : base->undef;
1046 radeon_bld->inputs[radeon_llvm_reg_index_soa(input_index, 1)] =
1047 mask & 0x2 ? LLVMGetParam(main_fn, offset++) : base->undef;
1048 radeon_bld->inputs[radeon_llvm_reg_index_soa(input_index, 2)] =
1049 mask & 0x4 ? LLVMGetParam(main_fn, offset++) : base->undef;
1050 radeon_bld->inputs[radeon_llvm_reg_index_soa(input_index, 3)] =
1051 mask & 0x8 ? LLVMGetParam(main_fn, offset++) : base->undef;
1052 return;
1053 }
1054
1055 interp_param_idx = lookup_interp_param_index(decl->Interp.Interpolate,
1056 decl->Interp.Location);
1057 if (interp_param_idx == -1)
1058 return;
1059 else if (interp_param_idx) {
1060 interp_param_idx = select_interp_param(ctx,
1061 interp_param_idx);
1062 interp_param = LLVMGetParam(main_fn, interp_param_idx);
1063 }
1064
1065 interp_fs_input(ctx, input_index, decl->Semantic.Name,
1066 decl->Semantic.Index, shader->selector->info.num_inputs,
1067 shader->selector->info.colors_read, interp_param,
1068 LLVMGetParam(main_fn, SI_PARAM_PRIM_MASK),
1069 LLVMGetParam(main_fn, SI_PARAM_FRONT_FACE),
1070 &radeon_bld->inputs[radeon_llvm_reg_index_soa(input_index, 0)]);
1071 }
1072
1073 static LLVMValueRef get_sample_id(struct radeon_llvm_context *radeon_bld)
1074 {
1075 return unpack_param(si_shader_context(&radeon_bld->soa.bld_base),
1076 SI_PARAM_ANCILLARY, 8, 4);
1077 }
1078
1079 /**
1080 * Load a dword from a constant buffer.
1081 */
1082 static LLVMValueRef buffer_load_const(LLVMBuilderRef builder, LLVMValueRef resource,
1083 LLVMValueRef offset, LLVMTypeRef return_type)
1084 {
1085 LLVMValueRef args[2] = {resource, offset};
1086
1087 return lp_build_intrinsic(builder, "llvm.SI.load.const", return_type, args, 2,
1088 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
1089 }
1090
1091 static LLVMValueRef load_sample_position(struct radeon_llvm_context *radeon_bld, LLVMValueRef sample_id)
1092 {
1093 struct si_shader_context *ctx =
1094 si_shader_context(&radeon_bld->soa.bld_base);
1095 struct lp_build_context *uint_bld = &radeon_bld->soa.bld_base.uint_bld;
1096 struct gallivm_state *gallivm = &radeon_bld->gallivm;
1097 LLVMBuilderRef builder = gallivm->builder;
1098 LLVMValueRef desc = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_CONST_BUFFERS);
1099 LLVMValueRef buf_index = lp_build_const_int32(gallivm, SI_DRIVER_STATE_CONST_BUF);
1100 LLVMValueRef resource = build_indexed_load_const(ctx, desc, buf_index);
1101
1102 /* offset = sample_id * 8 (8 = 2 floats containing samplepos.xy) */
1103 LLVMValueRef offset0 = lp_build_mul_imm(uint_bld, sample_id, 8);
1104 LLVMValueRef offset1 = LLVMBuildAdd(builder, offset0, lp_build_const_int32(gallivm, 4), "");
1105
1106 LLVMValueRef pos[4] = {
1107 buffer_load_const(builder, resource, offset0, ctx->f32),
1108 buffer_load_const(builder, resource, offset1, ctx->f32),
1109 lp_build_const_float(gallivm, 0),
1110 lp_build_const_float(gallivm, 0)
1111 };
1112
1113 return lp_build_gather_values(gallivm, pos, 4);
1114 }
1115
1116 static void declare_system_value(
1117 struct radeon_llvm_context *radeon_bld,
1118 unsigned index,
1119 const struct tgsi_full_declaration *decl)
1120 {
1121 struct si_shader_context *ctx =
1122 si_shader_context(&radeon_bld->soa.bld_base);
1123 struct lp_build_context *bld = &radeon_bld->soa.bld_base.base;
1124 struct gallivm_state *gallivm = &radeon_bld->gallivm;
1125 LLVMValueRef value = 0;
1126
1127 switch (decl->Semantic.Name) {
1128 case TGSI_SEMANTIC_INSTANCEID:
1129 value = LLVMGetParam(radeon_bld->main_fn,
1130 ctx->param_instance_id);
1131 break;
1132
1133 case TGSI_SEMANTIC_VERTEXID:
1134 value = LLVMBuildAdd(gallivm->builder,
1135 LLVMGetParam(radeon_bld->main_fn,
1136 ctx->param_vertex_id),
1137 LLVMGetParam(radeon_bld->main_fn,
1138 SI_PARAM_BASE_VERTEX), "");
1139 break;
1140
1141 case TGSI_SEMANTIC_VERTEXID_NOBASE:
1142 value = LLVMGetParam(radeon_bld->main_fn,
1143 ctx->param_vertex_id);
1144 break;
1145
1146 case TGSI_SEMANTIC_BASEVERTEX:
1147 value = LLVMGetParam(radeon_bld->main_fn,
1148 SI_PARAM_BASE_VERTEX);
1149 break;
1150
1151 case TGSI_SEMANTIC_INVOCATIONID:
1152 if (ctx->type == TGSI_PROCESSOR_TESS_CTRL)
1153 value = unpack_param(ctx, SI_PARAM_REL_IDS, 8, 5);
1154 else if (ctx->type == TGSI_PROCESSOR_GEOMETRY)
1155 value = LLVMGetParam(radeon_bld->main_fn,
1156 SI_PARAM_GS_INSTANCE_ID);
1157 else
1158 assert(!"INVOCATIONID not implemented");
1159 break;
1160
1161 case TGSI_SEMANTIC_POSITION:
1162 {
1163 LLVMValueRef pos[4] = {
1164 LLVMGetParam(radeon_bld->main_fn, SI_PARAM_POS_X_FLOAT),
1165 LLVMGetParam(radeon_bld->main_fn, SI_PARAM_POS_Y_FLOAT),
1166 LLVMGetParam(radeon_bld->main_fn, SI_PARAM_POS_Z_FLOAT),
1167 lp_build_emit_llvm_unary(&radeon_bld->soa.bld_base, TGSI_OPCODE_RCP,
1168 LLVMGetParam(radeon_bld->main_fn,
1169 SI_PARAM_POS_W_FLOAT)),
1170 };
1171 value = lp_build_gather_values(gallivm, pos, 4);
1172 break;
1173 }
1174
1175 case TGSI_SEMANTIC_FACE:
1176 value = LLVMGetParam(radeon_bld->main_fn, SI_PARAM_FRONT_FACE);
1177 break;
1178
1179 case TGSI_SEMANTIC_SAMPLEID:
1180 value = get_sample_id(radeon_bld);
1181 break;
1182
1183 case TGSI_SEMANTIC_SAMPLEPOS: {
1184 LLVMValueRef pos[4] = {
1185 LLVMGetParam(radeon_bld->main_fn, SI_PARAM_POS_X_FLOAT),
1186 LLVMGetParam(radeon_bld->main_fn, SI_PARAM_POS_Y_FLOAT),
1187 lp_build_const_float(gallivm, 0),
1188 lp_build_const_float(gallivm, 0)
1189 };
1190 pos[0] = lp_build_emit_llvm_unary(&radeon_bld->soa.bld_base,
1191 TGSI_OPCODE_FRC, pos[0]);
1192 pos[1] = lp_build_emit_llvm_unary(&radeon_bld->soa.bld_base,
1193 TGSI_OPCODE_FRC, pos[1]);
1194 value = lp_build_gather_values(gallivm, pos, 4);
1195 break;
1196 }
1197
1198 case TGSI_SEMANTIC_SAMPLEMASK:
1199 /* This can only occur with the OpenGL Core profile, which
1200 * doesn't support smoothing.
1201 */
1202 value = LLVMGetParam(radeon_bld->main_fn, SI_PARAM_SAMPLE_COVERAGE);
1203 break;
1204
1205 case TGSI_SEMANTIC_TESSCOORD:
1206 {
1207 LLVMValueRef coord[4] = {
1208 LLVMGetParam(radeon_bld->main_fn, ctx->param_tes_u),
1209 LLVMGetParam(radeon_bld->main_fn, ctx->param_tes_v),
1210 bld->zero,
1211 bld->zero
1212 };
1213
1214 /* For triangles, the vector should be (u, v, 1-u-v). */
1215 if (ctx->shader->selector->info.properties[TGSI_PROPERTY_TES_PRIM_MODE] ==
1216 PIPE_PRIM_TRIANGLES)
1217 coord[2] = lp_build_sub(bld, bld->one,
1218 lp_build_add(bld, coord[0], coord[1]));
1219
1220 value = lp_build_gather_values(gallivm, coord, 4);
1221 break;
1222 }
1223
1224 case TGSI_SEMANTIC_VERTICESIN:
1225 value = unpack_param(ctx, SI_PARAM_TCS_OUT_LAYOUT, 26, 6);
1226 break;
1227
1228 case TGSI_SEMANTIC_TESSINNER:
1229 case TGSI_SEMANTIC_TESSOUTER:
1230 {
1231 LLVMValueRef dw_addr;
1232 int param = si_shader_io_get_unique_index(decl->Semantic.Name, 0);
1233
1234 dw_addr = get_tcs_out_current_patch_data_offset(ctx);
1235 dw_addr = LLVMBuildAdd(gallivm->builder, dw_addr,
1236 lp_build_const_int32(gallivm, param * 4), "");
1237
1238 value = lds_load(&radeon_bld->soa.bld_base, TGSI_TYPE_FLOAT,
1239 ~0, dw_addr);
1240 break;
1241 }
1242
1243 case TGSI_SEMANTIC_PRIMID:
1244 value = get_primitive_id(&radeon_bld->soa.bld_base, 0);
1245 break;
1246
1247 default:
1248 assert(!"unknown system value");
1249 return;
1250 }
1251
1252 radeon_bld->system_values[index] = value;
1253 }
1254
1255 static LLVMValueRef fetch_constant(
1256 struct lp_build_tgsi_context *bld_base,
1257 const struct tgsi_full_src_register *reg,
1258 enum tgsi_opcode_type type,
1259 unsigned swizzle)
1260 {
1261 struct si_shader_context *ctx = si_shader_context(bld_base);
1262 struct lp_build_context *base = &bld_base->base;
1263 const struct tgsi_ind_register *ireg = &reg->Indirect;
1264 unsigned buf, idx;
1265
1266 LLVMValueRef addr, bufp;
1267 LLVMValueRef result;
1268
1269 if (swizzle == LP_CHAN_ALL) {
1270 unsigned chan;
1271 LLVMValueRef values[4];
1272 for (chan = 0; chan < TGSI_NUM_CHANNELS; ++chan)
1273 values[chan] = fetch_constant(bld_base, reg, type, chan);
1274
1275 return lp_build_gather_values(bld_base->base.gallivm, values, 4);
1276 }
1277
1278 buf = reg->Register.Dimension ? reg->Dimension.Index : 0;
1279 idx = reg->Register.Index * 4 + swizzle;
1280
1281 if (!reg->Register.Indirect && !reg->Dimension.Indirect) {
1282 if (type != TGSI_TYPE_DOUBLE)
1283 return bitcast(bld_base, type, ctx->constants[buf][idx]);
1284 else {
1285 return radeon_llvm_emit_fetch_double(bld_base,
1286 ctx->constants[buf][idx],
1287 ctx->constants[buf][idx + 1]);
1288 }
1289 }
1290
1291 if (reg->Register.Dimension && reg->Dimension.Indirect) {
1292 LLVMValueRef ptr = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_CONST_BUFFERS);
1293 LLVMValueRef index;
1294 index = get_indirect_index(ctx, &reg->DimIndirect,
1295 reg->Dimension.Index);
1296 bufp = build_indexed_load_const(ctx, ptr, index);
1297 } else
1298 bufp = ctx->const_buffers[buf];
1299
1300 addr = ctx->radeon_bld.soa.addr[ireg->Index][ireg->Swizzle];
1301 addr = LLVMBuildLoad(base->gallivm->builder, addr, "load addr reg");
1302 addr = lp_build_mul_imm(&bld_base->uint_bld, addr, 16);
1303 addr = lp_build_add(&bld_base->uint_bld, addr,
1304 lp_build_const_int32(base->gallivm, idx * 4));
1305
1306 result = buffer_load_const(base->gallivm->builder, bufp,
1307 addr, ctx->f32);
1308
1309 if (type != TGSI_TYPE_DOUBLE)
1310 result = bitcast(bld_base, type, result);
1311 else {
1312 LLVMValueRef addr2, result2;
1313 addr2 = ctx->radeon_bld.soa.addr[ireg->Index][ireg->Swizzle + 1];
1314 addr2 = LLVMBuildLoad(base->gallivm->builder, addr2, "load addr reg2");
1315 addr2 = lp_build_mul_imm(&bld_base->uint_bld, addr2, 16);
1316 addr2 = lp_build_add(&bld_base->uint_bld, addr2,
1317 lp_build_const_int32(base->gallivm, idx * 4));
1318
1319 result2 = buffer_load_const(base->gallivm->builder, ctx->const_buffers[buf],
1320 addr2, ctx->f32);
1321
1322 result = radeon_llvm_emit_fetch_double(bld_base,
1323 result, result2);
1324 }
1325 return result;
1326 }
1327
1328 /* Upper 16 bits must be zero. */
1329 static LLVMValueRef si_llvm_pack_two_int16(struct gallivm_state *gallivm,
1330 LLVMValueRef val[2])
1331 {
1332 return LLVMBuildOr(gallivm->builder, val[0],
1333 LLVMBuildShl(gallivm->builder, val[1],
1334 lp_build_const_int32(gallivm, 16),
1335 ""), "");
1336 }
1337
1338 /* Upper 16 bits are ignored and will be dropped. */
1339 static LLVMValueRef si_llvm_pack_two_int32_as_int16(struct gallivm_state *gallivm,
1340 LLVMValueRef val[2])
1341 {
1342 LLVMValueRef v[2] = {
1343 LLVMBuildAnd(gallivm->builder, val[0],
1344 lp_build_const_int32(gallivm, 0xffff), ""),
1345 val[1],
1346 };
1347 return si_llvm_pack_two_int16(gallivm, v);
1348 }
1349
1350 /* Initialize arguments for the shader export intrinsic */
1351 static void si_llvm_init_export_args(struct lp_build_tgsi_context *bld_base,
1352 LLVMValueRef *values,
1353 unsigned target,
1354 LLVMValueRef *args)
1355 {
1356 struct si_shader_context *ctx = si_shader_context(bld_base);
1357 struct lp_build_context *uint =
1358 &ctx->radeon_bld.soa.bld_base.uint_bld;
1359 struct lp_build_context *base = &bld_base->base;
1360 struct gallivm_state *gallivm = base->gallivm;
1361 LLVMBuilderRef builder = base->gallivm->builder;
1362 LLVMValueRef val[4];
1363 unsigned spi_shader_col_format = V_028714_SPI_SHADER_32_ABGR;
1364 unsigned chan;
1365 bool is_int8;
1366
1367 /* Default is 0xf. Adjusted below depending on the format. */
1368 args[0] = lp_build_const_int32(base->gallivm, 0xf); /* writemask */
1369
1370 /* Specify whether the EXEC mask represents the valid mask */
1371 args[1] = uint->zero;
1372
1373 /* Specify whether this is the last export */
1374 args[2] = uint->zero;
1375
1376 /* Specify the target we are exporting */
1377 args[3] = lp_build_const_int32(base->gallivm, target);
1378
1379 if (ctx->type == TGSI_PROCESSOR_FRAGMENT) {
1380 const union si_shader_key *key = &ctx->shader->key;
1381 unsigned col_formats = key->ps.epilog.spi_shader_col_format;
1382 int cbuf = target - V_008DFC_SQ_EXP_MRT;
1383
1384 assert(cbuf >= 0 && cbuf < 8);
1385 spi_shader_col_format = (col_formats >> (cbuf * 4)) & 0xf;
1386 is_int8 = (key->ps.epilog.color_is_int8 >> cbuf) & 0x1;
1387 }
1388
1389 args[4] = uint->zero; /* COMPR flag */
1390 args[5] = base->undef;
1391 args[6] = base->undef;
1392 args[7] = base->undef;
1393 args[8] = base->undef;
1394
1395 switch (spi_shader_col_format) {
1396 case V_028714_SPI_SHADER_ZERO:
1397 args[0] = uint->zero; /* writemask */
1398 args[3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_NULL);
1399 break;
1400
1401 case V_028714_SPI_SHADER_32_R:
1402 args[0] = uint->one; /* writemask */
1403 args[5] = values[0];
1404 break;
1405
1406 case V_028714_SPI_SHADER_32_GR:
1407 args[0] = lp_build_const_int32(base->gallivm, 0x3); /* writemask */
1408 args[5] = values[0];
1409 args[6] = values[1];
1410 break;
1411
1412 case V_028714_SPI_SHADER_32_AR:
1413 args[0] = lp_build_const_int32(base->gallivm, 0x9); /* writemask */
1414 args[5] = values[0];
1415 args[8] = values[3];
1416 break;
1417
1418 case V_028714_SPI_SHADER_FP16_ABGR:
1419 args[4] = uint->one; /* COMPR flag */
1420
1421 for (chan = 0; chan < 2; chan++) {
1422 LLVMValueRef pack_args[2] = {
1423 values[2 * chan],
1424 values[2 * chan + 1]
1425 };
1426 LLVMValueRef packed;
1427
1428 packed = lp_build_intrinsic(base->gallivm->builder,
1429 "llvm.SI.packf16",
1430 ctx->i32, pack_args, 2,
1431 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
1432 args[chan + 5] =
1433 LLVMBuildBitCast(base->gallivm->builder,
1434 packed, ctx->f32, "");
1435 }
1436 break;
1437
1438 case V_028714_SPI_SHADER_UNORM16_ABGR:
1439 for (chan = 0; chan < 4; chan++) {
1440 val[chan] = radeon_llvm_saturate(bld_base, values[chan]);
1441 val[chan] = LLVMBuildFMul(builder, val[chan],
1442 lp_build_const_float(gallivm, 65535), "");
1443 val[chan] = LLVMBuildFAdd(builder, val[chan],
1444 lp_build_const_float(gallivm, 0.5), "");
1445 val[chan] = LLVMBuildFPToUI(builder, val[chan],
1446 ctx->i32, "");
1447 }
1448
1449 args[4] = uint->one; /* COMPR flag */
1450 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT,
1451 si_llvm_pack_two_int16(gallivm, val));
1452 args[6] = bitcast(bld_base, TGSI_TYPE_FLOAT,
1453 si_llvm_pack_two_int16(gallivm, val+2));
1454 break;
1455
1456 case V_028714_SPI_SHADER_SNORM16_ABGR:
1457 for (chan = 0; chan < 4; chan++) {
1458 /* Clamp between [-1, 1]. */
1459 val[chan] = lp_build_emit_llvm_binary(bld_base, TGSI_OPCODE_MIN,
1460 values[chan],
1461 lp_build_const_float(gallivm, 1));
1462 val[chan] = lp_build_emit_llvm_binary(bld_base, TGSI_OPCODE_MAX,
1463 val[chan],
1464 lp_build_const_float(gallivm, -1));
1465 /* Convert to a signed integer in [-32767, 32767]. */
1466 val[chan] = LLVMBuildFMul(builder, val[chan],
1467 lp_build_const_float(gallivm, 32767), "");
1468 /* If positive, add 0.5, else add -0.5. */
1469 val[chan] = LLVMBuildFAdd(builder, val[chan],
1470 LLVMBuildSelect(builder,
1471 LLVMBuildFCmp(builder, LLVMRealOGE,
1472 val[chan], base->zero, ""),
1473 lp_build_const_float(gallivm, 0.5),
1474 lp_build_const_float(gallivm, -0.5), ""), "");
1475 val[chan] = LLVMBuildFPToSI(builder, val[chan], ctx->i32, "");
1476 }
1477
1478 args[4] = uint->one; /* COMPR flag */
1479 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT,
1480 si_llvm_pack_two_int32_as_int16(gallivm, val));
1481 args[6] = bitcast(bld_base, TGSI_TYPE_FLOAT,
1482 si_llvm_pack_two_int32_as_int16(gallivm, val+2));
1483 break;
1484
1485 case V_028714_SPI_SHADER_UINT16_ABGR: {
1486 LLVMValueRef max = lp_build_const_int32(gallivm, is_int8 ?
1487 255 : 65535);
1488 /* Clamp. */
1489 for (chan = 0; chan < 4; chan++) {
1490 val[chan] = bitcast(bld_base, TGSI_TYPE_UNSIGNED, values[chan]);
1491 val[chan] = lp_build_emit_llvm_binary(bld_base, TGSI_OPCODE_UMIN,
1492 val[chan], max);
1493 }
1494
1495 args[4] = uint->one; /* COMPR flag */
1496 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT,
1497 si_llvm_pack_two_int16(gallivm, val));
1498 args[6] = bitcast(bld_base, TGSI_TYPE_FLOAT,
1499 si_llvm_pack_two_int16(gallivm, val+2));
1500 break;
1501 }
1502
1503 case V_028714_SPI_SHADER_SINT16_ABGR: {
1504 LLVMValueRef max = lp_build_const_int32(gallivm, is_int8 ?
1505 127 : 32767);
1506 LLVMValueRef min = lp_build_const_int32(gallivm, is_int8 ?
1507 -128 : -32768);
1508 /* Clamp. */
1509 for (chan = 0; chan < 4; chan++) {
1510 val[chan] = bitcast(bld_base, TGSI_TYPE_UNSIGNED, values[chan]);
1511 val[chan] = lp_build_emit_llvm_binary(bld_base,
1512 TGSI_OPCODE_IMIN,
1513 val[chan], max);
1514 val[chan] = lp_build_emit_llvm_binary(bld_base,
1515 TGSI_OPCODE_IMAX,
1516 val[chan], min);
1517 }
1518
1519 args[4] = uint->one; /* COMPR flag */
1520 args[5] = bitcast(bld_base, TGSI_TYPE_FLOAT,
1521 si_llvm_pack_two_int32_as_int16(gallivm, val));
1522 args[6] = bitcast(bld_base, TGSI_TYPE_FLOAT,
1523 si_llvm_pack_two_int32_as_int16(gallivm, val+2));
1524 break;
1525 }
1526
1527 case V_028714_SPI_SHADER_32_ABGR:
1528 memcpy(&args[5], values, sizeof(values[0]) * 4);
1529 break;
1530 }
1531 }
1532
1533 static void si_alpha_test(struct lp_build_tgsi_context *bld_base,
1534 LLVMValueRef alpha)
1535 {
1536 struct si_shader_context *ctx = si_shader_context(bld_base);
1537 struct gallivm_state *gallivm = bld_base->base.gallivm;
1538
1539 if (ctx->shader->key.ps.epilog.alpha_func != PIPE_FUNC_NEVER) {
1540 LLVMValueRef alpha_ref = LLVMGetParam(ctx->radeon_bld.main_fn,
1541 SI_PARAM_ALPHA_REF);
1542
1543 LLVMValueRef alpha_pass =
1544 lp_build_cmp(&bld_base->base,
1545 ctx->shader->key.ps.epilog.alpha_func,
1546 alpha, alpha_ref);
1547 LLVMValueRef arg =
1548 lp_build_select(&bld_base->base,
1549 alpha_pass,
1550 lp_build_const_float(gallivm, 1.0f),
1551 lp_build_const_float(gallivm, -1.0f));
1552
1553 lp_build_intrinsic(gallivm->builder, "llvm.AMDGPU.kill",
1554 ctx->voidt, &arg, 1, 0);
1555 } else {
1556 lp_build_intrinsic(gallivm->builder, "llvm.AMDGPU.kilp",
1557 ctx->voidt, NULL, 0, 0);
1558 }
1559 }
1560
1561 static LLVMValueRef si_scale_alpha_by_sample_mask(struct lp_build_tgsi_context *bld_base,
1562 LLVMValueRef alpha,
1563 unsigned samplemask_param)
1564 {
1565 struct si_shader_context *ctx = si_shader_context(bld_base);
1566 struct gallivm_state *gallivm = bld_base->base.gallivm;
1567 LLVMValueRef coverage;
1568
1569 /* alpha = alpha * popcount(coverage) / SI_NUM_SMOOTH_AA_SAMPLES */
1570 coverage = LLVMGetParam(ctx->radeon_bld.main_fn,
1571 samplemask_param);
1572 coverage = bitcast(bld_base, TGSI_TYPE_SIGNED, coverage);
1573
1574 coverage = lp_build_intrinsic(gallivm->builder, "llvm.ctpop.i32",
1575 ctx->i32,
1576 &coverage, 1, LLVMReadNoneAttribute);
1577
1578 coverage = LLVMBuildUIToFP(gallivm->builder, coverage,
1579 ctx->f32, "");
1580
1581 coverage = LLVMBuildFMul(gallivm->builder, coverage,
1582 lp_build_const_float(gallivm,
1583 1.0 / SI_NUM_SMOOTH_AA_SAMPLES), "");
1584
1585 return LLVMBuildFMul(gallivm->builder, alpha, coverage, "");
1586 }
1587
1588 static void si_llvm_emit_clipvertex(struct lp_build_tgsi_context *bld_base,
1589 LLVMValueRef (*pos)[9], LLVMValueRef *out_elts)
1590 {
1591 struct si_shader_context *ctx = si_shader_context(bld_base);
1592 struct lp_build_context *base = &bld_base->base;
1593 struct lp_build_context *uint = &ctx->radeon_bld.soa.bld_base.uint_bld;
1594 unsigned reg_index;
1595 unsigned chan;
1596 unsigned const_chan;
1597 LLVMValueRef base_elt;
1598 LLVMValueRef ptr = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_CONST_BUFFERS);
1599 LLVMValueRef constbuf_index = lp_build_const_int32(base->gallivm, SI_DRIVER_STATE_CONST_BUF);
1600 LLVMValueRef const_resource = build_indexed_load_const(ctx, ptr, constbuf_index);
1601
1602 for (reg_index = 0; reg_index < 2; reg_index ++) {
1603 LLVMValueRef *args = pos[2 + reg_index];
1604
1605 args[5] =
1606 args[6] =
1607 args[7] =
1608 args[8] = lp_build_const_float(base->gallivm, 0.0f);
1609
1610 /* Compute dot products of position and user clip plane vectors */
1611 for (chan = 0; chan < TGSI_NUM_CHANNELS; chan++) {
1612 for (const_chan = 0; const_chan < TGSI_NUM_CHANNELS; const_chan++) {
1613 args[1] = lp_build_const_int32(base->gallivm,
1614 ((reg_index * 4 + chan) * 4 +
1615 const_chan) * 4);
1616 base_elt = buffer_load_const(base->gallivm->builder, const_resource,
1617 args[1], ctx->f32);
1618 args[5 + chan] =
1619 lp_build_add(base, args[5 + chan],
1620 lp_build_mul(base, base_elt,
1621 out_elts[const_chan]));
1622 }
1623 }
1624
1625 args[0] = lp_build_const_int32(base->gallivm, 0xf);
1626 args[1] = uint->zero;
1627 args[2] = uint->zero;
1628 args[3] = lp_build_const_int32(base->gallivm,
1629 V_008DFC_SQ_EXP_POS + 2 + reg_index);
1630 args[4] = uint->zero;
1631 }
1632 }
1633
1634 static void si_dump_streamout(struct pipe_stream_output_info *so)
1635 {
1636 unsigned i;
1637
1638 if (so->num_outputs)
1639 fprintf(stderr, "STREAMOUT\n");
1640
1641 for (i = 0; i < so->num_outputs; i++) {
1642 unsigned mask = ((1 << so->output[i].num_components) - 1) <<
1643 so->output[i].start_component;
1644 fprintf(stderr, " %i: BUF%i[%i..%i] <- OUT[%i].%s%s%s%s\n",
1645 i, so->output[i].output_buffer,
1646 so->output[i].dst_offset, so->output[i].dst_offset + so->output[i].num_components - 1,
1647 so->output[i].register_index,
1648 mask & 1 ? "x" : "",
1649 mask & 2 ? "y" : "",
1650 mask & 4 ? "z" : "",
1651 mask & 8 ? "w" : "");
1652 }
1653 }
1654
1655 /* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
1656 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
1657 * or v4i32 (num_channels=3,4). */
1658 static void build_tbuffer_store(struct si_shader_context *ctx,
1659 LLVMValueRef rsrc,
1660 LLVMValueRef vdata,
1661 unsigned num_channels,
1662 LLVMValueRef vaddr,
1663 LLVMValueRef soffset,
1664 unsigned inst_offset,
1665 unsigned dfmt,
1666 unsigned nfmt,
1667 unsigned offen,
1668 unsigned idxen,
1669 unsigned glc,
1670 unsigned slc,
1671 unsigned tfe)
1672 {
1673 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
1674 LLVMValueRef args[] = {
1675 rsrc,
1676 vdata,
1677 LLVMConstInt(ctx->i32, num_channels, 0),
1678 vaddr,
1679 soffset,
1680 LLVMConstInt(ctx->i32, inst_offset, 0),
1681 LLVMConstInt(ctx->i32, dfmt, 0),
1682 LLVMConstInt(ctx->i32, nfmt, 0),
1683 LLVMConstInt(ctx->i32, offen, 0),
1684 LLVMConstInt(ctx->i32, idxen, 0),
1685 LLVMConstInt(ctx->i32, glc, 0),
1686 LLVMConstInt(ctx->i32, slc, 0),
1687 LLVMConstInt(ctx->i32, tfe, 0)
1688 };
1689
1690 /* The instruction offset field has 12 bits */
1691 assert(offen || inst_offset < (1 << 12));
1692
1693 /* The intrinsic is overloaded, we need to add a type suffix for overloading to work. */
1694 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1695 const char *types[] = {"i32", "v2i32", "v4i32"};
1696 char name[256];
1697 snprintf(name, sizeof(name), "llvm.SI.tbuffer.store.%s", types[func]);
1698
1699 lp_build_intrinsic(gallivm->builder, name, ctx->voidt,
1700 args, Elements(args), 0);
1701 }
1702
1703 static void build_tbuffer_store_dwords(struct si_shader_context *ctx,
1704 LLVMValueRef rsrc,
1705 LLVMValueRef vdata,
1706 unsigned num_channels,
1707 LLVMValueRef vaddr,
1708 LLVMValueRef soffset,
1709 unsigned inst_offset)
1710 {
1711 static unsigned dfmt[] = {
1712 V_008F0C_BUF_DATA_FORMAT_32,
1713 V_008F0C_BUF_DATA_FORMAT_32_32,
1714 V_008F0C_BUF_DATA_FORMAT_32_32_32,
1715 V_008F0C_BUF_DATA_FORMAT_32_32_32_32
1716 };
1717 assert(num_channels >= 1 && num_channels <= 4);
1718
1719 build_tbuffer_store(ctx, rsrc, vdata, num_channels, vaddr, soffset,
1720 inst_offset, dfmt[num_channels-1],
1721 V_008F0C_BUF_NUM_FORMAT_UINT, 1, 0, 1, 1, 0);
1722 }
1723
1724 /* On SI, the vertex shader is responsible for writing streamout data
1725 * to buffers. */
1726 static void si_llvm_emit_streamout(struct si_shader_context *ctx,
1727 struct si_shader_output_values *outputs,
1728 unsigned noutput)
1729 {
1730 struct pipe_stream_output_info *so = &ctx->shader->selector->so;
1731 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
1732 LLVMBuilderRef builder = gallivm->builder;
1733 int i, j;
1734 struct lp_build_if_state if_ctx;
1735
1736 /* Get bits [22:16], i.e. (so_param >> 16) & 127; */
1737 LLVMValueRef so_vtx_count =
1738 unpack_param(ctx, ctx->param_streamout_config, 16, 7);
1739
1740 LLVMValueRef tid = lp_build_intrinsic(builder, "llvm.SI.tid", ctx->i32,
1741 NULL, 0, LLVMReadNoneAttribute);
1742
1743 /* can_emit = tid < so_vtx_count; */
1744 LLVMValueRef can_emit =
1745 LLVMBuildICmp(builder, LLVMIntULT, tid, so_vtx_count, "");
1746
1747 LLVMValueRef stream_id =
1748 unpack_param(ctx, ctx->param_streamout_config, 24, 2);
1749
1750 /* Emit the streamout code conditionally. This actually avoids
1751 * out-of-bounds buffer access. The hw tells us via the SGPR
1752 * (so_vtx_count) which threads are allowed to emit streamout data. */
1753 lp_build_if(&if_ctx, gallivm, can_emit);
1754 {
1755 /* The buffer offset is computed as follows:
1756 * ByteOffset = streamout_offset[buffer_id]*4 +
1757 * (streamout_write_index + thread_id)*stride[buffer_id] +
1758 * attrib_offset
1759 */
1760
1761 LLVMValueRef so_write_index =
1762 LLVMGetParam(ctx->radeon_bld.main_fn,
1763 ctx->param_streamout_write_index);
1764
1765 /* Compute (streamout_write_index + thread_id). */
1766 so_write_index = LLVMBuildAdd(builder, so_write_index, tid, "");
1767
1768 /* Compute the write offset for each enabled buffer. */
1769 LLVMValueRef so_write_offset[4] = {};
1770 for (i = 0; i < 4; i++) {
1771 if (!so->stride[i])
1772 continue;
1773
1774 LLVMValueRef so_offset = LLVMGetParam(ctx->radeon_bld.main_fn,
1775 ctx->param_streamout_offset[i]);
1776 so_offset = LLVMBuildMul(builder, so_offset, LLVMConstInt(ctx->i32, 4, 0), "");
1777
1778 so_write_offset[i] = LLVMBuildMul(builder, so_write_index,
1779 LLVMConstInt(ctx->i32, so->stride[i]*4, 0), "");
1780 so_write_offset[i] = LLVMBuildAdd(builder, so_write_offset[i], so_offset, "");
1781 }
1782
1783 /* Write streamout data. */
1784 for (i = 0; i < so->num_outputs; i++) {
1785 unsigned buf_idx = so->output[i].output_buffer;
1786 unsigned reg = so->output[i].register_index;
1787 unsigned start = so->output[i].start_component;
1788 unsigned num_comps = so->output[i].num_components;
1789 unsigned stream = so->output[i].stream;
1790 LLVMValueRef out[4];
1791 struct lp_build_if_state if_ctx_stream;
1792
1793 assert(num_comps && num_comps <= 4);
1794 if (!num_comps || num_comps > 4)
1795 continue;
1796
1797 if (reg >= noutput)
1798 continue;
1799
1800 /* Load the output as int. */
1801 for (j = 0; j < num_comps; j++) {
1802 out[j] = LLVMBuildBitCast(builder,
1803 outputs[reg].values[start+j],
1804 ctx->i32, "");
1805 }
1806
1807 /* Pack the output. */
1808 LLVMValueRef vdata = NULL;
1809
1810 switch (num_comps) {
1811 case 1: /* as i32 */
1812 vdata = out[0];
1813 break;
1814 case 2: /* as v2i32 */
1815 case 3: /* as v4i32 (aligned to 4) */
1816 case 4: /* as v4i32 */
1817 vdata = LLVMGetUndef(LLVMVectorType(ctx->i32, util_next_power_of_two(num_comps)));
1818 for (j = 0; j < num_comps; j++) {
1819 vdata = LLVMBuildInsertElement(builder, vdata, out[j],
1820 LLVMConstInt(ctx->i32, j, 0), "");
1821 }
1822 break;
1823 }
1824
1825 LLVMValueRef can_emit_stream =
1826 LLVMBuildICmp(builder, LLVMIntEQ,
1827 stream_id,
1828 lp_build_const_int32(gallivm, stream), "");
1829
1830 lp_build_if(&if_ctx_stream, gallivm, can_emit_stream);
1831 build_tbuffer_store_dwords(ctx, ctx->so_buffers[buf_idx],
1832 vdata, num_comps,
1833 so_write_offset[buf_idx],
1834 LLVMConstInt(ctx->i32, 0, 0),
1835 so->output[i].dst_offset*4);
1836 lp_build_endif(&if_ctx_stream);
1837 }
1838 }
1839 lp_build_endif(&if_ctx);
1840 }
1841
1842
1843 /* Generate export instructions for hardware VS shader stage */
1844 static void si_llvm_export_vs(struct lp_build_tgsi_context *bld_base,
1845 struct si_shader_output_values *outputs,
1846 unsigned noutput)
1847 {
1848 struct si_shader_context *ctx = si_shader_context(bld_base);
1849 struct si_shader *shader = ctx->shader;
1850 struct lp_build_context *base = &bld_base->base;
1851 struct lp_build_context *uint =
1852 &ctx->radeon_bld.soa.bld_base.uint_bld;
1853 LLVMValueRef args[9];
1854 LLVMValueRef pos_args[4][9] = { { 0 } };
1855 LLVMValueRef psize_value = NULL, edgeflag_value = NULL, layer_value = NULL, viewport_index_value = NULL;
1856 unsigned semantic_name, semantic_index;
1857 unsigned target;
1858 unsigned param_count = 0;
1859 unsigned pos_idx;
1860 int i;
1861
1862 if (outputs && ctx->shader->selector->so.num_outputs) {
1863 si_llvm_emit_streamout(ctx, outputs, noutput);
1864 }
1865
1866 for (i = 0; i < noutput; i++) {
1867 semantic_name = outputs[i].name;
1868 semantic_index = outputs[i].sid;
1869
1870 handle_semantic:
1871 /* Select the correct target */
1872 switch(semantic_name) {
1873 case TGSI_SEMANTIC_PSIZE:
1874 psize_value = outputs[i].values[0];
1875 continue;
1876 case TGSI_SEMANTIC_EDGEFLAG:
1877 edgeflag_value = outputs[i].values[0];
1878 continue;
1879 case TGSI_SEMANTIC_LAYER:
1880 layer_value = outputs[i].values[0];
1881 semantic_name = TGSI_SEMANTIC_GENERIC;
1882 goto handle_semantic;
1883 case TGSI_SEMANTIC_VIEWPORT_INDEX:
1884 viewport_index_value = outputs[i].values[0];
1885 semantic_name = TGSI_SEMANTIC_GENERIC;
1886 goto handle_semantic;
1887 case TGSI_SEMANTIC_POSITION:
1888 target = V_008DFC_SQ_EXP_POS;
1889 break;
1890 case TGSI_SEMANTIC_COLOR:
1891 case TGSI_SEMANTIC_BCOLOR:
1892 target = V_008DFC_SQ_EXP_PARAM + param_count;
1893 shader->vs_output_param_offset[i] = param_count;
1894 param_count++;
1895 break;
1896 case TGSI_SEMANTIC_CLIPDIST:
1897 target = V_008DFC_SQ_EXP_POS + 2 + semantic_index;
1898 break;
1899 case TGSI_SEMANTIC_CLIPVERTEX:
1900 si_llvm_emit_clipvertex(bld_base, pos_args, outputs[i].values);
1901 continue;
1902 case TGSI_SEMANTIC_PRIMID:
1903 case TGSI_SEMANTIC_FOG:
1904 case TGSI_SEMANTIC_TEXCOORD:
1905 case TGSI_SEMANTIC_GENERIC:
1906 target = V_008DFC_SQ_EXP_PARAM + param_count;
1907 shader->vs_output_param_offset[i] = param_count;
1908 param_count++;
1909 break;
1910 default:
1911 target = 0;
1912 fprintf(stderr,
1913 "Warning: SI unhandled vs output type:%d\n",
1914 semantic_name);
1915 }
1916
1917 si_llvm_init_export_args(bld_base, outputs[i].values, target, args);
1918
1919 if (target >= V_008DFC_SQ_EXP_POS &&
1920 target <= (V_008DFC_SQ_EXP_POS + 3)) {
1921 memcpy(pos_args[target - V_008DFC_SQ_EXP_POS],
1922 args, sizeof(args));
1923 } else {
1924 lp_build_intrinsic(base->gallivm->builder,
1925 "llvm.SI.export", ctx->voidt,
1926 args, 9, 0);
1927 }
1928
1929 if (semantic_name == TGSI_SEMANTIC_CLIPDIST) {
1930 semantic_name = TGSI_SEMANTIC_GENERIC;
1931 goto handle_semantic;
1932 }
1933 }
1934
1935 shader->nr_param_exports = param_count;
1936
1937 /* We need to add the position output manually if it's missing. */
1938 if (!pos_args[0][0]) {
1939 pos_args[0][0] = lp_build_const_int32(base->gallivm, 0xf); /* writemask */
1940 pos_args[0][1] = uint->zero; /* EXEC mask */
1941 pos_args[0][2] = uint->zero; /* last export? */
1942 pos_args[0][3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_POS);
1943 pos_args[0][4] = uint->zero; /* COMPR flag */
1944 pos_args[0][5] = base->zero; /* X */
1945 pos_args[0][6] = base->zero; /* Y */
1946 pos_args[0][7] = base->zero; /* Z */
1947 pos_args[0][8] = base->one; /* W */
1948 }
1949
1950 /* Write the misc vector (point size, edgeflag, layer, viewport). */
1951 if (shader->selector->info.writes_psize ||
1952 shader->selector->info.writes_edgeflag ||
1953 shader->selector->info.writes_viewport_index ||
1954 shader->selector->info.writes_layer) {
1955 pos_args[1][0] = lp_build_const_int32(base->gallivm, /* writemask */
1956 shader->selector->info.writes_psize |
1957 (shader->selector->info.writes_edgeflag << 1) |
1958 (shader->selector->info.writes_layer << 2) |
1959 (shader->selector->info.writes_viewport_index << 3));
1960 pos_args[1][1] = uint->zero; /* EXEC mask */
1961 pos_args[1][2] = uint->zero; /* last export? */
1962 pos_args[1][3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_POS + 1);
1963 pos_args[1][4] = uint->zero; /* COMPR flag */
1964 pos_args[1][5] = base->zero; /* X */
1965 pos_args[1][6] = base->zero; /* Y */
1966 pos_args[1][7] = base->zero; /* Z */
1967 pos_args[1][8] = base->zero; /* W */
1968
1969 if (shader->selector->info.writes_psize)
1970 pos_args[1][5] = psize_value;
1971
1972 if (shader->selector->info.writes_edgeflag) {
1973 /* The output is a float, but the hw expects an integer
1974 * with the first bit containing the edge flag. */
1975 edgeflag_value = LLVMBuildFPToUI(base->gallivm->builder,
1976 edgeflag_value,
1977 ctx->i32, "");
1978 edgeflag_value = lp_build_min(&bld_base->int_bld,
1979 edgeflag_value,
1980 bld_base->int_bld.one);
1981
1982 /* The LLVM intrinsic expects a float. */
1983 pos_args[1][6] = LLVMBuildBitCast(base->gallivm->builder,
1984 edgeflag_value,
1985 ctx->f32, "");
1986 }
1987
1988 if (shader->selector->info.writes_layer)
1989 pos_args[1][7] = layer_value;
1990
1991 if (shader->selector->info.writes_viewport_index)
1992 pos_args[1][8] = viewport_index_value;
1993 }
1994
1995 for (i = 0; i < 4; i++)
1996 if (pos_args[i][0])
1997 shader->nr_pos_exports++;
1998
1999 pos_idx = 0;
2000 for (i = 0; i < 4; i++) {
2001 if (!pos_args[i][0])
2002 continue;
2003
2004 /* Specify the target we are exporting */
2005 pos_args[i][3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_POS + pos_idx++);
2006
2007 if (pos_idx == shader->nr_pos_exports)
2008 /* Specify that this is the last export */
2009 pos_args[i][2] = uint->one;
2010
2011 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
2012 ctx->voidt, pos_args[i], 9, 0);
2013 }
2014 }
2015
2016 static void si_write_tess_factors(struct lp_build_tgsi_context *bld_base,
2017 LLVMValueRef rel_patch_id,
2018 LLVMValueRef invocation_id,
2019 LLVMValueRef tcs_out_current_patch_data_offset)
2020 {
2021 struct si_shader_context *ctx = si_shader_context(bld_base);
2022 struct gallivm_state *gallivm = bld_base->base.gallivm;
2023 struct si_shader *shader = ctx->shader;
2024 unsigned tess_inner_index, tess_outer_index;
2025 LLVMValueRef lds_base, lds_inner, lds_outer, byteoffset, buffer;
2026 LLVMValueRef out[6], vec0, vec1, rw_buffers, tf_base;
2027 unsigned stride, outer_comps, inner_comps, i;
2028 struct lp_build_if_state if_ctx;
2029
2030 /* Do this only for invocation 0, because the tess levels are per-patch,
2031 * not per-vertex.
2032 *
2033 * This can't jump, because invocation 0 executes this. It should
2034 * at least mask out the loads and stores for other invocations.
2035 */
2036 lp_build_if(&if_ctx, gallivm,
2037 LLVMBuildICmp(gallivm->builder, LLVMIntEQ,
2038 invocation_id, bld_base->uint_bld.zero, ""));
2039
2040 /* Determine the layout of one tess factor element in the buffer. */
2041 switch (shader->key.tcs.epilog.prim_mode) {
2042 case PIPE_PRIM_LINES:
2043 stride = 2; /* 2 dwords, 1 vec2 store */
2044 outer_comps = 2;
2045 inner_comps = 0;
2046 break;
2047 case PIPE_PRIM_TRIANGLES:
2048 stride = 4; /* 4 dwords, 1 vec4 store */
2049 outer_comps = 3;
2050 inner_comps = 1;
2051 break;
2052 case PIPE_PRIM_QUADS:
2053 stride = 6; /* 6 dwords, 2 stores (vec4 + vec2) */
2054 outer_comps = 4;
2055 inner_comps = 2;
2056 break;
2057 default:
2058 assert(0);
2059 return;
2060 }
2061
2062 /* Load tess_inner and tess_outer from LDS.
2063 * Any invocation can write them, so we can't get them from a temporary.
2064 */
2065 tess_inner_index = si_shader_io_get_unique_index(TGSI_SEMANTIC_TESSINNER, 0);
2066 tess_outer_index = si_shader_io_get_unique_index(TGSI_SEMANTIC_TESSOUTER, 0);
2067
2068 lds_base = tcs_out_current_patch_data_offset;
2069 lds_inner = LLVMBuildAdd(gallivm->builder, lds_base,
2070 lp_build_const_int32(gallivm,
2071 tess_inner_index * 4), "");
2072 lds_outer = LLVMBuildAdd(gallivm->builder, lds_base,
2073 lp_build_const_int32(gallivm,
2074 tess_outer_index * 4), "");
2075
2076 for (i = 0; i < outer_comps; i++)
2077 out[i] = lds_load(bld_base, TGSI_TYPE_SIGNED, i, lds_outer);
2078 for (i = 0; i < inner_comps; i++)
2079 out[outer_comps+i] = lds_load(bld_base, TGSI_TYPE_SIGNED, i, lds_inner);
2080
2081 /* Convert the outputs to vectors for stores. */
2082 vec0 = lp_build_gather_values(gallivm, out, MIN2(stride, 4));
2083 vec1 = NULL;
2084
2085 if (stride > 4)
2086 vec1 = lp_build_gather_values(gallivm, out+4, stride - 4);
2087
2088 /* Get the buffer. */
2089 rw_buffers = LLVMGetParam(ctx->radeon_bld.main_fn,
2090 SI_PARAM_RW_BUFFERS);
2091 buffer = build_indexed_load_const(ctx, rw_buffers,
2092 lp_build_const_int32(gallivm, SI_RING_TESS_FACTOR));
2093
2094 /* Get the offset. */
2095 tf_base = LLVMGetParam(ctx->radeon_bld.main_fn,
2096 SI_PARAM_TESS_FACTOR_OFFSET);
2097 byteoffset = LLVMBuildMul(gallivm->builder, rel_patch_id,
2098 lp_build_const_int32(gallivm, 4 * stride), "");
2099
2100 /* Store the outputs. */
2101 build_tbuffer_store_dwords(ctx, buffer, vec0,
2102 MIN2(stride, 4), byteoffset, tf_base, 0);
2103 if (vec1)
2104 build_tbuffer_store_dwords(ctx, buffer, vec1,
2105 stride - 4, byteoffset, tf_base, 16);
2106 lp_build_endif(&if_ctx);
2107 }
2108
2109 /* This only writes the tessellation factor levels. */
2110 static void si_llvm_emit_tcs_epilogue(struct lp_build_tgsi_context *bld_base)
2111 {
2112 struct si_shader_context *ctx = si_shader_context(bld_base);
2113 LLVMValueRef rel_patch_id, invocation_id, tf_lds_offset;
2114
2115 rel_patch_id = get_rel_patch_id(ctx);
2116 invocation_id = unpack_param(ctx, SI_PARAM_REL_IDS, 8, 5);
2117 tf_lds_offset = get_tcs_out_current_patch_data_offset(ctx);
2118
2119 if (!ctx->is_monolithic) {
2120 /* Return epilog parameters from this function. */
2121 LLVMBuilderRef builder = bld_base->base.gallivm->builder;
2122 LLVMValueRef ret = ctx->return_value;
2123 LLVMValueRef rw_buffers, rw0, rw1, tf_soffset;
2124 unsigned vgpr;
2125
2126 /* RW_BUFFERS pointer */
2127 rw_buffers = LLVMGetParam(ctx->radeon_bld.main_fn,
2128 SI_PARAM_RW_BUFFERS);
2129 rw_buffers = LLVMBuildPtrToInt(builder, rw_buffers, ctx->i64, "");
2130 rw_buffers = LLVMBuildBitCast(builder, rw_buffers, ctx->v2i32, "");
2131 rw0 = LLVMBuildExtractElement(builder, rw_buffers,
2132 bld_base->uint_bld.zero, "");
2133 rw1 = LLVMBuildExtractElement(builder, rw_buffers,
2134 bld_base->uint_bld.one, "");
2135 ret = LLVMBuildInsertValue(builder, ret, rw0, 0, "");
2136 ret = LLVMBuildInsertValue(builder, ret, rw1, 1, "");
2137
2138 /* Tess factor buffer soffset is after user SGPRs. */
2139 tf_soffset = LLVMGetParam(ctx->radeon_bld.main_fn,
2140 SI_PARAM_TESS_FACTOR_OFFSET);
2141 ret = LLVMBuildInsertValue(builder, ret, tf_soffset,
2142 SI_TCS_NUM_USER_SGPR, "");
2143
2144 /* VGPRs */
2145 rel_patch_id = bitcast(bld_base, TGSI_TYPE_FLOAT, rel_patch_id);
2146 invocation_id = bitcast(bld_base, TGSI_TYPE_FLOAT, invocation_id);
2147 tf_lds_offset = bitcast(bld_base, TGSI_TYPE_FLOAT, tf_lds_offset);
2148
2149 vgpr = SI_TCS_NUM_USER_SGPR + 1;
2150 ret = LLVMBuildInsertValue(builder, ret, rel_patch_id, vgpr++, "");
2151 ret = LLVMBuildInsertValue(builder, ret, invocation_id, vgpr++, "");
2152 ret = LLVMBuildInsertValue(builder, ret, tf_lds_offset, vgpr++, "");
2153 ctx->return_value = ret;
2154 return;
2155 }
2156
2157 si_write_tess_factors(bld_base, rel_patch_id, invocation_id, tf_lds_offset);
2158 }
2159
2160 static void si_llvm_emit_ls_epilogue(struct lp_build_tgsi_context *bld_base)
2161 {
2162 struct si_shader_context *ctx = si_shader_context(bld_base);
2163 struct si_shader *shader = ctx->shader;
2164 struct tgsi_shader_info *info = &shader->selector->info;
2165 struct gallivm_state *gallivm = bld_base->base.gallivm;
2166 unsigned i, chan;
2167 LLVMValueRef vertex_id = LLVMGetParam(ctx->radeon_bld.main_fn,
2168 ctx->param_rel_auto_id);
2169 LLVMValueRef vertex_dw_stride =
2170 unpack_param(ctx, SI_PARAM_LS_OUT_LAYOUT, 13, 8);
2171 LLVMValueRef base_dw_addr = LLVMBuildMul(gallivm->builder, vertex_id,
2172 vertex_dw_stride, "");
2173
2174 /* Write outputs to LDS. The next shader (TCS aka HS) will read
2175 * its inputs from it. */
2176 for (i = 0; i < info->num_outputs; i++) {
2177 LLVMValueRef *out_ptr = ctx->radeon_bld.soa.outputs[i];
2178 unsigned name = info->output_semantic_name[i];
2179 unsigned index = info->output_semantic_index[i];
2180 int param = si_shader_io_get_unique_index(name, index);
2181 LLVMValueRef dw_addr = LLVMBuildAdd(gallivm->builder, base_dw_addr,
2182 lp_build_const_int32(gallivm, param * 4), "");
2183
2184 for (chan = 0; chan < 4; chan++) {
2185 lds_store(bld_base, chan, dw_addr,
2186 LLVMBuildLoad(gallivm->builder, out_ptr[chan], ""));
2187 }
2188 }
2189 }
2190
2191 static void si_llvm_emit_es_epilogue(struct lp_build_tgsi_context *bld_base)
2192 {
2193 struct si_shader_context *ctx = si_shader_context(bld_base);
2194 struct gallivm_state *gallivm = bld_base->base.gallivm;
2195 struct si_shader *es = ctx->shader;
2196 struct tgsi_shader_info *info = &es->selector->info;
2197 LLVMValueRef soffset = LLVMGetParam(ctx->radeon_bld.main_fn,
2198 ctx->param_es2gs_offset);
2199 unsigned chan;
2200 int i;
2201
2202 for (i = 0; i < info->num_outputs; i++) {
2203 LLVMValueRef *out_ptr =
2204 ctx->radeon_bld.soa.outputs[i];
2205 int param_index;
2206
2207 if (info->output_semantic_name[i] == TGSI_SEMANTIC_VIEWPORT_INDEX ||
2208 info->output_semantic_name[i] == TGSI_SEMANTIC_LAYER)
2209 continue;
2210
2211 param_index = si_shader_io_get_unique_index(info->output_semantic_name[i],
2212 info->output_semantic_index[i]);
2213
2214 for (chan = 0; chan < 4; chan++) {
2215 LLVMValueRef out_val = LLVMBuildLoad(gallivm->builder, out_ptr[chan], "");
2216 out_val = LLVMBuildBitCast(gallivm->builder, out_val, ctx->i32, "");
2217
2218 build_tbuffer_store(ctx,
2219 ctx->esgs_ring,
2220 out_val, 1,
2221 LLVMGetUndef(ctx->i32), soffset,
2222 (4 * param_index + chan) * 4,
2223 V_008F0C_BUF_DATA_FORMAT_32,
2224 V_008F0C_BUF_NUM_FORMAT_UINT,
2225 0, 0, 1, 1, 0);
2226 }
2227 }
2228 }
2229
2230 static void si_llvm_emit_gs_epilogue(struct lp_build_tgsi_context *bld_base)
2231 {
2232 struct si_shader_context *ctx = si_shader_context(bld_base);
2233 struct gallivm_state *gallivm = bld_base->base.gallivm;
2234 LLVMValueRef args[2];
2235
2236 args[0] = lp_build_const_int32(gallivm, SENDMSG_GS_OP_NOP | SENDMSG_GS_DONE);
2237 args[1] = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_GS_WAVE_ID);
2238 lp_build_intrinsic(gallivm->builder, "llvm.SI.sendmsg",
2239 ctx->voidt, args, 2, LLVMNoUnwindAttribute);
2240 }
2241
2242 static void si_llvm_emit_vs_epilogue(struct lp_build_tgsi_context *bld_base)
2243 {
2244 struct si_shader_context *ctx = si_shader_context(bld_base);
2245 struct gallivm_state *gallivm = bld_base->base.gallivm;
2246 struct tgsi_shader_info *info = &ctx->shader->selector->info;
2247 struct si_shader_output_values *outputs = NULL;
2248 int i,j;
2249
2250 assert(!ctx->is_gs_copy_shader);
2251
2252 outputs = MALLOC((info->num_outputs + 1) * sizeof(outputs[0]));
2253
2254 /* Vertex color clamping.
2255 *
2256 * This uses a state constant loaded in a user data SGPR and
2257 * an IF statement is added that clamps all colors if the constant
2258 * is true.
2259 */
2260 if (ctx->type == TGSI_PROCESSOR_VERTEX) {
2261 struct lp_build_if_state if_ctx;
2262 LLVMValueRef cond = NULL;
2263 LLVMValueRef addr, val;
2264
2265 for (i = 0; i < info->num_outputs; i++) {
2266 if (info->output_semantic_name[i] != TGSI_SEMANTIC_COLOR &&
2267 info->output_semantic_name[i] != TGSI_SEMANTIC_BCOLOR)
2268 continue;
2269
2270 /* We've found a color. */
2271 if (!cond) {
2272 /* The state is in the first bit of the user SGPR. */
2273 cond = LLVMGetParam(ctx->radeon_bld.main_fn,
2274 SI_PARAM_VS_STATE_BITS);
2275 cond = LLVMBuildTrunc(gallivm->builder, cond,
2276 ctx->i1, "");
2277 lp_build_if(&if_ctx, gallivm, cond);
2278 }
2279
2280 for (j = 0; j < 4; j++) {
2281 addr = ctx->radeon_bld.soa.outputs[i][j];
2282 val = LLVMBuildLoad(gallivm->builder, addr, "");
2283 val = radeon_llvm_saturate(bld_base, val);
2284 LLVMBuildStore(gallivm->builder, val, addr);
2285 }
2286 }
2287
2288 if (cond)
2289 lp_build_endif(&if_ctx);
2290 }
2291
2292 for (i = 0; i < info->num_outputs; i++) {
2293 outputs[i].name = info->output_semantic_name[i];
2294 outputs[i].sid = info->output_semantic_index[i];
2295
2296 for (j = 0; j < 4; j++)
2297 outputs[i].values[j] =
2298 LLVMBuildLoad(gallivm->builder,
2299 ctx->radeon_bld.soa.outputs[i][j],
2300 "");
2301 }
2302
2303 if (ctx->is_monolithic) {
2304 /* Export PrimitiveID when PS needs it. */
2305 if (si_vs_exports_prim_id(ctx->shader)) {
2306 outputs[i].name = TGSI_SEMANTIC_PRIMID;
2307 outputs[i].sid = 0;
2308 outputs[i].values[0] = bitcast(bld_base, TGSI_TYPE_FLOAT,
2309 get_primitive_id(bld_base, 0));
2310 outputs[i].values[1] = bld_base->base.undef;
2311 outputs[i].values[2] = bld_base->base.undef;
2312 outputs[i].values[3] = bld_base->base.undef;
2313 i++;
2314 }
2315 } else {
2316 /* Return the primitive ID from the LLVM function. */
2317 ctx->return_value =
2318 LLVMBuildInsertValue(gallivm->builder,
2319 ctx->return_value,
2320 bitcast(bld_base, TGSI_TYPE_FLOAT,
2321 get_primitive_id(bld_base, 0)),
2322 VS_EPILOG_PRIMID_LOC, "");
2323 }
2324
2325 si_llvm_export_vs(bld_base, outputs, i);
2326 FREE(outputs);
2327 }
2328
2329 static void si_export_mrt_z(struct lp_build_tgsi_context *bld_base,
2330 LLVMValueRef depth, LLVMValueRef stencil,
2331 LLVMValueRef samplemask)
2332 {
2333 struct si_shader_context *ctx = si_shader_context(bld_base);
2334 struct lp_build_context *base = &bld_base->base;
2335 struct lp_build_context *uint = &bld_base->uint_bld;
2336 LLVMValueRef args[9];
2337 unsigned mask = 0;
2338
2339 assert(depth || stencil || samplemask);
2340
2341 args[1] = uint->one; /* whether the EXEC mask is valid */
2342 args[2] = uint->one; /* DONE bit */
2343
2344 /* Specify the target we are exporting */
2345 args[3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_MRTZ);
2346
2347 args[4] = uint->zero; /* COMP flag */
2348 args[5] = base->undef; /* R, depth */
2349 args[6] = base->undef; /* G, stencil test value[0:7], stencil op value[8:15] */
2350 args[7] = base->undef; /* B, sample mask */
2351 args[8] = base->undef; /* A, alpha to mask */
2352
2353 if (depth) {
2354 args[5] = depth;
2355 mask |= 0x1;
2356 }
2357
2358 if (stencil) {
2359 args[6] = stencil;
2360 mask |= 0x2;
2361 }
2362
2363 if (samplemask) {
2364 args[7] = samplemask;
2365 mask |= 0x4;
2366 }
2367
2368 /* SI (except OLAND) has a bug that it only looks
2369 * at the X writemask component. */
2370 if (ctx->screen->b.chip_class == SI &&
2371 ctx->screen->b.family != CHIP_OLAND)
2372 mask |= 0x1;
2373
2374 /* Specify which components to enable */
2375 args[0] = lp_build_const_int32(base->gallivm, mask);
2376
2377 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
2378 ctx->voidt, args, 9, 0);
2379 }
2380
2381 static void si_export_mrt_color(struct lp_build_tgsi_context *bld_base,
2382 LLVMValueRef *color, unsigned index,
2383 unsigned samplemask_param,
2384 bool is_last)
2385 {
2386 struct si_shader_context *ctx = si_shader_context(bld_base);
2387 struct lp_build_context *base = &bld_base->base;
2388 int i;
2389
2390 /* Clamp color */
2391 if (ctx->shader->key.ps.epilog.clamp_color)
2392 for (i = 0; i < 4; i++)
2393 color[i] = radeon_llvm_saturate(bld_base, color[i]);
2394
2395 /* Alpha to one */
2396 if (ctx->shader->key.ps.epilog.alpha_to_one)
2397 color[3] = base->one;
2398
2399 /* Alpha test */
2400 if (index == 0 &&
2401 ctx->shader->key.ps.epilog.alpha_func != PIPE_FUNC_ALWAYS)
2402 si_alpha_test(bld_base, color[3]);
2403
2404 /* Line & polygon smoothing */
2405 if (ctx->shader->key.ps.epilog.poly_line_smoothing)
2406 color[3] = si_scale_alpha_by_sample_mask(bld_base, color[3],
2407 samplemask_param);
2408
2409 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
2410 if (ctx->shader->key.ps.epilog.last_cbuf > 0) {
2411 LLVMValueRef args[8][9];
2412 int c, last = -1;
2413
2414 /* Get the export arguments, also find out what the last one is. */
2415 for (c = 0; c <= ctx->shader->key.ps.epilog.last_cbuf; c++) {
2416 si_llvm_init_export_args(bld_base, color,
2417 V_008DFC_SQ_EXP_MRT + c, args[c]);
2418 if (args[c][0] != bld_base->uint_bld.zero)
2419 last = c;
2420 }
2421
2422 /* Emit all exports. */
2423 for (c = 0; c <= ctx->shader->key.ps.epilog.last_cbuf; c++) {
2424 if (is_last && last == c) {
2425 args[c][1] = bld_base->uint_bld.one; /* whether the EXEC mask is valid */
2426 args[c][2] = bld_base->uint_bld.one; /* DONE bit */
2427 } else if (args[c][0] == bld_base->uint_bld.zero)
2428 continue; /* unnecessary NULL export */
2429
2430 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
2431 ctx->voidt, args[c], 9, 0);
2432 }
2433 } else {
2434 LLVMValueRef args[9];
2435
2436 /* Export */
2437 si_llvm_init_export_args(bld_base, color, V_008DFC_SQ_EXP_MRT + index,
2438 args);
2439 if (is_last) {
2440 args[1] = bld_base->uint_bld.one; /* whether the EXEC mask is valid */
2441 args[2] = bld_base->uint_bld.one; /* DONE bit */
2442 } else if (args[0] == bld_base->uint_bld.zero)
2443 return; /* unnecessary NULL export */
2444
2445 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
2446 ctx->voidt, args, 9, 0);
2447 }
2448 }
2449
2450 static void si_export_null(struct lp_build_tgsi_context *bld_base)
2451 {
2452 struct si_shader_context *ctx = si_shader_context(bld_base);
2453 struct lp_build_context *base = &bld_base->base;
2454 struct lp_build_context *uint = &bld_base->uint_bld;
2455 LLVMValueRef args[9];
2456
2457 args[0] = lp_build_const_int32(base->gallivm, 0x0); /* enabled channels */
2458 args[1] = uint->one; /* whether the EXEC mask is valid */
2459 args[2] = uint->one; /* DONE bit */
2460 args[3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_NULL);
2461 args[4] = uint->zero; /* COMPR flag (0 = 32-bit export) */
2462 args[5] = uint->undef; /* R */
2463 args[6] = uint->undef; /* G */
2464 args[7] = uint->undef; /* B */
2465 args[8] = uint->undef; /* A */
2466
2467 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
2468 ctx->voidt, args, 9, 0);
2469 }
2470
2471 static void si_llvm_emit_fs_epilogue(struct lp_build_tgsi_context *bld_base)
2472 {
2473 struct si_shader_context *ctx = si_shader_context(bld_base);
2474 struct si_shader *shader = ctx->shader;
2475 struct lp_build_context *base = &bld_base->base;
2476 struct tgsi_shader_info *info = &shader->selector->info;
2477 LLVMBuilderRef builder = base->gallivm->builder;
2478 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
2479 int last_color_export = -1;
2480 int i;
2481
2482 /* Determine the last export. If MRTZ is present, it's always last.
2483 * Otherwise, find the last color export.
2484 */
2485 if (!info->writes_z && !info->writes_stencil && !info->writes_samplemask) {
2486 unsigned spi_format = shader->key.ps.epilog.spi_shader_col_format;
2487
2488 /* Don't export NULL and return if alpha-test is enabled. */
2489 if (shader->key.ps.epilog.alpha_func != PIPE_FUNC_ALWAYS &&
2490 shader->key.ps.epilog.alpha_func != PIPE_FUNC_NEVER &&
2491 (spi_format & 0xf) == 0)
2492 spi_format |= V_028714_SPI_SHADER_32_AR;
2493
2494 for (i = 0; i < info->num_outputs; i++) {
2495 unsigned index = info->output_semantic_index[i];
2496
2497 if (info->output_semantic_name[i] != TGSI_SEMANTIC_COLOR)
2498 continue;
2499
2500 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
2501 if (shader->key.ps.epilog.last_cbuf > 0) {
2502 /* Just set this if any of the colorbuffers are enabled. */
2503 if (spi_format &
2504 ((1llu << (4 * (shader->key.ps.epilog.last_cbuf + 1))) - 1))
2505 last_color_export = i;
2506 continue;
2507 }
2508
2509 if ((spi_format >> (index * 4)) & 0xf)
2510 last_color_export = i;
2511 }
2512
2513 /* If there are no outputs, export NULL. */
2514 if (last_color_export == -1) {
2515 si_export_null(bld_base);
2516 return;
2517 }
2518 }
2519
2520 for (i = 0; i < info->num_outputs; i++) {
2521 unsigned semantic_name = info->output_semantic_name[i];
2522 unsigned semantic_index = info->output_semantic_index[i];
2523 unsigned j;
2524 LLVMValueRef color[4] = {};
2525
2526 /* Select the correct target */
2527 switch (semantic_name) {
2528 case TGSI_SEMANTIC_POSITION:
2529 depth = LLVMBuildLoad(builder,
2530 ctx->radeon_bld.soa.outputs[i][2], "");
2531 break;
2532 case TGSI_SEMANTIC_STENCIL:
2533 stencil = LLVMBuildLoad(builder,
2534 ctx->radeon_bld.soa.outputs[i][1], "");
2535 break;
2536 case TGSI_SEMANTIC_SAMPLEMASK:
2537 samplemask = LLVMBuildLoad(builder,
2538 ctx->radeon_bld.soa.outputs[i][0], "");
2539 break;
2540 case TGSI_SEMANTIC_COLOR:
2541 for (j = 0; j < 4; j++)
2542 color[j] = LLVMBuildLoad(builder,
2543 ctx->radeon_bld.soa.outputs[i][j], "");
2544
2545 si_export_mrt_color(bld_base, color, semantic_index,
2546 SI_PARAM_SAMPLE_COVERAGE,
2547 last_color_export == i);
2548 break;
2549 default:
2550 fprintf(stderr,
2551 "Warning: SI unhandled fs output type:%d\n",
2552 semantic_name);
2553 }
2554 }
2555
2556 if (depth || stencil || samplemask)
2557 si_export_mrt_z(bld_base, depth, stencil, samplemask);
2558 }
2559
2560 /**
2561 * Return PS outputs in this order:
2562 *
2563 * v[0:3] = color0.xyzw
2564 * v[4:7] = color1.xyzw
2565 * ...
2566 * vN+0 = Depth
2567 * vN+1 = Stencil
2568 * vN+2 = SampleMask
2569 * vN+3 = SampleMaskIn (used for OpenGL smoothing)
2570 *
2571 * The alpha-ref SGPR is returned via its original location.
2572 */
2573 static void si_llvm_return_fs_outputs(struct lp_build_tgsi_context *bld_base)
2574 {
2575 struct si_shader_context *ctx = si_shader_context(bld_base);
2576 struct si_shader *shader = ctx->shader;
2577 struct lp_build_context *base = &bld_base->base;
2578 struct tgsi_shader_info *info = &shader->selector->info;
2579 LLVMBuilderRef builder = base->gallivm->builder;
2580 unsigned i, j, first_vgpr, vgpr;
2581
2582 LLVMValueRef color[8][4] = {};
2583 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
2584 LLVMValueRef ret;
2585
2586 /* Read the output values. */
2587 for (i = 0; i < info->num_outputs; i++) {
2588 unsigned semantic_name = info->output_semantic_name[i];
2589 unsigned semantic_index = info->output_semantic_index[i];
2590
2591 switch (semantic_name) {
2592 case TGSI_SEMANTIC_COLOR:
2593 assert(semantic_index < 8);
2594 for (j = 0; j < 4; j++) {
2595 LLVMValueRef ptr = ctx->radeon_bld.soa.outputs[i][j];
2596 LLVMValueRef result = LLVMBuildLoad(builder, ptr, "");
2597 color[semantic_index][j] = result;
2598 }
2599 break;
2600 case TGSI_SEMANTIC_POSITION:
2601 depth = LLVMBuildLoad(builder,
2602 ctx->radeon_bld.soa.outputs[i][2], "");
2603 break;
2604 case TGSI_SEMANTIC_STENCIL:
2605 stencil = LLVMBuildLoad(builder,
2606 ctx->radeon_bld.soa.outputs[i][1], "");
2607 break;
2608 case TGSI_SEMANTIC_SAMPLEMASK:
2609 samplemask = LLVMBuildLoad(builder,
2610 ctx->radeon_bld.soa.outputs[i][0], "");
2611 break;
2612 default:
2613 fprintf(stderr, "Warning: SI unhandled fs output type:%d\n",
2614 semantic_name);
2615 }
2616 }
2617
2618 /* Fill the return structure. */
2619 ret = ctx->return_value;
2620
2621 /* Set SGPRs. */
2622 ret = LLVMBuildInsertValue(builder, ret,
2623 bitcast(bld_base, TGSI_TYPE_SIGNED,
2624 LLVMGetParam(ctx->radeon_bld.main_fn,
2625 SI_PARAM_ALPHA_REF)),
2626 SI_SGPR_ALPHA_REF, "");
2627
2628 /* Set VGPRs */
2629 first_vgpr = vgpr = SI_SGPR_ALPHA_REF + 1;
2630 for (i = 0; i < ARRAY_SIZE(color); i++) {
2631 if (!color[i][0])
2632 continue;
2633
2634 for (j = 0; j < 4; j++)
2635 ret = LLVMBuildInsertValue(builder, ret, color[i][j], vgpr++, "");
2636 }
2637 if (depth)
2638 ret = LLVMBuildInsertValue(builder, ret, depth, vgpr++, "");
2639 if (stencil)
2640 ret = LLVMBuildInsertValue(builder, ret, stencil, vgpr++, "");
2641 if (samplemask)
2642 ret = LLVMBuildInsertValue(builder, ret, samplemask, vgpr++, "");
2643
2644 /* Add the input sample mask for smoothing at the end. */
2645 if (vgpr < first_vgpr + PS_EPILOG_SAMPLEMASK_MIN_LOC)
2646 vgpr = first_vgpr + PS_EPILOG_SAMPLEMASK_MIN_LOC;
2647 ret = LLVMBuildInsertValue(builder, ret,
2648 LLVMGetParam(ctx->radeon_bld.main_fn,
2649 SI_PARAM_SAMPLE_COVERAGE), vgpr++, "");
2650
2651 ctx->return_value = ret;
2652 }
2653
2654 static void build_tex_intrinsic(const struct lp_build_tgsi_action *action,
2655 struct lp_build_tgsi_context *bld_base,
2656 struct lp_build_emit_data *emit_data);
2657
2658 static bool tgsi_is_array_sampler(unsigned target)
2659 {
2660 return target == TGSI_TEXTURE_1D_ARRAY ||
2661 target == TGSI_TEXTURE_SHADOW1D_ARRAY ||
2662 target == TGSI_TEXTURE_2D_ARRAY ||
2663 target == TGSI_TEXTURE_SHADOW2D_ARRAY ||
2664 target == TGSI_TEXTURE_CUBE_ARRAY ||
2665 target == TGSI_TEXTURE_SHADOWCUBE_ARRAY ||
2666 target == TGSI_TEXTURE_2D_ARRAY_MSAA;
2667 }
2668
2669 static void set_tex_fetch_args(struct si_shader_context *ctx,
2670 struct lp_build_emit_data *emit_data,
2671 unsigned opcode, unsigned target,
2672 LLVMValueRef res_ptr, LLVMValueRef samp_ptr,
2673 LLVMValueRef *param, unsigned count,
2674 unsigned dmask)
2675 {
2676 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
2677 unsigned num_args;
2678 unsigned is_rect = target == TGSI_TEXTURE_RECT;
2679
2680 /* Pad to power of two vector */
2681 while (count < util_next_power_of_two(count))
2682 param[count++] = LLVMGetUndef(ctx->i32);
2683
2684 /* Texture coordinates. */
2685 if (count > 1)
2686 emit_data->args[0] = lp_build_gather_values(gallivm, param, count);
2687 else
2688 emit_data->args[0] = param[0];
2689
2690 /* Resource. */
2691 emit_data->args[1] = res_ptr;
2692 num_args = 2;
2693
2694 if (opcode == TGSI_OPCODE_TXF || opcode == TGSI_OPCODE_TXQ)
2695 emit_data->dst_type = ctx->v4i32;
2696 else {
2697 emit_data->dst_type = ctx->v4f32;
2698
2699 emit_data->args[num_args++] = samp_ptr;
2700 }
2701
2702 emit_data->args[num_args++] = lp_build_const_int32(gallivm, dmask);
2703 emit_data->args[num_args++] = lp_build_const_int32(gallivm, is_rect); /* unorm */
2704 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* r128 */
2705 emit_data->args[num_args++] = lp_build_const_int32(gallivm,
2706 tgsi_is_array_sampler(target)); /* da */
2707 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* glc */
2708 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* slc */
2709 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* tfe */
2710 emit_data->args[num_args++] = lp_build_const_int32(gallivm, 0); /* lwe */
2711
2712 emit_data->arg_count = num_args;
2713 }
2714
2715 static const struct lp_build_tgsi_action tex_action;
2716
2717 enum desc_type {
2718 DESC_IMAGE,
2719 DESC_FMASK,
2720 DESC_SAMPLER
2721 };
2722
2723 static LLVMTypeRef const_array(LLVMTypeRef elem_type, int num_elements)
2724 {
2725 return LLVMPointerType(LLVMArrayType(elem_type, num_elements),
2726 CONST_ADDR_SPACE);
2727 }
2728
2729 /**
2730 * Load an image view, fmask view. or sampler state descriptor.
2731 */
2732 static LLVMValueRef get_sampler_desc(struct si_shader_context *ctx,
2733 LLVMValueRef index, enum desc_type type)
2734 {
2735 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
2736 LLVMBuilderRef builder = gallivm->builder;
2737 LLVMValueRef ptr = LLVMGetParam(ctx->radeon_bld.main_fn,
2738 SI_PARAM_SAMPLERS);
2739
2740 switch (type) {
2741 case DESC_IMAGE:
2742 /* The image is at [0:7]. */
2743 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 2, 0), "");
2744 break;
2745 case DESC_FMASK:
2746 /* The FMASK is at [8:15]. */
2747 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 2, 0), "");
2748 index = LLVMBuildAdd(builder, index, LLVMConstInt(ctx->i32, 1, 0), "");
2749 break;
2750 case DESC_SAMPLER:
2751 /* The sampler state is at [12:15]. */
2752 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
2753 index = LLVMBuildAdd(builder, index, LLVMConstInt(ctx->i32, 3, 0), "");
2754 ptr = LLVMBuildPointerCast(builder, ptr,
2755 const_array(ctx->v4i32, 0), "");
2756 break;
2757 }
2758
2759 return build_indexed_load_const(ctx, ptr, index);
2760 }
2761
2762 static void tex_fetch_ptrs(
2763 struct lp_build_tgsi_context *bld_base,
2764 struct lp_build_emit_data *emit_data,
2765 LLVMValueRef *res_ptr, LLVMValueRef *samp_ptr, LLVMValueRef *fmask_ptr)
2766 {
2767 struct si_shader_context *ctx = si_shader_context(bld_base);
2768 const struct tgsi_full_instruction *inst = emit_data->inst;
2769 unsigned target = inst->Texture.Texture;
2770 unsigned sampler_src;
2771 unsigned sampler_index;
2772
2773 sampler_src = emit_data->inst->Instruction.NumSrcRegs - 1;
2774 sampler_index = emit_data->inst->Src[sampler_src].Register.Index;
2775
2776 if (emit_data->inst->Src[sampler_src].Register.Indirect) {
2777 const struct tgsi_full_src_register *reg = &emit_data->inst->Src[sampler_src];
2778 LLVMValueRef ind_index;
2779
2780 ind_index = get_indirect_index(ctx, &reg->Indirect, reg->Register.Index);
2781
2782 *res_ptr = get_sampler_desc(ctx, ind_index, DESC_IMAGE);
2783
2784 if (target == TGSI_TEXTURE_2D_MSAA ||
2785 target == TGSI_TEXTURE_2D_ARRAY_MSAA) {
2786 *samp_ptr = NULL;
2787 *fmask_ptr = get_sampler_desc(ctx, ind_index, DESC_FMASK);
2788 } else {
2789 *samp_ptr = get_sampler_desc(ctx, ind_index, DESC_SAMPLER);
2790 *fmask_ptr = NULL;
2791 }
2792 } else {
2793 *res_ptr = ctx->sampler_views[sampler_index];
2794 *samp_ptr = ctx->sampler_states[sampler_index];
2795 *fmask_ptr = ctx->fmasks[sampler_index];
2796 }
2797 }
2798
2799 static void tex_fetch_args(
2800 struct lp_build_tgsi_context *bld_base,
2801 struct lp_build_emit_data *emit_data)
2802 {
2803 struct si_shader_context *ctx = si_shader_context(bld_base);
2804 struct gallivm_state *gallivm = bld_base->base.gallivm;
2805 LLVMBuilderRef builder = gallivm->builder;
2806 const struct tgsi_full_instruction *inst = emit_data->inst;
2807 unsigned opcode = inst->Instruction.Opcode;
2808 unsigned target = inst->Texture.Texture;
2809 LLVMValueRef coords[5], derivs[6];
2810 LLVMValueRef address[16];
2811 int ref_pos;
2812 unsigned num_coords = tgsi_util_get_texture_coord_dim(target, &ref_pos);
2813 unsigned count = 0;
2814 unsigned chan;
2815 unsigned num_deriv_channels = 0;
2816 bool has_offset = inst->Texture.NumOffsets > 0;
2817 LLVMValueRef res_ptr, samp_ptr, fmask_ptr = NULL;
2818 unsigned dmask = 0xf;
2819
2820 tex_fetch_ptrs(bld_base, emit_data, &res_ptr, &samp_ptr, &fmask_ptr);
2821
2822 if (opcode == TGSI_OPCODE_TXQ) {
2823 if (target == TGSI_TEXTURE_BUFFER) {
2824 /* Read the size from the buffer descriptor directly. */
2825 LLVMValueRef res = LLVMBuildBitCast(builder, res_ptr, ctx->v8i32, "");
2826 LLVMValueRef size = LLVMBuildExtractElement(builder, res,
2827 lp_build_const_int32(gallivm, 6), "");
2828
2829 if (ctx->screen->b.chip_class >= VI) {
2830 /* On VI, the descriptor contains the size in bytes,
2831 * but TXQ must return the size in elements.
2832 * The stride is always non-zero for resources using TXQ.
2833 */
2834 LLVMValueRef stride =
2835 LLVMBuildExtractElement(builder, res,
2836 lp_build_const_int32(gallivm, 5), "");
2837 stride = LLVMBuildLShr(builder, stride,
2838 lp_build_const_int32(gallivm, 16), "");
2839 stride = LLVMBuildAnd(builder, stride,
2840 lp_build_const_int32(gallivm, 0x3FFF), "");
2841
2842 size = LLVMBuildUDiv(builder, size, stride, "");
2843 }
2844
2845 emit_data->args[0] = size;
2846 return;
2847 }
2848
2849 /* Textures - set the mip level. */
2850 address[count++] = lp_build_emit_fetch(bld_base, inst, 0, TGSI_CHAN_X);
2851
2852 set_tex_fetch_args(ctx, emit_data, opcode, target, res_ptr,
2853 NULL, address, count, 0xf);
2854 return;
2855 }
2856
2857 if (target == TGSI_TEXTURE_BUFFER) {
2858 LLVMTypeRef v2i128 = LLVMVectorType(ctx->i128, 2);
2859
2860 /* Bitcast and truncate v8i32 to v16i8. */
2861 LLVMValueRef res = res_ptr;
2862 res = LLVMBuildBitCast(gallivm->builder, res, v2i128, "");
2863 res = LLVMBuildExtractElement(gallivm->builder, res, bld_base->uint_bld.one, "");
2864 res = LLVMBuildBitCast(gallivm->builder, res, ctx->v16i8, "");
2865
2866 emit_data->dst_type = ctx->v4f32;
2867 emit_data->args[0] = res;
2868 emit_data->args[1] = bld_base->uint_bld.zero;
2869 emit_data->args[2] = lp_build_emit_fetch(bld_base, emit_data->inst, 0, TGSI_CHAN_X);
2870 emit_data->arg_count = 3;
2871 return;
2872 }
2873
2874 /* Fetch and project texture coordinates */
2875 coords[3] = lp_build_emit_fetch(bld_base, emit_data->inst, 0, TGSI_CHAN_W);
2876 for (chan = 0; chan < 3; chan++ ) {
2877 coords[chan] = lp_build_emit_fetch(bld_base,
2878 emit_data->inst, 0,
2879 chan);
2880 if (opcode == TGSI_OPCODE_TXP)
2881 coords[chan] = lp_build_emit_llvm_binary(bld_base,
2882 TGSI_OPCODE_DIV,
2883 coords[chan],
2884 coords[3]);
2885 }
2886
2887 if (opcode == TGSI_OPCODE_TXP)
2888 coords[3] = bld_base->base.one;
2889
2890 /* Pack offsets. */
2891 if (has_offset && opcode != TGSI_OPCODE_TXF) {
2892 /* The offsets are six-bit signed integers packed like this:
2893 * X=[5:0], Y=[13:8], and Z=[21:16].
2894 */
2895 LLVMValueRef offset[3], pack;
2896
2897 assert(inst->Texture.NumOffsets == 1);
2898
2899 for (chan = 0; chan < 3; chan++) {
2900 offset[chan] = lp_build_emit_fetch_texoffset(bld_base,
2901 emit_data->inst, 0, chan);
2902 offset[chan] = LLVMBuildAnd(gallivm->builder, offset[chan],
2903 lp_build_const_int32(gallivm, 0x3f), "");
2904 if (chan)
2905 offset[chan] = LLVMBuildShl(gallivm->builder, offset[chan],
2906 lp_build_const_int32(gallivm, chan*8), "");
2907 }
2908
2909 pack = LLVMBuildOr(gallivm->builder, offset[0], offset[1], "");
2910 pack = LLVMBuildOr(gallivm->builder, pack, offset[2], "");
2911 address[count++] = pack;
2912 }
2913
2914 /* Pack LOD bias value */
2915 if (opcode == TGSI_OPCODE_TXB)
2916 address[count++] = coords[3];
2917 if (opcode == TGSI_OPCODE_TXB2)
2918 address[count++] = lp_build_emit_fetch(bld_base, inst, 1, TGSI_CHAN_X);
2919
2920 /* Pack depth comparison value */
2921 if (tgsi_is_shadow_target(target) && opcode != TGSI_OPCODE_LODQ) {
2922 if (target == TGSI_TEXTURE_SHADOWCUBE_ARRAY) {
2923 address[count++] = lp_build_emit_fetch(bld_base, inst, 1, TGSI_CHAN_X);
2924 } else {
2925 assert(ref_pos >= 0);
2926 address[count++] = coords[ref_pos];
2927 }
2928 }
2929
2930 /* Pack user derivatives */
2931 if (opcode == TGSI_OPCODE_TXD) {
2932 int param, num_src_deriv_channels;
2933
2934 switch (target) {
2935 case TGSI_TEXTURE_3D:
2936 num_src_deriv_channels = 3;
2937 num_deriv_channels = 3;
2938 break;
2939 case TGSI_TEXTURE_2D:
2940 case TGSI_TEXTURE_SHADOW2D:
2941 case TGSI_TEXTURE_RECT:
2942 case TGSI_TEXTURE_SHADOWRECT:
2943 case TGSI_TEXTURE_2D_ARRAY:
2944 case TGSI_TEXTURE_SHADOW2D_ARRAY:
2945 num_src_deriv_channels = 2;
2946 num_deriv_channels = 2;
2947 break;
2948 case TGSI_TEXTURE_CUBE:
2949 case TGSI_TEXTURE_SHADOWCUBE:
2950 case TGSI_TEXTURE_CUBE_ARRAY:
2951 case TGSI_TEXTURE_SHADOWCUBE_ARRAY:
2952 /* Cube derivatives will be converted to 2D. */
2953 num_src_deriv_channels = 3;
2954 num_deriv_channels = 2;
2955 break;
2956 case TGSI_TEXTURE_1D:
2957 case TGSI_TEXTURE_SHADOW1D:
2958 case TGSI_TEXTURE_1D_ARRAY:
2959 case TGSI_TEXTURE_SHADOW1D_ARRAY:
2960 num_src_deriv_channels = 1;
2961 num_deriv_channels = 1;
2962 break;
2963 default:
2964 unreachable("invalid target");
2965 }
2966
2967 for (param = 0; param < 2; param++)
2968 for (chan = 0; chan < num_src_deriv_channels; chan++)
2969 derivs[param * num_src_deriv_channels + chan] =
2970 lp_build_emit_fetch(bld_base, inst, param+1, chan);
2971 }
2972
2973 if (target == TGSI_TEXTURE_CUBE ||
2974 target == TGSI_TEXTURE_CUBE_ARRAY ||
2975 target == TGSI_TEXTURE_SHADOWCUBE ||
2976 target == TGSI_TEXTURE_SHADOWCUBE_ARRAY)
2977 radeon_llvm_emit_prepare_cube_coords(bld_base, emit_data, coords, derivs);
2978
2979 if (opcode == TGSI_OPCODE_TXD)
2980 for (int i = 0; i < num_deriv_channels * 2; i++)
2981 address[count++] = derivs[i];
2982
2983 /* Pack texture coordinates */
2984 address[count++] = coords[0];
2985 if (num_coords > 1)
2986 address[count++] = coords[1];
2987 if (num_coords > 2)
2988 address[count++] = coords[2];
2989
2990 /* Pack LOD or sample index */
2991 if (opcode == TGSI_OPCODE_TXL || opcode == TGSI_OPCODE_TXF)
2992 address[count++] = coords[3];
2993 else if (opcode == TGSI_OPCODE_TXL2)
2994 address[count++] = lp_build_emit_fetch(bld_base, inst, 1, TGSI_CHAN_X);
2995
2996 if (count > 16) {
2997 assert(!"Cannot handle more than 16 texture address parameters");
2998 count = 16;
2999 }
3000
3001 for (chan = 0; chan < count; chan++ ) {
3002 address[chan] = LLVMBuildBitCast(gallivm->builder,
3003 address[chan], ctx->i32, "");
3004 }
3005
3006 /* Adjust the sample index according to FMASK.
3007 *
3008 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
3009 * which is the identity mapping. Each nibble says which physical sample
3010 * should be fetched to get that sample.
3011 *
3012 * For example, 0x11111100 means there are only 2 samples stored and
3013 * the second sample covers 3/4 of the pixel. When reading samples 0
3014 * and 1, return physical sample 0 (determined by the first two 0s
3015 * in FMASK), otherwise return physical sample 1.
3016 *
3017 * The sample index should be adjusted as follows:
3018 * sample_index = (fmask >> (sample_index * 4)) & 0xF;
3019 */
3020 if (target == TGSI_TEXTURE_2D_MSAA ||
3021 target == TGSI_TEXTURE_2D_ARRAY_MSAA) {
3022 struct lp_build_context *uint_bld = &bld_base->uint_bld;
3023 struct lp_build_emit_data txf_emit_data = *emit_data;
3024 LLVMValueRef txf_address[4];
3025 unsigned txf_count = count;
3026 struct tgsi_full_instruction inst = {};
3027
3028 memcpy(txf_address, address, sizeof(txf_address));
3029
3030 if (target == TGSI_TEXTURE_2D_MSAA) {
3031 txf_address[2] = bld_base->uint_bld.zero;
3032 }
3033 txf_address[3] = bld_base->uint_bld.zero;
3034
3035 /* Read FMASK using TXF. */
3036 inst.Instruction.Opcode = TGSI_OPCODE_TXF;
3037 inst.Texture.Texture = target;
3038 txf_emit_data.inst = &inst;
3039 txf_emit_data.chan = 0;
3040 set_tex_fetch_args(ctx, &txf_emit_data, TGSI_OPCODE_TXF,
3041 target, fmask_ptr, NULL,
3042 txf_address, txf_count, 0xf);
3043 build_tex_intrinsic(&tex_action, bld_base, &txf_emit_data);
3044
3045 /* Initialize some constants. */
3046 LLVMValueRef four = LLVMConstInt(ctx->i32, 4, 0);
3047 LLVMValueRef F = LLVMConstInt(ctx->i32, 0xF, 0);
3048
3049 /* Apply the formula. */
3050 LLVMValueRef fmask =
3051 LLVMBuildExtractElement(gallivm->builder,
3052 txf_emit_data.output[0],
3053 uint_bld->zero, "");
3054
3055 unsigned sample_chan = target == TGSI_TEXTURE_2D_MSAA ? 2 : 3;
3056
3057 LLVMValueRef sample_index4 =
3058 LLVMBuildMul(gallivm->builder, address[sample_chan], four, "");
3059
3060 LLVMValueRef shifted_fmask =
3061 LLVMBuildLShr(gallivm->builder, fmask, sample_index4, "");
3062
3063 LLVMValueRef final_sample =
3064 LLVMBuildAnd(gallivm->builder, shifted_fmask, F, "");
3065
3066 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
3067 * resource descriptor is 0 (invalid),
3068 */
3069 LLVMValueRef fmask_desc =
3070 LLVMBuildBitCast(gallivm->builder, fmask_ptr,
3071 ctx->v8i32, "");
3072
3073 LLVMValueRef fmask_word1 =
3074 LLVMBuildExtractElement(gallivm->builder, fmask_desc,
3075 uint_bld->one, "");
3076
3077 LLVMValueRef word1_is_nonzero =
3078 LLVMBuildICmp(gallivm->builder, LLVMIntNE,
3079 fmask_word1, uint_bld->zero, "");
3080
3081 /* Replace the MSAA sample index. */
3082 address[sample_chan] =
3083 LLVMBuildSelect(gallivm->builder, word1_is_nonzero,
3084 final_sample, address[sample_chan], "");
3085 }
3086
3087 if (opcode == TGSI_OPCODE_TXF) {
3088 /* add tex offsets */
3089 if (inst->Texture.NumOffsets) {
3090 struct lp_build_context *uint_bld = &bld_base->uint_bld;
3091 struct lp_build_tgsi_soa_context *bld = lp_soa_context(bld_base);
3092 const struct tgsi_texture_offset *off = inst->TexOffsets;
3093
3094 assert(inst->Texture.NumOffsets == 1);
3095
3096 switch (target) {
3097 case TGSI_TEXTURE_3D:
3098 address[2] = lp_build_add(uint_bld, address[2],
3099 bld->immediates[off->Index][off->SwizzleZ]);
3100 /* fall through */
3101 case TGSI_TEXTURE_2D:
3102 case TGSI_TEXTURE_SHADOW2D:
3103 case TGSI_TEXTURE_RECT:
3104 case TGSI_TEXTURE_SHADOWRECT:
3105 case TGSI_TEXTURE_2D_ARRAY:
3106 case TGSI_TEXTURE_SHADOW2D_ARRAY:
3107 address[1] =
3108 lp_build_add(uint_bld, address[1],
3109 bld->immediates[off->Index][off->SwizzleY]);
3110 /* fall through */
3111 case TGSI_TEXTURE_1D:
3112 case TGSI_TEXTURE_SHADOW1D:
3113 case TGSI_TEXTURE_1D_ARRAY:
3114 case TGSI_TEXTURE_SHADOW1D_ARRAY:
3115 address[0] =
3116 lp_build_add(uint_bld, address[0],
3117 bld->immediates[off->Index][off->SwizzleX]);
3118 break;
3119 /* texture offsets do not apply to other texture targets */
3120 }
3121 }
3122 }
3123
3124 if (opcode == TGSI_OPCODE_TG4) {
3125 unsigned gather_comp = 0;
3126
3127 /* DMASK was repurposed for GATHER4. 4 components are always
3128 * returned and DMASK works like a swizzle - it selects
3129 * the component to fetch. The only valid DMASK values are
3130 * 1=red, 2=green, 4=blue, 8=alpha. (e.g. 1 returns
3131 * (red,red,red,red) etc.) The ISA document doesn't mention
3132 * this.
3133 */
3134
3135 /* Get the component index from src1.x for Gather4. */
3136 if (!tgsi_is_shadow_target(target)) {
3137 LLVMValueRef (*imms)[4] = lp_soa_context(bld_base)->immediates;
3138 LLVMValueRef comp_imm;
3139 struct tgsi_src_register src1 = inst->Src[1].Register;
3140
3141 assert(src1.File == TGSI_FILE_IMMEDIATE);
3142
3143 comp_imm = imms[src1.Index][src1.SwizzleX];
3144 gather_comp = LLVMConstIntGetZExtValue(comp_imm);
3145 gather_comp = CLAMP(gather_comp, 0, 3);
3146 }
3147
3148 dmask = 1 << gather_comp;
3149 }
3150
3151 set_tex_fetch_args(ctx, emit_data, opcode, target, res_ptr,
3152 samp_ptr, address, count, dmask);
3153 }
3154
3155 static void build_tex_intrinsic(const struct lp_build_tgsi_action *action,
3156 struct lp_build_tgsi_context *bld_base,
3157 struct lp_build_emit_data *emit_data)
3158 {
3159 struct lp_build_context *base = &bld_base->base;
3160 unsigned opcode = emit_data->inst->Instruction.Opcode;
3161 unsigned target = emit_data->inst->Texture.Texture;
3162 char intr_name[127];
3163 bool has_offset = emit_data->inst->Texture.NumOffsets > 0;
3164 bool is_shadow = tgsi_is_shadow_target(target);
3165 char type[64];
3166 const char *name = "llvm.SI.image.sample";
3167 const char *infix = "";
3168
3169 if (opcode == TGSI_OPCODE_TXQ && target == TGSI_TEXTURE_BUFFER) {
3170 /* Just return the buffer size. */
3171 emit_data->output[emit_data->chan] = emit_data->args[0];
3172 return;
3173 }
3174
3175 if (target == TGSI_TEXTURE_BUFFER) {
3176 emit_data->output[emit_data->chan] = lp_build_intrinsic(
3177 base->gallivm->builder,
3178 "llvm.SI.vs.load.input", emit_data->dst_type,
3179 emit_data->args, emit_data->arg_count,
3180 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
3181 return;
3182 }
3183
3184 switch (opcode) {
3185 case TGSI_OPCODE_TXF:
3186 name = target == TGSI_TEXTURE_2D_MSAA ||
3187 target == TGSI_TEXTURE_2D_ARRAY_MSAA ?
3188 "llvm.SI.image.load" :
3189 "llvm.SI.image.load.mip";
3190 is_shadow = false;
3191 has_offset = false;
3192 break;
3193 case TGSI_OPCODE_TXQ:
3194 name = "llvm.SI.getresinfo";
3195 is_shadow = false;
3196 has_offset = false;
3197 break;
3198 case TGSI_OPCODE_LODQ:
3199 name = "llvm.SI.getlod";
3200 is_shadow = false;
3201 has_offset = false;
3202 break;
3203 case TGSI_OPCODE_TEX:
3204 case TGSI_OPCODE_TEX2:
3205 case TGSI_OPCODE_TXP:
3206 break;
3207 case TGSI_OPCODE_TXB:
3208 case TGSI_OPCODE_TXB2:
3209 infix = ".b";
3210 break;
3211 case TGSI_OPCODE_TXL:
3212 case TGSI_OPCODE_TXL2:
3213 infix = ".l";
3214 break;
3215 case TGSI_OPCODE_TXD:
3216 infix = ".d";
3217 break;
3218 case TGSI_OPCODE_TG4:
3219 name = "llvm.SI.gather4";
3220 break;
3221 default:
3222 assert(0);
3223 return;
3224 }
3225
3226 if (LLVMGetTypeKind(LLVMTypeOf(emit_data->args[0])) == LLVMVectorTypeKind)
3227 sprintf(type, ".v%ui32",
3228 LLVMGetVectorSize(LLVMTypeOf(emit_data->args[0])));
3229 else
3230 strcpy(type, ".i32");
3231
3232 /* Add the type and suffixes .c, .o if needed. */
3233 sprintf(intr_name, "%s%s%s%s%s",
3234 name, is_shadow ? ".c" : "", infix,
3235 has_offset ? ".o" : "", type);
3236
3237 emit_data->output[emit_data->chan] = lp_build_intrinsic(
3238 base->gallivm->builder, intr_name, emit_data->dst_type,
3239 emit_data->args, emit_data->arg_count,
3240 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
3241
3242 /* Divide the number of layers by 6 to get the number of cubes. */
3243 if (opcode == TGSI_OPCODE_TXQ &&
3244 (target == TGSI_TEXTURE_CUBE_ARRAY ||
3245 target == TGSI_TEXTURE_SHADOWCUBE_ARRAY)) {
3246 LLVMBuilderRef builder = bld_base->base.gallivm->builder;
3247 LLVMValueRef two = lp_build_const_int32(bld_base->base.gallivm, 2);
3248 LLVMValueRef six = lp_build_const_int32(bld_base->base.gallivm, 6);
3249
3250 LLVMValueRef v4 = emit_data->output[emit_data->chan];
3251 LLVMValueRef z = LLVMBuildExtractElement(builder, v4, two, "");
3252 z = LLVMBuildSDiv(builder, z, six, "");
3253
3254 emit_data->output[emit_data->chan] =
3255 LLVMBuildInsertElement(builder, v4, z, two, "");
3256 }
3257 }
3258
3259 static void si_llvm_emit_txqs(
3260 const struct lp_build_tgsi_action *action,
3261 struct lp_build_tgsi_context *bld_base,
3262 struct lp_build_emit_data *emit_data)
3263 {
3264 struct si_shader_context *ctx = si_shader_context(bld_base);
3265 struct gallivm_state *gallivm = bld_base->base.gallivm;
3266 LLVMBuilderRef builder = gallivm->builder;
3267 LLVMValueRef res, samples;
3268 LLVMValueRef res_ptr, samp_ptr, fmask_ptr = NULL;
3269
3270 tex_fetch_ptrs(bld_base, emit_data, &res_ptr, &samp_ptr, &fmask_ptr);
3271
3272
3273 /* Read the samples from the descriptor directly. */
3274 res = LLVMBuildBitCast(builder, res_ptr, ctx->v8i32, "");
3275 samples = LLVMBuildExtractElement(
3276 builder, res,
3277 lp_build_const_int32(gallivm, 3), "");
3278 samples = LLVMBuildLShr(builder, samples,
3279 lp_build_const_int32(gallivm, 16), "");
3280 samples = LLVMBuildAnd(builder, samples,
3281 lp_build_const_int32(gallivm, 0xf), "");
3282 samples = LLVMBuildShl(builder, lp_build_const_int32(gallivm, 1),
3283 samples, "");
3284
3285 emit_data->output[emit_data->chan] = samples;
3286 }
3287
3288 /*
3289 * SI implements derivatives using the local data store (LDS)
3290 * All writes to the LDS happen in all executing threads at
3291 * the same time. TID is the Thread ID for the current
3292 * thread and is a value between 0 and 63, representing
3293 * the thread's position in the wavefront.
3294 *
3295 * For the pixel shader threads are grouped into quads of four pixels.
3296 * The TIDs of the pixels of a quad are:
3297 *
3298 * +------+------+
3299 * |4n + 0|4n + 1|
3300 * +------+------+
3301 * |4n + 2|4n + 3|
3302 * +------+------+
3303 *
3304 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
3305 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
3306 * the current pixel's column, and masking with 0xfffffffe yields the TID
3307 * of the left pixel of the current pixel's row.
3308 *
3309 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
3310 * adding 2 yields the TID of the pixel below the top pixel.
3311 */
3312 /* masks for thread ID. */
3313 #define TID_MASK_TOP_LEFT 0xfffffffc
3314 #define TID_MASK_TOP 0xfffffffd
3315 #define TID_MASK_LEFT 0xfffffffe
3316
3317 static void si_llvm_emit_ddxy(
3318 const struct lp_build_tgsi_action *action,
3319 struct lp_build_tgsi_context *bld_base,
3320 struct lp_build_emit_data *emit_data)
3321 {
3322 struct si_shader_context *ctx = si_shader_context(bld_base);
3323 struct gallivm_state *gallivm = bld_base->base.gallivm;
3324 const struct tgsi_full_instruction *inst = emit_data->inst;
3325 unsigned opcode = inst->Instruction.Opcode;
3326 LLVMValueRef indices[2];
3327 LLVMValueRef store_ptr, load_ptr0, load_ptr1;
3328 LLVMValueRef tl, trbl, result[4];
3329 unsigned swizzle[4];
3330 unsigned c;
3331 int idx;
3332 unsigned mask;
3333
3334 indices[0] = bld_base->uint_bld.zero;
3335 indices[1] = lp_build_intrinsic(gallivm->builder, "llvm.SI.tid", ctx->i32,
3336 NULL, 0, LLVMReadNoneAttribute);
3337 store_ptr = LLVMBuildGEP(gallivm->builder, ctx->lds,
3338 indices, 2, "");
3339
3340 if (opcode == TGSI_OPCODE_DDX_FINE)
3341 mask = TID_MASK_LEFT;
3342 else if (opcode == TGSI_OPCODE_DDY_FINE)
3343 mask = TID_MASK_TOP;
3344 else
3345 mask = TID_MASK_TOP_LEFT;
3346
3347 indices[1] = LLVMBuildAnd(gallivm->builder, indices[1],
3348 lp_build_const_int32(gallivm, mask), "");
3349 load_ptr0 = LLVMBuildGEP(gallivm->builder, ctx->lds,
3350 indices, 2, "");
3351
3352 /* for DDX we want to next X pixel, DDY next Y pixel. */
3353 idx = (opcode == TGSI_OPCODE_DDX || opcode == TGSI_OPCODE_DDX_FINE) ? 1 : 2;
3354 indices[1] = LLVMBuildAdd(gallivm->builder, indices[1],
3355 lp_build_const_int32(gallivm, idx), "");
3356 load_ptr1 = LLVMBuildGEP(gallivm->builder, ctx->lds,
3357 indices, 2, "");
3358
3359 for (c = 0; c < 4; ++c) {
3360 unsigned i;
3361
3362 swizzle[c] = tgsi_util_get_full_src_register_swizzle(&inst->Src[0], c);
3363 for (i = 0; i < c; ++i) {
3364 if (swizzle[i] == swizzle[c]) {
3365 result[c] = result[i];
3366 break;
3367 }
3368 }
3369 if (i != c)
3370 continue;
3371
3372 LLVMBuildStore(gallivm->builder,
3373 LLVMBuildBitCast(gallivm->builder,
3374 lp_build_emit_fetch(bld_base, inst, 0, c),
3375 ctx->i32, ""),
3376 store_ptr);
3377
3378 tl = LLVMBuildLoad(gallivm->builder, load_ptr0, "");
3379 tl = LLVMBuildBitCast(gallivm->builder, tl, ctx->f32, "");
3380
3381 trbl = LLVMBuildLoad(gallivm->builder, load_ptr1, "");
3382 trbl = LLVMBuildBitCast(gallivm->builder, trbl, ctx->f32, "");
3383
3384 result[c] = LLVMBuildFSub(gallivm->builder, trbl, tl, "");
3385 }
3386
3387 emit_data->output[0] = lp_build_gather_values(gallivm, result, 4);
3388 }
3389
3390 /*
3391 * this takes an I,J coordinate pair,
3392 * and works out the X and Y derivatives.
3393 * it returns DDX(I), DDX(J), DDY(I), DDY(J).
3394 */
3395 static LLVMValueRef si_llvm_emit_ddxy_interp(
3396 struct lp_build_tgsi_context *bld_base,
3397 LLVMValueRef interp_ij)
3398 {
3399 struct si_shader_context *ctx = si_shader_context(bld_base);
3400 struct gallivm_state *gallivm = bld_base->base.gallivm;
3401 LLVMValueRef indices[2];
3402 LLVMValueRef store_ptr, load_ptr_x, load_ptr_y, load_ptr_ddx, load_ptr_ddy, temp, temp2;
3403 LLVMValueRef tl, tr, bl, result[4];
3404 unsigned c;
3405
3406 indices[0] = bld_base->uint_bld.zero;
3407 indices[1] = lp_build_intrinsic(gallivm->builder, "llvm.SI.tid", ctx->i32,
3408 NULL, 0, LLVMReadNoneAttribute);
3409 store_ptr = LLVMBuildGEP(gallivm->builder, ctx->lds,
3410 indices, 2, "");
3411
3412 temp = LLVMBuildAnd(gallivm->builder, indices[1],
3413 lp_build_const_int32(gallivm, TID_MASK_LEFT), "");
3414
3415 temp2 = LLVMBuildAnd(gallivm->builder, indices[1],
3416 lp_build_const_int32(gallivm, TID_MASK_TOP), "");
3417
3418 indices[1] = temp;
3419 load_ptr_x = LLVMBuildGEP(gallivm->builder, ctx->lds,
3420 indices, 2, "");
3421
3422 indices[1] = temp2;
3423 load_ptr_y = LLVMBuildGEP(gallivm->builder, ctx->lds,
3424 indices, 2, "");
3425
3426 indices[1] = LLVMBuildAdd(gallivm->builder, temp,
3427 lp_build_const_int32(gallivm, 1), "");
3428 load_ptr_ddx = LLVMBuildGEP(gallivm->builder, ctx->lds,
3429 indices, 2, "");
3430
3431 indices[1] = LLVMBuildAdd(gallivm->builder, temp2,
3432 lp_build_const_int32(gallivm, 2), "");
3433 load_ptr_ddy = LLVMBuildGEP(gallivm->builder, ctx->lds,
3434 indices, 2, "");
3435
3436 for (c = 0; c < 2; ++c) {
3437 LLVMValueRef store_val;
3438 LLVMValueRef c_ll = lp_build_const_int32(gallivm, c);
3439
3440 store_val = LLVMBuildExtractElement(gallivm->builder,
3441 interp_ij, c_ll, "");
3442 LLVMBuildStore(gallivm->builder,
3443 store_val,
3444 store_ptr);
3445
3446 tl = LLVMBuildLoad(gallivm->builder, load_ptr_x, "");
3447 tl = LLVMBuildBitCast(gallivm->builder, tl, ctx->f32, "");
3448
3449 tr = LLVMBuildLoad(gallivm->builder, load_ptr_ddx, "");
3450 tr = LLVMBuildBitCast(gallivm->builder, tr, ctx->f32, "");
3451
3452 result[c] = LLVMBuildFSub(gallivm->builder, tr, tl, "");
3453
3454 tl = LLVMBuildLoad(gallivm->builder, load_ptr_y, "");
3455 tl = LLVMBuildBitCast(gallivm->builder, tl, ctx->f32, "");
3456
3457 bl = LLVMBuildLoad(gallivm->builder, load_ptr_ddy, "");
3458 bl = LLVMBuildBitCast(gallivm->builder, bl, ctx->f32, "");
3459
3460 result[c + 2] = LLVMBuildFSub(gallivm->builder, bl, tl, "");
3461 }
3462
3463 return lp_build_gather_values(gallivm, result, 4);
3464 }
3465
3466 static void interp_fetch_args(
3467 struct lp_build_tgsi_context *bld_base,
3468 struct lp_build_emit_data *emit_data)
3469 {
3470 struct si_shader_context *ctx = si_shader_context(bld_base);
3471 struct gallivm_state *gallivm = bld_base->base.gallivm;
3472 const struct tgsi_full_instruction *inst = emit_data->inst;
3473
3474 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET) {
3475 /* offset is in second src, first two channels */
3476 emit_data->args[0] = lp_build_emit_fetch(bld_base,
3477 emit_data->inst, 1,
3478 TGSI_CHAN_X);
3479 emit_data->args[1] = lp_build_emit_fetch(bld_base,
3480 emit_data->inst, 1,
3481 TGSI_CHAN_Y);
3482 emit_data->arg_count = 2;
3483 } else if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE) {
3484 LLVMValueRef sample_position;
3485 LLVMValueRef sample_id;
3486 LLVMValueRef halfval = lp_build_const_float(gallivm, 0.5f);
3487
3488 /* fetch sample ID, then fetch its sample position,
3489 * and place into first two channels.
3490 */
3491 sample_id = lp_build_emit_fetch(bld_base,
3492 emit_data->inst, 1, TGSI_CHAN_X);
3493 sample_id = LLVMBuildBitCast(gallivm->builder, sample_id,
3494 ctx->i32, "");
3495 sample_position = load_sample_position(&ctx->radeon_bld, sample_id);
3496
3497 emit_data->args[0] = LLVMBuildExtractElement(gallivm->builder,
3498 sample_position,
3499 lp_build_const_int32(gallivm, 0), "");
3500
3501 emit_data->args[0] = LLVMBuildFSub(gallivm->builder, emit_data->args[0], halfval, "");
3502 emit_data->args[1] = LLVMBuildExtractElement(gallivm->builder,
3503 sample_position,
3504 lp_build_const_int32(gallivm, 1), "");
3505 emit_data->args[1] = LLVMBuildFSub(gallivm->builder, emit_data->args[1], halfval, "");
3506 emit_data->arg_count = 2;
3507 }
3508 }
3509
3510 static void build_interp_intrinsic(const struct lp_build_tgsi_action *action,
3511 struct lp_build_tgsi_context *bld_base,
3512 struct lp_build_emit_data *emit_data)
3513 {
3514 struct si_shader_context *ctx = si_shader_context(bld_base);
3515 struct si_shader *shader = ctx->shader;
3516 struct gallivm_state *gallivm = bld_base->base.gallivm;
3517 LLVMValueRef interp_param;
3518 const struct tgsi_full_instruction *inst = emit_data->inst;
3519 const char *intr_name;
3520 int input_index = inst->Src[0].Register.Index;
3521 int chan;
3522 int i;
3523 LLVMValueRef attr_number;
3524 LLVMValueRef params = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_PRIM_MASK);
3525 int interp_param_idx;
3526 unsigned interp = shader->selector->info.input_interpolate[input_index];
3527 unsigned location;
3528
3529 assert(inst->Src[0].Register.File == TGSI_FILE_INPUT);
3530
3531 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET ||
3532 inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE)
3533 location = TGSI_INTERPOLATE_LOC_CENTER;
3534 else
3535 location = TGSI_INTERPOLATE_LOC_CENTROID;
3536
3537 interp_param_idx = lookup_interp_param_index(interp, location);
3538 if (interp_param_idx == -1)
3539 return;
3540 else if (interp_param_idx)
3541 interp_param = LLVMGetParam(ctx->radeon_bld.main_fn, interp_param_idx);
3542 else
3543 interp_param = NULL;
3544
3545 attr_number = lp_build_const_int32(gallivm, input_index);
3546
3547 if (inst->Instruction.Opcode == TGSI_OPCODE_INTERP_OFFSET ||
3548 inst->Instruction.Opcode == TGSI_OPCODE_INTERP_SAMPLE) {
3549 LLVMValueRef ij_out[2];
3550 LLVMValueRef ddxy_out = si_llvm_emit_ddxy_interp(bld_base, interp_param);
3551
3552 /*
3553 * take the I then J parameters, and the DDX/Y for it, and
3554 * calculate the IJ inputs for the interpolator.
3555 * temp1 = ddx * offset/sample.x + I;
3556 * interp_param.I = ddy * offset/sample.y + temp1;
3557 * temp1 = ddx * offset/sample.x + J;
3558 * interp_param.J = ddy * offset/sample.y + temp1;
3559 */
3560 for (i = 0; i < 2; i++) {
3561 LLVMValueRef ix_ll = lp_build_const_int32(gallivm, i);
3562 LLVMValueRef iy_ll = lp_build_const_int32(gallivm, i + 2);
3563 LLVMValueRef ddx_el = LLVMBuildExtractElement(gallivm->builder,
3564 ddxy_out, ix_ll, "");
3565 LLVMValueRef ddy_el = LLVMBuildExtractElement(gallivm->builder,
3566 ddxy_out, iy_ll, "");
3567 LLVMValueRef interp_el = LLVMBuildExtractElement(gallivm->builder,
3568 interp_param, ix_ll, "");
3569 LLVMValueRef temp1, temp2;
3570
3571 interp_el = LLVMBuildBitCast(gallivm->builder, interp_el,
3572 ctx->f32, "");
3573
3574 temp1 = LLVMBuildFMul(gallivm->builder, ddx_el, emit_data->args[0], "");
3575
3576 temp1 = LLVMBuildFAdd(gallivm->builder, temp1, interp_el, "");
3577
3578 temp2 = LLVMBuildFMul(gallivm->builder, ddy_el, emit_data->args[1], "");
3579
3580 temp2 = LLVMBuildFAdd(gallivm->builder, temp2, temp1, "");
3581
3582 ij_out[i] = LLVMBuildBitCast(gallivm->builder,
3583 temp2, ctx->i32, "");
3584 }
3585 interp_param = lp_build_gather_values(bld_base->base.gallivm, ij_out, 2);
3586 }
3587
3588 intr_name = interp_param ? "llvm.SI.fs.interp" : "llvm.SI.fs.constant";
3589 for (chan = 0; chan < 2; chan++) {
3590 LLVMValueRef args[4];
3591 LLVMValueRef llvm_chan;
3592 unsigned schan;
3593
3594 schan = tgsi_util_get_full_src_register_swizzle(&inst->Src[0], chan);
3595 llvm_chan = lp_build_const_int32(gallivm, schan);
3596
3597 args[0] = llvm_chan;
3598 args[1] = attr_number;
3599 args[2] = params;
3600 args[3] = interp_param;
3601
3602 emit_data->output[chan] =
3603 lp_build_intrinsic(gallivm->builder, intr_name,
3604 ctx->f32, args, args[3] ? 4 : 3,
3605 LLVMReadNoneAttribute | LLVMNoUnwindAttribute);
3606 }
3607 }
3608
3609 static unsigned si_llvm_get_stream(struct lp_build_tgsi_context *bld_base,
3610 struct lp_build_emit_data *emit_data)
3611 {
3612 LLVMValueRef (*imms)[4] = lp_soa_context(bld_base)->immediates;
3613 struct tgsi_src_register src0 = emit_data->inst->Src[0].Register;
3614 unsigned stream;
3615
3616 assert(src0.File == TGSI_FILE_IMMEDIATE);
3617
3618 stream = LLVMConstIntGetZExtValue(imms[src0.Index][src0.SwizzleX]) & 0x3;
3619 return stream;
3620 }
3621
3622 /* Emit one vertex from the geometry shader */
3623 static void si_llvm_emit_vertex(
3624 const struct lp_build_tgsi_action *action,
3625 struct lp_build_tgsi_context *bld_base,
3626 struct lp_build_emit_data *emit_data)
3627 {
3628 struct si_shader_context *ctx = si_shader_context(bld_base);
3629 struct lp_build_context *uint = &bld_base->uint_bld;
3630 struct si_shader *shader = ctx->shader;
3631 struct tgsi_shader_info *info = &shader->selector->info;
3632 struct gallivm_state *gallivm = bld_base->base.gallivm;
3633 LLVMValueRef soffset = LLVMGetParam(ctx->radeon_bld.main_fn,
3634 SI_PARAM_GS2VS_OFFSET);
3635 LLVMValueRef gs_next_vertex;
3636 LLVMValueRef can_emit, kill;
3637 LLVMValueRef args[2];
3638 unsigned chan;
3639 int i;
3640 unsigned stream;
3641
3642 stream = si_llvm_get_stream(bld_base, emit_data);
3643
3644 /* Write vertex attribute values to GSVS ring */
3645 gs_next_vertex = LLVMBuildLoad(gallivm->builder,
3646 ctx->gs_next_vertex[stream],
3647 "");
3648
3649 /* If this thread has already emitted the declared maximum number of
3650 * vertices, kill it: excessive vertex emissions are not supposed to
3651 * have any effect, and GS threads have no externally observable
3652 * effects other than emitting vertices.
3653 */
3654 can_emit = LLVMBuildICmp(gallivm->builder, LLVMIntULE, gs_next_vertex,
3655 lp_build_const_int32(gallivm,
3656 shader->selector->gs_max_out_vertices), "");
3657 kill = lp_build_select(&bld_base->base, can_emit,
3658 lp_build_const_float(gallivm, 1.0f),
3659 lp_build_const_float(gallivm, -1.0f));
3660
3661 lp_build_intrinsic(gallivm->builder, "llvm.AMDGPU.kill",
3662 ctx->voidt, &kill, 1, 0);
3663
3664 for (i = 0; i < info->num_outputs; i++) {
3665 LLVMValueRef *out_ptr =
3666 ctx->radeon_bld.soa.outputs[i];
3667
3668 for (chan = 0; chan < 4; chan++) {
3669 LLVMValueRef out_val = LLVMBuildLoad(gallivm->builder, out_ptr[chan], "");
3670 LLVMValueRef voffset =
3671 lp_build_const_int32(gallivm, (i * 4 + chan) *
3672 shader->selector->gs_max_out_vertices);
3673
3674 voffset = lp_build_add(uint, voffset, gs_next_vertex);
3675 voffset = lp_build_mul_imm(uint, voffset, 4);
3676
3677 out_val = LLVMBuildBitCast(gallivm->builder, out_val, ctx->i32, "");
3678
3679 build_tbuffer_store(ctx,
3680 ctx->gsvs_ring[stream],
3681 out_val, 1,
3682 voffset, soffset, 0,
3683 V_008F0C_BUF_DATA_FORMAT_32,
3684 V_008F0C_BUF_NUM_FORMAT_UINT,
3685 1, 0, 1, 1, 0);
3686 }
3687 }
3688 gs_next_vertex = lp_build_add(uint, gs_next_vertex,
3689 lp_build_const_int32(gallivm, 1));
3690
3691 LLVMBuildStore(gallivm->builder, gs_next_vertex, ctx->gs_next_vertex[stream]);
3692
3693 /* Signal vertex emission */
3694 args[0] = lp_build_const_int32(gallivm, SENDMSG_GS_OP_EMIT | SENDMSG_GS | (stream << 8));
3695 args[1] = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_GS_WAVE_ID);
3696 lp_build_intrinsic(gallivm->builder, "llvm.SI.sendmsg",
3697 ctx->voidt, args, 2, LLVMNoUnwindAttribute);
3698 }
3699
3700 /* Cut one primitive from the geometry shader */
3701 static void si_llvm_emit_primitive(
3702 const struct lp_build_tgsi_action *action,
3703 struct lp_build_tgsi_context *bld_base,
3704 struct lp_build_emit_data *emit_data)
3705 {
3706 struct si_shader_context *ctx = si_shader_context(bld_base);
3707 struct gallivm_state *gallivm = bld_base->base.gallivm;
3708 LLVMValueRef args[2];
3709 unsigned stream;
3710
3711 /* Signal primitive cut */
3712 stream = si_llvm_get_stream(bld_base, emit_data);
3713 args[0] = lp_build_const_int32(gallivm, SENDMSG_GS_OP_CUT | SENDMSG_GS | (stream << 8));
3714 args[1] = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_GS_WAVE_ID);
3715 lp_build_intrinsic(gallivm->builder, "llvm.SI.sendmsg",
3716 ctx->voidt, args, 2, LLVMNoUnwindAttribute);
3717 }
3718
3719 static void si_llvm_emit_barrier(const struct lp_build_tgsi_action *action,
3720 struct lp_build_tgsi_context *bld_base,
3721 struct lp_build_emit_data *emit_data)
3722 {
3723 struct si_shader_context *ctx = si_shader_context(bld_base);
3724 struct gallivm_state *gallivm = bld_base->base.gallivm;
3725
3726 lp_build_intrinsic(gallivm->builder,
3727 HAVE_LLVM >= 0x0309 ? "llvm.amdgcn.s.barrier"
3728 : "llvm.AMDGPU.barrier.local",
3729 ctx->voidt, NULL, 0, LLVMNoUnwindAttribute);
3730 }
3731
3732 static const struct lp_build_tgsi_action tex_action = {
3733 .fetch_args = tex_fetch_args,
3734 .emit = build_tex_intrinsic,
3735 };
3736
3737 static const struct lp_build_tgsi_action interp_action = {
3738 .fetch_args = interp_fetch_args,
3739 .emit = build_interp_intrinsic,
3740 };
3741
3742 static void si_create_function(struct si_shader_context *ctx,
3743 LLVMTypeRef *returns, unsigned num_returns,
3744 LLVMTypeRef *params, unsigned num_params,
3745 int last_array_pointer, int last_sgpr)
3746 {
3747 int i;
3748
3749 radeon_llvm_create_func(&ctx->radeon_bld, returns, num_returns,
3750 params, num_params);
3751 radeon_llvm_shader_type(ctx->radeon_bld.main_fn, ctx->type);
3752 ctx->return_value = LLVMGetUndef(ctx->radeon_bld.return_type);
3753
3754 for (i = 0; i <= last_sgpr; ++i) {
3755 LLVMValueRef P = LLVMGetParam(ctx->radeon_bld.main_fn, i);
3756
3757 /* We tell llvm that array inputs are passed by value to allow Sinking pass
3758 * to move load. Inputs are constant so this is fine. */
3759 if (i <= last_array_pointer)
3760 LLVMAddAttribute(P, LLVMByValAttribute);
3761 else
3762 LLVMAddAttribute(P, LLVMInRegAttribute);
3763 }
3764 }
3765
3766 static void create_meta_data(struct si_shader_context *ctx)
3767 {
3768 struct gallivm_state *gallivm = ctx->radeon_bld.soa.bld_base.base.gallivm;
3769 LLVMValueRef args[3];
3770
3771 args[0] = LLVMMDStringInContext(gallivm->context, "const", 5);
3772 args[1] = 0;
3773 args[2] = lp_build_const_int32(gallivm, 1);
3774
3775 ctx->const_md = LLVMMDNodeInContext(gallivm->context, args, 3);
3776 }
3777
3778 static void declare_streamout_params(struct si_shader_context *ctx,
3779 struct pipe_stream_output_info *so,
3780 LLVMTypeRef *params, LLVMTypeRef i32,
3781 unsigned *num_params)
3782 {
3783 int i;
3784
3785 /* Streamout SGPRs. */
3786 if (so->num_outputs) {
3787 params[ctx->param_streamout_config = (*num_params)++] = i32;
3788 params[ctx->param_streamout_write_index = (*num_params)++] = i32;
3789 }
3790 /* A streamout buffer offset is loaded if the stride is non-zero. */
3791 for (i = 0; i < 4; i++) {
3792 if (!so->stride[i])
3793 continue;
3794
3795 params[ctx->param_streamout_offset[i] = (*num_params)++] = i32;
3796 }
3797 }
3798
3799 static unsigned llvm_get_type_size(LLVMTypeRef type)
3800 {
3801 LLVMTypeKind kind = LLVMGetTypeKind(type);
3802
3803 switch (kind) {
3804 case LLVMIntegerTypeKind:
3805 return LLVMGetIntTypeWidth(type) / 8;
3806 case LLVMFloatTypeKind:
3807 return 4;
3808 case LLVMPointerTypeKind:
3809 return 8;
3810 case LLVMVectorTypeKind:
3811 return LLVMGetVectorSize(type) *
3812 llvm_get_type_size(LLVMGetElementType(type));
3813 default:
3814 assert(0);
3815 return 0;
3816 }
3817 }
3818
3819 static void declare_tess_lds(struct si_shader_context *ctx)
3820 {
3821 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
3822 LLVMTypeRef i32 = ctx->radeon_bld.soa.bld_base.uint_bld.elem_type;
3823
3824 /* This is the upper bound, maximum is 32 inputs times 32 vertices */
3825 unsigned vertex_data_dw_size = 32*32*4;
3826 unsigned patch_data_dw_size = 32*4;
3827 /* The formula is: TCS inputs + TCS outputs + TCS patch outputs. */
3828 unsigned patch_dw_size = vertex_data_dw_size*2 + patch_data_dw_size;
3829 unsigned lds_dwords = patch_dw_size;
3830
3831 /* The actual size is computed outside of the shader to reduce
3832 * the number of shader variants. */
3833 ctx->lds =
3834 LLVMAddGlobalInAddressSpace(gallivm->module,
3835 LLVMArrayType(i32, lds_dwords),
3836 "tess_lds",
3837 LOCAL_ADDR_SPACE);
3838 }
3839
3840 static void create_function(struct si_shader_context *ctx)
3841 {
3842 struct lp_build_tgsi_context *bld_base = &ctx->radeon_bld.soa.bld_base;
3843 struct gallivm_state *gallivm = bld_base->base.gallivm;
3844 struct si_shader *shader = ctx->shader;
3845 LLVMTypeRef params[SI_NUM_PARAMS + SI_NUM_VERTEX_BUFFERS], v3i32;
3846 LLVMTypeRef returns[16+32*4];
3847 unsigned i, last_array_pointer, last_sgpr, num_params, num_return_sgprs;
3848 unsigned num_returns = 0;
3849
3850 v3i32 = LLVMVectorType(ctx->i32, 3);
3851
3852 params[SI_PARAM_RW_BUFFERS] = const_array(ctx->v16i8, SI_NUM_RW_BUFFERS);
3853 params[SI_PARAM_CONST_BUFFERS] = const_array(ctx->v16i8, SI_NUM_CONST_BUFFERS);
3854 params[SI_PARAM_SAMPLERS] = const_array(ctx->v8i32, SI_NUM_SAMPLERS);
3855 params[SI_PARAM_UNUSED] = LLVMPointerType(ctx->i32, CONST_ADDR_SPACE);
3856 last_array_pointer = SI_PARAM_UNUSED;
3857
3858 switch (ctx->type) {
3859 case TGSI_PROCESSOR_VERTEX:
3860 params[SI_PARAM_VERTEX_BUFFERS] = const_array(ctx->v16i8, SI_NUM_VERTEX_BUFFERS);
3861 last_array_pointer = SI_PARAM_VERTEX_BUFFERS;
3862 params[SI_PARAM_BASE_VERTEX] = ctx->i32;
3863 params[SI_PARAM_START_INSTANCE] = ctx->i32;
3864 num_params = SI_PARAM_START_INSTANCE+1;
3865
3866 if (shader->key.vs.as_es) {
3867 params[ctx->param_es2gs_offset = num_params++] = ctx->i32;
3868 } else if (shader->key.vs.as_ls) {
3869 params[SI_PARAM_LS_OUT_LAYOUT] = ctx->i32;
3870 num_params = SI_PARAM_LS_OUT_LAYOUT+1;
3871 } else {
3872 if (ctx->is_gs_copy_shader) {
3873 last_array_pointer = SI_PARAM_CONST_BUFFERS;
3874 num_params = SI_PARAM_CONST_BUFFERS+1;
3875 } else {
3876 params[SI_PARAM_VS_STATE_BITS] = ctx->i32;
3877 num_params = SI_PARAM_VS_STATE_BITS+1;
3878 }
3879
3880 /* The locations of the other parameters are assigned dynamically. */
3881 declare_streamout_params(ctx, &shader->selector->so,
3882 params, ctx->i32, &num_params);
3883 }
3884
3885 last_sgpr = num_params-1;
3886
3887 /* VGPRs */
3888 params[ctx->param_vertex_id = num_params++] = ctx->i32;
3889 params[ctx->param_rel_auto_id = num_params++] = ctx->i32;
3890 params[ctx->param_vs_prim_id = num_params++] = ctx->i32;
3891 params[ctx->param_instance_id = num_params++] = ctx->i32;
3892
3893 if (!ctx->is_monolithic &&
3894 !ctx->is_gs_copy_shader) {
3895 /* Vertex load indices. */
3896 ctx->param_vertex_index0 = num_params;
3897
3898 for (i = 0; i < shader->selector->info.num_inputs; i++)
3899 params[num_params++] = ctx->i32;
3900
3901 /* PrimitiveID output. */
3902 if (!shader->key.vs.as_es && !shader->key.vs.as_ls)
3903 for (i = 0; i <= VS_EPILOG_PRIMID_LOC; i++)
3904 returns[num_returns++] = ctx->f32;
3905 }
3906 break;
3907
3908 case TGSI_PROCESSOR_TESS_CTRL:
3909 params[SI_PARAM_TCS_OUT_OFFSETS] = ctx->i32;
3910 params[SI_PARAM_TCS_OUT_LAYOUT] = ctx->i32;
3911 params[SI_PARAM_TCS_IN_LAYOUT] = ctx->i32;
3912 params[SI_PARAM_TESS_FACTOR_OFFSET] = ctx->i32;
3913 last_sgpr = SI_PARAM_TESS_FACTOR_OFFSET;
3914
3915 /* VGPRs */
3916 params[SI_PARAM_PATCH_ID] = ctx->i32;
3917 params[SI_PARAM_REL_IDS] = ctx->i32;
3918 num_params = SI_PARAM_REL_IDS+1;
3919
3920 if (!ctx->is_monolithic) {
3921 /* PARAM_TESS_FACTOR_OFFSET is after user SGPRs. */
3922 for (i = 0; i <= SI_TCS_NUM_USER_SGPR; i++)
3923 returns[num_returns++] = ctx->i32; /* SGPRs */
3924
3925 for (i = 0; i < 3; i++)
3926 returns[num_returns++] = ctx->f32; /* VGPRs */
3927 }
3928 break;
3929
3930 case TGSI_PROCESSOR_TESS_EVAL:
3931 params[SI_PARAM_TCS_OUT_OFFSETS] = ctx->i32;
3932 params[SI_PARAM_TCS_OUT_LAYOUT] = ctx->i32;
3933 num_params = SI_PARAM_TCS_OUT_LAYOUT+1;
3934
3935 if (shader->key.tes.as_es) {
3936 params[ctx->param_es2gs_offset = num_params++] = ctx->i32;
3937 } else {
3938 declare_streamout_params(ctx, &shader->selector->so,
3939 params, ctx->i32, &num_params);
3940 }
3941 last_sgpr = num_params - 1;
3942
3943 /* VGPRs */
3944 params[ctx->param_tes_u = num_params++] = ctx->f32;
3945 params[ctx->param_tes_v = num_params++] = ctx->f32;
3946 params[ctx->param_tes_rel_patch_id = num_params++] = ctx->i32;
3947 params[ctx->param_tes_patch_id = num_params++] = ctx->i32;
3948
3949 /* PrimitiveID output. */
3950 if (!ctx->is_monolithic && !shader->key.tes.as_es)
3951 for (i = 0; i <= VS_EPILOG_PRIMID_LOC; i++)
3952 returns[num_returns++] = ctx->f32;
3953 break;
3954
3955 case TGSI_PROCESSOR_GEOMETRY:
3956 params[SI_PARAM_GS2VS_OFFSET] = ctx->i32;
3957 params[SI_PARAM_GS_WAVE_ID] = ctx->i32;
3958 last_sgpr = SI_PARAM_GS_WAVE_ID;
3959
3960 /* VGPRs */
3961 params[SI_PARAM_VTX0_OFFSET] = ctx->i32;
3962 params[SI_PARAM_VTX1_OFFSET] = ctx->i32;
3963 params[SI_PARAM_PRIMITIVE_ID] = ctx->i32;
3964 params[SI_PARAM_VTX2_OFFSET] = ctx->i32;
3965 params[SI_PARAM_VTX3_OFFSET] = ctx->i32;
3966 params[SI_PARAM_VTX4_OFFSET] = ctx->i32;
3967 params[SI_PARAM_VTX5_OFFSET] = ctx->i32;
3968 params[SI_PARAM_GS_INSTANCE_ID] = ctx->i32;
3969 num_params = SI_PARAM_GS_INSTANCE_ID+1;
3970 break;
3971
3972 case TGSI_PROCESSOR_FRAGMENT:
3973 params[SI_PARAM_ALPHA_REF] = ctx->f32;
3974 params[SI_PARAM_PRIM_MASK] = ctx->i32;
3975 last_sgpr = SI_PARAM_PRIM_MASK;
3976 params[SI_PARAM_PERSP_SAMPLE] = ctx->v2i32;
3977 params[SI_PARAM_PERSP_CENTER] = ctx->v2i32;
3978 params[SI_PARAM_PERSP_CENTROID] = ctx->v2i32;
3979 params[SI_PARAM_PERSP_PULL_MODEL] = v3i32;
3980 params[SI_PARAM_LINEAR_SAMPLE] = ctx->v2i32;
3981 params[SI_PARAM_LINEAR_CENTER] = ctx->v2i32;
3982 params[SI_PARAM_LINEAR_CENTROID] = ctx->v2i32;
3983 params[SI_PARAM_LINE_STIPPLE_TEX] = ctx->f32;
3984 params[SI_PARAM_POS_X_FLOAT] = ctx->f32;
3985 params[SI_PARAM_POS_Y_FLOAT] = ctx->f32;
3986 params[SI_PARAM_POS_Z_FLOAT] = ctx->f32;
3987 params[SI_PARAM_POS_W_FLOAT] = ctx->f32;
3988 params[SI_PARAM_FRONT_FACE] = ctx->i32;
3989 params[SI_PARAM_ANCILLARY] = ctx->i32;
3990 params[SI_PARAM_SAMPLE_COVERAGE] = ctx->f32;
3991 params[SI_PARAM_POS_FIXED_PT] = ctx->f32;
3992 num_params = SI_PARAM_POS_FIXED_PT+1;
3993
3994 if (!ctx->is_monolithic) {
3995 /* Color inputs from the prolog. */
3996 if (shader->selector->info.colors_read) {
3997 unsigned num_color_elements =
3998 util_bitcount(shader->selector->info.colors_read);
3999
4000 assert(num_params + num_color_elements <= ARRAY_SIZE(params));
4001 for (i = 0; i < num_color_elements; i++)
4002 params[num_params++] = ctx->f32;
4003 }
4004
4005 /* Outputs for the epilog. */
4006 num_return_sgprs = SI_SGPR_ALPHA_REF + 1;
4007 num_returns =
4008 num_return_sgprs +
4009 util_bitcount(shader->selector->info.colors_written) * 4 +
4010 shader->selector->info.writes_z +
4011 shader->selector->info.writes_stencil +
4012 shader->selector->info.writes_samplemask +
4013 1 /* SampleMaskIn */;
4014
4015 num_returns = MAX2(num_returns,
4016 num_return_sgprs +
4017 PS_EPILOG_SAMPLEMASK_MIN_LOC + 1);
4018
4019 for (i = 0; i < num_return_sgprs; i++)
4020 returns[i] = ctx->i32;
4021 for (; i < num_returns; i++)
4022 returns[i] = ctx->f32;
4023 }
4024 break;
4025
4026 default:
4027 assert(0 && "unimplemented shader");
4028 return;
4029 }
4030
4031 assert(num_params <= Elements(params));
4032
4033 si_create_function(ctx, returns, num_returns, params,
4034 num_params, last_array_pointer, last_sgpr);
4035
4036 /* Reserve register locations for VGPR inputs the PS prolog may need. */
4037 if (ctx->type == TGSI_PROCESSOR_FRAGMENT &&
4038 !ctx->is_monolithic) {
4039 radeon_llvm_add_attribute(ctx->radeon_bld.main_fn,
4040 "InitialPSInputAddr",
4041 S_0286D0_PERSP_SAMPLE_ENA(1) |
4042 S_0286D0_PERSP_CENTER_ENA(1) |
4043 S_0286D0_PERSP_CENTROID_ENA(1) |
4044 S_0286D0_LINEAR_SAMPLE_ENA(1) |
4045 S_0286D0_LINEAR_CENTER_ENA(1) |
4046 S_0286D0_LINEAR_CENTROID_ENA(1) |
4047 S_0286D0_FRONT_FACE_ENA(1));
4048 }
4049
4050 shader->num_input_sgprs = 0;
4051 shader->num_input_vgprs = 0;
4052
4053 for (i = 0; i <= last_sgpr; ++i)
4054 shader->num_input_sgprs += llvm_get_type_size(params[i]) / 4;
4055
4056 /* Unused fragment shader inputs are eliminated by the compiler,
4057 * so we don't know yet how many there will be.
4058 */
4059 if (ctx->type != TGSI_PROCESSOR_FRAGMENT)
4060 for (; i < num_params; ++i)
4061 shader->num_input_vgprs += llvm_get_type_size(params[i]) / 4;
4062
4063 if (bld_base->info &&
4064 (bld_base->info->opcode_count[TGSI_OPCODE_DDX] > 0 ||
4065 bld_base->info->opcode_count[TGSI_OPCODE_DDY] > 0 ||
4066 bld_base->info->opcode_count[TGSI_OPCODE_DDX_FINE] > 0 ||
4067 bld_base->info->opcode_count[TGSI_OPCODE_DDY_FINE] > 0 ||
4068 bld_base->info->opcode_count[TGSI_OPCODE_INTERP_OFFSET] > 0 ||
4069 bld_base->info->opcode_count[TGSI_OPCODE_INTERP_SAMPLE] > 0))
4070 ctx->lds =
4071 LLVMAddGlobalInAddressSpace(gallivm->module,
4072 LLVMArrayType(ctx->i32, 64),
4073 "ddxy_lds",
4074 LOCAL_ADDR_SPACE);
4075
4076 if ((ctx->type == TGSI_PROCESSOR_VERTEX && shader->key.vs.as_ls) ||
4077 ctx->type == TGSI_PROCESSOR_TESS_CTRL ||
4078 ctx->type == TGSI_PROCESSOR_TESS_EVAL)
4079 declare_tess_lds(ctx);
4080 }
4081
4082 static void preload_constants(struct si_shader_context *ctx)
4083 {
4084 struct lp_build_tgsi_context *bld_base = &ctx->radeon_bld.soa.bld_base;
4085 struct gallivm_state *gallivm = bld_base->base.gallivm;
4086 const struct tgsi_shader_info *info = bld_base->info;
4087 unsigned buf;
4088 LLVMValueRef ptr = LLVMGetParam(ctx->radeon_bld.main_fn, SI_PARAM_CONST_BUFFERS);
4089
4090 for (buf = 0; buf < SI_NUM_CONST_BUFFERS; buf++) {
4091 unsigned i, num_const = info->const_file_max[buf] + 1;
4092
4093 if (num_const == 0)
4094 continue;
4095
4096 /* Allocate space for the constant values */
4097 ctx->constants[buf] = CALLOC(num_const * 4, sizeof(LLVMValueRef));
4098
4099 /* Load the resource descriptor */
4100 ctx->const_buffers[buf] =
4101 build_indexed_load_const(ctx, ptr, lp_build_const_int32(gallivm, buf));
4102
4103 /* Load the constants, we rely on the code sinking to do the rest */
4104 for (i = 0; i < num_const * 4; ++i) {
4105 ctx->constants[buf][i] =
4106 buffer_load_const(gallivm->builder,
4107 ctx->const_buffers[buf],
4108 lp_build_const_int32(gallivm, i * 4),
4109 ctx->f32);
4110 }
4111 }
4112 }
4113
4114 static void preload_samplers(struct si_shader_context *ctx)
4115 {
4116 struct lp_build_tgsi_context *bld_base = &ctx->radeon_bld.soa.bld_base;
4117 struct gallivm_state *gallivm = bld_base->base.gallivm;
4118 const struct tgsi_shader_info *info = bld_base->info;
4119 unsigned i, num_samplers = info->file_max[TGSI_FILE_SAMPLER] + 1;
4120 LLVMValueRef offset;
4121
4122 if (num_samplers == 0)
4123 return;
4124
4125 /* Load the resources and samplers, we rely on the code sinking to do the rest */
4126 for (i = 0; i < num_samplers; ++i) {
4127 /* Resource */
4128 offset = lp_build_const_int32(gallivm, i);
4129 ctx->sampler_views[i] =
4130 get_sampler_desc(ctx, offset, DESC_IMAGE);
4131
4132 /* FMASK resource */
4133 if (info->is_msaa_sampler[i])
4134 ctx->fmasks[i] =
4135 get_sampler_desc(ctx, offset, DESC_FMASK);
4136 else
4137 ctx->sampler_states[i] =
4138 get_sampler_desc(ctx, offset, DESC_SAMPLER);
4139 }
4140 }
4141
4142 static void preload_streamout_buffers(struct si_shader_context *ctx)
4143 {
4144 struct lp_build_tgsi_context *bld_base = &ctx->radeon_bld.soa.bld_base;
4145 struct gallivm_state *gallivm = bld_base->base.gallivm;
4146 unsigned i;
4147
4148 /* Streamout can only be used if the shader is compiled as VS. */
4149 if (!ctx->shader->selector->so.num_outputs ||
4150 (ctx->type == TGSI_PROCESSOR_VERTEX &&
4151 (ctx->shader->key.vs.as_es ||
4152 ctx->shader->key.vs.as_ls)) ||
4153 (ctx->type == TGSI_PROCESSOR_TESS_EVAL &&
4154 ctx->shader->key.tes.as_es))
4155 return;
4156
4157 LLVMValueRef buf_ptr = LLVMGetParam(ctx->radeon_bld.main_fn,
4158 SI_PARAM_RW_BUFFERS);
4159
4160 /* Load the resources, we rely on the code sinking to do the rest */
4161 for (i = 0; i < 4; ++i) {
4162 if (ctx->shader->selector->so.stride[i]) {
4163 LLVMValueRef offset = lp_build_const_int32(gallivm,
4164 SI_SO_BUF_OFFSET + i);
4165
4166 ctx->so_buffers[i] = build_indexed_load_const(ctx, buf_ptr, offset);
4167 }
4168 }
4169 }
4170
4171 /**
4172 * Load ESGS and GSVS ring buffer resource descriptors and save the variables
4173 * for later use.
4174 */
4175 static void preload_ring_buffers(struct si_shader_context *ctx)
4176 {
4177 struct gallivm_state *gallivm =
4178 ctx->radeon_bld.soa.bld_base.base.gallivm;
4179
4180 LLVMValueRef buf_ptr = LLVMGetParam(ctx->radeon_bld.main_fn,
4181 SI_PARAM_RW_BUFFERS);
4182
4183 if ((ctx->type == TGSI_PROCESSOR_VERTEX &&
4184 ctx->shader->key.vs.as_es) ||
4185 (ctx->type == TGSI_PROCESSOR_TESS_EVAL &&
4186 ctx->shader->key.tes.as_es) ||
4187 ctx->type == TGSI_PROCESSOR_GEOMETRY) {
4188 LLVMValueRef offset = lp_build_const_int32(gallivm, SI_RING_ESGS);
4189
4190 ctx->esgs_ring =
4191 build_indexed_load_const(ctx, buf_ptr, offset);
4192 }
4193
4194 if (ctx->is_gs_copy_shader) {
4195 LLVMValueRef offset = lp_build_const_int32(gallivm, SI_RING_GSVS);
4196
4197 ctx->gsvs_ring[0] =
4198 build_indexed_load_const(ctx, buf_ptr, offset);
4199 }
4200 if (ctx->type == TGSI_PROCESSOR_GEOMETRY) {
4201 int i;
4202 for (i = 0; i < 4; i++) {
4203 LLVMValueRef offset = lp_build_const_int32(gallivm, SI_RING_GSVS + i);
4204
4205 ctx->gsvs_ring[i] =
4206 build_indexed_load_const(ctx, buf_ptr, offset);
4207 }
4208 }
4209 }
4210
4211 void si_shader_binary_read_config(struct radeon_shader_binary *binary,
4212 struct si_shader_config *conf,
4213 unsigned symbol_offset)
4214 {
4215 unsigned i;
4216 const unsigned char *config =
4217 radeon_shader_binary_config_start(binary, symbol_offset);
4218
4219 /* XXX: We may be able to emit some of these values directly rather than
4220 * extracting fields to be emitted later.
4221 */
4222
4223 for (i = 0; i < binary->config_size_per_symbol; i+= 8) {
4224 unsigned reg = util_le32_to_cpu(*(uint32_t*)(config + i));
4225 unsigned value = util_le32_to_cpu(*(uint32_t*)(config + i + 4));
4226 switch (reg) {
4227 case R_00B028_SPI_SHADER_PGM_RSRC1_PS:
4228 case R_00B128_SPI_SHADER_PGM_RSRC1_VS:
4229 case R_00B228_SPI_SHADER_PGM_RSRC1_GS:
4230 case R_00B848_COMPUTE_PGM_RSRC1:
4231 conf->num_sgprs = MAX2(conf->num_sgprs, (G_00B028_SGPRS(value) + 1) * 8);
4232 conf->num_vgprs = MAX2(conf->num_vgprs, (G_00B028_VGPRS(value) + 1) * 4);
4233 conf->float_mode = G_00B028_FLOAT_MODE(value);
4234 conf->rsrc1 = value;
4235 break;
4236 case R_00B02C_SPI_SHADER_PGM_RSRC2_PS:
4237 conf->lds_size = MAX2(conf->lds_size, G_00B02C_EXTRA_LDS_SIZE(value));
4238 break;
4239 case R_00B84C_COMPUTE_PGM_RSRC2:
4240 conf->lds_size = MAX2(conf->lds_size, G_00B84C_LDS_SIZE(value));
4241 conf->rsrc2 = value;
4242 break;
4243 case R_0286CC_SPI_PS_INPUT_ENA:
4244 conf->spi_ps_input_ena = value;
4245 break;
4246 case R_0286D0_SPI_PS_INPUT_ADDR:
4247 conf->spi_ps_input_addr = value;
4248 break;
4249 case R_0286E8_SPI_TMPRING_SIZE:
4250 case R_00B860_COMPUTE_TMPRING_SIZE:
4251 /* WAVESIZE is in units of 256 dwords. */
4252 conf->scratch_bytes_per_wave =
4253 G_00B860_WAVESIZE(value) * 256 * 4 * 1;
4254 break;
4255 default:
4256 {
4257 static bool printed;
4258
4259 if (!printed) {
4260 fprintf(stderr, "Warning: LLVM emitted unknown "
4261 "config register: 0x%x\n", reg);
4262 printed = true;
4263 }
4264 }
4265 break;
4266 }
4267
4268 if (!conf->spi_ps_input_addr)
4269 conf->spi_ps_input_addr = conf->spi_ps_input_ena;
4270 }
4271 }
4272
4273 void si_shader_apply_scratch_relocs(struct si_context *sctx,
4274 struct si_shader *shader,
4275 uint64_t scratch_va)
4276 {
4277 unsigned i;
4278 uint32_t scratch_rsrc_dword0 = scratch_va;
4279 uint32_t scratch_rsrc_dword1 =
4280 S_008F04_BASE_ADDRESS_HI(scratch_va >> 32)
4281 | S_008F04_STRIDE(shader->config.scratch_bytes_per_wave / 64);
4282
4283 for (i = 0 ; i < shader->binary.reloc_count; i++) {
4284 const struct radeon_shader_reloc *reloc =
4285 &shader->binary.relocs[i];
4286 if (!strcmp(scratch_rsrc_dword0_symbol, reloc->name)) {
4287 util_memcpy_cpu_to_le32(shader->binary.code + reloc->offset,
4288 &scratch_rsrc_dword0, 4);
4289 } else if (!strcmp(scratch_rsrc_dword1_symbol, reloc->name)) {
4290 util_memcpy_cpu_to_le32(shader->binary.code + reloc->offset,
4291 &scratch_rsrc_dword1, 4);
4292 }
4293 }
4294 }
4295
4296 static unsigned si_get_shader_binary_size(struct si_shader *shader)
4297 {
4298 unsigned size = shader->binary.code_size;
4299
4300 if (shader->prolog)
4301 size += shader->prolog->binary.code_size;
4302 if (shader->epilog)
4303 size += shader->epilog->binary.code_size;
4304 return size;
4305 }
4306
4307 int si_shader_binary_upload(struct si_screen *sscreen, struct si_shader *shader)
4308 {
4309 const struct radeon_shader_binary *prolog =
4310 shader->prolog ? &shader->prolog->binary : NULL;
4311 const struct radeon_shader_binary *epilog =
4312 shader->epilog ? &shader->epilog->binary : NULL;
4313 const struct radeon_shader_binary *mainb = &shader->binary;
4314 unsigned bo_size = si_get_shader_binary_size(shader) +
4315 (!epilog ? mainb->rodata_size : 0);
4316 unsigned char *ptr;
4317
4318 assert(!prolog || !prolog->rodata_size);
4319 assert((!prolog && !epilog) || !mainb->rodata_size);
4320 assert(!epilog || !epilog->rodata_size);
4321
4322 r600_resource_reference(&shader->bo, NULL);
4323 shader->bo = si_resource_create_custom(&sscreen->b.b,
4324 PIPE_USAGE_IMMUTABLE,
4325 bo_size);
4326 if (!shader->bo)
4327 return -ENOMEM;
4328
4329 /* Upload. */
4330 ptr = sscreen->b.ws->buffer_map(shader->bo->buf, NULL,
4331 PIPE_TRANSFER_READ_WRITE);
4332
4333 if (prolog) {
4334 util_memcpy_cpu_to_le32(ptr, prolog->code, prolog->code_size);
4335 ptr += prolog->code_size;
4336 }
4337
4338 util_memcpy_cpu_to_le32(ptr, mainb->code, mainb->code_size);
4339 ptr += mainb->code_size;
4340
4341 if (epilog)
4342 util_memcpy_cpu_to_le32(ptr, epilog->code, epilog->code_size);
4343 else if (mainb->rodata_size > 0)
4344 util_memcpy_cpu_to_le32(ptr, mainb->rodata, mainb->rodata_size);
4345
4346 sscreen->b.ws->buffer_unmap(shader->bo->buf);
4347 return 0;
4348 }
4349
4350 static void si_shader_dump_disassembly(const struct radeon_shader_binary *binary,
4351 struct pipe_debug_callback *debug,
4352 const char *name)
4353 {
4354 char *line, *p;
4355 unsigned i, count;
4356
4357 if (binary->disasm_string) {
4358 fprintf(stderr, "Shader %s disassembly:\n", name);
4359 fprintf(stderr, "%s", binary->disasm_string);
4360
4361 if (debug && debug->debug_message) {
4362 /* Very long debug messages are cut off, so send the
4363 * disassembly one line at a time. This causes more
4364 * overhead, but on the plus side it simplifies
4365 * parsing of resulting logs.
4366 */
4367 pipe_debug_message(debug, SHADER_INFO,
4368 "Shader Disassembly Begin");
4369
4370 line = binary->disasm_string;
4371 while (*line) {
4372 p = strchrnul(line, '\n');
4373 count = p - line;
4374
4375 if (count) {
4376 pipe_debug_message(debug, SHADER_INFO,
4377 "%.*s", count, line);
4378 }
4379
4380 if (!*p)
4381 break;
4382 line = p + 1;
4383 }
4384
4385 pipe_debug_message(debug, SHADER_INFO,
4386 "Shader Disassembly End");
4387 }
4388 } else {
4389 fprintf(stderr, "Shader %s binary:\n", name);
4390 for (i = 0; i < binary->code_size; i += 4) {
4391 fprintf(stderr, "@0x%x: %02x%02x%02x%02x\n", i,
4392 binary->code[i + 3], binary->code[i + 2],
4393 binary->code[i + 1], binary->code[i]);
4394 }
4395 }
4396 }
4397
4398 static void si_shader_dump_stats(struct si_screen *sscreen,
4399 struct si_shader_config *conf,
4400 unsigned num_inputs,
4401 unsigned code_size,
4402 struct pipe_debug_callback *debug,
4403 unsigned processor)
4404 {
4405 unsigned lds_increment = sscreen->b.chip_class >= CIK ? 512 : 256;
4406 unsigned lds_per_wave = 0;
4407 unsigned max_simd_waves = 10;
4408
4409 /* Compute LDS usage for PS. */
4410 if (processor == TGSI_PROCESSOR_FRAGMENT) {
4411 /* The minimum usage per wave is (num_inputs * 36). The maximum
4412 * usage is (num_inputs * 36 * 16).
4413 * We can get anything in between and it varies between waves.
4414 *
4415 * Other stages don't know the size at compile time or don't
4416 * allocate LDS per wave, but instead they do it per thread group.
4417 */
4418 lds_per_wave = conf->lds_size * lds_increment +
4419 align(num_inputs * 36, lds_increment);
4420 }
4421
4422 /* Compute the per-SIMD wave counts. */
4423 if (conf->num_sgprs) {
4424 if (sscreen->b.chip_class >= VI)
4425 max_simd_waves = MIN2(max_simd_waves, 800 / conf->num_sgprs);
4426 else
4427 max_simd_waves = MIN2(max_simd_waves, 512 / conf->num_sgprs);
4428 }
4429
4430 if (conf->num_vgprs)
4431 max_simd_waves = MIN2(max_simd_waves, 256 / conf->num_vgprs);
4432
4433 /* LDS is 64KB per CU (4 SIMDs), divided into 16KB blocks per SIMD
4434 * that PS can use.
4435 */
4436 if (lds_per_wave)
4437 max_simd_waves = MIN2(max_simd_waves, 16384 / lds_per_wave);
4438
4439 if (r600_can_dump_shader(&sscreen->b, processor)) {
4440 if (processor == TGSI_PROCESSOR_FRAGMENT) {
4441 fprintf(stderr, "*** SHADER CONFIG ***\n"
4442 "SPI_PS_INPUT_ADDR = 0x%04x\n"
4443 "SPI_PS_INPUT_ENA = 0x%04x\n",
4444 conf->spi_ps_input_addr, conf->spi_ps_input_ena);
4445 }
4446
4447 fprintf(stderr, "*** SHADER STATS ***\n"
4448 "SGPRS: %d\n"
4449 "VGPRS: %d\n"
4450 "Code Size: %d bytes\n"
4451 "LDS: %d blocks\n"
4452 "Scratch: %d bytes per wave\n"
4453 "Max Waves: %d\n"
4454 "********************\n",
4455 conf->num_sgprs, conf->num_vgprs, code_size,
4456 conf->lds_size, conf->scratch_bytes_per_wave,
4457 max_simd_waves);
4458 }
4459
4460 pipe_debug_message(debug, SHADER_INFO,
4461 "Shader Stats: SGPRS: %d VGPRS: %d Code Size: %d "
4462 "LDS: %d Scratch: %d Max Waves: %d",
4463 conf->num_sgprs, conf->num_vgprs, code_size,
4464 conf->lds_size, conf->scratch_bytes_per_wave,
4465 max_simd_waves);
4466 }
4467
4468 void si_shader_dump(struct si_screen *sscreen, struct si_shader *shader,
4469 struct pipe_debug_callback *debug, unsigned processor)
4470 {
4471 if (r600_can_dump_shader(&sscreen->b, processor) &&
4472 !(sscreen->b.debug_flags & DBG_NO_ASM)) {
4473 fprintf(stderr, "\n");
4474
4475 if (shader->prolog)
4476 si_shader_dump_disassembly(&shader->prolog->binary,
4477 debug, "prolog");
4478
4479 si_shader_dump_disassembly(&shader->binary, debug, "main");
4480
4481 if (shader->epilog)
4482 si_shader_dump_disassembly(&shader->epilog->binary,
4483 debug, "epilog");
4484 fprintf(stderr, "\n");
4485 }
4486
4487 si_shader_dump_stats(sscreen, &shader->config,
4488 shader->selector ? shader->selector->info.num_inputs : 0,
4489 si_get_shader_binary_size(shader), debug, processor);
4490 }
4491
4492 int si_compile_llvm(struct si_screen *sscreen,
4493 struct radeon_shader_binary *binary,
4494 struct si_shader_config *conf,
4495 LLVMTargetMachineRef tm,
4496 LLVMModuleRef mod,
4497 struct pipe_debug_callback *debug,
4498 unsigned processor,
4499 const char *name)
4500 {
4501 int r = 0;
4502 unsigned count = p_atomic_inc_return(&sscreen->b.num_compilations);
4503
4504 if (r600_can_dump_shader(&sscreen->b, processor)) {
4505 fprintf(stderr, "radeonsi: Compiling shader %d\n", count);
4506
4507 if (!(sscreen->b.debug_flags & (DBG_NO_IR | DBG_PREOPT_IR))) {
4508 fprintf(stderr, "%s LLVM IR:\n\n", name);
4509 LLVMDumpModule(mod);
4510 fprintf(stderr, "\n");
4511 }
4512 }
4513
4514 if (!si_replace_shader(count, binary)) {
4515 r = radeon_llvm_compile(mod, binary,
4516 r600_get_llvm_processor_name(sscreen->b.family), tm,
4517 debug);
4518 if (r)
4519 return r;
4520 }
4521
4522 si_shader_binary_read_config(binary, conf, 0);
4523
4524 /* Enable 64-bit and 16-bit denormals, because there is no performance
4525 * cost.
4526 *
4527 * If denormals are enabled, all floating-point output modifiers are
4528 * ignored.
4529 *
4530 * Don't enable denormals for 32-bit floats, because:
4531 * - Floating-point output modifiers would be ignored by the hw.
4532 * - Some opcodes don't support denormals, such as v_mad_f32. We would
4533 * have to stop using those.
4534 * - SI & CI would be very slow.
4535 */
4536 conf->float_mode |= V_00B028_FP_64_DENORMS;
4537
4538 FREE(binary->config);
4539 FREE(binary->global_symbol_offsets);
4540 binary->config = NULL;
4541 binary->global_symbol_offsets = NULL;
4542
4543 /* Some shaders can't have rodata because their binaries can be
4544 * concatenated.
4545 */
4546 if (binary->rodata_size &&
4547 (processor == TGSI_PROCESSOR_VERTEX ||
4548 processor == TGSI_PROCESSOR_TESS_CTRL ||
4549 processor == TGSI_PROCESSOR_TESS_EVAL ||
4550 processor == TGSI_PROCESSOR_FRAGMENT)) {
4551 fprintf(stderr, "radeonsi: The shader can't have rodata.");
4552 return -EINVAL;
4553 }
4554
4555 return r;
4556 }
4557
4558 /* Generate code for the hardware VS shader stage to go with a geometry shader */
4559 static int si_generate_gs_copy_shader(struct si_screen *sscreen,
4560 struct si_shader_context *ctx,
4561 struct si_shader *gs,
4562 struct pipe_debug_callback *debug)
4563 {
4564 struct gallivm_state *gallivm = &ctx->radeon_bld.gallivm;
4565 struct lp_build_tgsi_context *bld_base = &ctx->radeon_bld.soa.bld_base;
4566 struct lp_build_context *uint = &bld_base->uint_bld;
4567 struct si_shader_output_values *outputs;
4568 struct tgsi_shader_info *gsinfo = &gs->selector->info;
4569 LLVMValueRef args[9];
4570 int i, r;
4571
4572 outputs = MALLOC(gsinfo->num_outputs * sizeof(outputs[0]));
4573
4574 si_init_shader_ctx(ctx, sscreen, ctx->shader, ctx->tm, gsinfo);
4575 ctx->type = TGSI_PROCESSOR_VERTEX;
4576 ctx->is_gs_copy_shader = true;
4577
4578 create_meta_data(ctx);
4579 create_function(ctx);
4580 preload_streamout_buffers(ctx);
4581 preload_ring_buffers(ctx);
4582
4583 args[0] = ctx->gsvs_ring[0];
4584 args[1] = lp_build_mul_imm(uint,
4585 LLVMGetParam(ctx->radeon_bld.main_fn,
4586 ctx->param_vertex_id),
4587 4);
4588 args[3] = uint->zero;
4589 args[4] = uint->one; /* OFFEN */
4590 args[5] = uint->zero; /* IDXEN */
4591 args[6] = uint->one; /* GLC */
4592 args[7] = uint->one; /* SLC */
4593 args[8] = uint->zero; /* TFE */
4594
4595 /* Fetch vertex data from GSVS ring */
4596 for (i = 0; i < gsinfo->num_outputs; ++i) {
4597 unsigned chan;
4598
4599 outputs[i].name = gsinfo->output_semantic_name[i];
4600 outputs[i].sid = gsinfo->output_semantic_index[i];
4601
4602 for (chan = 0; chan < 4; chan++) {
4603 args[2] = lp_build_const_int32(gallivm,
4604 (i * 4 + chan) *
4605 gs->selector->gs_max_out_vertices * 16 * 4);
4606
4607 outputs[i].values[chan] =
4608 LLVMBuildBitCast(gallivm->builder,
4609 lp_build_intrinsic(gallivm->builder,
4610 "llvm.SI.buffer.load.dword.i32.i32",
4611 ctx->i32, args, 9,
4612 LLVMReadOnlyAttribute | LLVMNoUnwindAttribute),
4613 ctx->f32, "");
4614 }
4615 }
4616
4617 si_llvm_export_vs(bld_base, outputs, gsinfo->num_outputs);
4618
4619 LLVMBuildRet(gallivm->builder, ctx->return_value);
4620
4621 /* Dump LLVM IR before any optimization passes */
4622 if (sscreen->b.debug_flags & DBG_PREOPT_IR &&
4623 r600_can_dump_shader(&sscreen->b, TGSI_PROCESSOR_GEOMETRY))
4624 LLVMDumpModule(bld_base->base.gallivm->module);
4625
4626 radeon_llvm_finalize_module(&ctx->radeon_bld);
4627
4628 r = si_compile_llvm(sscreen, &ctx->shader->binary,
4629 &ctx->shader->config, ctx->tm,
4630 bld_base->base.gallivm->module,
4631 debug, TGSI_PROCESSOR_GEOMETRY,
4632 "GS Copy Shader");
4633 if (!r) {
4634 if (r600_can_dump_shader(&sscreen->b, TGSI_PROCESSOR_GEOMETRY))
4635 fprintf(stderr, "GS Copy Shader:\n");
4636 si_shader_dump(sscreen, ctx->shader, debug,
4637 TGSI_PROCESSOR_GEOMETRY);
4638 r = si_shader_binary_upload(sscreen, ctx->shader);
4639 }
4640
4641 radeon_llvm_dispose(&ctx->radeon_bld);
4642
4643 FREE(outputs);
4644 return r;
4645 }
4646
4647 void si_dump_shader_key(unsigned shader, union si_shader_key *key, FILE *f)
4648 {
4649 int i;
4650
4651 fprintf(f, "SHADER KEY\n");
4652
4653 switch (shader) {
4654 case PIPE_SHADER_VERTEX:
4655 fprintf(f, " instance_divisors = {");
4656 for (i = 0; i < Elements(key->vs.prolog.instance_divisors); i++)
4657 fprintf(f, !i ? "%u" : ", %u",
4658 key->vs.prolog.instance_divisors[i]);
4659 fprintf(f, "}\n");
4660 fprintf(f, " as_es = %u\n", key->vs.as_es);
4661 fprintf(f, " as_ls = %u\n", key->vs.as_ls);
4662 fprintf(f, " export_prim_id = %u\n", key->vs.epilog.export_prim_id);
4663 break;
4664
4665 case PIPE_SHADER_TESS_CTRL:
4666 fprintf(f, " prim_mode = %u\n", key->tcs.epilog.prim_mode);
4667 break;
4668
4669 case PIPE_SHADER_TESS_EVAL:
4670 fprintf(f, " as_es = %u\n", key->tes.as_es);
4671 fprintf(f, " export_prim_id = %u\n", key->tes.epilog.export_prim_id);
4672 break;
4673
4674 case PIPE_SHADER_GEOMETRY:
4675 break;
4676
4677 case PIPE_SHADER_FRAGMENT:
4678 fprintf(f, " prolog.color_two_side = %u\n", key->ps.prolog.color_two_side);
4679 fprintf(f, " prolog.poly_stipple = %u\n", key->ps.prolog.poly_stipple);
4680 fprintf(f, " prolog.force_persample_interp = %u\n", key->ps.prolog.force_persample_interp);
4681 fprintf(f, " epilog.spi_shader_col_format = 0x%x\n", key->ps.epilog.spi_shader_col_format);
4682 fprintf(f, " epilog.color_is_int8 = 0x%X\n", key->ps.epilog.color_is_int8);
4683 fprintf(f, " epilog.last_cbuf = %u\n", key->ps.epilog.last_cbuf);
4684 fprintf(f, " epilog.alpha_func = %u\n", key->ps.epilog.alpha_func);
4685 fprintf(f, " epilog.alpha_to_one = %u\n", key->ps.epilog.alpha_to_one);
4686 fprintf(f, " epilog.poly_line_smoothing = %u\n", key->ps.epilog.poly_line_smoothing);
4687 fprintf(f, " epilog.clamp_color = %u\n", key->ps.epilog.clamp_color);
4688 break;
4689
4690 default:
4691 assert(0);
4692 }
4693 }
4694
4695 static void si_init_shader_ctx(struct si_shader_context *ctx,
4696 struct si_screen *sscreen,
4697 struct si_shader *shader,
4698 LLVMTargetMachineRef tm,
4699 struct tgsi_shader_info *info)
4700 {
4701 struct lp_build_tgsi_context *bld_base;
4702
4703 memset(ctx, 0, sizeof(*ctx));
4704 radeon_llvm_context_init(&ctx->radeon_bld, "amdgcn--");
4705 ctx->tm = tm;
4706 ctx->screen = sscreen;
4707 if (shader && shader->selector)
4708 ctx->type = shader->selector->info.processor;
4709 else
4710 ctx->type = -1;
4711 ctx->shader = shader;
4712
4713 ctx->voidt = LLVMVoidTypeInContext(ctx->radeon_bld.gallivm.context);
4714 ctx->i1 = LLVMInt1TypeInContext(ctx->radeon_bld.gallivm.context);
4715 ctx->i8 = LLVMInt8TypeInContext(ctx->radeon_bld.gallivm.context);
4716 ctx->i32 = LLVMInt32TypeInContext(ctx->radeon_bld.gallivm.context);
4717 ctx->i64 = LLVMInt64TypeInContext(ctx->radeon_bld.gallivm.context);
4718 ctx->i128 = LLVMIntTypeInContext(ctx->radeon_bld.gallivm.context, 128);
4719 ctx->f32 = LLVMFloatTypeInContext(ctx->radeon_bld.gallivm.context);
4720 ctx->v16i8 = LLVMVectorType(ctx->i8, 16);
4721 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
4722 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
4723 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
4724 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
4725
4726 bld_base = &ctx->radeon_bld.soa.bld_base;
4727 bld_base->info = info;
4728 bld_base->emit_fetch_funcs[TGSI_FILE_CONSTANT] = fetch_constant;
4729
4730 bld_base->op_actions[TGSI_OPCODE_INTERP_CENTROID] = interp_action;
4731 bld_base->op_actions[TGSI_OPCODE_INTERP_SAMPLE] = interp_action;
4732 bld_base->op_actions[TGSI_OPCODE_INTERP_OFFSET] = interp_action;
4733
4734 bld_base->op_actions[TGSI_OPCODE_TEX] = tex_action;
4735 bld_base->op_actions[TGSI_OPCODE_TEX2] = tex_action;
4736 bld_base->op_actions[TGSI_OPCODE_TXB] = tex_action;
4737 bld_base->op_actions[TGSI_OPCODE_TXB2] = tex_action;
4738 bld_base->op_actions[TGSI_OPCODE_TXD] = tex_action;
4739 bld_base->op_actions[TGSI_OPCODE_TXF] = tex_action;
4740 bld_base->op_actions[TGSI_OPCODE_TXL] = tex_action;
4741 bld_base->op_actions[TGSI_OPCODE_TXL2] = tex_action;
4742 bld_base->op_actions[TGSI_OPCODE_TXP] = tex_action;
4743 bld_base->op_actions[TGSI_OPCODE_TXQ] = tex_action;
4744 bld_base->op_actions[TGSI_OPCODE_TG4] = tex_action;
4745 bld_base->op_actions[TGSI_OPCODE_LODQ] = tex_action;
4746 bld_base->op_actions[TGSI_OPCODE_TXQS].emit = si_llvm_emit_txqs;
4747
4748 bld_base->op_actions[TGSI_OPCODE_DDX].emit = si_llvm_emit_ddxy;
4749 bld_base->op_actions[TGSI_OPCODE_DDY].emit = si_llvm_emit_ddxy;
4750 bld_base->op_actions[TGSI_OPCODE_DDX_FINE].emit = si_llvm_emit_ddxy;
4751 bld_base->op_actions[TGSI_OPCODE_DDY_FINE].emit = si_llvm_emit_ddxy;
4752
4753 bld_base->op_actions[TGSI_OPCODE_EMIT].emit = si_llvm_emit_vertex;
4754 bld_base->op_actions[TGSI_OPCODE_ENDPRIM].emit = si_llvm_emit_primitive;
4755 bld_base->op_actions[TGSI_OPCODE_BARRIER].emit = si_llvm_emit_barrier;
4756
4757 bld_base->op_actions[TGSI_OPCODE_MAX].emit = build_tgsi_intrinsic_nomem;
4758 bld_base->op_actions[TGSI_OPCODE_MAX].intr_name = "llvm.maxnum.f32";
4759 bld_base->op_actions[TGSI_OPCODE_MIN].emit = build_tgsi_intrinsic_nomem;
4760 bld_base->op_actions[TGSI_OPCODE_MIN].intr_name = "llvm.minnum.f32";
4761 }
4762
4763 static int si_compile_tgsi_shader(struct si_screen *sscreen,
4764 LLVMTargetMachineRef tm,
4765 struct si_shader *shader,
4766 bool is_monolithic,
4767 struct pipe_debug_callback *debug)
4768 {
4769 struct si_shader_selector *sel = shader->selector;
4770 struct tgsi_token *tokens = sel->tokens;
4771 struct si_shader_context ctx;
4772 struct lp_build_tgsi_context *bld_base;
4773 struct tgsi_shader_info stipple_shader_info;
4774 LLVMModuleRef mod;
4775 int r = 0;
4776 bool poly_stipple = sel->type == PIPE_SHADER_FRAGMENT &&
4777 shader->key.ps.prolog.poly_stipple;
4778
4779 if (poly_stipple) {
4780 tokens = util_pstipple_create_fragment_shader(tokens, NULL,
4781 SI_POLY_STIPPLE_SAMPLER,
4782 TGSI_FILE_SYSTEM_VALUE);
4783 tgsi_scan_shader(tokens, &stipple_shader_info);
4784 }
4785
4786 /* Dump TGSI code before doing TGSI->LLVM conversion in case the
4787 * conversion fails. */
4788 if (r600_can_dump_shader(&sscreen->b, sel->info.processor) &&
4789 !(sscreen->b.debug_flags & DBG_NO_TGSI)) {
4790 si_dump_shader_key(sel->type, &shader->key, stderr);
4791 tgsi_dump(tokens, 0);
4792 si_dump_streamout(&sel->so);
4793 }
4794
4795 si_init_shader_ctx(&ctx, sscreen, shader, tm,
4796 poly_stipple ? &stipple_shader_info : &sel->info);
4797 ctx.is_monolithic = is_monolithic;
4798
4799 shader->uses_instanceid = sel->info.uses_instanceid;
4800
4801 bld_base = &ctx.radeon_bld.soa.bld_base;
4802 ctx.radeon_bld.load_system_value = declare_system_value;
4803
4804 switch (ctx.type) {
4805 case TGSI_PROCESSOR_VERTEX:
4806 ctx.radeon_bld.load_input = declare_input_vs;
4807 if (shader->key.vs.as_ls)
4808 bld_base->emit_epilogue = si_llvm_emit_ls_epilogue;
4809 else if (shader->key.vs.as_es)
4810 bld_base->emit_epilogue = si_llvm_emit_es_epilogue;
4811 else
4812 bld_base->emit_epilogue = si_llvm_emit_vs_epilogue;
4813 break;
4814 case TGSI_PROCESSOR_TESS_CTRL:
4815 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_tcs;
4816 bld_base->emit_fetch_funcs[TGSI_FILE_OUTPUT] = fetch_output_tcs;
4817 bld_base->emit_store = store_output_tcs;
4818 bld_base->emit_epilogue = si_llvm_emit_tcs_epilogue;
4819 break;
4820 case TGSI_PROCESSOR_TESS_EVAL:
4821 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_tes;
4822 if (shader->key.tes.as_es)
4823 bld_base->emit_epilogue = si_llvm_emit_es_epilogue;
4824 else
4825 bld_base->emit_epilogue = si_llvm_emit_vs_epilogue;
4826 break;
4827 case TGSI_PROCESSOR_GEOMETRY:
4828 bld_base->emit_fetch_funcs[TGSI_FILE_INPUT] = fetch_input_gs;
4829 bld_base->emit_epilogue = si_llvm_emit_gs_epilogue;
4830 break;
4831 case TGSI_PROCESSOR_FRAGMENT:
4832 ctx.radeon_bld.load_input = declare_input_fs;
4833 if (is_monolithic)
4834 bld_base->emit_epilogue = si_llvm_emit_fs_epilogue;
4835 else
4836 bld_base->emit_epilogue = si_llvm_return_fs_outputs;
4837 break;
4838 default:
4839 assert(!"Unsupported shader type");
4840 return -1;
4841 }
4842
4843 create_meta_data(&ctx);
4844 create_function(&ctx);
4845 preload_constants(&ctx);
4846 preload_samplers(&ctx);
4847 preload_streamout_buffers(&ctx);
4848 preload_ring_buffers(&ctx);
4849
4850 if (ctx.type == TGSI_PROCESSOR_GEOMETRY) {
4851 int i;
4852 for (i = 0; i < 4; i++) {
4853 ctx.gs_next_vertex[i] =
4854 lp_build_alloca(bld_base->base.gallivm,
4855 ctx.i32, "");
4856 }
4857 }
4858
4859 if (!lp_build_tgsi_llvm(bld_base, tokens)) {
4860 fprintf(stderr, "Failed to translate shader from TGSI to LLVM\n");
4861 goto out;
4862 }
4863
4864 LLVMBuildRet(bld_base->base.gallivm->builder, ctx.return_value);
4865 mod = bld_base->base.gallivm->module;
4866
4867 /* Dump LLVM IR before any optimization passes */
4868 if (sscreen->b.debug_flags & DBG_PREOPT_IR &&
4869 r600_can_dump_shader(&sscreen->b, ctx.type))
4870 LLVMDumpModule(mod);
4871
4872 radeon_llvm_finalize_module(&ctx.radeon_bld);
4873
4874 r = si_compile_llvm(sscreen, &shader->binary, &shader->config, tm,
4875 mod, debug, ctx.type, "TGSI shader");
4876 if (r) {
4877 fprintf(stderr, "LLVM failed to compile shader\n");
4878 goto out;
4879 }
4880
4881 radeon_llvm_dispose(&ctx.radeon_bld);
4882
4883 /* Calculate the number of fragment input VGPRs. */
4884 if (ctx.type == TGSI_PROCESSOR_FRAGMENT) {
4885 shader->num_input_vgprs = 0;
4886 shader->face_vgpr_index = -1;
4887
4888 if (G_0286CC_PERSP_SAMPLE_ENA(shader->config.spi_ps_input_addr))
4889 shader->num_input_vgprs += 2;
4890 if (G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_addr))
4891 shader->num_input_vgprs += 2;
4892 if (G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_addr))
4893 shader->num_input_vgprs += 2;
4894 if (G_0286CC_PERSP_PULL_MODEL_ENA(shader->config.spi_ps_input_addr))
4895 shader->num_input_vgprs += 3;
4896 if (G_0286CC_LINEAR_SAMPLE_ENA(shader->config.spi_ps_input_addr))
4897 shader->num_input_vgprs += 2;
4898 if (G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_addr))
4899 shader->num_input_vgprs += 2;
4900 if (G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_addr))
4901 shader->num_input_vgprs += 2;
4902 if (G_0286CC_LINE_STIPPLE_TEX_ENA(shader->config.spi_ps_input_addr))
4903 shader->num_input_vgprs += 1;
4904 if (G_0286CC_POS_X_FLOAT_ENA(shader->config.spi_ps_input_addr))
4905 shader->num_input_vgprs += 1;
4906 if (G_0286CC_POS_Y_FLOAT_ENA(shader->config.spi_ps_input_addr))
4907 shader->num_input_vgprs += 1;
4908 if (G_0286CC_POS_Z_FLOAT_ENA(shader->config.spi_ps_input_addr))
4909 shader->num_input_vgprs += 1;
4910 if (G_0286CC_POS_W_FLOAT_ENA(shader->config.spi_ps_input_addr))
4911 shader->num_input_vgprs += 1;
4912 if (G_0286CC_FRONT_FACE_ENA(shader->config.spi_ps_input_addr)) {
4913 shader->face_vgpr_index = shader->num_input_vgprs;
4914 shader->num_input_vgprs += 1;
4915 }
4916 if (G_0286CC_ANCILLARY_ENA(shader->config.spi_ps_input_addr))
4917 shader->num_input_vgprs += 1;
4918 if (G_0286CC_SAMPLE_COVERAGE_ENA(shader->config.spi_ps_input_addr))
4919 shader->num_input_vgprs += 1;
4920 if (G_0286CC_POS_FIXED_PT_ENA(shader->config.spi_ps_input_addr))
4921 shader->num_input_vgprs += 1;
4922 }
4923
4924 if (ctx.type == TGSI_PROCESSOR_GEOMETRY) {
4925 shader->gs_copy_shader = CALLOC_STRUCT(si_shader);
4926 shader->gs_copy_shader->selector = shader->selector;
4927 ctx.shader = shader->gs_copy_shader;
4928 if ((r = si_generate_gs_copy_shader(sscreen, &ctx,
4929 shader, debug))) {
4930 free(shader->gs_copy_shader);
4931 shader->gs_copy_shader = NULL;
4932 goto out;
4933 }
4934 }
4935
4936 out:
4937 for (int i = 0; i < SI_NUM_CONST_BUFFERS; i++)
4938 FREE(ctx.constants[i]);
4939 if (poly_stipple)
4940 tgsi_free_tokens(tokens);
4941 return r;
4942 }
4943
4944 /**
4945 * Create, compile and return a shader part (prolog or epilog).
4946 *
4947 * \param sscreen screen
4948 * \param list list of shader parts of the same category
4949 * \param key shader part key
4950 * \param tm LLVM target machine
4951 * \param debug debug callback
4952 * \param compile the callback responsible for compilation
4953 * \return non-NULL on success
4954 */
4955 static struct si_shader_part *
4956 si_get_shader_part(struct si_screen *sscreen,
4957 struct si_shader_part **list,
4958 union si_shader_part_key *key,
4959 LLVMTargetMachineRef tm,
4960 struct pipe_debug_callback *debug,
4961 bool (*compile)(struct si_screen *,
4962 LLVMTargetMachineRef,
4963 struct pipe_debug_callback *,
4964 struct si_shader_part *))
4965 {
4966 struct si_shader_part *result;
4967
4968 pipe_mutex_lock(sscreen->shader_parts_mutex);
4969
4970 /* Find existing. */
4971 for (result = *list; result; result = result->next) {
4972 if (memcmp(&result->key, key, sizeof(*key)) == 0) {
4973 pipe_mutex_unlock(sscreen->shader_parts_mutex);
4974 return result;
4975 }
4976 }
4977
4978 /* Compile a new one. */
4979 result = CALLOC_STRUCT(si_shader_part);
4980 result->key = *key;
4981 if (!compile(sscreen, tm, debug, result)) {
4982 FREE(result);
4983 pipe_mutex_unlock(sscreen->shader_parts_mutex);
4984 return NULL;
4985 }
4986
4987 result->next = *list;
4988 *list = result;
4989 pipe_mutex_unlock(sscreen->shader_parts_mutex);
4990 return result;
4991 }
4992
4993 /**
4994 * Create a vertex shader prolog.
4995 *
4996 * The inputs are the same as VS (a lot of SGPRs and 4 VGPR system values).
4997 * All inputs are returned unmodified. The vertex load indices are
4998 * stored after them, which will used by the API VS for fetching inputs.
4999 *
5000 * For example, the expected outputs for instance_divisors[] = {0, 1, 2} are:
5001 * input_v0,
5002 * input_v1,
5003 * input_v2,
5004 * input_v3,
5005 * (VertexID + BaseVertex),
5006 * (InstanceID + StartInstance),
5007 * (InstanceID / 2 + StartInstance)
5008 */
5009 static bool si_compile_vs_prolog(struct si_screen *sscreen,
5010 LLVMTargetMachineRef tm,
5011 struct pipe_debug_callback *debug,
5012 struct si_shader_part *out)
5013 {
5014 union si_shader_part_key *key = &out->key;
5015 struct si_shader shader = {};
5016 struct si_shader_context ctx;
5017 struct gallivm_state *gallivm = &ctx.radeon_bld.gallivm;
5018 LLVMTypeRef *params, *returns;
5019 LLVMValueRef ret, func;
5020 int last_sgpr, num_params, num_returns, i;
5021 bool status = true;
5022
5023 si_init_shader_ctx(&ctx, sscreen, &shader, tm, NULL);
5024 ctx.type = TGSI_PROCESSOR_VERTEX;
5025 ctx.param_vertex_id = key->vs_prolog.num_input_sgprs;
5026 ctx.param_instance_id = key->vs_prolog.num_input_sgprs + 3;
5027
5028 /* 4 preloaded VGPRs + vertex load indices as prolog outputs */
5029 params = alloca((key->vs_prolog.num_input_sgprs + 4) *
5030 sizeof(LLVMTypeRef));
5031 returns = alloca((key->vs_prolog.num_input_sgprs + 4 +
5032 key->vs_prolog.last_input + 1) *
5033 sizeof(LLVMTypeRef));
5034 num_params = 0;
5035 num_returns = 0;
5036
5037 /* Declare input and output SGPRs. */
5038 num_params = 0;
5039 for (i = 0; i < key->vs_prolog.num_input_sgprs; i++) {
5040 params[num_params++] = ctx.i32;
5041 returns[num_returns++] = ctx.i32;
5042 }
5043 last_sgpr = num_params - 1;
5044
5045 /* 4 preloaded VGPRs (outputs must be floats) */
5046 for (i = 0; i < 4; i++) {
5047 params[num_params++] = ctx.i32;
5048 returns[num_returns++] = ctx.f32;
5049 }
5050
5051 /* Vertex load indices. */
5052 for (i = 0; i <= key->vs_prolog.last_input; i++)
5053 returns[num_returns++] = ctx.f32;
5054
5055 /* Create the function. */
5056 si_create_function(&ctx, returns, num_returns, params,
5057 num_params, -1, last_sgpr);
5058 func = ctx.radeon_bld.main_fn;
5059
5060 /* Copy inputs to outputs. This should be no-op, as the registers match,
5061 * but it will prevent the compiler from overwriting them unintentionally.
5062 */
5063 ret = ctx.return_value;
5064 for (i = 0; i < key->vs_prolog.num_input_sgprs; i++) {
5065 LLVMValueRef p = LLVMGetParam(func, i);
5066 ret = LLVMBuildInsertValue(gallivm->builder, ret, p, i, "");
5067 }
5068 for (i = num_params - 4; i < num_params; i++) {
5069 LLVMValueRef p = LLVMGetParam(func, i);
5070 p = LLVMBuildBitCast(gallivm->builder, p, ctx.f32, "");
5071 ret = LLVMBuildInsertValue(gallivm->builder, ret, p, i, "");
5072 }
5073
5074 /* Compute vertex load indices from instance divisors. */
5075 for (i = 0; i <= key->vs_prolog.last_input; i++) {
5076 unsigned divisor = key->vs_prolog.states.instance_divisors[i];
5077 LLVMValueRef index;
5078
5079 if (divisor) {
5080 /* InstanceID / Divisor + StartInstance */
5081 index = get_instance_index_for_fetch(&ctx.radeon_bld,
5082 SI_SGPR_START_INSTANCE,
5083 divisor);
5084 } else {
5085 /* VertexID + BaseVertex */
5086 index = LLVMBuildAdd(gallivm->builder,
5087 LLVMGetParam(func, ctx.param_vertex_id),
5088 LLVMGetParam(func, SI_SGPR_BASE_VERTEX), "");
5089 }
5090
5091 index = LLVMBuildBitCast(gallivm->builder, index, ctx.f32, "");
5092 ret = LLVMBuildInsertValue(gallivm->builder, ret, index,
5093 num_params++, "");
5094 }
5095
5096 /* Compile. */
5097 LLVMBuildRet(gallivm->builder, ret);
5098 radeon_llvm_finalize_module(&ctx.radeon_bld);
5099
5100 if (si_compile_llvm(sscreen, &out->binary, &out->config, tm,
5101 gallivm->module, debug, ctx.type,
5102 "Vertex Shader Prolog"))
5103 status = false;
5104
5105 radeon_llvm_dispose(&ctx.radeon_bld);
5106 return status;
5107 }
5108
5109 /**
5110 * Compile the vertex shader epilog. This is also used by the tessellation
5111 * evaluation shader compiled as VS.
5112 *
5113 * The input is PrimitiveID.
5114 *
5115 * If PrimitiveID is required by the pixel shader, export it.
5116 * Otherwise, do nothing.
5117 */
5118 static bool si_compile_vs_epilog(struct si_screen *sscreen,
5119 LLVMTargetMachineRef tm,
5120 struct pipe_debug_callback *debug,
5121 struct si_shader_part *out)
5122 {
5123 union si_shader_part_key *key = &out->key;
5124 struct si_shader_context ctx;
5125 struct gallivm_state *gallivm = &ctx.radeon_bld.gallivm;
5126 struct lp_build_tgsi_context *bld_base = &ctx.radeon_bld.soa.bld_base;
5127 LLVMTypeRef params[5];
5128 int num_params, i;
5129 bool status = true;
5130
5131 si_init_shader_ctx(&ctx, sscreen, NULL, tm, NULL);
5132 ctx.type = TGSI_PROCESSOR_VERTEX;
5133
5134 /* Declare input VGPRs. */
5135 num_params = key->vs_epilog.states.export_prim_id ?
5136 (VS_EPILOG_PRIMID_LOC + 1) : 0;
5137 assert(num_params <= ARRAY_SIZE(params));
5138
5139 for (i = 0; i < num_params; i++)
5140 params[i] = ctx.f32;
5141
5142 /* Create the function. */
5143 si_create_function(&ctx, NULL, 0, params, num_params,
5144 -1, -1);
5145
5146 /* Emit exports. */
5147 if (key->vs_epilog.states.export_prim_id) {
5148 struct lp_build_context *base = &bld_base->base;
5149 struct lp_build_context *uint = &bld_base->uint_bld;
5150 LLVMValueRef args[9];
5151
5152 args[0] = lp_build_const_int32(base->gallivm, 0x0); /* enabled channels */
5153 args[1] = uint->zero; /* whether the EXEC mask is valid */
5154 args[2] = uint->zero; /* DONE bit */
5155 args[3] = lp_build_const_int32(base->gallivm, V_008DFC_SQ_EXP_PARAM +
5156 key->vs_epilog.prim_id_param_offset);
5157 args[4] = uint->zero; /* COMPR flag (0 = 32-bit export) */
5158 args[5] = LLVMGetParam(ctx.radeon_bld.main_fn,
5159 VS_EPILOG_PRIMID_LOC); /* X */
5160 args[6] = uint->undef; /* Y */
5161 args[7] = uint->undef; /* Z */
5162 args[8] = uint->undef; /* W */
5163
5164 lp_build_intrinsic(base->gallivm->builder, "llvm.SI.export",
5165 LLVMVoidTypeInContext(base->gallivm->context),
5166 args, 9, 0);
5167 }
5168
5169 /* Compile. */
5170 LLVMBuildRet(gallivm->builder, ctx.return_value);
5171 radeon_llvm_finalize_module(&ctx.radeon_bld);
5172
5173 if (si_compile_llvm(sscreen, &out->binary, &out->config, tm,
5174 gallivm->module, debug, ctx.type,
5175 "Vertex Shader Epilog"))
5176 status = false;
5177
5178 radeon_llvm_dispose(&ctx.radeon_bld);
5179 return status;
5180 }
5181
5182 /**
5183 * Create & compile a vertex shader epilog. This a helper used by VS and TES.
5184 */
5185 static bool si_get_vs_epilog(struct si_screen *sscreen,
5186 LLVMTargetMachineRef tm,
5187 struct si_shader *shader,
5188 struct pipe_debug_callback *debug,
5189 struct si_vs_epilog_bits *states)
5190 {
5191 union si_shader_part_key epilog_key;
5192
5193 memset(&epilog_key, 0, sizeof(epilog_key));
5194 epilog_key.vs_epilog.states = *states;
5195
5196 /* Set up the PrimitiveID output. */
5197 if (shader->key.vs.epilog.export_prim_id) {
5198 unsigned index = shader->selector->info.num_outputs;
5199 unsigned offset = shader->nr_param_exports++;
5200
5201 epilog_key.vs_epilog.prim_id_param_offset = offset;
5202 shader->vs_output_param_offset[index] = offset;
5203 }
5204
5205 shader->epilog = si_get_shader_part(sscreen, &sscreen->vs_epilogs,
5206 &epilog_key, tm, debug,
5207 si_compile_vs_epilog);
5208 return shader->epilog != NULL;
5209 }
5210
5211 /**
5212 * Select and compile (or reuse) vertex shader parts (prolog & epilog).
5213 */
5214 static bool si_shader_select_vs_parts(struct si_screen *sscreen,
5215 LLVMTargetMachineRef tm,
5216 struct si_shader *shader,
5217 struct pipe_debug_callback *debug)
5218 {
5219 struct tgsi_shader_info *info = &shader->selector->info;
5220 union si_shader_part_key prolog_key;
5221 unsigned i;
5222
5223 /* Get the prolog. */
5224 memset(&prolog_key, 0, sizeof(prolog_key));
5225 prolog_key.vs_prolog.states = shader->key.vs.prolog;
5226 prolog_key.vs_prolog.num_input_sgprs = shader->num_input_sgprs;
5227 prolog_key.vs_prolog.last_input = MAX2(1, info->num_inputs) - 1;
5228
5229 /* The prolog is a no-op if there are no inputs. */
5230 if (info->num_inputs) {
5231 shader->prolog =
5232 si_get_shader_part(sscreen, &sscreen->vs_prologs,
5233 &prolog_key, tm, debug,
5234 si_compile_vs_prolog);
5235 if (!shader->prolog)
5236 return false;
5237 }
5238
5239 /* Get the epilog. */
5240 if (!shader->key.vs.as_es && !shader->key.vs.as_ls &&
5241 !si_get_vs_epilog(sscreen, tm, shader, debug,
5242 &shader->key.vs.epilog))
5243 return false;
5244
5245 /* Set the instanceID flag. */
5246 for (i = 0; i < info->num_inputs; i++)
5247 if (prolog_key.vs_prolog.states.instance_divisors[i])
5248 shader->uses_instanceid = true;
5249
5250 return true;
5251 }
5252
5253 /**
5254 * Select and compile (or reuse) TES parts (epilog).
5255 */
5256 static bool si_shader_select_tes_parts(struct si_screen *sscreen,
5257 LLVMTargetMachineRef tm,
5258 struct si_shader *shader,
5259 struct pipe_debug_callback *debug)
5260 {
5261 if (shader->key.tes.as_es)
5262 return true;
5263
5264 /* TES compiled as VS. */
5265 return si_get_vs_epilog(sscreen, tm, shader, debug,
5266 &shader->key.tes.epilog);
5267 }
5268
5269 /**
5270 * Compile the TCS epilog. This writes tesselation factors to memory based on
5271 * the output primitive type of the tesselator (determined by TES).
5272 */
5273 static bool si_compile_tcs_epilog(struct si_screen *sscreen,
5274 LLVMTargetMachineRef tm,
5275 struct pipe_debug_callback *debug,
5276 struct si_shader_part *out)
5277 {
5278 union si_shader_part_key *key = &out->key;
5279 struct si_shader shader = {};
5280 struct si_shader_context ctx;
5281 struct gallivm_state *gallivm = &ctx.radeon_bld.gallivm;
5282 struct lp_build_tgsi_context *bld_base = &ctx.radeon_bld.soa.bld_base;
5283 LLVMTypeRef params[16];
5284 LLVMValueRef func;
5285 int last_array_pointer, last_sgpr, num_params;
5286 bool status = true;
5287
5288 si_init_shader_ctx(&ctx, sscreen, &shader, tm, NULL);
5289 ctx.type = TGSI_PROCESSOR_TESS_CTRL;
5290 shader.key.tcs.epilog = key->tcs_epilog.states;
5291
5292 /* Declare inputs. Only RW_BUFFERS and TESS_FACTOR_OFFSET are used. */
5293 params[SI_PARAM_RW_BUFFERS] = const_array(ctx.v16i8, SI_NUM_RW_BUFFERS);
5294 last_array_pointer = SI_PARAM_RW_BUFFERS;
5295 params[SI_PARAM_CONST_BUFFERS] = ctx.i64;
5296 params[SI_PARAM_SAMPLERS] = ctx.i64;
5297 params[SI_PARAM_UNUSED] = ctx.i64;
5298 params[SI_PARAM_TCS_OUT_OFFSETS] = ctx.i32;
5299 params[SI_PARAM_TCS_OUT_LAYOUT] = ctx.i32;
5300 params[SI_PARAM_TCS_IN_LAYOUT] = ctx.i32;
5301 params[SI_PARAM_TESS_FACTOR_OFFSET] = ctx.i32;
5302 last_sgpr = SI_PARAM_TESS_FACTOR_OFFSET;
5303 num_params = last_sgpr + 1;
5304
5305 params[num_params++] = ctx.i32; /* patch index within the wave (REL_PATCH_ID) */
5306 params[num_params++] = ctx.i32; /* invocation ID within the patch */
5307 params[num_params++] = ctx.i32; /* LDS offset where tess factors should be loaded from */
5308
5309 /* Create the function. */
5310 si_create_function(&ctx, NULL, 0, params, num_params,
5311 last_array_pointer, last_sgpr);
5312 declare_tess_lds(&ctx);
5313 func = ctx.radeon_bld.main_fn;
5314
5315 si_write_tess_factors(bld_base,
5316 LLVMGetParam(func, last_sgpr + 1),
5317 LLVMGetParam(func, last_sgpr + 2),
5318 LLVMGetParam(func, last_sgpr + 3));
5319
5320 /* Compile. */
5321 LLVMBuildRet(gallivm->builder, ctx.return_value);
5322 radeon_llvm_finalize_module(&ctx.radeon_bld);
5323
5324 if (si_compile_llvm(sscreen, &out->binary, &out->config, tm,
5325 gallivm->module, debug, ctx.type,
5326 "Tessellation Control Shader Epilog"))
5327 status = false;
5328
5329 radeon_llvm_dispose(&ctx.radeon_bld);
5330 return status;
5331 }
5332
5333 /**
5334 * Select and compile (or reuse) TCS parts (epilog).
5335 */
5336 static bool si_shader_select_tcs_parts(struct si_screen *sscreen,
5337 LLVMTargetMachineRef tm,
5338 struct si_shader *shader,
5339 struct pipe_debug_callback *debug)
5340 {
5341 union si_shader_part_key epilog_key;
5342
5343 /* Get the epilog. */
5344 memset(&epilog_key, 0, sizeof(epilog_key));
5345 epilog_key.tcs_epilog.states = shader->key.tcs.epilog;
5346
5347 shader->epilog = si_get_shader_part(sscreen, &sscreen->tcs_epilogs,
5348 &epilog_key, tm, debug,
5349 si_compile_tcs_epilog);
5350 return shader->epilog != NULL;
5351 }
5352
5353 /**
5354 * Compile the pixel shader prolog. This handles:
5355 * - two-side color selection and interpolation
5356 * - overriding interpolation parameters for the API PS
5357 * - polygon stippling
5358 *
5359 * All preloaded SGPRs and VGPRs are passed through unmodified unless they are
5360 * overriden by other states. (e.g. per-sample interpolation)
5361 * Interpolated colors are stored after the preloaded VGPRs.
5362 */
5363 static bool si_compile_ps_prolog(struct si_screen *sscreen,
5364 LLVMTargetMachineRef tm,
5365 struct pipe_debug_callback *debug,
5366 struct si_shader_part *out)
5367 {
5368 union si_shader_part_key *key = &out->key;
5369 struct si_shader shader = {};
5370 struct si_shader_context ctx;
5371 struct gallivm_state *gallivm = &ctx.radeon_bld.gallivm;
5372 LLVMTypeRef *params;
5373 LLVMValueRef ret, func;
5374 int last_sgpr, num_params, num_returns, i, num_color_channels;
5375 bool status = true;
5376
5377 si_init_shader_ctx(&ctx, sscreen, &shader, tm, NULL);
5378 ctx.type = TGSI_PROCESSOR_FRAGMENT;
5379 shader.key.ps.prolog = key->ps_prolog.states;
5380
5381 /* Number of inputs + 8 color elements. */
5382 params = alloca((key->ps_prolog.num_input_sgprs +
5383 key->ps_prolog.num_input_vgprs + 8) *
5384 sizeof(LLVMTypeRef));
5385
5386 /* Declare inputs. */
5387 num_params = 0;
5388 for (i = 0; i < key->ps_prolog.num_input_sgprs; i++)
5389 params[num_params++] = ctx.i32;
5390 last_sgpr = num_params - 1;
5391
5392 for (i = 0; i < key->ps_prolog.num_input_vgprs; i++)
5393 params[num_params++] = ctx.f32;
5394
5395 /* Declare outputs (same as inputs + add colors if needed) */
5396 num_returns = num_params;
5397 num_color_channels = util_bitcount(key->ps_prolog.colors_read);
5398 for (i = 0; i < num_color_channels; i++)
5399 params[num_returns++] = ctx.f32;
5400
5401 /* Create the function. */
5402 si_create_function(&ctx, params, num_returns, params,
5403 num_params, -1, last_sgpr);
5404 func = ctx.radeon_bld.main_fn;
5405
5406 /* Copy inputs to outputs. This should be no-op, as the registers match,
5407 * but it will prevent the compiler from overwriting them unintentionally.
5408 */
5409 ret = ctx.return_value;
5410 for (i = 0; i < num_params; i++) {
5411 LLVMValueRef p = LLVMGetParam(func, i);
5412 ret = LLVMBuildInsertValue(gallivm->builder, ret, p, i, "");
5413 }
5414
5415 /* Interpolate colors. */
5416 for (i = 0; i < 2; i++) {
5417 unsigned writemask = (key->ps_prolog.colors_read >> (i * 4)) & 0xf;
5418 unsigned face_vgpr = key->ps_prolog.num_input_sgprs +
5419 key->ps_prolog.face_vgpr_index;
5420 LLVMValueRef interp[2], color[4];
5421 LLVMValueRef interp_ij = NULL, prim_mask = NULL, face = NULL;
5422
5423 if (!writemask)
5424 continue;
5425
5426 /* If the interpolation qualifier is not CONSTANT (-1). */
5427 if (key->ps_prolog.color_interp_vgpr_index[i] != -1) {
5428 unsigned interp_vgpr = key->ps_prolog.num_input_sgprs +
5429 key->ps_prolog.color_interp_vgpr_index[i];
5430
5431 interp[0] = LLVMGetParam(func, interp_vgpr);
5432 interp[1] = LLVMGetParam(func, interp_vgpr + 1);
5433 interp_ij = lp_build_gather_values(gallivm, interp, 2);
5434 interp_ij = LLVMBuildBitCast(gallivm->builder, interp_ij,
5435 ctx.v2i32, "");
5436 }
5437
5438 /* Use the absolute location of the input. */
5439 prim_mask = LLVMGetParam(func, SI_PS_NUM_USER_SGPR);
5440
5441 if (key->ps_prolog.states.color_two_side) {
5442 face = LLVMGetParam(func, face_vgpr);
5443 face = LLVMBuildBitCast(gallivm->builder, face, ctx.i32, "");
5444 }
5445
5446 interp_fs_input(&ctx,
5447 key->ps_prolog.color_attr_index[i],
5448 TGSI_SEMANTIC_COLOR, i,
5449 key->ps_prolog.num_interp_inputs,
5450 key->ps_prolog.colors_read, interp_ij,
5451 prim_mask, face, color);
5452
5453 while (writemask) {
5454 unsigned chan = u_bit_scan(&writemask);
5455 ret = LLVMBuildInsertValue(gallivm->builder, ret, color[chan],
5456 num_params++, "");
5457 }
5458 }
5459
5460 /* Force per-sample interpolation. */
5461 if (key->ps_prolog.states.force_persample_interp) {
5462 unsigned i, base = key->ps_prolog.num_input_sgprs;
5463 LLVMValueRef persp_sample[2], linear_sample[2];
5464
5465 /* Read PERSP_SAMPLE. */
5466 for (i = 0; i < 2; i++)
5467 persp_sample[i] = LLVMGetParam(func, base + i);
5468 /* Overwrite PERSP_CENTER. */
5469 for (i = 0; i < 2; i++)
5470 ret = LLVMBuildInsertValue(gallivm->builder, ret,
5471 persp_sample[i], base + 2 + i, "");
5472 /* Overwrite PERSP_CENTROID. */
5473 for (i = 0; i < 2; i++)
5474 ret = LLVMBuildInsertValue(gallivm->builder, ret,
5475 persp_sample[i], base + 4 + i, "");
5476 /* Read LINEAR_SAMPLE. */
5477 for (i = 0; i < 2; i++)
5478 linear_sample[i] = LLVMGetParam(func, base + 6 + i);
5479 /* Overwrite LINEAR_CENTER. */
5480 for (i = 0; i < 2; i++)
5481 ret = LLVMBuildInsertValue(gallivm->builder, ret,
5482 linear_sample[i], base + 8 + i, "");
5483 /* Overwrite LINEAR_CENTROID. */
5484 for (i = 0; i < 2; i++)
5485 ret = LLVMBuildInsertValue(gallivm->builder, ret,
5486 linear_sample[i], base + 10 + i, "");
5487 }
5488
5489 /* TODO: polygon stippling */
5490
5491 /* Compile. */
5492 LLVMBuildRet(gallivm->builder, ret);
5493 radeon_llvm_finalize_module(&ctx.radeon_bld);
5494
5495 if (si_compile_llvm(sscreen, &out->binary, &out->config, tm,
5496 gallivm->module, debug, ctx.type,
5497 "Fragment Shader Prolog"))
5498 status = false;
5499
5500 radeon_llvm_dispose(&ctx.radeon_bld);
5501 return status;
5502 }
5503
5504 /**
5505 * Compile the pixel shader epilog. This handles everything that must be
5506 * emulated for pixel shader exports. (alpha-test, format conversions, etc)
5507 */
5508 static bool si_compile_ps_epilog(struct si_screen *sscreen,
5509 LLVMTargetMachineRef tm,
5510 struct pipe_debug_callback *debug,
5511 struct si_shader_part *out)
5512 {
5513 union si_shader_part_key *key = &out->key;
5514 struct si_shader shader = {};
5515 struct si_shader_context ctx;
5516 struct gallivm_state *gallivm = &ctx.radeon_bld.gallivm;
5517 struct lp_build_tgsi_context *bld_base = &ctx.radeon_bld.soa.bld_base;
5518 LLVMTypeRef params[16+8*4+3];
5519 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
5520 int last_array_pointer, last_sgpr, num_params, i;
5521 bool status = true;
5522
5523 si_init_shader_ctx(&ctx, sscreen, &shader, tm, NULL);
5524 ctx.type = TGSI_PROCESSOR_FRAGMENT;
5525 shader.key.ps.epilog = key->ps_epilog.states;
5526
5527 /* Declare input SGPRs. */
5528 params[SI_PARAM_RW_BUFFERS] = ctx.i64;
5529 params[SI_PARAM_CONST_BUFFERS] = ctx.i64;
5530 params[SI_PARAM_SAMPLERS] = ctx.i64;
5531 params[SI_PARAM_UNUSED] = ctx.i64;
5532 params[SI_PARAM_ALPHA_REF] = ctx.f32;
5533 last_array_pointer = -1;
5534 last_sgpr = SI_PARAM_ALPHA_REF;
5535
5536 /* Declare input VGPRs. */
5537 num_params = (last_sgpr + 1) +
5538 util_bitcount(key->ps_epilog.colors_written) * 4 +
5539 key->ps_epilog.writes_z +
5540 key->ps_epilog.writes_stencil +
5541 key->ps_epilog.writes_samplemask;
5542
5543 num_params = MAX2(num_params,
5544 last_sgpr + 1 + PS_EPILOG_SAMPLEMASK_MIN_LOC + 1);
5545
5546 assert(num_params <= ARRAY_SIZE(params));
5547
5548 for (i = last_sgpr + 1; i < num_params; i++)
5549 params[i] = ctx.f32;
5550
5551 /* Create the function. */
5552 si_create_function(&ctx, NULL, 0, params, num_params,
5553 last_array_pointer, last_sgpr);
5554 /* Disable elimination of unused inputs. */
5555 radeon_llvm_add_attribute(ctx.radeon_bld.main_fn,
5556 "InitialPSInputAddr", 0xffffff);
5557
5558 /* Process colors. */
5559 unsigned vgpr = last_sgpr + 1;
5560 unsigned colors_written = key->ps_epilog.colors_written;
5561 int last_color_export = -1;
5562
5563 /* Find the last color export. */
5564 if (!key->ps_epilog.writes_z &&
5565 !key->ps_epilog.writes_stencil &&
5566 !key->ps_epilog.writes_samplemask) {
5567 unsigned spi_format = key->ps_epilog.states.spi_shader_col_format;
5568
5569 /* If last_cbuf > 0, FS_COLOR0_WRITES_ALL_CBUFS is true. */
5570 if (colors_written == 0x1 && key->ps_epilog.states.last_cbuf > 0) {
5571 /* Just set this if any of the colorbuffers are enabled. */
5572 if (spi_format &
5573 ((1llu << (4 * (key->ps_epilog.states.last_cbuf + 1))) - 1))
5574 last_color_export = 0;
5575 } else {
5576 for (i = 0; i < 8; i++)
5577 if (colors_written & (1 << i) &&
5578 (spi_format >> (i * 4)) & 0xf)
5579 last_color_export = i;
5580 }
5581 }
5582
5583 while (colors_written) {
5584 LLVMValueRef color[4];
5585 int mrt = u_bit_scan(&colors_written);
5586
5587 for (i = 0; i < 4; i++)
5588 color[i] = LLVMGetParam(ctx.radeon_bld.main_fn, vgpr++);
5589
5590 si_export_mrt_color(bld_base, color, mrt,
5591 num_params - 1,
5592 mrt == last_color_export);
5593 }
5594
5595 /* Process depth, stencil, samplemask. */
5596 if (key->ps_epilog.writes_z)
5597 depth = LLVMGetParam(ctx.radeon_bld.main_fn, vgpr++);
5598 if (key->ps_epilog.writes_stencil)
5599 stencil = LLVMGetParam(ctx.radeon_bld.main_fn, vgpr++);
5600 if (key->ps_epilog.writes_samplemask)
5601 samplemask = LLVMGetParam(ctx.radeon_bld.main_fn, vgpr++);
5602
5603 if (depth || stencil || samplemask)
5604 si_export_mrt_z(bld_base, depth, stencil, samplemask);
5605 else if (last_color_export == -1)
5606 si_export_null(bld_base);
5607
5608 /* Compile. */
5609 LLVMBuildRetVoid(gallivm->builder);
5610 radeon_llvm_finalize_module(&ctx.radeon_bld);
5611
5612 if (si_compile_llvm(sscreen, &out->binary, &out->config, tm,
5613 gallivm->module, debug, ctx.type,
5614 "Fragment Shader Epilog"))
5615 status = false;
5616
5617 radeon_llvm_dispose(&ctx.radeon_bld);
5618 return status;
5619 }
5620
5621 /**
5622 * Select and compile (or reuse) pixel shader parts (prolog & epilog).
5623 */
5624 static bool si_shader_select_ps_parts(struct si_screen *sscreen,
5625 LLVMTargetMachineRef tm,
5626 struct si_shader *shader,
5627 struct pipe_debug_callback *debug)
5628 {
5629 struct tgsi_shader_info *info = &shader->selector->info;
5630 union si_shader_part_key prolog_key;
5631 union si_shader_part_key epilog_key;
5632 unsigned i;
5633
5634 /* Get the prolog. */
5635 memset(&prolog_key, 0, sizeof(prolog_key));
5636 prolog_key.ps_prolog.states = shader->key.ps.prolog;
5637 prolog_key.ps_prolog.colors_read = info->colors_read;
5638 prolog_key.ps_prolog.num_input_sgprs = shader->num_input_sgprs;
5639 prolog_key.ps_prolog.num_input_vgprs = shader->num_input_vgprs;
5640
5641 if (info->colors_read) {
5642 unsigned *color = shader->selector->color_attr_index;
5643
5644 if (shader->key.ps.prolog.color_two_side) {
5645 /* BCOLORs are stored after the last input. */
5646 prolog_key.ps_prolog.num_interp_inputs = info->num_inputs;
5647 prolog_key.ps_prolog.face_vgpr_index = shader->face_vgpr_index;
5648 shader->config.spi_ps_input_ena |= S_0286CC_FRONT_FACE_ENA(1);
5649 }
5650
5651 for (i = 0; i < 2; i++) {
5652 unsigned location = info->input_interpolate_loc[color[i]];
5653
5654 if (!(info->colors_read & (0xf << i*4)))
5655 continue;
5656
5657 prolog_key.ps_prolog.color_attr_index[i] = color[i];
5658
5659 /* Force per-sample interpolation for the colors here. */
5660 if (shader->key.ps.prolog.force_persample_interp)
5661 location = TGSI_INTERPOLATE_LOC_SAMPLE;
5662
5663 switch (info->input_interpolate[color[i]]) {
5664 case TGSI_INTERPOLATE_CONSTANT:
5665 prolog_key.ps_prolog.color_interp_vgpr_index[i] = -1;
5666 break;
5667 case TGSI_INTERPOLATE_PERSPECTIVE:
5668 case TGSI_INTERPOLATE_COLOR:
5669 switch (location) {
5670 case TGSI_INTERPOLATE_LOC_SAMPLE:
5671 prolog_key.ps_prolog.color_interp_vgpr_index[i] = 0;
5672 shader->config.spi_ps_input_ena |=
5673 S_0286CC_PERSP_SAMPLE_ENA(1);
5674 break;
5675 case TGSI_INTERPOLATE_LOC_CENTER:
5676 prolog_key.ps_prolog.color_interp_vgpr_index[i] = 2;
5677 shader->config.spi_ps_input_ena |=
5678 S_0286CC_PERSP_CENTER_ENA(1);
5679 break;
5680 case TGSI_INTERPOLATE_LOC_CENTROID:
5681 prolog_key.ps_prolog.color_interp_vgpr_index[i] = 4;
5682 shader->config.spi_ps_input_ena |=
5683 S_0286CC_PERSP_CENTROID_ENA(1);
5684 break;
5685 default:
5686 assert(0);
5687 }
5688 break;
5689 case TGSI_INTERPOLATE_LINEAR:
5690 switch (location) {
5691 case TGSI_INTERPOLATE_LOC_SAMPLE:
5692 prolog_key.ps_prolog.color_interp_vgpr_index[i] = 6;
5693 shader->config.spi_ps_input_ena |=
5694 S_0286CC_LINEAR_SAMPLE_ENA(1);
5695 break;
5696 case TGSI_INTERPOLATE_LOC_CENTER:
5697 prolog_key.ps_prolog.color_interp_vgpr_index[i] = 8;
5698 shader->config.spi_ps_input_ena |=
5699 S_0286CC_LINEAR_CENTER_ENA(1);
5700 break;
5701 case TGSI_INTERPOLATE_LOC_CENTROID:
5702 prolog_key.ps_prolog.color_interp_vgpr_index[i] = 10;
5703 shader->config.spi_ps_input_ena |=
5704 S_0286CC_LINEAR_CENTROID_ENA(1);
5705 break;
5706 default:
5707 assert(0);
5708 }
5709 break;
5710 default:
5711 assert(0);
5712 }
5713 }
5714 }
5715
5716 /* The prolog is a no-op if these aren't set. */
5717 if (prolog_key.ps_prolog.colors_read ||
5718 prolog_key.ps_prolog.states.force_persample_interp ||
5719 prolog_key.ps_prolog.states.poly_stipple) {
5720 shader->prolog =
5721 si_get_shader_part(sscreen, &sscreen->ps_prologs,
5722 &prolog_key, tm, debug,
5723 si_compile_ps_prolog);
5724 if (!shader->prolog)
5725 return false;
5726 }
5727
5728 /* Get the epilog. */
5729 memset(&epilog_key, 0, sizeof(epilog_key));
5730 epilog_key.ps_epilog.colors_written = info->colors_written;
5731 epilog_key.ps_epilog.writes_z = info->writes_z;
5732 epilog_key.ps_epilog.writes_stencil = info->writes_stencil;
5733 epilog_key.ps_epilog.writes_samplemask = info->writes_samplemask;
5734 epilog_key.ps_epilog.states = shader->key.ps.epilog;
5735
5736 shader->epilog =
5737 si_get_shader_part(sscreen, &sscreen->ps_epilogs,
5738 &epilog_key, tm, debug,
5739 si_compile_ps_epilog);
5740 if (!shader->epilog)
5741 return false;
5742
5743 /* Set up the enable bits for per-sample shading if needed. */
5744 if (shader->key.ps.prolog.force_persample_interp) {
5745 if (G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_ena) ||
5746 G_0286CC_PERSP_CENTROID_ENA(shader->config.spi_ps_input_ena)) {
5747 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTER_ENA;
5748 shader->config.spi_ps_input_ena &= C_0286CC_PERSP_CENTROID_ENA;
5749 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_SAMPLE_ENA(1);
5750 }
5751 if (G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_ena) ||
5752 G_0286CC_LINEAR_CENTROID_ENA(shader->config.spi_ps_input_ena)) {
5753 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTER_ENA;
5754 shader->config.spi_ps_input_ena &= C_0286CC_LINEAR_CENTROID_ENA;
5755 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_SAMPLE_ENA(1);
5756 }
5757 }
5758
5759 /* POW_W_FLOAT requires that one of the perspective weights is enabled. */
5760 if (G_0286CC_POS_W_FLOAT_ENA(shader->config.spi_ps_input_ena) &&
5761 !(shader->config.spi_ps_input_ena & 0xf)) {
5762 shader->config.spi_ps_input_ena |= S_0286CC_PERSP_CENTER_ENA(1);
5763 assert(G_0286CC_PERSP_CENTER_ENA(shader->config.spi_ps_input_addr));
5764 }
5765
5766 /* At least one pair of interpolation weights must be enabled. */
5767 if (!(shader->config.spi_ps_input_ena & 0x7f)) {
5768 shader->config.spi_ps_input_ena |= S_0286CC_LINEAR_CENTER_ENA(1);
5769 assert(G_0286CC_LINEAR_CENTER_ENA(shader->config.spi_ps_input_addr));
5770 }
5771
5772 /* The sample mask input is always enabled, because the API shader always
5773 * passes it through to the epilog. Disable it here if it's unused.
5774 */
5775 if (!shader->key.ps.epilog.poly_line_smoothing &&
5776 !shader->selector->info.reads_samplemask)
5777 shader->config.spi_ps_input_ena &= C_0286CC_SAMPLE_COVERAGE_ENA;
5778
5779 return true;
5780 }
5781
5782 int si_shader_create(struct si_screen *sscreen, LLVMTargetMachineRef tm,
5783 struct si_shader *shader,
5784 struct pipe_debug_callback *debug)
5785 {
5786 int r;
5787
5788 /* Compile TGSI. */
5789 r = si_compile_tgsi_shader(sscreen, tm, shader,
5790 sscreen->use_monolithic_shaders, debug);
5791 if (r)
5792 return r;
5793
5794 if (!sscreen->use_monolithic_shaders) {
5795 switch (shader->selector->type) {
5796 case PIPE_SHADER_VERTEX:
5797 if (!si_shader_select_vs_parts(sscreen, tm, shader, debug))
5798 return -1;
5799 break;
5800 case PIPE_SHADER_TESS_CTRL:
5801 if (!si_shader_select_tcs_parts(sscreen, tm, shader, debug))
5802 return -1;
5803 break;
5804 case PIPE_SHADER_TESS_EVAL:
5805 if (!si_shader_select_tes_parts(sscreen, tm, shader, debug))
5806 return -1;
5807 break;
5808 case PIPE_SHADER_FRAGMENT:
5809 if (!si_shader_select_ps_parts(sscreen, tm, shader, debug))
5810 return -1;
5811
5812 /* Make sure we have at least as many VGPRs as there
5813 * are allocated inputs.
5814 */
5815 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
5816 shader->num_input_vgprs);
5817 break;
5818 }
5819
5820 /* Update SGPR and VGPR counts. */
5821 if (shader->prolog) {
5822 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
5823 shader->prolog->config.num_sgprs);
5824 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
5825 shader->prolog->config.num_vgprs);
5826 }
5827 if (shader->epilog) {
5828 shader->config.num_sgprs = MAX2(shader->config.num_sgprs,
5829 shader->epilog->config.num_sgprs);
5830 shader->config.num_vgprs = MAX2(shader->config.num_vgprs,
5831 shader->epilog->config.num_vgprs);
5832 }
5833 }
5834
5835 si_shader_dump(sscreen, shader, debug, shader->selector->info.processor);
5836
5837 /* Upload. */
5838 r = si_shader_binary_upload(sscreen, shader);
5839 if (r) {
5840 fprintf(stderr, "LLVM failed to upload shader\n");
5841 return r;
5842 }
5843
5844 return 0;
5845 }
5846
5847 void si_shader_destroy(struct si_shader *shader)
5848 {
5849 if (shader->gs_copy_shader) {
5850 si_shader_destroy(shader->gs_copy_shader);
5851 FREE(shader->gs_copy_shader);
5852 }
5853
5854 if (shader->scratch_bo)
5855 r600_resource_reference(&shader->scratch_bo, NULL);
5856
5857 r600_resource_reference(&shader->bo, NULL);
5858
5859 radeon_shader_binary_clean(&shader->binary);
5860 }