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