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