ac: add support for 16bit UBO loads
[mesa.git] / src / amd / common / ac_llvm_build.c
1 /*
2 * Copyright 2014 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
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sub license, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
15 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
16 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
18 * USE OR OTHER DEALINGS IN THE SOFTWARE.
19 *
20 * The above copyright notice and this permission notice (including the
21 * next paragraph) shall be included in all copies or substantial portions
22 * of the Software.
23 *
24 */
25 /* based on pieces from si_pipe.c and radeon_llvm_emit.c */
26 #include "ac_llvm_build.h"
27
28 #include <llvm-c/Core.h>
29
30 #include "c11/threads.h"
31
32 #include <assert.h>
33 #include <stdio.h>
34
35 #include "ac_llvm_util.h"
36 #include "ac_exp_param.h"
37 #include "util/bitscan.h"
38 #include "util/macros.h"
39 #include "util/u_atomic.h"
40 #include "util/u_math.h"
41 #include "sid.h"
42
43 #include "shader_enums.h"
44
45 #define AC_LLVM_INITIAL_CF_DEPTH 4
46
47 /* Data for if/else/endif and bgnloop/endloop control flow structures.
48 */
49 struct ac_llvm_flow {
50 /* Loop exit or next part of if/else/endif. */
51 LLVMBasicBlockRef next_block;
52 LLVMBasicBlockRef loop_entry_block;
53 };
54
55 /* Initialize module-independent parts of the context.
56 *
57 * The caller is responsible for initializing ctx::module and ctx::builder.
58 */
59 void
60 ac_llvm_context_init(struct ac_llvm_context *ctx,
61 enum chip_class chip_class, enum radeon_family family)
62 {
63 LLVMValueRef args[1];
64
65 ctx->context = LLVMContextCreate();
66
67 ctx->chip_class = chip_class;
68 ctx->family = family;
69 ctx->module = NULL;
70 ctx->builder = NULL;
71
72 ctx->voidt = LLVMVoidTypeInContext(ctx->context);
73 ctx->i1 = LLVMInt1TypeInContext(ctx->context);
74 ctx->i8 = LLVMInt8TypeInContext(ctx->context);
75 ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
76 ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
77 ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
78 ctx->intptr = HAVE_32BIT_POINTERS ? ctx->i32 : ctx->i64;
79 ctx->f16 = LLVMHalfTypeInContext(ctx->context);
80 ctx->f32 = LLVMFloatTypeInContext(ctx->context);
81 ctx->f64 = LLVMDoubleTypeInContext(ctx->context);
82 ctx->v2i16 = LLVMVectorType(ctx->i16, 2);
83 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
84 ctx->v3i32 = LLVMVectorType(ctx->i32, 3);
85 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
86 ctx->v2f32 = LLVMVectorType(ctx->f32, 2);
87 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
88 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
89
90 ctx->i32_0 = LLVMConstInt(ctx->i32, 0, false);
91 ctx->i32_1 = LLVMConstInt(ctx->i32, 1, false);
92 ctx->i64_0 = LLVMConstInt(ctx->i64, 0, false);
93 ctx->i64_1 = LLVMConstInt(ctx->i64, 1, false);
94 ctx->f32_0 = LLVMConstReal(ctx->f32, 0.0);
95 ctx->f32_1 = LLVMConstReal(ctx->f32, 1.0);
96 ctx->f64_0 = LLVMConstReal(ctx->f64, 0.0);
97 ctx->f64_1 = LLVMConstReal(ctx->f64, 1.0);
98
99 ctx->i1false = LLVMConstInt(ctx->i1, 0, false);
100 ctx->i1true = LLVMConstInt(ctx->i1, 1, false);
101
102 ctx->range_md_kind = LLVMGetMDKindIDInContext(ctx->context,
103 "range", 5);
104
105 ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(ctx->context,
106 "invariant.load", 14);
107
108 ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->context, "fpmath", 6);
109
110 args[0] = LLVMConstReal(ctx->f32, 2.5);
111 ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->context, args, 1);
112
113 ctx->uniform_md_kind = LLVMGetMDKindIDInContext(ctx->context,
114 "amdgpu.uniform", 14);
115
116 ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
117 }
118
119 void
120 ac_llvm_context_dispose(struct ac_llvm_context *ctx)
121 {
122 free(ctx->flow);
123 ctx->flow = NULL;
124 ctx->flow_depth_max = 0;
125 }
126
127 int
128 ac_get_llvm_num_components(LLVMValueRef value)
129 {
130 LLVMTypeRef type = LLVMTypeOf(value);
131 unsigned num_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
132 ? LLVMGetVectorSize(type)
133 : 1;
134 return num_components;
135 }
136
137 LLVMValueRef
138 ac_llvm_extract_elem(struct ac_llvm_context *ac,
139 LLVMValueRef value,
140 int index)
141 {
142 if (LLVMGetTypeKind(LLVMTypeOf(value)) != LLVMVectorTypeKind) {
143 assert(index == 0);
144 return value;
145 }
146
147 return LLVMBuildExtractElement(ac->builder, value,
148 LLVMConstInt(ac->i32, index, false), "");
149 }
150
151 int
152 ac_get_elem_bits(struct ac_llvm_context *ctx, LLVMTypeRef type)
153 {
154 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
155 type = LLVMGetElementType(type);
156
157 if (LLVMGetTypeKind(type) == LLVMIntegerTypeKind)
158 return LLVMGetIntTypeWidth(type);
159
160 if (type == ctx->f16)
161 return 16;
162 if (type == ctx->f32)
163 return 32;
164 if (type == ctx->f64)
165 return 64;
166
167 unreachable("Unhandled type kind in get_elem_bits");
168 }
169
170 unsigned
171 ac_get_type_size(LLVMTypeRef type)
172 {
173 LLVMTypeKind kind = LLVMGetTypeKind(type);
174
175 switch (kind) {
176 case LLVMIntegerTypeKind:
177 return LLVMGetIntTypeWidth(type) / 8;
178 case LLVMHalfTypeKind:
179 return 2;
180 case LLVMFloatTypeKind:
181 return 4;
182 case LLVMDoubleTypeKind:
183 return 8;
184 case LLVMPointerTypeKind:
185 if (LLVMGetPointerAddressSpace(type) == AC_CONST_32BIT_ADDR_SPACE)
186 return 4;
187 return 8;
188 case LLVMVectorTypeKind:
189 return LLVMGetVectorSize(type) *
190 ac_get_type_size(LLVMGetElementType(type));
191 case LLVMArrayTypeKind:
192 return LLVMGetArrayLength(type) *
193 ac_get_type_size(LLVMGetElementType(type));
194 default:
195 assert(0);
196 return 0;
197 }
198 }
199
200 static LLVMTypeRef to_integer_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
201 {
202 if (t == ctx->f16 || t == ctx->i16)
203 return ctx->i16;
204 else if (t == ctx->f32 || t == ctx->i32)
205 return ctx->i32;
206 else if (t == ctx->f64 || t == ctx->i64)
207 return ctx->i64;
208 else
209 unreachable("Unhandled integer size");
210 }
211
212 LLVMTypeRef
213 ac_to_integer_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
214 {
215 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
216 LLVMTypeRef elem_type = LLVMGetElementType(t);
217 return LLVMVectorType(to_integer_type_scalar(ctx, elem_type),
218 LLVMGetVectorSize(t));
219 }
220 return to_integer_type_scalar(ctx, t);
221 }
222
223 LLVMValueRef
224 ac_to_integer(struct ac_llvm_context *ctx, LLVMValueRef v)
225 {
226 LLVMTypeRef type = LLVMTypeOf(v);
227 return LLVMBuildBitCast(ctx->builder, v, ac_to_integer_type(ctx, type), "");
228 }
229
230 static LLVMTypeRef to_float_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
231 {
232 if (t == ctx->i16 || t == ctx->f16)
233 return ctx->f16;
234 else if (t == ctx->i32 || t == ctx->f32)
235 return ctx->f32;
236 else if (t == ctx->i64 || t == ctx->f64)
237 return ctx->f64;
238 else
239 unreachable("Unhandled float size");
240 }
241
242 LLVMTypeRef
243 ac_to_float_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
244 {
245 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
246 LLVMTypeRef elem_type = LLVMGetElementType(t);
247 return LLVMVectorType(to_float_type_scalar(ctx, elem_type),
248 LLVMGetVectorSize(t));
249 }
250 return to_float_type_scalar(ctx, t);
251 }
252
253 LLVMValueRef
254 ac_to_float(struct ac_llvm_context *ctx, LLVMValueRef v)
255 {
256 LLVMTypeRef type = LLVMTypeOf(v);
257 return LLVMBuildBitCast(ctx->builder, v, ac_to_float_type(ctx, type), "");
258 }
259
260
261 LLVMValueRef
262 ac_build_intrinsic(struct ac_llvm_context *ctx, const char *name,
263 LLVMTypeRef return_type, LLVMValueRef *params,
264 unsigned param_count, unsigned attrib_mask)
265 {
266 LLVMValueRef function, call;
267 bool set_callsite_attrs = !(attrib_mask & AC_FUNC_ATTR_LEGACY);
268
269 function = LLVMGetNamedFunction(ctx->module, name);
270 if (!function) {
271 LLVMTypeRef param_types[32], function_type;
272 unsigned i;
273
274 assert(param_count <= 32);
275
276 for (i = 0; i < param_count; ++i) {
277 assert(params[i]);
278 param_types[i] = LLVMTypeOf(params[i]);
279 }
280 function_type =
281 LLVMFunctionType(return_type, param_types, param_count, 0);
282 function = LLVMAddFunction(ctx->module, name, function_type);
283
284 LLVMSetFunctionCallConv(function, LLVMCCallConv);
285 LLVMSetLinkage(function, LLVMExternalLinkage);
286
287 if (!set_callsite_attrs)
288 ac_add_func_attributes(ctx->context, function, attrib_mask);
289 }
290
291 call = LLVMBuildCall(ctx->builder, function, params, param_count, "");
292 if (set_callsite_attrs)
293 ac_add_func_attributes(ctx->context, call, attrib_mask);
294 return call;
295 }
296
297 /**
298 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
299 * intrinsic names).
300 */
301 void ac_build_type_name_for_intr(LLVMTypeRef type, char *buf, unsigned bufsize)
302 {
303 LLVMTypeRef elem_type = type;
304
305 assert(bufsize >= 8);
306
307 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
308 int ret = snprintf(buf, bufsize, "v%u",
309 LLVMGetVectorSize(type));
310 if (ret < 0) {
311 char *type_name = LLVMPrintTypeToString(type);
312 fprintf(stderr, "Error building type name for: %s\n",
313 type_name);
314 return;
315 }
316 elem_type = LLVMGetElementType(type);
317 buf += ret;
318 bufsize -= ret;
319 }
320 switch (LLVMGetTypeKind(elem_type)) {
321 default: break;
322 case LLVMIntegerTypeKind:
323 snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
324 break;
325 case LLVMHalfTypeKind:
326 snprintf(buf, bufsize, "f16");
327 break;
328 case LLVMFloatTypeKind:
329 snprintf(buf, bufsize, "f32");
330 break;
331 case LLVMDoubleTypeKind:
332 snprintf(buf, bufsize, "f64");
333 break;
334 }
335 }
336
337 /**
338 * Helper function that builds an LLVM IR PHI node and immediately adds
339 * incoming edges.
340 */
341 LLVMValueRef
342 ac_build_phi(struct ac_llvm_context *ctx, LLVMTypeRef type,
343 unsigned count_incoming, LLVMValueRef *values,
344 LLVMBasicBlockRef *blocks)
345 {
346 LLVMValueRef phi = LLVMBuildPhi(ctx->builder, type, "");
347 LLVMAddIncoming(phi, values, blocks, count_incoming);
348 return phi;
349 }
350
351 /* Prevent optimizations (at least of memory accesses) across the current
352 * point in the program by emitting empty inline assembly that is marked as
353 * having side effects.
354 *
355 * Optionally, a value can be passed through the inline assembly to prevent
356 * LLVM from hoisting calls to ReadNone functions.
357 */
358 void
359 ac_build_optimization_barrier(struct ac_llvm_context *ctx,
360 LLVMValueRef *pvgpr)
361 {
362 static int counter = 0;
363
364 LLVMBuilderRef builder = ctx->builder;
365 char code[16];
366
367 snprintf(code, sizeof(code), "; %d", p_atomic_inc_return(&counter));
368
369 if (!pvgpr) {
370 LLVMTypeRef ftype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
371 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "", true, false);
372 LLVMBuildCall(builder, inlineasm, NULL, 0, "");
373 } else {
374 LLVMTypeRef ftype = LLVMFunctionType(ctx->i32, &ctx->i32, 1, false);
375 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "=v,0", true, false);
376 LLVMValueRef vgpr = *pvgpr;
377 LLVMTypeRef vgpr_type = LLVMTypeOf(vgpr);
378 unsigned vgpr_size = ac_get_type_size(vgpr_type);
379 LLVMValueRef vgpr0;
380
381 assert(vgpr_size % 4 == 0);
382
383 vgpr = LLVMBuildBitCast(builder, vgpr, LLVMVectorType(ctx->i32, vgpr_size / 4), "");
384 vgpr0 = LLVMBuildExtractElement(builder, vgpr, ctx->i32_0, "");
385 vgpr0 = LLVMBuildCall(builder, inlineasm, &vgpr0, 1, "");
386 vgpr = LLVMBuildInsertElement(builder, vgpr, vgpr0, ctx->i32_0, "");
387 vgpr = LLVMBuildBitCast(builder, vgpr, vgpr_type, "");
388
389 *pvgpr = vgpr;
390 }
391 }
392
393 LLVMValueRef
394 ac_build_shader_clock(struct ac_llvm_context *ctx)
395 {
396 LLVMValueRef tmp = ac_build_intrinsic(ctx, "llvm.readcyclecounter",
397 ctx->i64, NULL, 0, 0);
398 return LLVMBuildBitCast(ctx->builder, tmp, ctx->v2i32, "");
399 }
400
401 LLVMValueRef
402 ac_build_ballot(struct ac_llvm_context *ctx,
403 LLVMValueRef value)
404 {
405 LLVMValueRef args[3] = {
406 value,
407 ctx->i32_0,
408 LLVMConstInt(ctx->i32, LLVMIntNE, 0)
409 };
410
411 /* We currently have no other way to prevent LLVM from lifting the icmp
412 * calls to a dominating basic block.
413 */
414 ac_build_optimization_barrier(ctx, &args[0]);
415
416 args[0] = ac_to_integer(ctx, args[0]);
417
418 return ac_build_intrinsic(ctx,
419 "llvm.amdgcn.icmp.i32",
420 ctx->i64, args, 3,
421 AC_FUNC_ATTR_NOUNWIND |
422 AC_FUNC_ATTR_READNONE |
423 AC_FUNC_ATTR_CONVERGENT);
424 }
425
426 LLVMValueRef
427 ac_build_vote_all(struct ac_llvm_context *ctx, LLVMValueRef value)
428 {
429 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
430 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
431 return LLVMBuildICmp(ctx->builder, LLVMIntEQ, vote_set, active_set, "");
432 }
433
434 LLVMValueRef
435 ac_build_vote_any(struct ac_llvm_context *ctx, LLVMValueRef value)
436 {
437 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
438 return LLVMBuildICmp(ctx->builder, LLVMIntNE, vote_set,
439 LLVMConstInt(ctx->i64, 0, 0), "");
440 }
441
442 LLVMValueRef
443 ac_build_vote_eq(struct ac_llvm_context *ctx, LLVMValueRef value)
444 {
445 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
446 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
447
448 LLVMValueRef all = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
449 vote_set, active_set, "");
450 LLVMValueRef none = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
451 vote_set,
452 LLVMConstInt(ctx->i64, 0, 0), "");
453 return LLVMBuildOr(ctx->builder, all, none, "");
454 }
455
456 LLVMValueRef
457 ac_build_varying_gather_values(struct ac_llvm_context *ctx, LLVMValueRef *values,
458 unsigned value_count, unsigned component)
459 {
460 LLVMValueRef vec = NULL;
461
462 if (value_count == 1) {
463 return values[component];
464 } else if (!value_count)
465 unreachable("value_count is 0");
466
467 for (unsigned i = component; i < value_count + component; i++) {
468 LLVMValueRef value = values[i];
469
470 if (i == component)
471 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
472 LLVMValueRef index = LLVMConstInt(ctx->i32, i - component, false);
473 vec = LLVMBuildInsertElement(ctx->builder, vec, value, index, "");
474 }
475 return vec;
476 }
477
478 LLVMValueRef
479 ac_build_gather_values_extended(struct ac_llvm_context *ctx,
480 LLVMValueRef *values,
481 unsigned value_count,
482 unsigned value_stride,
483 bool load,
484 bool always_vector)
485 {
486 LLVMBuilderRef builder = ctx->builder;
487 LLVMValueRef vec = NULL;
488 unsigned i;
489
490 if (value_count == 1 && !always_vector) {
491 if (load)
492 return LLVMBuildLoad(builder, values[0], "");
493 return values[0];
494 } else if (!value_count)
495 unreachable("value_count is 0");
496
497 for (i = 0; i < value_count; i++) {
498 LLVMValueRef value = values[i * value_stride];
499 if (load)
500 value = LLVMBuildLoad(builder, value, "");
501
502 if (!i)
503 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
504 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
505 vec = LLVMBuildInsertElement(builder, vec, value, index, "");
506 }
507 return vec;
508 }
509
510 LLVMValueRef
511 ac_build_gather_values(struct ac_llvm_context *ctx,
512 LLVMValueRef *values,
513 unsigned value_count)
514 {
515 return ac_build_gather_values_extended(ctx, values, value_count, 1, false, false);
516 }
517
518 /* Expand a scalar or vector to <4 x type> by filling the remaining channels
519 * with undef. Extract at most num_channels components from the input.
520 */
521 LLVMValueRef ac_build_expand_to_vec4(struct ac_llvm_context *ctx,
522 LLVMValueRef value,
523 unsigned num_channels)
524 {
525 LLVMTypeRef elemtype;
526 LLVMValueRef chan[4];
527
528 if (LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMVectorTypeKind) {
529 unsigned vec_size = LLVMGetVectorSize(LLVMTypeOf(value));
530 num_channels = MIN2(num_channels, vec_size);
531
532 if (num_channels >= 4)
533 return value;
534
535 for (unsigned i = 0; i < num_channels; i++)
536 chan[i] = ac_llvm_extract_elem(ctx, value, i);
537
538 elemtype = LLVMGetElementType(LLVMTypeOf(value));
539 } else {
540 if (num_channels) {
541 assert(num_channels == 1);
542 chan[0] = value;
543 }
544 elemtype = LLVMTypeOf(value);
545 }
546
547 while (num_channels < 4)
548 chan[num_channels++] = LLVMGetUndef(elemtype);
549
550 return ac_build_gather_values(ctx, chan, 4);
551 }
552
553 LLVMValueRef
554 ac_build_fdiv(struct ac_llvm_context *ctx,
555 LLVMValueRef num,
556 LLVMValueRef den)
557 {
558 LLVMValueRef ret = LLVMBuildFDiv(ctx->builder, num, den, "");
559
560 /* Use v_rcp_f32 instead of precise division. */
561 if (!LLVMIsConstant(ret))
562 LLVMSetMetadata(ret, ctx->fpmath_md_kind, ctx->fpmath_md_2p5_ulp);
563 return ret;
564 }
565
566 /* Coordinates for cube map selection. sc, tc, and ma are as in Table 8.27
567 * of the OpenGL 4.5 (Compatibility Profile) specification, except ma is
568 * already multiplied by two. id is the cube face number.
569 */
570 struct cube_selection_coords {
571 LLVMValueRef stc[2];
572 LLVMValueRef ma;
573 LLVMValueRef id;
574 };
575
576 static void
577 build_cube_intrinsic(struct ac_llvm_context *ctx,
578 LLVMValueRef in[3],
579 struct cube_selection_coords *out)
580 {
581 LLVMTypeRef f32 = ctx->f32;
582
583 out->stc[1] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubetc",
584 f32, in, 3, AC_FUNC_ATTR_READNONE);
585 out->stc[0] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubesc",
586 f32, in, 3, AC_FUNC_ATTR_READNONE);
587 out->ma = ac_build_intrinsic(ctx, "llvm.amdgcn.cubema",
588 f32, in, 3, AC_FUNC_ATTR_READNONE);
589 out->id = ac_build_intrinsic(ctx, "llvm.amdgcn.cubeid",
590 f32, in, 3, AC_FUNC_ATTR_READNONE);
591 }
592
593 /**
594 * Build a manual selection sequence for cube face sc/tc coordinates and
595 * major axis vector (multiplied by 2 for consistency) for the given
596 * vec3 \p coords, for the face implied by \p selcoords.
597 *
598 * For the major axis, we always adjust the sign to be in the direction of
599 * selcoords.ma; i.e., a positive out_ma means that coords is pointed towards
600 * the selcoords major axis.
601 */
602 static void build_cube_select(struct ac_llvm_context *ctx,
603 const struct cube_selection_coords *selcoords,
604 const LLVMValueRef *coords,
605 LLVMValueRef *out_st,
606 LLVMValueRef *out_ma)
607 {
608 LLVMBuilderRef builder = ctx->builder;
609 LLVMTypeRef f32 = LLVMTypeOf(coords[0]);
610 LLVMValueRef is_ma_positive;
611 LLVMValueRef sgn_ma;
612 LLVMValueRef is_ma_z, is_not_ma_z;
613 LLVMValueRef is_ma_y;
614 LLVMValueRef is_ma_x;
615 LLVMValueRef sgn;
616 LLVMValueRef tmp;
617
618 is_ma_positive = LLVMBuildFCmp(builder, LLVMRealUGE,
619 selcoords->ma, LLVMConstReal(f32, 0.0), "");
620 sgn_ma = LLVMBuildSelect(builder, is_ma_positive,
621 LLVMConstReal(f32, 1.0), LLVMConstReal(f32, -1.0), "");
622
623 is_ma_z = LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 4.0), "");
624 is_not_ma_z = LLVMBuildNot(builder, is_ma_z, "");
625 is_ma_y = LLVMBuildAnd(builder, is_not_ma_z,
626 LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 2.0), ""), "");
627 is_ma_x = LLVMBuildAnd(builder, is_not_ma_z, LLVMBuildNot(builder, is_ma_y, ""), "");
628
629 /* Select sc */
630 tmp = LLVMBuildSelect(builder, is_ma_x, coords[2], coords[0], "");
631 sgn = LLVMBuildSelect(builder, is_ma_y, LLVMConstReal(f32, 1.0),
632 LLVMBuildSelect(builder, is_ma_z, sgn_ma,
633 LLVMBuildFNeg(builder, sgn_ma, ""), ""), "");
634 out_st[0] = LLVMBuildFMul(builder, tmp, sgn, "");
635
636 /* Select tc */
637 tmp = LLVMBuildSelect(builder, is_ma_y, coords[2], coords[1], "");
638 sgn = LLVMBuildSelect(builder, is_ma_y, sgn_ma,
639 LLVMConstReal(f32, -1.0), "");
640 out_st[1] = LLVMBuildFMul(builder, tmp, sgn, "");
641
642 /* Select ma */
643 tmp = LLVMBuildSelect(builder, is_ma_z, coords[2],
644 LLVMBuildSelect(builder, is_ma_y, coords[1], coords[0], ""), "");
645 tmp = ac_build_intrinsic(ctx, "llvm.fabs.f32",
646 ctx->f32, &tmp, 1, AC_FUNC_ATTR_READNONE);
647 *out_ma = LLVMBuildFMul(builder, tmp, LLVMConstReal(f32, 2.0), "");
648 }
649
650 void
651 ac_prepare_cube_coords(struct ac_llvm_context *ctx,
652 bool is_deriv, bool is_array, bool is_lod,
653 LLVMValueRef *coords_arg,
654 LLVMValueRef *derivs_arg)
655 {
656
657 LLVMBuilderRef builder = ctx->builder;
658 struct cube_selection_coords selcoords;
659 LLVMValueRef coords[3];
660 LLVMValueRef invma;
661
662 if (is_array && !is_lod) {
663 LLVMValueRef tmp = coords_arg[3];
664 tmp = ac_build_intrinsic(ctx, "llvm.rint.f32", ctx->f32, &tmp, 1, 0);
665
666 /* Section 8.9 (Texture Functions) of the GLSL 4.50 spec says:
667 *
668 * "For Array forms, the array layer used will be
669 *
670 * max(0, min(d−1, floor(layer+0.5)))
671 *
672 * where d is the depth of the texture array and layer
673 * comes from the component indicated in the tables below.
674 * Workaroudn for an issue where the layer is taken from a
675 * helper invocation which happens to fall on a different
676 * layer due to extrapolation."
677 *
678 * VI and earlier attempt to implement this in hardware by
679 * clamping the value of coords[2] = (8 * layer) + face.
680 * Unfortunately, this means that the we end up with the wrong
681 * face when clamping occurs.
682 *
683 * Clamp the layer earlier to work around the issue.
684 */
685 if (ctx->chip_class <= VI) {
686 LLVMValueRef ge0;
687 ge0 = LLVMBuildFCmp(builder, LLVMRealOGE, tmp, ctx->f32_0, "");
688 tmp = LLVMBuildSelect(builder, ge0, tmp, ctx->f32_0, "");
689 }
690
691 coords_arg[3] = tmp;
692 }
693
694 build_cube_intrinsic(ctx, coords_arg, &selcoords);
695
696 invma = ac_build_intrinsic(ctx, "llvm.fabs.f32",
697 ctx->f32, &selcoords.ma, 1, AC_FUNC_ATTR_READNONE);
698 invma = ac_build_fdiv(ctx, LLVMConstReal(ctx->f32, 1.0), invma);
699
700 for (int i = 0; i < 2; ++i)
701 coords[i] = LLVMBuildFMul(builder, selcoords.stc[i], invma, "");
702
703 coords[2] = selcoords.id;
704
705 if (is_deriv && derivs_arg) {
706 LLVMValueRef derivs[4];
707 int axis;
708
709 /* Convert cube derivatives to 2D derivatives. */
710 for (axis = 0; axis < 2; axis++) {
711 LLVMValueRef deriv_st[2];
712 LLVMValueRef deriv_ma;
713
714 /* Transform the derivative alongside the texture
715 * coordinate. Mathematically, the correct formula is
716 * as follows. Assume we're projecting onto the +Z face
717 * and denote by dx/dh the derivative of the (original)
718 * X texture coordinate with respect to horizontal
719 * window coordinates. The projection onto the +Z face
720 * plane is:
721 *
722 * f(x,z) = x/z
723 *
724 * Then df/dh = df/dx * dx/dh + df/dz * dz/dh
725 * = 1/z * dx/dh - x/z * 1/z * dz/dh.
726 *
727 * This motivatives the implementation below.
728 *
729 * Whether this actually gives the expected results for
730 * apps that might feed in derivatives obtained via
731 * finite differences is anyone's guess. The OpenGL spec
732 * seems awfully quiet about how textureGrad for cube
733 * maps should be handled.
734 */
735 build_cube_select(ctx, &selcoords, &derivs_arg[axis * 3],
736 deriv_st, &deriv_ma);
737
738 deriv_ma = LLVMBuildFMul(builder, deriv_ma, invma, "");
739
740 for (int i = 0; i < 2; ++i)
741 derivs[axis * 2 + i] =
742 LLVMBuildFSub(builder,
743 LLVMBuildFMul(builder, deriv_st[i], invma, ""),
744 LLVMBuildFMul(builder, deriv_ma, coords[i], ""), "");
745 }
746
747 memcpy(derivs_arg, derivs, sizeof(derivs));
748 }
749
750 /* Shift the texture coordinate. This must be applied after the
751 * derivative calculation.
752 */
753 for (int i = 0; i < 2; ++i)
754 coords[i] = LLVMBuildFAdd(builder, coords[i], LLVMConstReal(ctx->f32, 1.5), "");
755
756 if (is_array) {
757 /* for cube arrays coord.z = coord.w(array_index) * 8 + face */
758 /* coords_arg.w component - array_index for cube arrays */
759 LLVMValueRef tmp = LLVMBuildFMul(ctx->builder, coords_arg[3], LLVMConstReal(ctx->f32, 8.0), "");
760 coords[2] = LLVMBuildFAdd(ctx->builder, tmp, coords[2], "");
761 }
762
763 memcpy(coords_arg, coords, sizeof(coords));
764 }
765
766
767 LLVMValueRef
768 ac_build_fs_interp(struct ac_llvm_context *ctx,
769 LLVMValueRef llvm_chan,
770 LLVMValueRef attr_number,
771 LLVMValueRef params,
772 LLVMValueRef i,
773 LLVMValueRef j)
774 {
775 LLVMValueRef args[5];
776 LLVMValueRef p1;
777
778 args[0] = i;
779 args[1] = llvm_chan;
780 args[2] = attr_number;
781 args[3] = params;
782
783 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1",
784 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
785
786 args[0] = p1;
787 args[1] = j;
788 args[2] = llvm_chan;
789 args[3] = attr_number;
790 args[4] = params;
791
792 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2",
793 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
794 }
795
796 LLVMValueRef
797 ac_build_fs_interp_mov(struct ac_llvm_context *ctx,
798 LLVMValueRef parameter,
799 LLVMValueRef llvm_chan,
800 LLVMValueRef attr_number,
801 LLVMValueRef params)
802 {
803 LLVMValueRef args[4];
804
805 args[0] = parameter;
806 args[1] = llvm_chan;
807 args[2] = attr_number;
808 args[3] = params;
809
810 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.mov",
811 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
812 }
813
814 LLVMValueRef
815 ac_build_gep0(struct ac_llvm_context *ctx,
816 LLVMValueRef base_ptr,
817 LLVMValueRef index)
818 {
819 LLVMValueRef indices[2] = {
820 LLVMConstInt(ctx->i32, 0, 0),
821 index,
822 };
823 return LLVMBuildGEP(ctx->builder, base_ptr,
824 indices, 2, "");
825 }
826
827 void
828 ac_build_indexed_store(struct ac_llvm_context *ctx,
829 LLVMValueRef base_ptr, LLVMValueRef index,
830 LLVMValueRef value)
831 {
832 LLVMBuildStore(ctx->builder, value,
833 ac_build_gep0(ctx, base_ptr, index));
834 }
835
836 /**
837 * Build an LLVM bytecode indexed load using LLVMBuildGEP + LLVMBuildLoad.
838 * It's equivalent to doing a load from &base_ptr[index].
839 *
840 * \param base_ptr Where the array starts.
841 * \param index The element index into the array.
842 * \param uniform Whether the base_ptr and index can be assumed to be
843 * dynamically uniform (i.e. load to an SGPR)
844 * \param invariant Whether the load is invariant (no other opcodes affect it)
845 */
846 static LLVMValueRef
847 ac_build_load_custom(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
848 LLVMValueRef index, bool uniform, bool invariant)
849 {
850 LLVMValueRef pointer, result;
851
852 pointer = ac_build_gep0(ctx, base_ptr, index);
853 if (uniform)
854 LLVMSetMetadata(pointer, ctx->uniform_md_kind, ctx->empty_md);
855 result = LLVMBuildLoad(ctx->builder, pointer, "");
856 if (invariant)
857 LLVMSetMetadata(result, ctx->invariant_load_md_kind, ctx->empty_md);
858 return result;
859 }
860
861 LLVMValueRef ac_build_load(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
862 LLVMValueRef index)
863 {
864 return ac_build_load_custom(ctx, base_ptr, index, false, false);
865 }
866
867 LLVMValueRef ac_build_load_invariant(struct ac_llvm_context *ctx,
868 LLVMValueRef base_ptr, LLVMValueRef index)
869 {
870 return ac_build_load_custom(ctx, base_ptr, index, false, true);
871 }
872
873 LLVMValueRef ac_build_load_to_sgpr(struct ac_llvm_context *ctx,
874 LLVMValueRef base_ptr, LLVMValueRef index)
875 {
876 return ac_build_load_custom(ctx, base_ptr, index, true, true);
877 }
878
879 /* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
880 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
881 * or v4i32 (num_channels=3,4).
882 */
883 void
884 ac_build_buffer_store_dword(struct ac_llvm_context *ctx,
885 LLVMValueRef rsrc,
886 LLVMValueRef vdata,
887 unsigned num_channels,
888 LLVMValueRef voffset,
889 LLVMValueRef soffset,
890 unsigned inst_offset,
891 bool glc,
892 bool slc,
893 bool writeonly_memory,
894 bool swizzle_enable_hint)
895 {
896 /* Split 3 channel stores, becase LLVM doesn't support 3-channel
897 * intrinsics. */
898 if (num_channels == 3) {
899 LLVMValueRef v[3], v01;
900
901 for (int i = 0; i < 3; i++) {
902 v[i] = LLVMBuildExtractElement(ctx->builder, vdata,
903 LLVMConstInt(ctx->i32, i, 0), "");
904 }
905 v01 = ac_build_gather_values(ctx, v, 2);
906
907 ac_build_buffer_store_dword(ctx, rsrc, v01, 2, voffset,
908 soffset, inst_offset, glc, slc,
909 writeonly_memory, swizzle_enable_hint);
910 ac_build_buffer_store_dword(ctx, rsrc, v[2], 1, voffset,
911 soffset, inst_offset + 8,
912 glc, slc,
913 writeonly_memory, swizzle_enable_hint);
914 return;
915 }
916
917 /* SWIZZLE_ENABLE requires that soffset isn't folded into voffset
918 * (voffset is swizzled, but soffset isn't swizzled).
919 * llvm.amdgcn.buffer.store doesn't have a separate soffset parameter.
920 */
921 if (!swizzle_enable_hint) {
922 LLVMValueRef offset = soffset;
923
924 static const char *types[] = {"f32", "v2f32", "v4f32"};
925
926 if (inst_offset)
927 offset = LLVMBuildAdd(ctx->builder, offset,
928 LLVMConstInt(ctx->i32, inst_offset, 0), "");
929 if (voffset)
930 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
931
932 LLVMValueRef args[] = {
933 ac_to_float(ctx, vdata),
934 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
935 LLVMConstInt(ctx->i32, 0, 0),
936 offset,
937 LLVMConstInt(ctx->i1, glc, 0),
938 LLVMConstInt(ctx->i1, slc, 0),
939 };
940
941 char name[256];
942 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.store.%s",
943 types[CLAMP(num_channels, 1, 3) - 1]);
944
945 ac_build_intrinsic(ctx, name, ctx->voidt,
946 args, ARRAY_SIZE(args),
947 writeonly_memory ?
948 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY :
949 AC_FUNC_ATTR_WRITEONLY);
950 return;
951 }
952
953 static const unsigned dfmt[] = {
954 V_008F0C_BUF_DATA_FORMAT_32,
955 V_008F0C_BUF_DATA_FORMAT_32_32,
956 V_008F0C_BUF_DATA_FORMAT_32_32_32,
957 V_008F0C_BUF_DATA_FORMAT_32_32_32_32
958 };
959 static const char *types[] = {"i32", "v2i32", "v4i32"};
960 LLVMValueRef args[] = {
961 vdata,
962 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
963 LLVMConstInt(ctx->i32, 0, 0),
964 voffset ? voffset : LLVMConstInt(ctx->i32, 0, 0),
965 soffset,
966 LLVMConstInt(ctx->i32, inst_offset, 0),
967 LLVMConstInt(ctx->i32, dfmt[num_channels - 1], 0),
968 LLVMConstInt(ctx->i32, V_008F0C_BUF_NUM_FORMAT_UINT, 0),
969 LLVMConstInt(ctx->i1, glc, 0),
970 LLVMConstInt(ctx->i1, slc, 0),
971 };
972 char name[256];
973 snprintf(name, sizeof(name), "llvm.amdgcn.tbuffer.store.%s",
974 types[CLAMP(num_channels, 1, 3) - 1]);
975
976 ac_build_intrinsic(ctx, name, ctx->voidt,
977 args, ARRAY_SIZE(args),
978 writeonly_memory ?
979 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY :
980 AC_FUNC_ATTR_WRITEONLY);
981 }
982
983 static LLVMValueRef
984 ac_build_buffer_load_common(struct ac_llvm_context *ctx,
985 LLVMValueRef rsrc,
986 LLVMValueRef vindex,
987 LLVMValueRef voffset,
988 unsigned num_channels,
989 bool glc,
990 bool slc,
991 bool can_speculate,
992 bool use_format)
993 {
994 LLVMValueRef args[] = {
995 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
996 vindex ? vindex : LLVMConstInt(ctx->i32, 0, 0),
997 voffset,
998 LLVMConstInt(ctx->i1, glc, 0),
999 LLVMConstInt(ctx->i1, slc, 0)
1000 };
1001 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1002
1003 LLVMTypeRef types[] = {ctx->f32, ctx->v2f32, ctx->v4f32};
1004 const char *type_names[] = {"f32", "v2f32", "v4f32"};
1005 char name[256];
1006
1007 if (use_format) {
1008 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.format.%s",
1009 type_names[func]);
1010 } else {
1011 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.%s",
1012 type_names[func]);
1013 }
1014
1015 return ac_build_intrinsic(ctx, name, types[func], args,
1016 ARRAY_SIZE(args),
1017 ac_get_load_intr_attribs(can_speculate));
1018 }
1019
1020 LLVMValueRef
1021 ac_build_buffer_load(struct ac_llvm_context *ctx,
1022 LLVMValueRef rsrc,
1023 int num_channels,
1024 LLVMValueRef vindex,
1025 LLVMValueRef voffset,
1026 LLVMValueRef soffset,
1027 unsigned inst_offset,
1028 unsigned glc,
1029 unsigned slc,
1030 bool can_speculate,
1031 bool allow_smem)
1032 {
1033 LLVMValueRef offset = LLVMConstInt(ctx->i32, inst_offset, 0);
1034 if (voffset)
1035 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
1036 if (soffset)
1037 offset = LLVMBuildAdd(ctx->builder, offset, soffset, "");
1038
1039 /* TODO: VI and later generations can use SMEM with GLC=1.*/
1040 if (allow_smem && !glc && !slc) {
1041 assert(vindex == NULL);
1042
1043 LLVMValueRef result[8];
1044
1045 for (int i = 0; i < num_channels; i++) {
1046 if (i) {
1047 offset = LLVMBuildAdd(ctx->builder, offset,
1048 LLVMConstInt(ctx->i32, 4, 0), "");
1049 }
1050 LLVMValueRef args[2] = {rsrc, offset};
1051 result[i] = ac_build_intrinsic(ctx, "llvm.SI.load.const.v4i32",
1052 ctx->f32, args, 2,
1053 AC_FUNC_ATTR_READNONE |
1054 AC_FUNC_ATTR_LEGACY);
1055 }
1056 if (num_channels == 1)
1057 return result[0];
1058
1059 if (num_channels == 3)
1060 result[num_channels++] = LLVMGetUndef(ctx->f32);
1061 return ac_build_gather_values(ctx, result, num_channels);
1062 }
1063
1064 return ac_build_buffer_load_common(ctx, rsrc, vindex, offset,
1065 num_channels, glc, slc,
1066 can_speculate, false);
1067 }
1068
1069 LLVMValueRef ac_build_buffer_load_format(struct ac_llvm_context *ctx,
1070 LLVMValueRef rsrc,
1071 LLVMValueRef vindex,
1072 LLVMValueRef voffset,
1073 unsigned num_channels,
1074 bool glc,
1075 bool can_speculate)
1076 {
1077 return ac_build_buffer_load_common(ctx, rsrc, vindex, voffset,
1078 num_channels, glc, false,
1079 can_speculate, true);
1080 }
1081
1082 LLVMValueRef ac_build_buffer_load_format_gfx9_safe(struct ac_llvm_context *ctx,
1083 LLVMValueRef rsrc,
1084 LLVMValueRef vindex,
1085 LLVMValueRef voffset,
1086 unsigned num_channels,
1087 bool glc,
1088 bool can_speculate)
1089 {
1090 LLVMValueRef elem_count = LLVMBuildExtractElement(ctx->builder, rsrc, LLVMConstInt(ctx->i32, 2, 0), "");
1091 LLVMValueRef stride = LLVMBuildExtractElement(ctx->builder, rsrc, LLVMConstInt(ctx->i32, 1, 0), "");
1092 stride = LLVMBuildLShr(ctx->builder, stride, LLVMConstInt(ctx->i32, 16, 0), "");
1093
1094 LLVMValueRef new_elem_count = LLVMBuildSelect(ctx->builder,
1095 LLVMBuildICmp(ctx->builder, LLVMIntUGT, elem_count, stride, ""),
1096 elem_count, stride, "");
1097
1098 LLVMValueRef new_rsrc = LLVMBuildInsertElement(ctx->builder, rsrc, new_elem_count,
1099 LLVMConstInt(ctx->i32, 2, 0), "");
1100
1101 return ac_build_buffer_load_common(ctx, new_rsrc, vindex, voffset,
1102 num_channels, glc, false,
1103 can_speculate, true);
1104 }
1105
1106 LLVMValueRef
1107 ac_build_tbuffer_load_short(struct ac_llvm_context *ctx,
1108 LLVMValueRef rsrc,
1109 LLVMValueRef vindex,
1110 LLVMValueRef voffset,
1111 LLVMValueRef soffset,
1112 LLVMValueRef immoffset)
1113 {
1114 const char *name = "llvm.amdgcn.tbuffer.load.i32";
1115 LLVMTypeRef type = ctx->i32;
1116 LLVMValueRef params[] = {
1117 rsrc,
1118 vindex,
1119 voffset,
1120 soffset,
1121 immoffset,
1122 LLVMConstInt(ctx->i32, V_008F0C_BUF_DATA_FORMAT_16, false),
1123 LLVMConstInt(ctx->i32, V_008F0C_BUF_NUM_FORMAT_UINT, false),
1124 ctx->i1false,
1125 ctx->i1false,
1126 };
1127 LLVMValueRef res = ac_build_intrinsic(ctx, name, type, params, 9, 0);
1128 return LLVMBuildTrunc(ctx->builder, res, ctx->i16, "");
1129 }
1130
1131 /**
1132 * Set range metadata on an instruction. This can only be used on load and
1133 * call instructions. If you know an instruction can only produce the values
1134 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
1135 * \p lo is the minimum value inclusive.
1136 * \p hi is the maximum value exclusive.
1137 */
1138 static void set_range_metadata(struct ac_llvm_context *ctx,
1139 LLVMValueRef value, unsigned lo, unsigned hi)
1140 {
1141 LLVMValueRef range_md, md_args[2];
1142 LLVMTypeRef type = LLVMTypeOf(value);
1143 LLVMContextRef context = LLVMGetTypeContext(type);
1144
1145 md_args[0] = LLVMConstInt(type, lo, false);
1146 md_args[1] = LLVMConstInt(type, hi, false);
1147 range_md = LLVMMDNodeInContext(context, md_args, 2);
1148 LLVMSetMetadata(value, ctx->range_md_kind, range_md);
1149 }
1150
1151 LLVMValueRef
1152 ac_get_thread_id(struct ac_llvm_context *ctx)
1153 {
1154 LLVMValueRef tid;
1155
1156 LLVMValueRef tid_args[2];
1157 tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
1158 tid_args[1] = LLVMConstInt(ctx->i32, 0, false);
1159 tid_args[1] = ac_build_intrinsic(ctx,
1160 "llvm.amdgcn.mbcnt.lo", ctx->i32,
1161 tid_args, 2, AC_FUNC_ATTR_READNONE);
1162
1163 tid = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi",
1164 ctx->i32, tid_args,
1165 2, AC_FUNC_ATTR_READNONE);
1166 set_range_metadata(ctx, tid, 0, 64);
1167 return tid;
1168 }
1169
1170 /*
1171 * SI implements derivatives using the local data store (LDS)
1172 * All writes to the LDS happen in all executing threads at
1173 * the same time. TID is the Thread ID for the current
1174 * thread and is a value between 0 and 63, representing
1175 * the thread's position in the wavefront.
1176 *
1177 * For the pixel shader threads are grouped into quads of four pixels.
1178 * The TIDs of the pixels of a quad are:
1179 *
1180 * +------+------+
1181 * |4n + 0|4n + 1|
1182 * +------+------+
1183 * |4n + 2|4n + 3|
1184 * +------+------+
1185 *
1186 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
1187 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
1188 * the current pixel's column, and masking with 0xfffffffe yields the TID
1189 * of the left pixel of the current pixel's row.
1190 *
1191 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
1192 * adding 2 yields the TID of the pixel below the top pixel.
1193 */
1194 LLVMValueRef
1195 ac_build_ddxy(struct ac_llvm_context *ctx,
1196 uint32_t mask,
1197 int idx,
1198 LLVMValueRef val)
1199 {
1200 LLVMValueRef tl, trbl, args[2];
1201 LLVMValueRef result;
1202
1203 if (HAVE_LLVM >= 0x0700) {
1204 unsigned tl_lanes[4], trbl_lanes[4];
1205
1206 for (unsigned i = 0; i < 4; ++i) {
1207 tl_lanes[i] = i & mask;
1208 trbl_lanes[i] = (i & mask) + idx;
1209 }
1210
1211 tl = ac_build_quad_swizzle(ctx, val,
1212 tl_lanes[0], tl_lanes[1],
1213 tl_lanes[2], tl_lanes[3]);
1214 trbl = ac_build_quad_swizzle(ctx, val,
1215 trbl_lanes[0], trbl_lanes[1],
1216 trbl_lanes[2], trbl_lanes[3]);
1217 } else if (ctx->chip_class >= VI) {
1218 LLVMValueRef thread_id, tl_tid, trbl_tid;
1219 thread_id = ac_get_thread_id(ctx);
1220
1221 tl_tid = LLVMBuildAnd(ctx->builder, thread_id,
1222 LLVMConstInt(ctx->i32, mask, false), "");
1223
1224 trbl_tid = LLVMBuildAdd(ctx->builder, tl_tid,
1225 LLVMConstInt(ctx->i32, idx, false), "");
1226
1227 args[0] = LLVMBuildMul(ctx->builder, tl_tid,
1228 LLVMConstInt(ctx->i32, 4, false), "");
1229 args[1] = val;
1230 tl = ac_build_intrinsic(ctx,
1231 "llvm.amdgcn.ds.bpermute", ctx->i32,
1232 args, 2,
1233 AC_FUNC_ATTR_READNONE |
1234 AC_FUNC_ATTR_CONVERGENT);
1235
1236 args[0] = LLVMBuildMul(ctx->builder, trbl_tid,
1237 LLVMConstInt(ctx->i32, 4, false), "");
1238 trbl = ac_build_intrinsic(ctx,
1239 "llvm.amdgcn.ds.bpermute", ctx->i32,
1240 args, 2,
1241 AC_FUNC_ATTR_READNONE |
1242 AC_FUNC_ATTR_CONVERGENT);
1243 } else {
1244 uint32_t masks[2] = {};
1245
1246 switch (mask) {
1247 case AC_TID_MASK_TOP_LEFT:
1248 masks[0] = 0x8000;
1249 if (idx == 1)
1250 masks[1] = 0x8055;
1251 else
1252 masks[1] = 0x80aa;
1253
1254 break;
1255 case AC_TID_MASK_TOP:
1256 masks[0] = 0x8044;
1257 masks[1] = 0x80ee;
1258 break;
1259 case AC_TID_MASK_LEFT:
1260 masks[0] = 0x80a0;
1261 masks[1] = 0x80f5;
1262 break;
1263 default:
1264 assert(0);
1265 }
1266
1267 args[0] = val;
1268 args[1] = LLVMConstInt(ctx->i32, masks[0], false);
1269
1270 tl = ac_build_intrinsic(ctx,
1271 "llvm.amdgcn.ds.swizzle", ctx->i32,
1272 args, 2,
1273 AC_FUNC_ATTR_READNONE |
1274 AC_FUNC_ATTR_CONVERGENT);
1275
1276 args[1] = LLVMConstInt(ctx->i32, masks[1], false);
1277 trbl = ac_build_intrinsic(ctx,
1278 "llvm.amdgcn.ds.swizzle", ctx->i32,
1279 args, 2,
1280 AC_FUNC_ATTR_READNONE |
1281 AC_FUNC_ATTR_CONVERGENT);
1282 }
1283
1284 tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
1285 trbl = LLVMBuildBitCast(ctx->builder, trbl, ctx->f32, "");
1286 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
1287
1288 if (HAVE_LLVM >= 0x0700) {
1289 result = ac_build_intrinsic(ctx,
1290 "llvm.amdgcn.wqm.f32", ctx->f32,
1291 &result, 1, 0);
1292 }
1293
1294 return result;
1295 }
1296
1297 void
1298 ac_build_sendmsg(struct ac_llvm_context *ctx,
1299 uint32_t msg,
1300 LLVMValueRef wave_id)
1301 {
1302 LLVMValueRef args[2];
1303 args[0] = LLVMConstInt(ctx->i32, msg, false);
1304 args[1] = wave_id;
1305 ac_build_intrinsic(ctx, "llvm.amdgcn.s.sendmsg", ctx->voidt, args, 2, 0);
1306 }
1307
1308 LLVMValueRef
1309 ac_build_imsb(struct ac_llvm_context *ctx,
1310 LLVMValueRef arg,
1311 LLVMTypeRef dst_type)
1312 {
1313 LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.amdgcn.sffbh.i32",
1314 dst_type, &arg, 1,
1315 AC_FUNC_ATTR_READNONE);
1316
1317 /* The HW returns the last bit index from MSB, but NIR/TGSI wants
1318 * the index from LSB. Invert it by doing "31 - msb". */
1319 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
1320 msb, "");
1321
1322 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
1323 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
1324 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1325 arg, LLVMConstInt(ctx->i32, 0, 0), ""),
1326 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1327 arg, all_ones, ""), "");
1328
1329 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
1330 }
1331
1332 LLVMValueRef
1333 ac_build_umsb(struct ac_llvm_context *ctx,
1334 LLVMValueRef arg,
1335 LLVMTypeRef dst_type)
1336 {
1337 const char *intrin_name;
1338 LLVMTypeRef type;
1339 LLVMValueRef highest_bit;
1340 LLVMValueRef zero;
1341
1342 if (ac_get_elem_bits(ctx, LLVMTypeOf(arg)) == 64) {
1343 intrin_name = "llvm.ctlz.i64";
1344 type = ctx->i64;
1345 highest_bit = LLVMConstInt(ctx->i64, 63, false);
1346 zero = ctx->i64_0;
1347 } else {
1348 intrin_name = "llvm.ctlz.i32";
1349 type = ctx->i32;
1350 highest_bit = LLVMConstInt(ctx->i32, 31, false);
1351 zero = ctx->i32_0;
1352 }
1353
1354 LLVMValueRef params[2] = {
1355 arg,
1356 ctx->i1true,
1357 };
1358
1359 LLVMValueRef msb = ac_build_intrinsic(ctx, intrin_name, type,
1360 params, 2,
1361 AC_FUNC_ATTR_READNONE);
1362
1363 /* The HW returns the last bit index from MSB, but TGSI/NIR wants
1364 * the index from LSB. Invert it by doing "31 - msb". */
1365 msb = LLVMBuildSub(ctx->builder, highest_bit, msb, "");
1366 msb = LLVMBuildTruncOrBitCast(ctx->builder, msb, ctx->i32, "");
1367
1368 /* check for zero */
1369 return LLVMBuildSelect(ctx->builder,
1370 LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg, zero, ""),
1371 LLVMConstInt(ctx->i32, -1, true), msb, "");
1372 }
1373
1374 LLVMValueRef ac_build_fmin(struct ac_llvm_context *ctx, LLVMValueRef a,
1375 LLVMValueRef b)
1376 {
1377 LLVMValueRef args[2] = {a, b};
1378 return ac_build_intrinsic(ctx, "llvm.minnum.f32", ctx->f32, args, 2,
1379 AC_FUNC_ATTR_READNONE);
1380 }
1381
1382 LLVMValueRef ac_build_fmax(struct ac_llvm_context *ctx, LLVMValueRef a,
1383 LLVMValueRef b)
1384 {
1385 LLVMValueRef args[2] = {a, b};
1386 return ac_build_intrinsic(ctx, "llvm.maxnum.f32", ctx->f32, args, 2,
1387 AC_FUNC_ATTR_READNONE);
1388 }
1389
1390 LLVMValueRef ac_build_imin(struct ac_llvm_context *ctx, LLVMValueRef a,
1391 LLVMValueRef b)
1392 {
1393 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSLE, a, b, "");
1394 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1395 }
1396
1397 LLVMValueRef ac_build_imax(struct ac_llvm_context *ctx, LLVMValueRef a,
1398 LLVMValueRef b)
1399 {
1400 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, a, b, "");
1401 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1402 }
1403
1404 LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
1405 LLVMValueRef b)
1406 {
1407 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
1408 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1409 }
1410
1411 LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
1412 {
1413 return ac_build_fmin(ctx, ac_build_fmax(ctx, value, ctx->f32_0),
1414 ctx->f32_1);
1415 }
1416
1417 void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
1418 {
1419 LLVMValueRef args[9];
1420
1421 args[0] = LLVMConstInt(ctx->i32, a->target, 0);
1422 args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
1423
1424 if (a->compr) {
1425 LLVMTypeRef i16 = LLVMInt16TypeInContext(ctx->context);
1426 LLVMTypeRef v2i16 = LLVMVectorType(i16, 2);
1427
1428 args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
1429 v2i16, "");
1430 args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
1431 v2i16, "");
1432 args[4] = LLVMConstInt(ctx->i1, a->done, 0);
1433 args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1434
1435 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
1436 ctx->voidt, args, 6, 0);
1437 } else {
1438 args[2] = a->out[0];
1439 args[3] = a->out[1];
1440 args[4] = a->out[2];
1441 args[5] = a->out[3];
1442 args[6] = LLVMConstInt(ctx->i1, a->done, 0);
1443 args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1444
1445 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
1446 ctx->voidt, args, 8, 0);
1447 }
1448 }
1449
1450 void ac_build_export_null(struct ac_llvm_context *ctx)
1451 {
1452 struct ac_export_args args;
1453
1454 args.enabled_channels = 0x0; /* enabled channels */
1455 args.valid_mask = 1; /* whether the EXEC mask is valid */
1456 args.done = 1; /* DONE bit */
1457 args.target = V_008DFC_SQ_EXP_NULL;
1458 args.compr = 0; /* COMPR flag (0 = 32-bit export) */
1459 args.out[0] = LLVMGetUndef(ctx->f32); /* R */
1460 args.out[1] = LLVMGetUndef(ctx->f32); /* G */
1461 args.out[2] = LLVMGetUndef(ctx->f32); /* B */
1462 args.out[3] = LLVMGetUndef(ctx->f32); /* A */
1463
1464 ac_build_export(ctx, &args);
1465 }
1466
1467 static unsigned ac_num_coords(enum ac_image_dim dim)
1468 {
1469 switch (dim) {
1470 case ac_image_1d:
1471 return 1;
1472 case ac_image_2d:
1473 case ac_image_1darray:
1474 return 2;
1475 case ac_image_3d:
1476 case ac_image_cube:
1477 case ac_image_2darray:
1478 case ac_image_2dmsaa:
1479 return 3;
1480 case ac_image_2darraymsaa:
1481 return 4;
1482 default:
1483 unreachable("ac_num_coords: bad dim");
1484 }
1485 }
1486
1487 static unsigned ac_num_derivs(enum ac_image_dim dim)
1488 {
1489 switch (dim) {
1490 case ac_image_1d:
1491 case ac_image_1darray:
1492 return 2;
1493 case ac_image_2d:
1494 case ac_image_2darray:
1495 case ac_image_cube:
1496 return 4;
1497 case ac_image_3d:
1498 return 6;
1499 case ac_image_2dmsaa:
1500 case ac_image_2darraymsaa:
1501 default:
1502 unreachable("derivatives not supported");
1503 }
1504 }
1505
1506 static const char *get_atomic_name(enum ac_atomic_op op)
1507 {
1508 switch (op) {
1509 case ac_atomic_swap: return "swap";
1510 case ac_atomic_add: return "add";
1511 case ac_atomic_sub: return "sub";
1512 case ac_atomic_smin: return "smin";
1513 case ac_atomic_umin: return "umin";
1514 case ac_atomic_smax: return "smax";
1515 case ac_atomic_umax: return "umax";
1516 case ac_atomic_and: return "and";
1517 case ac_atomic_or: return "or";
1518 case ac_atomic_xor: return "xor";
1519 }
1520 unreachable("bad atomic op");
1521 }
1522
1523 /* LLVM 6 and older */
1524 static LLVMValueRef ac_build_image_opcode_llvm6(struct ac_llvm_context *ctx,
1525 struct ac_image_args *a)
1526 {
1527 LLVMValueRef args[16];
1528 LLVMTypeRef retty = ctx->v4f32;
1529 const char *name = NULL;
1530 const char *atomic_subop = "";
1531 char intr_name[128], coords_type[64];
1532
1533 bool sample = a->opcode == ac_image_sample ||
1534 a->opcode == ac_image_gather4 ||
1535 a->opcode == ac_image_get_lod;
1536 bool atomic = a->opcode == ac_image_atomic ||
1537 a->opcode == ac_image_atomic_cmpswap;
1538 bool da = a->dim == ac_image_cube ||
1539 a->dim == ac_image_1darray ||
1540 a->dim == ac_image_2darray ||
1541 a->dim == ac_image_2darraymsaa;
1542 if (a->opcode == ac_image_get_lod)
1543 da = false;
1544
1545 unsigned num_coords =
1546 a->opcode != ac_image_get_resinfo ? ac_num_coords(a->dim) : 0;
1547 LLVMValueRef addr;
1548 unsigned num_addr = 0;
1549
1550 if (a->opcode == ac_image_get_lod) {
1551 switch (a->dim) {
1552 case ac_image_1darray:
1553 num_coords = 1;
1554 break;
1555 case ac_image_2darray:
1556 case ac_image_cube:
1557 num_coords = 2;
1558 break;
1559 default:
1560 break;
1561 }
1562 }
1563
1564 if (a->offset)
1565 args[num_addr++] = ac_to_integer(ctx, a->offset);
1566 if (a->bias)
1567 args[num_addr++] = ac_to_integer(ctx, a->bias);
1568 if (a->compare)
1569 args[num_addr++] = ac_to_integer(ctx, a->compare);
1570 if (a->derivs[0]) {
1571 unsigned num_derivs = ac_num_derivs(a->dim);
1572 for (unsigned i = 0; i < num_derivs; ++i)
1573 args[num_addr++] = ac_to_integer(ctx, a->derivs[i]);
1574 }
1575 for (unsigned i = 0; i < num_coords; ++i)
1576 args[num_addr++] = ac_to_integer(ctx, a->coords[i]);
1577 if (a->lod)
1578 args[num_addr++] = ac_to_integer(ctx, a->lod);
1579
1580 unsigned pad_goal = util_next_power_of_two(num_addr);
1581 while (num_addr < pad_goal)
1582 args[num_addr++] = LLVMGetUndef(ctx->i32);
1583
1584 addr = ac_build_gather_values(ctx, args, num_addr);
1585
1586 unsigned num_args = 0;
1587 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
1588 args[num_args++] = a->data[0];
1589 if (a->opcode == ac_image_atomic_cmpswap)
1590 args[num_args++] = a->data[1];
1591 }
1592
1593 unsigned coords_arg = num_args;
1594 if (sample)
1595 args[num_args++] = ac_to_float(ctx, addr);
1596 else
1597 args[num_args++] = ac_to_integer(ctx, addr);
1598
1599 args[num_args++] = a->resource;
1600 if (sample)
1601 args[num_args++] = a->sampler;
1602 if (!atomic) {
1603 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, 0);
1604 if (sample)
1605 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, 0);
1606 args[num_args++] = a->cache_policy & ac_glc ? ctx->i1true : ctx->i1false;
1607 args[num_args++] = a->cache_policy & ac_slc ? ctx->i1true : ctx->i1false;
1608 args[num_args++] = ctx->i1false; /* lwe */
1609 args[num_args++] = LLVMConstInt(ctx->i1, da, 0);
1610 } else {
1611 args[num_args++] = ctx->i1false; /* r128 */
1612 args[num_args++] = LLVMConstInt(ctx->i1, da, 0);
1613 args[num_args++] = a->cache_policy & ac_slc ? ctx->i1true : ctx->i1false;
1614 }
1615
1616 switch (a->opcode) {
1617 case ac_image_sample:
1618 name = "llvm.amdgcn.image.sample";
1619 break;
1620 case ac_image_gather4:
1621 name = "llvm.amdgcn.image.gather4";
1622 break;
1623 case ac_image_load:
1624 name = "llvm.amdgcn.image.load";
1625 break;
1626 case ac_image_load_mip:
1627 name = "llvm.amdgcn.image.load.mip";
1628 break;
1629 case ac_image_store:
1630 name = "llvm.amdgcn.image.store";
1631 retty = ctx->voidt;
1632 break;
1633 case ac_image_store_mip:
1634 name = "llvm.amdgcn.image.store.mip";
1635 retty = ctx->voidt;
1636 break;
1637 case ac_image_atomic:
1638 case ac_image_atomic_cmpswap:
1639 name = "llvm.amdgcn.image.atomic.";
1640 retty = ctx->i32;
1641 if (a->opcode == ac_image_atomic_cmpswap) {
1642 atomic_subop = "cmpswap";
1643 } else {
1644 atomic_subop = get_atomic_name(a->atomic);
1645 }
1646 break;
1647 case ac_image_get_lod:
1648 name = "llvm.amdgcn.image.getlod";
1649 break;
1650 case ac_image_get_resinfo:
1651 name = "llvm.amdgcn.image.getresinfo";
1652 break;
1653 default:
1654 unreachable("invalid image opcode");
1655 }
1656
1657 ac_build_type_name_for_intr(LLVMTypeOf(args[coords_arg]), coords_type,
1658 sizeof(coords_type));
1659
1660 if (atomic) {
1661 snprintf(intr_name, sizeof(intr_name), "llvm.amdgcn.image.atomic.%s.%s",
1662 atomic_subop, coords_type);
1663 } else {
1664 bool lod_suffix =
1665 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
1666
1667 snprintf(intr_name, sizeof(intr_name), "%s%s%s%s.v4f32.%s.v8i32",
1668 name,
1669 a->compare ? ".c" : "",
1670 a->bias ? ".b" :
1671 lod_suffix ? ".l" :
1672 a->derivs[0] ? ".d" :
1673 a->level_zero ? ".lz" : "",
1674 a->offset ? ".o" : "",
1675 coords_type);
1676 }
1677
1678 LLVMValueRef result =
1679 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
1680 a->attributes);
1681 if (!sample && retty == ctx->v4f32) {
1682 result = LLVMBuildBitCast(ctx->builder, result,
1683 ctx->v4i32, "");
1684 }
1685 return result;
1686 }
1687
1688 LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
1689 struct ac_image_args *a)
1690 {
1691 const char *overload[3] = { "", "", "" };
1692 unsigned num_overloads = 0;
1693 LLVMValueRef args[18];
1694 unsigned num_args = 0;
1695 enum ac_image_dim dim = a->dim;
1696
1697 assert(!a->lod || a->lod == ctx->i32_0 || a->lod == ctx->f32_0 ||
1698 !a->level_zero);
1699 assert((a->opcode != ac_image_get_resinfo && a->opcode != ac_image_load_mip &&
1700 a->opcode != ac_image_store_mip) ||
1701 a->lod);
1702 assert(a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
1703 (!a->compare && !a->offset));
1704 assert((a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
1705 a->opcode == ac_image_get_lod) ||
1706 !a->bias);
1707 assert((a->bias ? 1 : 0) +
1708 (a->lod ? 1 : 0) +
1709 (a->level_zero ? 1 : 0) +
1710 (a->derivs[0] ? 1 : 0) <= 1);
1711
1712 if (HAVE_LLVM < 0x0700)
1713 return ac_build_image_opcode_llvm6(ctx, a);
1714
1715 if (a->opcode == ac_image_get_lod) {
1716 switch (dim) {
1717 case ac_image_1darray:
1718 dim = ac_image_1d;
1719 break;
1720 case ac_image_2darray:
1721 case ac_image_cube:
1722 dim = ac_image_2d;
1723 break;
1724 default:
1725 break;
1726 }
1727 }
1728
1729 bool sample = a->opcode == ac_image_sample ||
1730 a->opcode == ac_image_gather4 ||
1731 a->opcode == ac_image_get_lod;
1732 bool atomic = a->opcode == ac_image_atomic ||
1733 a->opcode == ac_image_atomic_cmpswap;
1734 LLVMTypeRef coord_type = sample ? ctx->f32 : ctx->i32;
1735
1736 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
1737 args[num_args++] = a->data[0];
1738 if (a->opcode == ac_image_atomic_cmpswap)
1739 args[num_args++] = a->data[1];
1740 }
1741
1742 if (!atomic)
1743 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, false);
1744
1745 if (a->offset)
1746 args[num_args++] = ac_to_integer(ctx, a->offset);
1747 if (a->bias) {
1748 args[num_args++] = ac_to_float(ctx, a->bias);
1749 overload[num_overloads++] = ".f32";
1750 }
1751 if (a->compare)
1752 args[num_args++] = ac_to_float(ctx, a->compare);
1753 if (a->derivs[0]) {
1754 unsigned count = ac_num_derivs(dim);
1755 for (unsigned i = 0; i < count; ++i)
1756 args[num_args++] = ac_to_float(ctx, a->derivs[i]);
1757 overload[num_overloads++] = ".f32";
1758 }
1759 unsigned num_coords =
1760 a->opcode != ac_image_get_resinfo ? ac_num_coords(dim) : 0;
1761 for (unsigned i = 0; i < num_coords; ++i)
1762 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->coords[i], coord_type, "");
1763 if (a->lod)
1764 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->lod, coord_type, "");
1765 overload[num_overloads++] = sample ? ".f32" : ".i32";
1766
1767 args[num_args++] = a->resource;
1768 if (sample) {
1769 args[num_args++] = a->sampler;
1770 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, false);
1771 }
1772
1773 args[num_args++] = ctx->i32_0; /* texfailctrl */
1774 args[num_args++] = LLVMConstInt(ctx->i32, a->cache_policy, false);
1775
1776 const char *name;
1777 const char *atomic_subop = "";
1778 switch (a->opcode) {
1779 case ac_image_sample: name = "sample"; break;
1780 case ac_image_gather4: name = "gather4"; break;
1781 case ac_image_load: name = "load"; break;
1782 case ac_image_load_mip: name = "load.mip"; break;
1783 case ac_image_store: name = "store"; break;
1784 case ac_image_store_mip: name = "store.mip"; break;
1785 case ac_image_atomic:
1786 name = "atomic.";
1787 atomic_subop = get_atomic_name(a->atomic);
1788 break;
1789 case ac_image_atomic_cmpswap:
1790 name = "atomic.";
1791 atomic_subop = "cmpswap";
1792 break;
1793 case ac_image_get_lod: name = "getlod"; break;
1794 case ac_image_get_resinfo: name = "getresinfo"; break;
1795 default: unreachable("invalid image opcode");
1796 }
1797
1798 const char *dimname;
1799 switch (dim) {
1800 case ac_image_1d: dimname = "1d"; break;
1801 case ac_image_2d: dimname = "2d"; break;
1802 case ac_image_3d: dimname = "3d"; break;
1803 case ac_image_cube: dimname = "cube"; break;
1804 case ac_image_1darray: dimname = "1darray"; break;
1805 case ac_image_2darray: dimname = "2darray"; break;
1806 case ac_image_2dmsaa: dimname = "2dmsaa"; break;
1807 case ac_image_2darraymsaa: dimname = "2darraymsaa"; break;
1808 default: unreachable("invalid dim");
1809 }
1810
1811 bool lod_suffix =
1812 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
1813 char intr_name[96];
1814 snprintf(intr_name, sizeof(intr_name),
1815 "llvm.amdgcn.image.%s%s" /* base name */
1816 "%s%s%s" /* sample/gather modifiers */
1817 ".%s.%s%s%s%s", /* dimension and type overloads */
1818 name, atomic_subop,
1819 a->compare ? ".c" : "",
1820 a->bias ? ".b" :
1821 lod_suffix ? ".l" :
1822 a->derivs[0] ? ".d" :
1823 a->level_zero ? ".lz" : "",
1824 a->offset ? ".o" : "",
1825 dimname,
1826 atomic ? "i32" : "v4f32",
1827 overload[0], overload[1], overload[2]);
1828
1829 LLVMTypeRef retty;
1830 if (atomic)
1831 retty = ctx->i32;
1832 else if (a->opcode == ac_image_store || a->opcode == ac_image_store_mip)
1833 retty = ctx->voidt;
1834 else
1835 retty = ctx->v4f32;
1836
1837 LLVMValueRef result =
1838 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
1839 a->attributes);
1840 if (!sample && retty == ctx->v4f32) {
1841 result = LLVMBuildBitCast(ctx->builder, result,
1842 ctx->v4i32, "");
1843 }
1844 return result;
1845 }
1846
1847 LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
1848 LLVMValueRef args[2])
1849 {
1850 LLVMTypeRef v2f16 =
1851 LLVMVectorType(LLVMHalfTypeInContext(ctx->context), 2);
1852
1853 return ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz", v2f16,
1854 args, 2, AC_FUNC_ATTR_READNONE);
1855 }
1856
1857 /* Upper 16 bits must be zero. */
1858 static LLVMValueRef ac_llvm_pack_two_int16(struct ac_llvm_context *ctx,
1859 LLVMValueRef val[2])
1860 {
1861 return LLVMBuildOr(ctx->builder, val[0],
1862 LLVMBuildShl(ctx->builder, val[1],
1863 LLVMConstInt(ctx->i32, 16, 0),
1864 ""), "");
1865 }
1866
1867 /* Upper 16 bits are ignored and will be dropped. */
1868 static LLVMValueRef ac_llvm_pack_two_int32_as_int16(struct ac_llvm_context *ctx,
1869 LLVMValueRef val[2])
1870 {
1871 LLVMValueRef v[2] = {
1872 LLVMBuildAnd(ctx->builder, val[0],
1873 LLVMConstInt(ctx->i32, 0xffff, 0), ""),
1874 val[1],
1875 };
1876 return ac_llvm_pack_two_int16(ctx, v);
1877 }
1878
1879 LLVMValueRef ac_build_cvt_pknorm_i16(struct ac_llvm_context *ctx,
1880 LLVMValueRef args[2])
1881 {
1882 if (HAVE_LLVM >= 0x0600) {
1883 LLVMValueRef res =
1884 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.i16",
1885 ctx->v2i16, args, 2,
1886 AC_FUNC_ATTR_READNONE);
1887 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1888 }
1889
1890 LLVMValueRef val[2];
1891
1892 for (int chan = 0; chan < 2; chan++) {
1893 /* Clamp between [-1, 1]. */
1894 val[chan] = ac_build_fmin(ctx, args[chan], ctx->f32_1);
1895 val[chan] = ac_build_fmax(ctx, val[chan], LLVMConstReal(ctx->f32, -1));
1896 /* Convert to a signed integer in [-32767, 32767]. */
1897 val[chan] = LLVMBuildFMul(ctx->builder, val[chan],
1898 LLVMConstReal(ctx->f32, 32767), "");
1899 /* If positive, add 0.5, else add -0.5. */
1900 val[chan] = LLVMBuildFAdd(ctx->builder, val[chan],
1901 LLVMBuildSelect(ctx->builder,
1902 LLVMBuildFCmp(ctx->builder, LLVMRealOGE,
1903 val[chan], ctx->f32_0, ""),
1904 LLVMConstReal(ctx->f32, 0.5),
1905 LLVMConstReal(ctx->f32, -0.5), ""), "");
1906 val[chan] = LLVMBuildFPToSI(ctx->builder, val[chan], ctx->i32, "");
1907 }
1908 return ac_llvm_pack_two_int32_as_int16(ctx, val);
1909 }
1910
1911 LLVMValueRef ac_build_cvt_pknorm_u16(struct ac_llvm_context *ctx,
1912 LLVMValueRef args[2])
1913 {
1914 if (HAVE_LLVM >= 0x0600) {
1915 LLVMValueRef res =
1916 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.u16",
1917 ctx->v2i16, args, 2,
1918 AC_FUNC_ATTR_READNONE);
1919 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1920 }
1921
1922 LLVMValueRef val[2];
1923
1924 for (int chan = 0; chan < 2; chan++) {
1925 val[chan] = ac_build_clamp(ctx, args[chan]);
1926 val[chan] = LLVMBuildFMul(ctx->builder, val[chan],
1927 LLVMConstReal(ctx->f32, 65535), "");
1928 val[chan] = LLVMBuildFAdd(ctx->builder, val[chan],
1929 LLVMConstReal(ctx->f32, 0.5), "");
1930 val[chan] = LLVMBuildFPToUI(ctx->builder, val[chan],
1931 ctx->i32, "");
1932 }
1933 return ac_llvm_pack_two_int32_as_int16(ctx, val);
1934 }
1935
1936 /* The 8-bit and 10-bit clamping is for HW workarounds. */
1937 LLVMValueRef ac_build_cvt_pk_i16(struct ac_llvm_context *ctx,
1938 LLVMValueRef args[2], unsigned bits, bool hi)
1939 {
1940 assert(bits == 8 || bits == 10 || bits == 16);
1941
1942 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
1943 bits == 8 ? 127 : bits == 10 ? 511 : 32767, 0);
1944 LLVMValueRef min_rgb = LLVMConstInt(ctx->i32,
1945 bits == 8 ? -128 : bits == 10 ? -512 : -32768, 0);
1946 LLVMValueRef max_alpha =
1947 bits != 10 ? max_rgb : ctx->i32_1;
1948 LLVMValueRef min_alpha =
1949 bits != 10 ? min_rgb : LLVMConstInt(ctx->i32, -2, 0);
1950 bool has_intrinsic = HAVE_LLVM >= 0x0600;
1951
1952 /* Clamp. */
1953 if (!has_intrinsic || bits != 16) {
1954 for (int i = 0; i < 2; i++) {
1955 bool alpha = hi && i == 1;
1956 args[i] = ac_build_imin(ctx, args[i],
1957 alpha ? max_alpha : max_rgb);
1958 args[i] = ac_build_imax(ctx, args[i],
1959 alpha ? min_alpha : min_rgb);
1960 }
1961 }
1962
1963 if (has_intrinsic) {
1964 LLVMValueRef res =
1965 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.i16",
1966 ctx->v2i16, args, 2,
1967 AC_FUNC_ATTR_READNONE);
1968 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1969 }
1970
1971 return ac_llvm_pack_two_int32_as_int16(ctx, args);
1972 }
1973
1974 /* The 8-bit and 10-bit clamping is for HW workarounds. */
1975 LLVMValueRef ac_build_cvt_pk_u16(struct ac_llvm_context *ctx,
1976 LLVMValueRef args[2], unsigned bits, bool hi)
1977 {
1978 assert(bits == 8 || bits == 10 || bits == 16);
1979
1980 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
1981 bits == 8 ? 255 : bits == 10 ? 1023 : 65535, 0);
1982 LLVMValueRef max_alpha =
1983 bits != 10 ? max_rgb : LLVMConstInt(ctx->i32, 3, 0);
1984 bool has_intrinsic = HAVE_LLVM >= 0x0600;
1985
1986 /* Clamp. */
1987 if (!has_intrinsic || bits != 16) {
1988 for (int i = 0; i < 2; i++) {
1989 bool alpha = hi && i == 1;
1990 args[i] = ac_build_umin(ctx, args[i],
1991 alpha ? max_alpha : max_rgb);
1992 }
1993 }
1994
1995 if (has_intrinsic) {
1996 LLVMValueRef res =
1997 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.u16",
1998 ctx->v2i16, args, 2,
1999 AC_FUNC_ATTR_READNONE);
2000 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2001 }
2002
2003 return ac_llvm_pack_two_int16(ctx, args);
2004 }
2005
2006 LLVMValueRef ac_build_wqm_vote(struct ac_llvm_context *ctx, LLVMValueRef i1)
2007 {
2008 assert(HAVE_LLVM >= 0x0600);
2009 return ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.vote", ctx->i1,
2010 &i1, 1, AC_FUNC_ATTR_READNONE);
2011 }
2012
2013 void ac_build_kill_if_false(struct ac_llvm_context *ctx, LLVMValueRef i1)
2014 {
2015 if (HAVE_LLVM >= 0x0600) {
2016 ac_build_intrinsic(ctx, "llvm.amdgcn.kill", ctx->voidt,
2017 &i1, 1, 0);
2018 return;
2019 }
2020
2021 LLVMValueRef value = LLVMBuildSelect(ctx->builder, i1,
2022 LLVMConstReal(ctx->f32, 1),
2023 LLVMConstReal(ctx->f32, -1), "");
2024 ac_build_intrinsic(ctx, "llvm.AMDGPU.kill", ctx->voidt,
2025 &value, 1, AC_FUNC_ATTR_LEGACY);
2026 }
2027
2028 LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
2029 LLVMValueRef offset, LLVMValueRef width,
2030 bool is_signed)
2031 {
2032 LLVMValueRef args[] = {
2033 input,
2034 offset,
2035 width,
2036 };
2037
2038 return ac_build_intrinsic(ctx,
2039 is_signed ? "llvm.amdgcn.sbfe.i32" :
2040 "llvm.amdgcn.ubfe.i32",
2041 ctx->i32, args, 3,
2042 AC_FUNC_ATTR_READNONE);
2043 }
2044
2045 void ac_build_waitcnt(struct ac_llvm_context *ctx, unsigned simm16)
2046 {
2047 LLVMValueRef args[1] = {
2048 LLVMConstInt(ctx->i32, simm16, false),
2049 };
2050 ac_build_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
2051 ctx->voidt, args, 1, 0);
2052 }
2053
2054 LLVMValueRef ac_build_fract(struct ac_llvm_context *ctx, LLVMValueRef src0,
2055 unsigned bitsize)
2056 {
2057 LLVMTypeRef type;
2058 char *intr;
2059
2060 if (bitsize == 32) {
2061 intr = "llvm.floor.f32";
2062 type = ctx->f32;
2063 } else {
2064 intr = "llvm.floor.f64";
2065 type = ctx->f64;
2066 }
2067
2068 LLVMValueRef params[] = {
2069 src0,
2070 };
2071 LLVMValueRef floor = ac_build_intrinsic(ctx, intr, type, params, 1,
2072 AC_FUNC_ATTR_READNONE);
2073 return LLVMBuildFSub(ctx->builder, src0, floor, "");
2074 }
2075
2076 LLVMValueRef ac_build_isign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2077 unsigned bitsize)
2078 {
2079 LLVMValueRef cmp, val, zero, one;
2080 LLVMTypeRef type;
2081
2082 if (bitsize == 32) {
2083 type = ctx->i32;
2084 zero = ctx->i32_0;
2085 one = ctx->i32_1;
2086 } else {
2087 type = ctx->i64;
2088 zero = ctx->i64_0;
2089 one = ctx->i64_1;
2090 }
2091
2092 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, zero, "");
2093 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2094 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, zero, "");
2095 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(type, -1, true), "");
2096 return val;
2097 }
2098
2099 LLVMValueRef ac_build_fsign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2100 unsigned bitsize)
2101 {
2102 LLVMValueRef cmp, val, zero, one;
2103 LLVMTypeRef type;
2104
2105 if (bitsize == 32) {
2106 type = ctx->f32;
2107 zero = ctx->f32_0;
2108 one = ctx->f32_1;
2109 } else {
2110 type = ctx->f64;
2111 zero = ctx->f64_0;
2112 one = ctx->f64_1;
2113 }
2114
2115 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, zero, "");
2116 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2117 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, zero, "");
2118 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(type, -1.0), "");
2119 return val;
2120 }
2121
2122 #define AC_EXP_TARGET 0
2123 #define AC_EXP_ENABLED_CHANNELS 1
2124 #define AC_EXP_OUT0 2
2125
2126 enum ac_ir_type {
2127 AC_IR_UNDEF,
2128 AC_IR_CONST,
2129 AC_IR_VALUE,
2130 };
2131
2132 struct ac_vs_exp_chan
2133 {
2134 LLVMValueRef value;
2135 float const_float;
2136 enum ac_ir_type type;
2137 };
2138
2139 struct ac_vs_exp_inst {
2140 unsigned offset;
2141 LLVMValueRef inst;
2142 struct ac_vs_exp_chan chan[4];
2143 };
2144
2145 struct ac_vs_exports {
2146 unsigned num;
2147 struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
2148 };
2149
2150 /* Return true if the PARAM export has been eliminated. */
2151 static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
2152 uint32_t num_outputs,
2153 struct ac_vs_exp_inst *exp)
2154 {
2155 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
2156 bool is_zero[4] = {}, is_one[4] = {};
2157
2158 for (i = 0; i < 4; i++) {
2159 /* It's a constant expression. Undef outputs are eliminated too. */
2160 if (exp->chan[i].type == AC_IR_UNDEF) {
2161 is_zero[i] = true;
2162 is_one[i] = true;
2163 } else if (exp->chan[i].type == AC_IR_CONST) {
2164 if (exp->chan[i].const_float == 0)
2165 is_zero[i] = true;
2166 else if (exp->chan[i].const_float == 1)
2167 is_one[i] = true;
2168 else
2169 return false; /* other constant */
2170 } else
2171 return false;
2172 }
2173
2174 /* Only certain combinations of 0 and 1 can be eliminated. */
2175 if (is_zero[0] && is_zero[1] && is_zero[2])
2176 default_val = is_zero[3] ? 0 : 1;
2177 else if (is_one[0] && is_one[1] && is_one[2])
2178 default_val = is_zero[3] ? 2 : 3;
2179 else
2180 return false;
2181
2182 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
2183 LLVMInstructionEraseFromParent(exp->inst);
2184
2185 /* Change OFFSET to DEFAULT_VAL. */
2186 for (i = 0; i < num_outputs; i++) {
2187 if (vs_output_param_offset[i] == exp->offset) {
2188 vs_output_param_offset[i] =
2189 AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
2190 break;
2191 }
2192 }
2193 return true;
2194 }
2195
2196 static bool ac_eliminate_duplicated_output(struct ac_llvm_context *ctx,
2197 uint8_t *vs_output_param_offset,
2198 uint32_t num_outputs,
2199 struct ac_vs_exports *processed,
2200 struct ac_vs_exp_inst *exp)
2201 {
2202 unsigned p, copy_back_channels = 0;
2203
2204 /* See if the output is already in the list of processed outputs.
2205 * The LLVMValueRef comparison relies on SSA.
2206 */
2207 for (p = 0; p < processed->num; p++) {
2208 bool different = false;
2209
2210 for (unsigned j = 0; j < 4; j++) {
2211 struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
2212 struct ac_vs_exp_chan *c2 = &exp->chan[j];
2213
2214 /* Treat undef as a match. */
2215 if (c2->type == AC_IR_UNDEF)
2216 continue;
2217
2218 /* If c1 is undef but c2 isn't, we can copy c2 to c1
2219 * and consider the instruction duplicated.
2220 */
2221 if (c1->type == AC_IR_UNDEF) {
2222 copy_back_channels |= 1 << j;
2223 continue;
2224 }
2225
2226 /* Test whether the channels are not equal. */
2227 if (c1->type != c2->type ||
2228 (c1->type == AC_IR_CONST &&
2229 c1->const_float != c2->const_float) ||
2230 (c1->type == AC_IR_VALUE &&
2231 c1->value != c2->value)) {
2232 different = true;
2233 break;
2234 }
2235 }
2236 if (!different)
2237 break;
2238
2239 copy_back_channels = 0;
2240 }
2241 if (p == processed->num)
2242 return false;
2243
2244 /* If a match was found, but the matching export has undef where the new
2245 * one has a normal value, copy the normal value to the undef channel.
2246 */
2247 struct ac_vs_exp_inst *match = &processed->exp[p];
2248
2249 /* Get current enabled channels mask. */
2250 LLVMValueRef arg = LLVMGetOperand(match->inst, AC_EXP_ENABLED_CHANNELS);
2251 unsigned enabled_channels = LLVMConstIntGetZExtValue(arg);
2252
2253 while (copy_back_channels) {
2254 unsigned chan = u_bit_scan(&copy_back_channels);
2255
2256 assert(match->chan[chan].type == AC_IR_UNDEF);
2257 LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
2258 exp->chan[chan].value);
2259 match->chan[chan] = exp->chan[chan];
2260
2261 /* Update number of enabled channels because the original mask
2262 * is not always 0xf.
2263 */
2264 enabled_channels |= (1 << chan);
2265 LLVMSetOperand(match->inst, AC_EXP_ENABLED_CHANNELS,
2266 LLVMConstInt(ctx->i32, enabled_channels, 0));
2267 }
2268
2269 /* The PARAM export is duplicated. Kill it. */
2270 LLVMInstructionEraseFromParent(exp->inst);
2271
2272 /* Change OFFSET to the matching export. */
2273 for (unsigned i = 0; i < num_outputs; i++) {
2274 if (vs_output_param_offset[i] == exp->offset) {
2275 vs_output_param_offset[i] = match->offset;
2276 break;
2277 }
2278 }
2279 return true;
2280 }
2281
2282 void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
2283 LLVMValueRef main_fn,
2284 uint8_t *vs_output_param_offset,
2285 uint32_t num_outputs,
2286 uint8_t *num_param_exports)
2287 {
2288 LLVMBasicBlockRef bb;
2289 bool removed_any = false;
2290 struct ac_vs_exports exports;
2291
2292 exports.num = 0;
2293
2294 /* Process all LLVM instructions. */
2295 bb = LLVMGetFirstBasicBlock(main_fn);
2296 while (bb) {
2297 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
2298
2299 while (inst) {
2300 LLVMValueRef cur = inst;
2301 inst = LLVMGetNextInstruction(inst);
2302 struct ac_vs_exp_inst exp;
2303
2304 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
2305 continue;
2306
2307 LLVMValueRef callee = ac_llvm_get_called_value(cur);
2308
2309 if (!ac_llvm_is_function(callee))
2310 continue;
2311
2312 const char *name = LLVMGetValueName(callee);
2313 unsigned num_args = LLVMCountParams(callee);
2314
2315 /* Check if this is an export instruction. */
2316 if ((num_args != 9 && num_args != 8) ||
2317 (strcmp(name, "llvm.SI.export") &&
2318 strcmp(name, "llvm.amdgcn.exp.f32")))
2319 continue;
2320
2321 LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
2322 unsigned target = LLVMConstIntGetZExtValue(arg);
2323
2324 if (target < V_008DFC_SQ_EXP_PARAM)
2325 continue;
2326
2327 target -= V_008DFC_SQ_EXP_PARAM;
2328
2329 /* Parse the instruction. */
2330 memset(&exp, 0, sizeof(exp));
2331 exp.offset = target;
2332 exp.inst = cur;
2333
2334 for (unsigned i = 0; i < 4; i++) {
2335 LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);
2336
2337 exp.chan[i].value = v;
2338
2339 if (LLVMIsUndef(v)) {
2340 exp.chan[i].type = AC_IR_UNDEF;
2341 } else if (LLVMIsAConstantFP(v)) {
2342 LLVMBool loses_info;
2343 exp.chan[i].type = AC_IR_CONST;
2344 exp.chan[i].const_float =
2345 LLVMConstRealGetDouble(v, &loses_info);
2346 } else {
2347 exp.chan[i].type = AC_IR_VALUE;
2348 }
2349 }
2350
2351 /* Eliminate constant and duplicated PARAM exports. */
2352 if (ac_eliminate_const_output(vs_output_param_offset,
2353 num_outputs, &exp) ||
2354 ac_eliminate_duplicated_output(ctx,
2355 vs_output_param_offset,
2356 num_outputs, &exports,
2357 &exp)) {
2358 removed_any = true;
2359 } else {
2360 exports.exp[exports.num++] = exp;
2361 }
2362 }
2363 bb = LLVMGetNextBasicBlock(bb);
2364 }
2365
2366 /* Remove holes in export memory due to removed PARAM exports.
2367 * This is done by renumbering all PARAM exports.
2368 */
2369 if (removed_any) {
2370 uint8_t old_offset[VARYING_SLOT_MAX];
2371 unsigned out, i;
2372
2373 /* Make a copy of the offsets. We need the old version while
2374 * we are modifying some of them. */
2375 memcpy(old_offset, vs_output_param_offset,
2376 sizeof(old_offset));
2377
2378 for (i = 0; i < exports.num; i++) {
2379 unsigned offset = exports.exp[i].offset;
2380
2381 /* Update vs_output_param_offset. Multiple outputs can
2382 * have the same offset.
2383 */
2384 for (out = 0; out < num_outputs; out++) {
2385 if (old_offset[out] == offset)
2386 vs_output_param_offset[out] = i;
2387 }
2388
2389 /* Change the PARAM offset in the instruction. */
2390 LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
2391 LLVMConstInt(ctx->i32,
2392 V_008DFC_SQ_EXP_PARAM + i, 0));
2393 }
2394 *num_param_exports = exports.num;
2395 }
2396 }
2397
2398 void ac_init_exec_full_mask(struct ac_llvm_context *ctx)
2399 {
2400 LLVMValueRef full_mask = LLVMConstInt(ctx->i64, ~0ull, 0);
2401 ac_build_intrinsic(ctx,
2402 "llvm.amdgcn.init.exec", ctx->voidt,
2403 &full_mask, 1, AC_FUNC_ATTR_CONVERGENT);
2404 }
2405
2406 void ac_declare_lds_as_pointer(struct ac_llvm_context *ctx)
2407 {
2408 unsigned lds_size = ctx->chip_class >= CIK ? 65536 : 32768;
2409 ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32_0,
2410 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), AC_LOCAL_ADDR_SPACE),
2411 "lds");
2412 }
2413
2414 LLVMValueRef ac_lds_load(struct ac_llvm_context *ctx,
2415 LLVMValueRef dw_addr)
2416 {
2417 return ac_build_load(ctx, ctx->lds, dw_addr);
2418 }
2419
2420 void ac_lds_store(struct ac_llvm_context *ctx,
2421 LLVMValueRef dw_addr,
2422 LLVMValueRef value)
2423 {
2424 value = ac_to_integer(ctx, value);
2425 ac_build_indexed_store(ctx, ctx->lds,
2426 dw_addr, value);
2427 }
2428
2429 LLVMValueRef ac_find_lsb(struct ac_llvm_context *ctx,
2430 LLVMTypeRef dst_type,
2431 LLVMValueRef src0)
2432 {
2433 unsigned src0_bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2434 const char *intrin_name;
2435 LLVMTypeRef type;
2436 LLVMValueRef zero;
2437 if (src0_bitsize == 64) {
2438 intrin_name = "llvm.cttz.i64";
2439 type = ctx->i64;
2440 zero = ctx->i64_0;
2441 } else {
2442 intrin_name = "llvm.cttz.i32";
2443 type = ctx->i32;
2444 zero = ctx->i32_0;
2445 }
2446
2447 LLVMValueRef params[2] = {
2448 src0,
2449
2450 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
2451 * add special code to check for x=0. The reason is that
2452 * the LLVM behavior for x=0 is different from what we
2453 * need here. However, LLVM also assumes that ffs(x) is
2454 * in [0, 31], but GLSL expects that ffs(0) = -1, so
2455 * a conditional assignment to handle 0 is still required.
2456 *
2457 * The hardware already implements the correct behavior.
2458 */
2459 LLVMConstInt(ctx->i1, 1, false),
2460 };
2461
2462 LLVMValueRef lsb = ac_build_intrinsic(ctx, intrin_name, type,
2463 params, 2,
2464 AC_FUNC_ATTR_READNONE);
2465
2466 if (src0_bitsize == 64) {
2467 lsb = LLVMBuildTrunc(ctx->builder, lsb, ctx->i32, "");
2468 }
2469
2470 /* TODO: We need an intrinsic to skip this conditional. */
2471 /* Check for zero: */
2472 return LLVMBuildSelect(ctx->builder, LLVMBuildICmp(ctx->builder,
2473 LLVMIntEQ, src0,
2474 zero, ""),
2475 LLVMConstInt(ctx->i32, -1, 0), lsb, "");
2476 }
2477
2478 LLVMTypeRef ac_array_in_const_addr_space(LLVMTypeRef elem_type)
2479 {
2480 return LLVMPointerType(LLVMArrayType(elem_type, 0),
2481 AC_CONST_ADDR_SPACE);
2482 }
2483
2484 LLVMTypeRef ac_array_in_const32_addr_space(LLVMTypeRef elem_type)
2485 {
2486 if (!HAVE_32BIT_POINTERS)
2487 return ac_array_in_const_addr_space(elem_type);
2488
2489 return LLVMPointerType(LLVMArrayType(elem_type, 0),
2490 AC_CONST_32BIT_ADDR_SPACE);
2491 }
2492
2493 static struct ac_llvm_flow *
2494 get_current_flow(struct ac_llvm_context *ctx)
2495 {
2496 if (ctx->flow_depth > 0)
2497 return &ctx->flow[ctx->flow_depth - 1];
2498 return NULL;
2499 }
2500
2501 static struct ac_llvm_flow *
2502 get_innermost_loop(struct ac_llvm_context *ctx)
2503 {
2504 for (unsigned i = ctx->flow_depth; i > 0; --i) {
2505 if (ctx->flow[i - 1].loop_entry_block)
2506 return &ctx->flow[i - 1];
2507 }
2508 return NULL;
2509 }
2510
2511 static struct ac_llvm_flow *
2512 push_flow(struct ac_llvm_context *ctx)
2513 {
2514 struct ac_llvm_flow *flow;
2515
2516 if (ctx->flow_depth >= ctx->flow_depth_max) {
2517 unsigned new_max = MAX2(ctx->flow_depth << 1,
2518 AC_LLVM_INITIAL_CF_DEPTH);
2519
2520 ctx->flow = realloc(ctx->flow, new_max * sizeof(*ctx->flow));
2521 ctx->flow_depth_max = new_max;
2522 }
2523
2524 flow = &ctx->flow[ctx->flow_depth];
2525 ctx->flow_depth++;
2526
2527 flow->next_block = NULL;
2528 flow->loop_entry_block = NULL;
2529 return flow;
2530 }
2531
2532 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base,
2533 int label_id)
2534 {
2535 char buf[32];
2536 snprintf(buf, sizeof(buf), "%s%d", base, label_id);
2537 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
2538 }
2539
2540 /* Append a basic block at the level of the parent flow.
2541 */
2542 static LLVMBasicBlockRef append_basic_block(struct ac_llvm_context *ctx,
2543 const char *name)
2544 {
2545 assert(ctx->flow_depth >= 1);
2546
2547 if (ctx->flow_depth >= 2) {
2548 struct ac_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];
2549
2550 return LLVMInsertBasicBlockInContext(ctx->context,
2551 flow->next_block, name);
2552 }
2553
2554 LLVMValueRef main_fn =
2555 LLVMGetBasicBlockParent(LLVMGetInsertBlock(ctx->builder));
2556 return LLVMAppendBasicBlockInContext(ctx->context, main_fn, name);
2557 }
2558
2559 /* Emit a branch to the given default target for the current block if
2560 * applicable -- that is, if the current block does not already contain a
2561 * branch from a break or continue.
2562 */
2563 static void emit_default_branch(LLVMBuilderRef builder,
2564 LLVMBasicBlockRef target)
2565 {
2566 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
2567 LLVMBuildBr(builder, target);
2568 }
2569
2570 void ac_build_bgnloop(struct ac_llvm_context *ctx, int label_id)
2571 {
2572 struct ac_llvm_flow *flow = push_flow(ctx);
2573 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
2574 flow->next_block = append_basic_block(ctx, "ENDLOOP");
2575 set_basicblock_name(flow->loop_entry_block, "loop", label_id);
2576 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
2577 LLVMPositionBuilderAtEnd(ctx->builder, flow->loop_entry_block);
2578 }
2579
2580 void ac_build_break(struct ac_llvm_context *ctx)
2581 {
2582 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
2583 LLVMBuildBr(ctx->builder, flow->next_block);
2584 }
2585
2586 void ac_build_continue(struct ac_llvm_context *ctx)
2587 {
2588 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
2589 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
2590 }
2591
2592 void ac_build_else(struct ac_llvm_context *ctx, int label_id)
2593 {
2594 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
2595 LLVMBasicBlockRef endif_block;
2596
2597 assert(!current_branch->loop_entry_block);
2598
2599 endif_block = append_basic_block(ctx, "ENDIF");
2600 emit_default_branch(ctx->builder, endif_block);
2601
2602 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
2603 set_basicblock_name(current_branch->next_block, "else", label_id);
2604
2605 current_branch->next_block = endif_block;
2606 }
2607
2608 void ac_build_endif(struct ac_llvm_context *ctx, int label_id)
2609 {
2610 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
2611
2612 assert(!current_branch->loop_entry_block);
2613
2614 emit_default_branch(ctx->builder, current_branch->next_block);
2615 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
2616 set_basicblock_name(current_branch->next_block, "endif", label_id);
2617
2618 ctx->flow_depth--;
2619 }
2620
2621 void ac_build_endloop(struct ac_llvm_context *ctx, int label_id)
2622 {
2623 struct ac_llvm_flow *current_loop = get_current_flow(ctx);
2624
2625 assert(current_loop->loop_entry_block);
2626
2627 emit_default_branch(ctx->builder, current_loop->loop_entry_block);
2628
2629 LLVMPositionBuilderAtEnd(ctx->builder, current_loop->next_block);
2630 set_basicblock_name(current_loop->next_block, "endloop", label_id);
2631 ctx->flow_depth--;
2632 }
2633
2634 static void if_cond_emit(struct ac_llvm_context *ctx, LLVMValueRef cond,
2635 int label_id)
2636 {
2637 struct ac_llvm_flow *flow = push_flow(ctx);
2638 LLVMBasicBlockRef if_block;
2639
2640 if_block = append_basic_block(ctx, "IF");
2641 flow->next_block = append_basic_block(ctx, "ELSE");
2642 set_basicblock_name(if_block, "if", label_id);
2643 LLVMBuildCondBr(ctx->builder, cond, if_block, flow->next_block);
2644 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
2645 }
2646
2647 void ac_build_if(struct ac_llvm_context *ctx, LLVMValueRef value,
2648 int label_id)
2649 {
2650 LLVMValueRef cond = LLVMBuildFCmp(ctx->builder, LLVMRealUNE,
2651 value, ctx->f32_0, "");
2652 if_cond_emit(ctx, cond, label_id);
2653 }
2654
2655 void ac_build_uif(struct ac_llvm_context *ctx, LLVMValueRef value,
2656 int label_id)
2657 {
2658 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
2659 ac_to_integer(ctx, value),
2660 ctx->i32_0, "");
2661 if_cond_emit(ctx, cond, label_id);
2662 }
2663
2664 LLVMValueRef ac_build_alloca(struct ac_llvm_context *ac, LLVMTypeRef type,
2665 const char *name)
2666 {
2667 LLVMBuilderRef builder = ac->builder;
2668 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
2669 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
2670 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
2671 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
2672 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ac->context);
2673 LLVMValueRef res;
2674
2675 if (first_instr) {
2676 LLVMPositionBuilderBefore(first_builder, first_instr);
2677 } else {
2678 LLVMPositionBuilderAtEnd(first_builder, first_block);
2679 }
2680
2681 res = LLVMBuildAlloca(first_builder, type, name);
2682 LLVMBuildStore(builder, LLVMConstNull(type), res);
2683
2684 LLVMDisposeBuilder(first_builder);
2685
2686 return res;
2687 }
2688
2689 LLVMValueRef ac_build_alloca_undef(struct ac_llvm_context *ac,
2690 LLVMTypeRef type, const char *name)
2691 {
2692 LLVMValueRef ptr = ac_build_alloca(ac, type, name);
2693 LLVMBuildStore(ac->builder, LLVMGetUndef(type), ptr);
2694 return ptr;
2695 }
2696
2697 LLVMValueRef ac_cast_ptr(struct ac_llvm_context *ctx, LLVMValueRef ptr,
2698 LLVMTypeRef type)
2699 {
2700 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
2701 return LLVMBuildBitCast(ctx->builder, ptr,
2702 LLVMPointerType(type, addr_space), "");
2703 }
2704
2705 LLVMValueRef ac_trim_vector(struct ac_llvm_context *ctx, LLVMValueRef value,
2706 unsigned count)
2707 {
2708 unsigned num_components = ac_get_llvm_num_components(value);
2709 if (count == num_components)
2710 return value;
2711
2712 LLVMValueRef masks[] = {
2713 LLVMConstInt(ctx->i32, 0, false), LLVMConstInt(ctx->i32, 1, false),
2714 LLVMConstInt(ctx->i32, 2, false), LLVMConstInt(ctx->i32, 3, false)};
2715
2716 if (count == 1)
2717 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
2718 "");
2719
2720 LLVMValueRef swizzle = LLVMConstVector(masks, count);
2721 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
2722 }
2723
2724 LLVMValueRef ac_unpack_param(struct ac_llvm_context *ctx, LLVMValueRef param,
2725 unsigned rshift, unsigned bitwidth)
2726 {
2727 LLVMValueRef value = param;
2728 if (rshift)
2729 value = LLVMBuildLShr(ctx->builder, value,
2730 LLVMConstInt(ctx->i32, rshift, false), "");
2731
2732 if (rshift + bitwidth < 32) {
2733 unsigned mask = (1 << bitwidth) - 1;
2734 value = LLVMBuildAnd(ctx->builder, value,
2735 LLVMConstInt(ctx->i32, mask, false), "");
2736 }
2737 return value;
2738 }
2739
2740 /* Adjust the sample index according to FMASK.
2741 *
2742 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
2743 * which is the identity mapping. Each nibble says which physical sample
2744 * should be fetched to get that sample.
2745 *
2746 * For example, 0x11111100 means there are only 2 samples stored and
2747 * the second sample covers 3/4 of the pixel. When reading samples 0
2748 * and 1, return physical sample 0 (determined by the first two 0s
2749 * in FMASK), otherwise return physical sample 1.
2750 *
2751 * The sample index should be adjusted as follows:
2752 * addr[sample_index] = (fmask >> (addr[sample_index] * 4)) & 0xF;
2753 */
2754 void ac_apply_fmask_to_sample(struct ac_llvm_context *ac, LLVMValueRef fmask,
2755 LLVMValueRef *addr, bool is_array_tex)
2756 {
2757 struct ac_image_args fmask_load = {};
2758 fmask_load.opcode = ac_image_load;
2759 fmask_load.resource = fmask;
2760 fmask_load.dmask = 0xf;
2761 fmask_load.dim = is_array_tex ? ac_image_2darray : ac_image_2d;
2762
2763 fmask_load.coords[0] = addr[0];
2764 fmask_load.coords[1] = addr[1];
2765 if (is_array_tex)
2766 fmask_load.coords[2] = addr[2];
2767
2768 LLVMValueRef fmask_value = ac_build_image_opcode(ac, &fmask_load);
2769 fmask_value = LLVMBuildExtractElement(ac->builder, fmask_value,
2770 ac->i32_0, "");
2771
2772 /* Apply the formula. */
2773 unsigned sample_chan = is_array_tex ? 3 : 2;
2774 LLVMValueRef final_sample;
2775 final_sample = LLVMBuildMul(ac->builder, addr[sample_chan],
2776 LLVMConstInt(ac->i32, 4, 0), "");
2777 final_sample = LLVMBuildLShr(ac->builder, fmask_value, final_sample, "");
2778 /* Mask the sample index by 0x7, because 0x8 means an unknown value
2779 * with EQAA, so those will map to 0. */
2780 final_sample = LLVMBuildAnd(ac->builder, final_sample,
2781 LLVMConstInt(ac->i32, 0x7, 0), "");
2782
2783 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
2784 * resource descriptor is 0 (invalid).
2785 */
2786 LLVMValueRef tmp;
2787 tmp = LLVMBuildBitCast(ac->builder, fmask, ac->v8i32, "");
2788 tmp = LLVMBuildExtractElement(ac->builder, tmp, ac->i32_1, "");
2789 tmp = LLVMBuildICmp(ac->builder, LLVMIntNE, tmp, ac->i32_0, "");
2790
2791 /* Replace the MSAA sample index. */
2792 addr[sample_chan] = LLVMBuildSelect(ac->builder, tmp, final_sample,
2793 addr[sample_chan], "");
2794 }
2795
2796 static LLVMValueRef
2797 _ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
2798 {
2799 ac_build_optimization_barrier(ctx, &src);
2800 return ac_build_intrinsic(ctx,
2801 lane == NULL ? "llvm.amdgcn.readfirstlane" : "llvm.amdgcn.readlane",
2802 LLVMTypeOf(src), (LLVMValueRef []) {
2803 src, lane },
2804 lane == NULL ? 1 : 2,
2805 AC_FUNC_ATTR_READNONE |
2806 AC_FUNC_ATTR_CONVERGENT);
2807 }
2808
2809 /**
2810 * Builds the "llvm.amdgcn.readlane" or "llvm.amdgcn.readfirstlane" intrinsic.
2811 * @param ctx
2812 * @param src
2813 * @param lane - id of the lane or NULL for the first active lane
2814 * @return value of the lane
2815 */
2816 LLVMValueRef
2817 ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
2818 {
2819 LLVMTypeRef src_type = LLVMTypeOf(src);
2820 src = ac_to_integer(ctx, src);
2821 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2822 LLVMValueRef ret;
2823
2824 if (bits == 32) {
2825 ret = _ac_build_readlane(ctx, src, lane);
2826 } else {
2827 assert(bits % 32 == 0);
2828 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2829 LLVMValueRef src_vector =
2830 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2831 ret = LLVMGetUndef(vec_type);
2832 for (unsigned i = 0; i < bits / 32; i++) {
2833 src = LLVMBuildExtractElement(ctx->builder, src_vector,
2834 LLVMConstInt(ctx->i32, i, 0), "");
2835 LLVMValueRef ret_comp = _ac_build_readlane(ctx, src, lane);
2836 ret = LLVMBuildInsertElement(ctx->builder, ret, ret_comp,
2837 LLVMConstInt(ctx->i32, i, 0), "");
2838 }
2839 }
2840 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2841 }
2842
2843 LLVMValueRef
2844 ac_build_writelane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef value, LLVMValueRef lane)
2845 {
2846 /* TODO: Use the actual instruction when LLVM adds an intrinsic for it.
2847 */
2848 LLVMValueRef pred = LLVMBuildICmp(ctx->builder, LLVMIntEQ, lane,
2849 ac_get_thread_id(ctx), "");
2850 return LLVMBuildSelect(ctx->builder, pred, value, src, "");
2851 }
2852
2853 LLVMValueRef
2854 ac_build_mbcnt(struct ac_llvm_context *ctx, LLVMValueRef mask)
2855 {
2856 LLVMValueRef mask_vec = LLVMBuildBitCast(ctx->builder, mask,
2857 LLVMVectorType(ctx->i32, 2),
2858 "");
2859 LLVMValueRef mask_lo = LLVMBuildExtractElement(ctx->builder, mask_vec,
2860 ctx->i32_0, "");
2861 LLVMValueRef mask_hi = LLVMBuildExtractElement(ctx->builder, mask_vec,
2862 ctx->i32_1, "");
2863 LLVMValueRef val =
2864 ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
2865 (LLVMValueRef []) { mask_lo, ctx->i32_0 },
2866 2, AC_FUNC_ATTR_READNONE);
2867 val = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi", ctx->i32,
2868 (LLVMValueRef []) { mask_hi, val },
2869 2, AC_FUNC_ATTR_READNONE);
2870 return val;
2871 }
2872
2873 enum dpp_ctrl {
2874 _dpp_quad_perm = 0x000,
2875 _dpp_row_sl = 0x100,
2876 _dpp_row_sr = 0x110,
2877 _dpp_row_rr = 0x120,
2878 dpp_wf_sl1 = 0x130,
2879 dpp_wf_rl1 = 0x134,
2880 dpp_wf_sr1 = 0x138,
2881 dpp_wf_rr1 = 0x13C,
2882 dpp_row_mirror = 0x140,
2883 dpp_row_half_mirror = 0x141,
2884 dpp_row_bcast15 = 0x142,
2885 dpp_row_bcast31 = 0x143
2886 };
2887
2888 static inline enum dpp_ctrl
2889 dpp_quad_perm(unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
2890 {
2891 assert(lane0 < 4 && lane1 < 4 && lane2 < 4 && lane3 < 4);
2892 return _dpp_quad_perm | lane0 | (lane1 << 2) | (lane2 << 4) | (lane3 << 6);
2893 }
2894
2895 static inline enum dpp_ctrl
2896 dpp_row_sl(unsigned amount)
2897 {
2898 assert(amount > 0 && amount < 16);
2899 return _dpp_row_sl | amount;
2900 }
2901
2902 static inline enum dpp_ctrl
2903 dpp_row_sr(unsigned amount)
2904 {
2905 assert(amount > 0 && amount < 16);
2906 return _dpp_row_sr | amount;
2907 }
2908
2909 static LLVMValueRef
2910 _ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
2911 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
2912 bool bound_ctrl)
2913 {
2914 return ac_build_intrinsic(ctx, "llvm.amdgcn.update.dpp.i32",
2915 LLVMTypeOf(old),
2916 (LLVMValueRef[]) {
2917 old, src,
2918 LLVMConstInt(ctx->i32, dpp_ctrl, 0),
2919 LLVMConstInt(ctx->i32, row_mask, 0),
2920 LLVMConstInt(ctx->i32, bank_mask, 0),
2921 LLVMConstInt(ctx->i1, bound_ctrl, 0) },
2922 6, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
2923 }
2924
2925 static LLVMValueRef
2926 ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
2927 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
2928 bool bound_ctrl)
2929 {
2930 LLVMTypeRef src_type = LLVMTypeOf(src);
2931 src = ac_to_integer(ctx, src);
2932 old = ac_to_integer(ctx, old);
2933 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2934 LLVMValueRef ret;
2935 if (bits == 32) {
2936 ret = _ac_build_dpp(ctx, old, src, dpp_ctrl, row_mask,
2937 bank_mask, bound_ctrl);
2938 } else {
2939 assert(bits % 32 == 0);
2940 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2941 LLVMValueRef src_vector =
2942 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2943 LLVMValueRef old_vector =
2944 LLVMBuildBitCast(ctx->builder, old, vec_type, "");
2945 ret = LLVMGetUndef(vec_type);
2946 for (unsigned i = 0; i < bits / 32; i++) {
2947 src = LLVMBuildExtractElement(ctx->builder, src_vector,
2948 LLVMConstInt(ctx->i32, i,
2949 0), "");
2950 old = LLVMBuildExtractElement(ctx->builder, old_vector,
2951 LLVMConstInt(ctx->i32, i,
2952 0), "");
2953 LLVMValueRef ret_comp = _ac_build_dpp(ctx, old, src,
2954 dpp_ctrl,
2955 row_mask,
2956 bank_mask,
2957 bound_ctrl);
2958 ret = LLVMBuildInsertElement(ctx->builder, ret,
2959 ret_comp,
2960 LLVMConstInt(ctx->i32, i,
2961 0), "");
2962 }
2963 }
2964 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2965 }
2966
2967 static inline unsigned
2968 ds_pattern_bitmode(unsigned and_mask, unsigned or_mask, unsigned xor_mask)
2969 {
2970 assert(and_mask < 32 && or_mask < 32 && xor_mask < 32);
2971 return and_mask | (or_mask << 5) | (xor_mask << 10);
2972 }
2973
2974 static LLVMValueRef
2975 _ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
2976 {
2977 return ac_build_intrinsic(ctx, "llvm.amdgcn.ds.swizzle",
2978 LLVMTypeOf(src), (LLVMValueRef []) {
2979 src, LLVMConstInt(ctx->i32, mask, 0) },
2980 2, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
2981 }
2982
2983 LLVMValueRef
2984 ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
2985 {
2986 LLVMTypeRef src_type = LLVMTypeOf(src);
2987 src = ac_to_integer(ctx, src);
2988 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2989 LLVMValueRef ret;
2990 if (bits == 32) {
2991 ret = _ac_build_ds_swizzle(ctx, src, mask);
2992 } else {
2993 assert(bits % 32 == 0);
2994 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2995 LLVMValueRef src_vector =
2996 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2997 ret = LLVMGetUndef(vec_type);
2998 for (unsigned i = 0; i < bits / 32; i++) {
2999 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3000 LLVMConstInt(ctx->i32, i,
3001 0), "");
3002 LLVMValueRef ret_comp = _ac_build_ds_swizzle(ctx, src,
3003 mask);
3004 ret = LLVMBuildInsertElement(ctx->builder, ret,
3005 ret_comp,
3006 LLVMConstInt(ctx->i32, i,
3007 0), "");
3008 }
3009 }
3010 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3011 }
3012
3013 static LLVMValueRef
3014 ac_build_wwm(struct ac_llvm_context *ctx, LLVMValueRef src)
3015 {
3016 char name[32], type[8];
3017 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3018 snprintf(name, sizeof(name), "llvm.amdgcn.wwm.%s", type);
3019 return ac_build_intrinsic(ctx, name, LLVMTypeOf(src),
3020 (LLVMValueRef []) { src }, 1,
3021 AC_FUNC_ATTR_READNONE);
3022 }
3023
3024 static LLVMValueRef
3025 ac_build_set_inactive(struct ac_llvm_context *ctx, LLVMValueRef src,
3026 LLVMValueRef inactive)
3027 {
3028 char name[33], type[8];
3029 LLVMTypeRef src_type = LLVMTypeOf(src);
3030 src = ac_to_integer(ctx, src);
3031 inactive = ac_to_integer(ctx, inactive);
3032 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3033 snprintf(name, sizeof(name), "llvm.amdgcn.set.inactive.%s", type);
3034 LLVMValueRef ret =
3035 ac_build_intrinsic(ctx, name,
3036 LLVMTypeOf(src), (LLVMValueRef []) {
3037 src, inactive }, 2,
3038 AC_FUNC_ATTR_READNONE |
3039 AC_FUNC_ATTR_CONVERGENT);
3040 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3041 }
3042
3043 static LLVMValueRef
3044 get_reduction_identity(struct ac_llvm_context *ctx, nir_op op, unsigned type_size)
3045 {
3046 if (type_size == 4) {
3047 switch (op) {
3048 case nir_op_iadd: return ctx->i32_0;
3049 case nir_op_fadd: return ctx->f32_0;
3050 case nir_op_imul: return ctx->i32_1;
3051 case nir_op_fmul: return ctx->f32_1;
3052 case nir_op_imin: return LLVMConstInt(ctx->i32, INT32_MAX, 0);
3053 case nir_op_umin: return LLVMConstInt(ctx->i32, UINT32_MAX, 0);
3054 case nir_op_fmin: return LLVMConstReal(ctx->f32, INFINITY);
3055 case nir_op_imax: return LLVMConstInt(ctx->i32, INT32_MIN, 0);
3056 case nir_op_umax: return ctx->i32_0;
3057 case nir_op_fmax: return LLVMConstReal(ctx->f32, -INFINITY);
3058 case nir_op_iand: return LLVMConstInt(ctx->i32, -1, 0);
3059 case nir_op_ior: return ctx->i32_0;
3060 case nir_op_ixor: return ctx->i32_0;
3061 default:
3062 unreachable("bad reduction intrinsic");
3063 }
3064 } else { /* type_size == 64bit */
3065 switch (op) {
3066 case nir_op_iadd: return ctx->i64_0;
3067 case nir_op_fadd: return ctx->f64_0;
3068 case nir_op_imul: return ctx->i64_1;
3069 case nir_op_fmul: return ctx->f64_1;
3070 case nir_op_imin: return LLVMConstInt(ctx->i64, INT64_MAX, 0);
3071 case nir_op_umin: return LLVMConstInt(ctx->i64, UINT64_MAX, 0);
3072 case nir_op_fmin: return LLVMConstReal(ctx->f64, INFINITY);
3073 case nir_op_imax: return LLVMConstInt(ctx->i64, INT64_MIN, 0);
3074 case nir_op_umax: return ctx->i64_0;
3075 case nir_op_fmax: return LLVMConstReal(ctx->f64, -INFINITY);
3076 case nir_op_iand: return LLVMConstInt(ctx->i64, -1, 0);
3077 case nir_op_ior: return ctx->i64_0;
3078 case nir_op_ixor: return ctx->i64_0;
3079 default:
3080 unreachable("bad reduction intrinsic");
3081 }
3082 }
3083 }
3084
3085 static LLVMValueRef
3086 ac_build_alu_op(struct ac_llvm_context *ctx, LLVMValueRef lhs, LLVMValueRef rhs, nir_op op)
3087 {
3088 bool _64bit = ac_get_type_size(LLVMTypeOf(lhs)) == 8;
3089 switch (op) {
3090 case nir_op_iadd: return LLVMBuildAdd(ctx->builder, lhs, rhs, "");
3091 case nir_op_fadd: return LLVMBuildFAdd(ctx->builder, lhs, rhs, "");
3092 case nir_op_imul: return LLVMBuildMul(ctx->builder, lhs, rhs, "");
3093 case nir_op_fmul: return LLVMBuildFMul(ctx->builder, lhs, rhs, "");
3094 case nir_op_imin: return LLVMBuildSelect(ctx->builder,
3095 LLVMBuildICmp(ctx->builder, LLVMIntSLT, lhs, rhs, ""),
3096 lhs, rhs, "");
3097 case nir_op_umin: return LLVMBuildSelect(ctx->builder,
3098 LLVMBuildICmp(ctx->builder, LLVMIntULT, lhs, rhs, ""),
3099 lhs, rhs, "");
3100 case nir_op_fmin: return ac_build_intrinsic(ctx,
3101 _64bit ? "llvm.minnum.f64" : "llvm.minnum.f32",
3102 _64bit ? ctx->f64 : ctx->f32,
3103 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
3104 case nir_op_imax: return LLVMBuildSelect(ctx->builder,
3105 LLVMBuildICmp(ctx->builder, LLVMIntSGT, lhs, rhs, ""),
3106 lhs, rhs, "");
3107 case nir_op_umax: return LLVMBuildSelect(ctx->builder,
3108 LLVMBuildICmp(ctx->builder, LLVMIntUGT, lhs, rhs, ""),
3109 lhs, rhs, "");
3110 case nir_op_fmax: return ac_build_intrinsic(ctx,
3111 _64bit ? "llvm.maxnum.f64" : "llvm.maxnum.f32",
3112 _64bit ? ctx->f64 : ctx->f32,
3113 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
3114 case nir_op_iand: return LLVMBuildAnd(ctx->builder, lhs, rhs, "");
3115 case nir_op_ior: return LLVMBuildOr(ctx->builder, lhs, rhs, "");
3116 case nir_op_ixor: return LLVMBuildXor(ctx->builder, lhs, rhs, "");
3117 default:
3118 unreachable("bad reduction intrinsic");
3119 }
3120 }
3121
3122 /* TODO: add inclusive and excluse scan functions for SI chip class. */
3123 static LLVMValueRef
3124 ac_build_scan(struct ac_llvm_context *ctx, nir_op op, LLVMValueRef src, LLVMValueRef identity)
3125 {
3126 LLVMValueRef result, tmp;
3127 result = src;
3128 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
3129 result = ac_build_alu_op(ctx, result, tmp, op);
3130 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(2), 0xf, 0xf, false);
3131 result = ac_build_alu_op(ctx, result, tmp, op);
3132 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(3), 0xf, 0xf, false);
3133 result = ac_build_alu_op(ctx, result, tmp, op);
3134 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(4), 0xf, 0xe, false);
3135 result = ac_build_alu_op(ctx, result, tmp, op);
3136 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(8), 0xf, 0xc, false);
3137 result = ac_build_alu_op(ctx, result, tmp, op);
3138 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
3139 result = ac_build_alu_op(ctx, result, tmp, op);
3140 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
3141 result = ac_build_alu_op(ctx, result, tmp, op);
3142 return result;
3143 }
3144
3145 LLVMValueRef
3146 ac_build_inclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
3147 {
3148 ac_build_optimization_barrier(ctx, &src);
3149 LLVMValueRef result;
3150 LLVMValueRef identity = get_reduction_identity(ctx, op,
3151 ac_get_type_size(LLVMTypeOf(src)));
3152 result = LLVMBuildBitCast(ctx->builder,
3153 ac_build_set_inactive(ctx, src, identity),
3154 LLVMTypeOf(identity), "");
3155 result = ac_build_scan(ctx, op, result, identity);
3156
3157 return ac_build_wwm(ctx, result);
3158 }
3159
3160 LLVMValueRef
3161 ac_build_exclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
3162 {
3163 ac_build_optimization_barrier(ctx, &src);
3164 LLVMValueRef result;
3165 LLVMValueRef identity = get_reduction_identity(ctx, op,
3166 ac_get_type_size(LLVMTypeOf(src)));
3167 result = LLVMBuildBitCast(ctx->builder,
3168 ac_build_set_inactive(ctx, src, identity),
3169 LLVMTypeOf(identity), "");
3170 result = ac_build_dpp(ctx, identity, result, dpp_wf_sr1, 0xf, 0xf, false);
3171 result = ac_build_scan(ctx, op, result, identity);
3172
3173 return ac_build_wwm(ctx, result);
3174 }
3175
3176 LLVMValueRef
3177 ac_build_reduce(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op, unsigned cluster_size)
3178 {
3179 if (cluster_size == 1) return src;
3180 ac_build_optimization_barrier(ctx, &src);
3181 LLVMValueRef result, swap;
3182 LLVMValueRef identity = get_reduction_identity(ctx, op,
3183 ac_get_type_size(LLVMTypeOf(src)));
3184 result = LLVMBuildBitCast(ctx->builder,
3185 ac_build_set_inactive(ctx, src, identity),
3186 LLVMTypeOf(identity), "");
3187 swap = ac_build_quad_swizzle(ctx, result, 1, 0, 3, 2);
3188 result = ac_build_alu_op(ctx, result, swap, op);
3189 if (cluster_size == 2) return ac_build_wwm(ctx, result);
3190
3191 swap = ac_build_quad_swizzle(ctx, result, 2, 3, 0, 1);
3192 result = ac_build_alu_op(ctx, result, swap, op);
3193 if (cluster_size == 4) return ac_build_wwm(ctx, result);
3194
3195 if (ctx->chip_class >= VI)
3196 swap = ac_build_dpp(ctx, identity, result, dpp_row_half_mirror, 0xf, 0xf, false);
3197 else
3198 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x04));
3199 result = ac_build_alu_op(ctx, result, swap, op);
3200 if (cluster_size == 8) return ac_build_wwm(ctx, result);
3201
3202 if (ctx->chip_class >= VI)
3203 swap = ac_build_dpp(ctx, identity, result, dpp_row_mirror, 0xf, 0xf, false);
3204 else
3205 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x08));
3206 result = ac_build_alu_op(ctx, result, swap, op);
3207 if (cluster_size == 16) return ac_build_wwm(ctx, result);
3208
3209 if (ctx->chip_class >= VI && cluster_size != 32)
3210 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
3211 else
3212 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x10));
3213 result = ac_build_alu_op(ctx, result, swap, op);
3214 if (cluster_size == 32) return ac_build_wwm(ctx, result);
3215
3216 if (ctx->chip_class >= VI) {
3217 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
3218 result = ac_build_alu_op(ctx, result, swap, op);
3219 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 63, 0));
3220 return ac_build_wwm(ctx, result);
3221 } else {
3222 swap = ac_build_readlane(ctx, result, ctx->i32_0);
3223 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 32, 0));
3224 result = ac_build_alu_op(ctx, result, swap, op);
3225 return ac_build_wwm(ctx, result);
3226 }
3227 }
3228
3229 LLVMValueRef
3230 ac_build_quad_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src,
3231 unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
3232 {
3233 unsigned mask = dpp_quad_perm(lane0, lane1, lane2, lane3);
3234 if (ctx->chip_class >= VI && HAVE_LLVM >= 0x0600) {
3235 return ac_build_dpp(ctx, src, src, mask, 0xf, 0xf, false);
3236 } else {
3237 return ac_build_ds_swizzle(ctx, src, (1 << 15) | mask);
3238 }
3239 }
3240
3241 LLVMValueRef
3242 ac_build_shuffle(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef index)
3243 {
3244 index = LLVMBuildMul(ctx->builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
3245 return ac_build_intrinsic(ctx,
3246 "llvm.amdgcn.ds.bpermute", ctx->i32,
3247 (LLVMValueRef []) {index, src}, 2,
3248 AC_FUNC_ATTR_READNONE |
3249 AC_FUNC_ATTR_CONVERGENT);
3250 }