amd: remove support for LLVM 4.0
[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, LLVMContextRef context,
61 enum chip_class chip_class, enum radeon_family family)
62 {
63 LLVMValueRef args[1];
64
65 ctx->chip_class = chip_class;
66 ctx->family = family;
67
68 ctx->context = context;
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 (ctx->chip_class >= VI) {
1174 LLVMValueRef thread_id, tl_tid, trbl_tid;
1175 thread_id = ac_get_thread_id(ctx);
1176
1177 tl_tid = LLVMBuildAnd(ctx->builder, thread_id,
1178 LLVMConstInt(ctx->i32, mask, false), "");
1179
1180 trbl_tid = LLVMBuildAdd(ctx->builder, tl_tid,
1181 LLVMConstInt(ctx->i32, idx, false), "");
1182
1183 args[0] = LLVMBuildMul(ctx->builder, tl_tid,
1184 LLVMConstInt(ctx->i32, 4, false), "");
1185 args[1] = val;
1186 tl = ac_build_intrinsic(ctx,
1187 "llvm.amdgcn.ds.bpermute", ctx->i32,
1188 args, 2,
1189 AC_FUNC_ATTR_READNONE |
1190 AC_FUNC_ATTR_CONVERGENT);
1191
1192 args[0] = LLVMBuildMul(ctx->builder, trbl_tid,
1193 LLVMConstInt(ctx->i32, 4, false), "");
1194 trbl = ac_build_intrinsic(ctx,
1195 "llvm.amdgcn.ds.bpermute", ctx->i32,
1196 args, 2,
1197 AC_FUNC_ATTR_READNONE |
1198 AC_FUNC_ATTR_CONVERGENT);
1199 } else {
1200 uint32_t masks[2] = {};
1201
1202 switch (mask) {
1203 case AC_TID_MASK_TOP_LEFT:
1204 masks[0] = 0x8000;
1205 if (idx == 1)
1206 masks[1] = 0x8055;
1207 else
1208 masks[1] = 0x80aa;
1209
1210 break;
1211 case AC_TID_MASK_TOP:
1212 masks[0] = 0x8044;
1213 masks[1] = 0x80ee;
1214 break;
1215 case AC_TID_MASK_LEFT:
1216 masks[0] = 0x80a0;
1217 masks[1] = 0x80f5;
1218 break;
1219 default:
1220 assert(0);
1221 }
1222
1223 args[0] = val;
1224 args[1] = LLVMConstInt(ctx->i32, masks[0], false);
1225
1226 tl = ac_build_intrinsic(ctx,
1227 "llvm.amdgcn.ds.swizzle", ctx->i32,
1228 args, 2,
1229 AC_FUNC_ATTR_READNONE |
1230 AC_FUNC_ATTR_CONVERGENT);
1231
1232 args[1] = LLVMConstInt(ctx->i32, masks[1], false);
1233 trbl = ac_build_intrinsic(ctx,
1234 "llvm.amdgcn.ds.swizzle", ctx->i32,
1235 args, 2,
1236 AC_FUNC_ATTR_READNONE |
1237 AC_FUNC_ATTR_CONVERGENT);
1238 }
1239
1240 tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
1241 trbl = LLVMBuildBitCast(ctx->builder, trbl, ctx->f32, "");
1242 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
1243
1244 if (HAVE_LLVM >= 0x0700) {
1245 result = ac_build_intrinsic(ctx,
1246 "llvm.amdgcn.wqm.f32", ctx->f32,
1247 &result, 1, 0);
1248 }
1249
1250 return result;
1251 }
1252
1253 void
1254 ac_build_sendmsg(struct ac_llvm_context *ctx,
1255 uint32_t msg,
1256 LLVMValueRef wave_id)
1257 {
1258 LLVMValueRef args[2];
1259 args[0] = LLVMConstInt(ctx->i32, msg, false);
1260 args[1] = wave_id;
1261 ac_build_intrinsic(ctx, "llvm.amdgcn.s.sendmsg", ctx->voidt, args, 2, 0);
1262 }
1263
1264 LLVMValueRef
1265 ac_build_imsb(struct ac_llvm_context *ctx,
1266 LLVMValueRef arg,
1267 LLVMTypeRef dst_type)
1268 {
1269 LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.amdgcn.sffbh.i32",
1270 dst_type, &arg, 1,
1271 AC_FUNC_ATTR_READNONE);
1272
1273 /* The HW returns the last bit index from MSB, but NIR/TGSI wants
1274 * the index from LSB. Invert it by doing "31 - msb". */
1275 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
1276 msb, "");
1277
1278 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
1279 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
1280 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1281 arg, LLVMConstInt(ctx->i32, 0, 0), ""),
1282 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1283 arg, all_ones, ""), "");
1284
1285 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
1286 }
1287
1288 LLVMValueRef
1289 ac_build_umsb(struct ac_llvm_context *ctx,
1290 LLVMValueRef arg,
1291 LLVMTypeRef dst_type)
1292 {
1293 const char *intrin_name;
1294 LLVMTypeRef type;
1295 LLVMValueRef highest_bit;
1296 LLVMValueRef zero;
1297
1298 if (ac_get_elem_bits(ctx, LLVMTypeOf(arg)) == 64) {
1299 intrin_name = "llvm.ctlz.i64";
1300 type = ctx->i64;
1301 highest_bit = LLVMConstInt(ctx->i64, 63, false);
1302 zero = ctx->i64_0;
1303 } else {
1304 intrin_name = "llvm.ctlz.i32";
1305 type = ctx->i32;
1306 highest_bit = LLVMConstInt(ctx->i32, 31, false);
1307 zero = ctx->i32_0;
1308 }
1309
1310 LLVMValueRef params[2] = {
1311 arg,
1312 ctx->i1true,
1313 };
1314
1315 LLVMValueRef msb = ac_build_intrinsic(ctx, intrin_name, type,
1316 params, 2,
1317 AC_FUNC_ATTR_READNONE);
1318
1319 /* The HW returns the last bit index from MSB, but TGSI/NIR wants
1320 * the index from LSB. Invert it by doing "31 - msb". */
1321 msb = LLVMBuildSub(ctx->builder, highest_bit, msb, "");
1322 msb = LLVMBuildTruncOrBitCast(ctx->builder, msb, ctx->i32, "");
1323
1324 /* check for zero */
1325 return LLVMBuildSelect(ctx->builder,
1326 LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg, zero, ""),
1327 LLVMConstInt(ctx->i32, -1, true), msb, "");
1328 }
1329
1330 LLVMValueRef ac_build_fmin(struct ac_llvm_context *ctx, LLVMValueRef a,
1331 LLVMValueRef b)
1332 {
1333 LLVMValueRef args[2] = {a, b};
1334 return ac_build_intrinsic(ctx, "llvm.minnum.f32", ctx->f32, args, 2,
1335 AC_FUNC_ATTR_READNONE);
1336 }
1337
1338 LLVMValueRef ac_build_fmax(struct ac_llvm_context *ctx, LLVMValueRef a,
1339 LLVMValueRef b)
1340 {
1341 LLVMValueRef args[2] = {a, b};
1342 return ac_build_intrinsic(ctx, "llvm.maxnum.f32", ctx->f32, args, 2,
1343 AC_FUNC_ATTR_READNONE);
1344 }
1345
1346 LLVMValueRef ac_build_imin(struct ac_llvm_context *ctx, LLVMValueRef a,
1347 LLVMValueRef b)
1348 {
1349 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSLE, a, b, "");
1350 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1351 }
1352
1353 LLVMValueRef ac_build_imax(struct ac_llvm_context *ctx, LLVMValueRef a,
1354 LLVMValueRef b)
1355 {
1356 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, a, b, "");
1357 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1358 }
1359
1360 LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
1361 LLVMValueRef b)
1362 {
1363 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
1364 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1365 }
1366
1367 LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
1368 {
1369 return ac_build_fmin(ctx, ac_build_fmax(ctx, value, ctx->f32_0),
1370 ctx->f32_1);
1371 }
1372
1373 void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
1374 {
1375 LLVMValueRef args[9];
1376
1377 args[0] = LLVMConstInt(ctx->i32, a->target, 0);
1378 args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
1379
1380 if (a->compr) {
1381 LLVMTypeRef i16 = LLVMInt16TypeInContext(ctx->context);
1382 LLVMTypeRef v2i16 = LLVMVectorType(i16, 2);
1383
1384 args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
1385 v2i16, "");
1386 args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
1387 v2i16, "");
1388 args[4] = LLVMConstInt(ctx->i1, a->done, 0);
1389 args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1390
1391 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
1392 ctx->voidt, args, 6, 0);
1393 } else {
1394 args[2] = a->out[0];
1395 args[3] = a->out[1];
1396 args[4] = a->out[2];
1397 args[5] = a->out[3];
1398 args[6] = LLVMConstInt(ctx->i1, a->done, 0);
1399 args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1400
1401 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
1402 ctx->voidt, args, 8, 0);
1403 }
1404 }
1405
1406 void ac_build_export_null(struct ac_llvm_context *ctx)
1407 {
1408 struct ac_export_args args;
1409
1410 args.enabled_channels = 0x0; /* enabled channels */
1411 args.valid_mask = 1; /* whether the EXEC mask is valid */
1412 args.done = 1; /* DONE bit */
1413 args.target = V_008DFC_SQ_EXP_NULL;
1414 args.compr = 0; /* COMPR flag (0 = 32-bit export) */
1415 args.out[0] = LLVMGetUndef(ctx->f32); /* R */
1416 args.out[1] = LLVMGetUndef(ctx->f32); /* G */
1417 args.out[2] = LLVMGetUndef(ctx->f32); /* B */
1418 args.out[3] = LLVMGetUndef(ctx->f32); /* A */
1419
1420 ac_build_export(ctx, &args);
1421 }
1422
1423 static unsigned ac_num_coords(enum ac_image_dim dim)
1424 {
1425 switch (dim) {
1426 case ac_image_1d:
1427 return 1;
1428 case ac_image_2d:
1429 case ac_image_1darray:
1430 return 2;
1431 case ac_image_3d:
1432 case ac_image_cube:
1433 case ac_image_2darray:
1434 case ac_image_2dmsaa:
1435 return 3;
1436 case ac_image_2darraymsaa:
1437 return 4;
1438 default:
1439 unreachable("ac_num_coords: bad dim");
1440 }
1441 }
1442
1443 static unsigned ac_num_derivs(enum ac_image_dim dim)
1444 {
1445 switch (dim) {
1446 case ac_image_1d:
1447 case ac_image_1darray:
1448 return 2;
1449 case ac_image_2d:
1450 case ac_image_2darray:
1451 case ac_image_cube:
1452 return 4;
1453 case ac_image_3d:
1454 return 6;
1455 case ac_image_2dmsaa:
1456 case ac_image_2darraymsaa:
1457 default:
1458 unreachable("derivatives not supported");
1459 }
1460 }
1461
1462 LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
1463 struct ac_image_args *a)
1464 {
1465 LLVMValueRef args[16];
1466 LLVMTypeRef retty = ctx->v4f32;
1467 const char *name = NULL;
1468 const char *atomic_subop = "";
1469 char intr_name[128], coords_type[64];
1470
1471 assert(!a->lod || a->lod == ctx->i32_0 || a->lod == ctx->f32_0 ||
1472 !a->level_zero);
1473 assert((a->opcode != ac_image_get_resinfo && a->opcode != ac_image_load_mip &&
1474 a->opcode != ac_image_store_mip) ||
1475 a->lod);
1476 assert((a->bias ? 1 : 0) +
1477 (a->lod ? 1 : 0) +
1478 (a->level_zero ? 1 : 0) +
1479 (a->derivs[0] ? 1 : 0) <= 1);
1480
1481 bool sample = a->opcode == ac_image_sample ||
1482 a->opcode == ac_image_gather4 ||
1483 a->opcode == ac_image_get_lod;
1484 bool atomic = a->opcode == ac_image_atomic ||
1485 a->opcode == ac_image_atomic_cmpswap;
1486 bool da = a->dim == ac_image_cube ||
1487 a->dim == ac_image_1darray ||
1488 a->dim == ac_image_2darray ||
1489 a->dim == ac_image_2darraymsaa;
1490 if (a->opcode == ac_image_get_lod)
1491 da = false;
1492
1493 unsigned num_coords =
1494 a->opcode != ac_image_get_resinfo ? ac_num_coords(a->dim) : 0;
1495 LLVMValueRef addr;
1496 unsigned num_addr = 0;
1497
1498 if (a->opcode == ac_image_get_lod) {
1499 switch (a->dim) {
1500 case ac_image_1darray:
1501 num_coords = 1;
1502 break;
1503 case ac_image_2darray:
1504 case ac_image_cube:
1505 num_coords = 2;
1506 break;
1507 default:
1508 break;
1509 }
1510 }
1511
1512 if (a->offset)
1513 args[num_addr++] = ac_to_integer(ctx, a->offset);
1514 if (a->bias)
1515 args[num_addr++] = ac_to_integer(ctx, a->bias);
1516 if (a->compare)
1517 args[num_addr++] = ac_to_integer(ctx, a->compare);
1518 if (a->derivs[0]) {
1519 unsigned num_derivs = ac_num_derivs(a->dim);
1520 for (unsigned i = 0; i < num_derivs; ++i)
1521 args[num_addr++] = ac_to_integer(ctx, a->derivs[i]);
1522 }
1523 for (unsigned i = 0; i < num_coords; ++i)
1524 args[num_addr++] = ac_to_integer(ctx, a->coords[i]);
1525 if (a->lod)
1526 args[num_addr++] = ac_to_integer(ctx, a->lod);
1527
1528 unsigned pad_goal = util_next_power_of_two(num_addr);
1529 while (num_addr < pad_goal)
1530 args[num_addr++] = LLVMGetUndef(ctx->i32);
1531
1532 addr = ac_build_gather_values(ctx, args, num_addr);
1533
1534 unsigned num_args = 0;
1535 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
1536 args[num_args++] = a->data[0];
1537 if (a->opcode == ac_image_atomic_cmpswap)
1538 args[num_args++] = a->data[1];
1539 }
1540
1541 unsigned coords_arg = num_args;
1542 if (sample)
1543 args[num_args++] = ac_to_float(ctx, addr);
1544 else
1545 args[num_args++] = ac_to_integer(ctx, addr);
1546
1547 args[num_args++] = a->resource;
1548 if (sample)
1549 args[num_args++] = a->sampler;
1550 if (!atomic) {
1551 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, 0);
1552 if (sample)
1553 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, 0);
1554 args[num_args++] = a->cache_policy & ac_glc ? ctx->i1true : ctx->i1false;
1555 args[num_args++] = a->cache_policy & ac_slc ? ctx->i1true : ctx->i1false;
1556 args[num_args++] = ctx->i1false; /* lwe */
1557 args[num_args++] = LLVMConstInt(ctx->i1, da, 0);
1558 } else {
1559 args[num_args++] = ctx->i1false; /* r128 */
1560 args[num_args++] = LLVMConstInt(ctx->i1, da, 0);
1561 args[num_args++] = a->cache_policy & ac_slc ? ctx->i1true : ctx->i1false;
1562 }
1563
1564 switch (a->opcode) {
1565 case ac_image_sample:
1566 name = "llvm.amdgcn.image.sample";
1567 break;
1568 case ac_image_gather4:
1569 name = "llvm.amdgcn.image.gather4";
1570 break;
1571 case ac_image_load:
1572 name = "llvm.amdgcn.image.load";
1573 break;
1574 case ac_image_load_mip:
1575 name = "llvm.amdgcn.image.load.mip";
1576 break;
1577 case ac_image_store:
1578 name = "llvm.amdgcn.image.store";
1579 retty = ctx->voidt;
1580 break;
1581 case ac_image_store_mip:
1582 name = "llvm.amdgcn.image.store.mip";
1583 retty = ctx->voidt;
1584 break;
1585 case ac_image_atomic:
1586 case ac_image_atomic_cmpswap:
1587 name = "llvm.amdgcn.image.atomic.";
1588 retty = ctx->i32;
1589 if (a->opcode == ac_image_atomic_cmpswap) {
1590 atomic_subop = "cmpswap";
1591 } else {
1592 switch (a->atomic) {
1593 case ac_atomic_swap: atomic_subop = "swap"; break;
1594 case ac_atomic_add: atomic_subop = "add"; break;
1595 case ac_atomic_sub: atomic_subop = "sub"; break;
1596 case ac_atomic_smin: atomic_subop = "smin"; break;
1597 case ac_atomic_umin: atomic_subop = "umin"; break;
1598 case ac_atomic_smax: atomic_subop = "smax"; break;
1599 case ac_atomic_umax: atomic_subop = "umax"; break;
1600 case ac_atomic_and: atomic_subop = "and"; break;
1601 case ac_atomic_or: atomic_subop = "or"; break;
1602 case ac_atomic_xor: atomic_subop = "xor"; break;
1603 }
1604 }
1605 break;
1606 case ac_image_get_lod:
1607 name = "llvm.amdgcn.image.getlod";
1608 break;
1609 case ac_image_get_resinfo:
1610 name = "llvm.amdgcn.image.getresinfo";
1611 break;
1612 default:
1613 unreachable("invalid image opcode");
1614 }
1615
1616 ac_build_type_name_for_intr(LLVMTypeOf(args[coords_arg]), coords_type,
1617 sizeof(coords_type));
1618
1619 if (atomic) {
1620 snprintf(intr_name, sizeof(intr_name), "llvm.amdgcn.image.atomic.%s.%s",
1621 atomic_subop, coords_type);
1622 } else {
1623 bool lod_suffix =
1624 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
1625
1626 snprintf(intr_name, sizeof(intr_name), "%s%s%s%s.v4f32.%s.v8i32",
1627 name,
1628 a->compare ? ".c" : "",
1629 a->bias ? ".b" :
1630 lod_suffix ? ".l" :
1631 a->derivs[0] ? ".d" :
1632 a->level_zero ? ".lz" : "",
1633 a->offset ? ".o" : "",
1634 coords_type);
1635 }
1636
1637 LLVMValueRef result =
1638 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
1639 a->attributes);
1640 if (!sample && retty == ctx->v4f32) {
1641 result = LLVMBuildBitCast(ctx->builder, result,
1642 ctx->v4i32, "");
1643 }
1644 return result;
1645 }
1646
1647 LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
1648 LLVMValueRef args[2])
1649 {
1650 LLVMTypeRef v2f16 =
1651 LLVMVectorType(LLVMHalfTypeInContext(ctx->context), 2);
1652 LLVMValueRef res =
1653 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz",
1654 v2f16, args, 2,
1655 AC_FUNC_ATTR_READNONE);
1656 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1657 }
1658
1659 /* Upper 16 bits must be zero. */
1660 static LLVMValueRef ac_llvm_pack_two_int16(struct ac_llvm_context *ctx,
1661 LLVMValueRef val[2])
1662 {
1663 return LLVMBuildOr(ctx->builder, val[0],
1664 LLVMBuildShl(ctx->builder, val[1],
1665 LLVMConstInt(ctx->i32, 16, 0),
1666 ""), "");
1667 }
1668
1669 /* Upper 16 bits are ignored and will be dropped. */
1670 static LLVMValueRef ac_llvm_pack_two_int32_as_int16(struct ac_llvm_context *ctx,
1671 LLVMValueRef val[2])
1672 {
1673 LLVMValueRef v[2] = {
1674 LLVMBuildAnd(ctx->builder, val[0],
1675 LLVMConstInt(ctx->i32, 0xffff, 0), ""),
1676 val[1],
1677 };
1678 return ac_llvm_pack_two_int16(ctx, v);
1679 }
1680
1681 LLVMValueRef ac_build_cvt_pknorm_i16(struct ac_llvm_context *ctx,
1682 LLVMValueRef args[2])
1683 {
1684 if (HAVE_LLVM >= 0x0600) {
1685 LLVMValueRef res =
1686 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.i16",
1687 ctx->v2i16, args, 2,
1688 AC_FUNC_ATTR_READNONE);
1689 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1690 }
1691
1692 LLVMValueRef val[2];
1693
1694 for (int chan = 0; chan < 2; chan++) {
1695 /* Clamp between [-1, 1]. */
1696 val[chan] = ac_build_fmin(ctx, args[chan], ctx->f32_1);
1697 val[chan] = ac_build_fmax(ctx, val[chan], LLVMConstReal(ctx->f32, -1));
1698 /* Convert to a signed integer in [-32767, 32767]. */
1699 val[chan] = LLVMBuildFMul(ctx->builder, val[chan],
1700 LLVMConstReal(ctx->f32, 32767), "");
1701 /* If positive, add 0.5, else add -0.5. */
1702 val[chan] = LLVMBuildFAdd(ctx->builder, val[chan],
1703 LLVMBuildSelect(ctx->builder,
1704 LLVMBuildFCmp(ctx->builder, LLVMRealOGE,
1705 val[chan], ctx->f32_0, ""),
1706 LLVMConstReal(ctx->f32, 0.5),
1707 LLVMConstReal(ctx->f32, -0.5), ""), "");
1708 val[chan] = LLVMBuildFPToSI(ctx->builder, val[chan], ctx->i32, "");
1709 }
1710 return ac_llvm_pack_two_int32_as_int16(ctx, val);
1711 }
1712
1713 LLVMValueRef ac_build_cvt_pknorm_u16(struct ac_llvm_context *ctx,
1714 LLVMValueRef args[2])
1715 {
1716 if (HAVE_LLVM >= 0x0600) {
1717 LLVMValueRef res =
1718 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.u16",
1719 ctx->v2i16, args, 2,
1720 AC_FUNC_ATTR_READNONE);
1721 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1722 }
1723
1724 LLVMValueRef val[2];
1725
1726 for (int chan = 0; chan < 2; chan++) {
1727 val[chan] = ac_build_clamp(ctx, args[chan]);
1728 val[chan] = LLVMBuildFMul(ctx->builder, val[chan],
1729 LLVMConstReal(ctx->f32, 65535), "");
1730 val[chan] = LLVMBuildFAdd(ctx->builder, val[chan],
1731 LLVMConstReal(ctx->f32, 0.5), "");
1732 val[chan] = LLVMBuildFPToUI(ctx->builder, val[chan],
1733 ctx->i32, "");
1734 }
1735 return ac_llvm_pack_two_int32_as_int16(ctx, val);
1736 }
1737
1738 /* The 8-bit and 10-bit clamping is for HW workarounds. */
1739 LLVMValueRef ac_build_cvt_pk_i16(struct ac_llvm_context *ctx,
1740 LLVMValueRef args[2], unsigned bits, bool hi)
1741 {
1742 assert(bits == 8 || bits == 10 || bits == 16);
1743
1744 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
1745 bits == 8 ? 127 : bits == 10 ? 511 : 32767, 0);
1746 LLVMValueRef min_rgb = LLVMConstInt(ctx->i32,
1747 bits == 8 ? -128 : bits == 10 ? -512 : -32768, 0);
1748 LLVMValueRef max_alpha =
1749 bits != 10 ? max_rgb : ctx->i32_1;
1750 LLVMValueRef min_alpha =
1751 bits != 10 ? min_rgb : LLVMConstInt(ctx->i32, -2, 0);
1752 bool has_intrinsic = HAVE_LLVM >= 0x0600;
1753
1754 /* Clamp. */
1755 if (!has_intrinsic || bits != 16) {
1756 for (int i = 0; i < 2; i++) {
1757 bool alpha = hi && i == 1;
1758 args[i] = ac_build_imin(ctx, args[i],
1759 alpha ? max_alpha : max_rgb);
1760 args[i] = ac_build_imax(ctx, args[i],
1761 alpha ? min_alpha : min_rgb);
1762 }
1763 }
1764
1765 if (has_intrinsic) {
1766 LLVMValueRef res =
1767 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.i16",
1768 ctx->v2i16, args, 2,
1769 AC_FUNC_ATTR_READNONE);
1770 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1771 }
1772
1773 return ac_llvm_pack_two_int32_as_int16(ctx, args);
1774 }
1775
1776 /* The 8-bit and 10-bit clamping is for HW workarounds. */
1777 LLVMValueRef ac_build_cvt_pk_u16(struct ac_llvm_context *ctx,
1778 LLVMValueRef args[2], unsigned bits, bool hi)
1779 {
1780 assert(bits == 8 || bits == 10 || bits == 16);
1781
1782 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
1783 bits == 8 ? 255 : bits == 10 ? 1023 : 65535, 0);
1784 LLVMValueRef max_alpha =
1785 bits != 10 ? max_rgb : LLVMConstInt(ctx->i32, 3, 0);
1786 bool has_intrinsic = HAVE_LLVM >= 0x0600;
1787
1788 /* Clamp. */
1789 if (!has_intrinsic || bits != 16) {
1790 for (int i = 0; i < 2; i++) {
1791 bool alpha = hi && i == 1;
1792 args[i] = ac_build_umin(ctx, args[i],
1793 alpha ? max_alpha : max_rgb);
1794 }
1795 }
1796
1797 if (has_intrinsic) {
1798 LLVMValueRef res =
1799 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.u16",
1800 ctx->v2i16, args, 2,
1801 AC_FUNC_ATTR_READNONE);
1802 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1803 }
1804
1805 return ac_llvm_pack_two_int16(ctx, args);
1806 }
1807
1808 LLVMValueRef ac_build_wqm_vote(struct ac_llvm_context *ctx, LLVMValueRef i1)
1809 {
1810 assert(HAVE_LLVM >= 0x0600);
1811 return ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.vote", ctx->i1,
1812 &i1, 1, AC_FUNC_ATTR_READNONE);
1813 }
1814
1815 void ac_build_kill_if_false(struct ac_llvm_context *ctx, LLVMValueRef i1)
1816 {
1817 if (HAVE_LLVM >= 0x0600) {
1818 ac_build_intrinsic(ctx, "llvm.amdgcn.kill", ctx->voidt,
1819 &i1, 1, 0);
1820 return;
1821 }
1822
1823 LLVMValueRef value = LLVMBuildSelect(ctx->builder, i1,
1824 LLVMConstReal(ctx->f32, 1),
1825 LLVMConstReal(ctx->f32, -1), "");
1826 ac_build_intrinsic(ctx, "llvm.AMDGPU.kill", ctx->voidt,
1827 &value, 1, AC_FUNC_ATTR_LEGACY);
1828 }
1829
1830 LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
1831 LLVMValueRef offset, LLVMValueRef width,
1832 bool is_signed)
1833 {
1834 LLVMValueRef args[] = {
1835 input,
1836 offset,
1837 width,
1838 };
1839
1840 return ac_build_intrinsic(ctx,
1841 is_signed ? "llvm.amdgcn.sbfe.i32" :
1842 "llvm.amdgcn.ubfe.i32",
1843 ctx->i32, args, 3,
1844 AC_FUNC_ATTR_READNONE);
1845 }
1846
1847 void ac_build_waitcnt(struct ac_llvm_context *ctx, unsigned simm16)
1848 {
1849 LLVMValueRef args[1] = {
1850 LLVMConstInt(ctx->i32, simm16, false),
1851 };
1852 ac_build_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
1853 ctx->voidt, args, 1, 0);
1854 }
1855
1856 LLVMValueRef ac_build_fract(struct ac_llvm_context *ctx, LLVMValueRef src0,
1857 unsigned bitsize)
1858 {
1859 LLVMTypeRef type;
1860 char *intr;
1861
1862 if (bitsize == 32) {
1863 intr = "llvm.floor.f32";
1864 type = ctx->f32;
1865 } else {
1866 intr = "llvm.floor.f64";
1867 type = ctx->f64;
1868 }
1869
1870 LLVMValueRef params[] = {
1871 src0,
1872 };
1873 LLVMValueRef floor = ac_build_intrinsic(ctx, intr, type, params, 1,
1874 AC_FUNC_ATTR_READNONE);
1875 return LLVMBuildFSub(ctx->builder, src0, floor, "");
1876 }
1877
1878 LLVMValueRef ac_build_isign(struct ac_llvm_context *ctx, LLVMValueRef src0,
1879 unsigned bitsize)
1880 {
1881 LLVMValueRef cmp, val, zero, one;
1882 LLVMTypeRef type;
1883
1884 if (bitsize == 32) {
1885 type = ctx->i32;
1886 zero = ctx->i32_0;
1887 one = ctx->i32_1;
1888 } else {
1889 type = ctx->i64;
1890 zero = ctx->i64_0;
1891 one = ctx->i64_1;
1892 }
1893
1894 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, zero, "");
1895 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
1896 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, zero, "");
1897 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(type, -1, true), "");
1898 return val;
1899 }
1900
1901 LLVMValueRef ac_build_fsign(struct ac_llvm_context *ctx, LLVMValueRef src0,
1902 unsigned bitsize)
1903 {
1904 LLVMValueRef cmp, val, zero, one;
1905 LLVMTypeRef type;
1906
1907 if (bitsize == 32) {
1908 type = ctx->f32;
1909 zero = ctx->f32_0;
1910 one = ctx->f32_1;
1911 } else {
1912 type = ctx->f64;
1913 zero = ctx->f64_0;
1914 one = ctx->f64_1;
1915 }
1916
1917 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, zero, "");
1918 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
1919 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, zero, "");
1920 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(type, -1.0), "");
1921 return val;
1922 }
1923
1924 #define AC_EXP_TARGET 0
1925 #define AC_EXP_ENABLED_CHANNELS 1
1926 #define AC_EXP_OUT0 2
1927
1928 enum ac_ir_type {
1929 AC_IR_UNDEF,
1930 AC_IR_CONST,
1931 AC_IR_VALUE,
1932 };
1933
1934 struct ac_vs_exp_chan
1935 {
1936 LLVMValueRef value;
1937 float const_float;
1938 enum ac_ir_type type;
1939 };
1940
1941 struct ac_vs_exp_inst {
1942 unsigned offset;
1943 LLVMValueRef inst;
1944 struct ac_vs_exp_chan chan[4];
1945 };
1946
1947 struct ac_vs_exports {
1948 unsigned num;
1949 struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
1950 };
1951
1952 /* Return true if the PARAM export has been eliminated. */
1953 static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
1954 uint32_t num_outputs,
1955 struct ac_vs_exp_inst *exp)
1956 {
1957 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
1958 bool is_zero[4] = {}, is_one[4] = {};
1959
1960 for (i = 0; i < 4; i++) {
1961 /* It's a constant expression. Undef outputs are eliminated too. */
1962 if (exp->chan[i].type == AC_IR_UNDEF) {
1963 is_zero[i] = true;
1964 is_one[i] = true;
1965 } else if (exp->chan[i].type == AC_IR_CONST) {
1966 if (exp->chan[i].const_float == 0)
1967 is_zero[i] = true;
1968 else if (exp->chan[i].const_float == 1)
1969 is_one[i] = true;
1970 else
1971 return false; /* other constant */
1972 } else
1973 return false;
1974 }
1975
1976 /* Only certain combinations of 0 and 1 can be eliminated. */
1977 if (is_zero[0] && is_zero[1] && is_zero[2])
1978 default_val = is_zero[3] ? 0 : 1;
1979 else if (is_one[0] && is_one[1] && is_one[2])
1980 default_val = is_zero[3] ? 2 : 3;
1981 else
1982 return false;
1983
1984 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
1985 LLVMInstructionEraseFromParent(exp->inst);
1986
1987 /* Change OFFSET to DEFAULT_VAL. */
1988 for (i = 0; i < num_outputs; i++) {
1989 if (vs_output_param_offset[i] == exp->offset) {
1990 vs_output_param_offset[i] =
1991 AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
1992 break;
1993 }
1994 }
1995 return true;
1996 }
1997
1998 static bool ac_eliminate_duplicated_output(struct ac_llvm_context *ctx,
1999 uint8_t *vs_output_param_offset,
2000 uint32_t num_outputs,
2001 struct ac_vs_exports *processed,
2002 struct ac_vs_exp_inst *exp)
2003 {
2004 unsigned p, copy_back_channels = 0;
2005
2006 /* See if the output is already in the list of processed outputs.
2007 * The LLVMValueRef comparison relies on SSA.
2008 */
2009 for (p = 0; p < processed->num; p++) {
2010 bool different = false;
2011
2012 for (unsigned j = 0; j < 4; j++) {
2013 struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
2014 struct ac_vs_exp_chan *c2 = &exp->chan[j];
2015
2016 /* Treat undef as a match. */
2017 if (c2->type == AC_IR_UNDEF)
2018 continue;
2019
2020 /* If c1 is undef but c2 isn't, we can copy c2 to c1
2021 * and consider the instruction duplicated.
2022 */
2023 if (c1->type == AC_IR_UNDEF) {
2024 copy_back_channels |= 1 << j;
2025 continue;
2026 }
2027
2028 /* Test whether the channels are not equal. */
2029 if (c1->type != c2->type ||
2030 (c1->type == AC_IR_CONST &&
2031 c1->const_float != c2->const_float) ||
2032 (c1->type == AC_IR_VALUE &&
2033 c1->value != c2->value)) {
2034 different = true;
2035 break;
2036 }
2037 }
2038 if (!different)
2039 break;
2040
2041 copy_back_channels = 0;
2042 }
2043 if (p == processed->num)
2044 return false;
2045
2046 /* If a match was found, but the matching export has undef where the new
2047 * one has a normal value, copy the normal value to the undef channel.
2048 */
2049 struct ac_vs_exp_inst *match = &processed->exp[p];
2050
2051 /* Get current enabled channels mask. */
2052 LLVMValueRef arg = LLVMGetOperand(match->inst, AC_EXP_ENABLED_CHANNELS);
2053 unsigned enabled_channels = LLVMConstIntGetZExtValue(arg);
2054
2055 while (copy_back_channels) {
2056 unsigned chan = u_bit_scan(&copy_back_channels);
2057
2058 assert(match->chan[chan].type == AC_IR_UNDEF);
2059 LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
2060 exp->chan[chan].value);
2061 match->chan[chan] = exp->chan[chan];
2062
2063 /* Update number of enabled channels because the original mask
2064 * is not always 0xf.
2065 */
2066 enabled_channels |= (1 << chan);
2067 LLVMSetOperand(match->inst, AC_EXP_ENABLED_CHANNELS,
2068 LLVMConstInt(ctx->i32, enabled_channels, 0));
2069 }
2070
2071 /* The PARAM export is duplicated. Kill it. */
2072 LLVMInstructionEraseFromParent(exp->inst);
2073
2074 /* Change OFFSET to the matching export. */
2075 for (unsigned i = 0; i < num_outputs; i++) {
2076 if (vs_output_param_offset[i] == exp->offset) {
2077 vs_output_param_offset[i] = match->offset;
2078 break;
2079 }
2080 }
2081 return true;
2082 }
2083
2084 void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
2085 LLVMValueRef main_fn,
2086 uint8_t *vs_output_param_offset,
2087 uint32_t num_outputs,
2088 uint8_t *num_param_exports)
2089 {
2090 LLVMBasicBlockRef bb;
2091 bool removed_any = false;
2092 struct ac_vs_exports exports;
2093
2094 exports.num = 0;
2095
2096 /* Process all LLVM instructions. */
2097 bb = LLVMGetFirstBasicBlock(main_fn);
2098 while (bb) {
2099 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
2100
2101 while (inst) {
2102 LLVMValueRef cur = inst;
2103 inst = LLVMGetNextInstruction(inst);
2104 struct ac_vs_exp_inst exp;
2105
2106 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
2107 continue;
2108
2109 LLVMValueRef callee = ac_llvm_get_called_value(cur);
2110
2111 if (!ac_llvm_is_function(callee))
2112 continue;
2113
2114 const char *name = LLVMGetValueName(callee);
2115 unsigned num_args = LLVMCountParams(callee);
2116
2117 /* Check if this is an export instruction. */
2118 if ((num_args != 9 && num_args != 8) ||
2119 (strcmp(name, "llvm.SI.export") &&
2120 strcmp(name, "llvm.amdgcn.exp.f32")))
2121 continue;
2122
2123 LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
2124 unsigned target = LLVMConstIntGetZExtValue(arg);
2125
2126 if (target < V_008DFC_SQ_EXP_PARAM)
2127 continue;
2128
2129 target -= V_008DFC_SQ_EXP_PARAM;
2130
2131 /* Parse the instruction. */
2132 memset(&exp, 0, sizeof(exp));
2133 exp.offset = target;
2134 exp.inst = cur;
2135
2136 for (unsigned i = 0; i < 4; i++) {
2137 LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);
2138
2139 exp.chan[i].value = v;
2140
2141 if (LLVMIsUndef(v)) {
2142 exp.chan[i].type = AC_IR_UNDEF;
2143 } else if (LLVMIsAConstantFP(v)) {
2144 LLVMBool loses_info;
2145 exp.chan[i].type = AC_IR_CONST;
2146 exp.chan[i].const_float =
2147 LLVMConstRealGetDouble(v, &loses_info);
2148 } else {
2149 exp.chan[i].type = AC_IR_VALUE;
2150 }
2151 }
2152
2153 /* Eliminate constant and duplicated PARAM exports. */
2154 if (ac_eliminate_const_output(vs_output_param_offset,
2155 num_outputs, &exp) ||
2156 ac_eliminate_duplicated_output(ctx,
2157 vs_output_param_offset,
2158 num_outputs, &exports,
2159 &exp)) {
2160 removed_any = true;
2161 } else {
2162 exports.exp[exports.num++] = exp;
2163 }
2164 }
2165 bb = LLVMGetNextBasicBlock(bb);
2166 }
2167
2168 /* Remove holes in export memory due to removed PARAM exports.
2169 * This is done by renumbering all PARAM exports.
2170 */
2171 if (removed_any) {
2172 uint8_t old_offset[VARYING_SLOT_MAX];
2173 unsigned out, i;
2174
2175 /* Make a copy of the offsets. We need the old version while
2176 * we are modifying some of them. */
2177 memcpy(old_offset, vs_output_param_offset,
2178 sizeof(old_offset));
2179
2180 for (i = 0; i < exports.num; i++) {
2181 unsigned offset = exports.exp[i].offset;
2182
2183 /* Update vs_output_param_offset. Multiple outputs can
2184 * have the same offset.
2185 */
2186 for (out = 0; out < num_outputs; out++) {
2187 if (old_offset[out] == offset)
2188 vs_output_param_offset[out] = i;
2189 }
2190
2191 /* Change the PARAM offset in the instruction. */
2192 LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
2193 LLVMConstInt(ctx->i32,
2194 V_008DFC_SQ_EXP_PARAM + i, 0));
2195 }
2196 *num_param_exports = exports.num;
2197 }
2198 }
2199
2200 void ac_init_exec_full_mask(struct ac_llvm_context *ctx)
2201 {
2202 LLVMValueRef full_mask = LLVMConstInt(ctx->i64, ~0ull, 0);
2203 ac_build_intrinsic(ctx,
2204 "llvm.amdgcn.init.exec", ctx->voidt,
2205 &full_mask, 1, AC_FUNC_ATTR_CONVERGENT);
2206 }
2207
2208 void ac_declare_lds_as_pointer(struct ac_llvm_context *ctx)
2209 {
2210 unsigned lds_size = ctx->chip_class >= CIK ? 65536 : 32768;
2211 ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32_0,
2212 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), AC_LOCAL_ADDR_SPACE),
2213 "lds");
2214 }
2215
2216 LLVMValueRef ac_lds_load(struct ac_llvm_context *ctx,
2217 LLVMValueRef dw_addr)
2218 {
2219 return ac_build_load(ctx, ctx->lds, dw_addr);
2220 }
2221
2222 void ac_lds_store(struct ac_llvm_context *ctx,
2223 LLVMValueRef dw_addr,
2224 LLVMValueRef value)
2225 {
2226 value = ac_to_integer(ctx, value);
2227 ac_build_indexed_store(ctx, ctx->lds,
2228 dw_addr, value);
2229 }
2230
2231 LLVMValueRef ac_find_lsb(struct ac_llvm_context *ctx,
2232 LLVMTypeRef dst_type,
2233 LLVMValueRef src0)
2234 {
2235 unsigned src0_bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2236 const char *intrin_name;
2237 LLVMTypeRef type;
2238 LLVMValueRef zero;
2239 if (src0_bitsize == 64) {
2240 intrin_name = "llvm.cttz.i64";
2241 type = ctx->i64;
2242 zero = ctx->i64_0;
2243 } else {
2244 intrin_name = "llvm.cttz.i32";
2245 type = ctx->i32;
2246 zero = ctx->i32_0;
2247 }
2248
2249 LLVMValueRef params[2] = {
2250 src0,
2251
2252 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
2253 * add special code to check for x=0. The reason is that
2254 * the LLVM behavior for x=0 is different from what we
2255 * need here. However, LLVM also assumes that ffs(x) is
2256 * in [0, 31], but GLSL expects that ffs(0) = -1, so
2257 * a conditional assignment to handle 0 is still required.
2258 *
2259 * The hardware already implements the correct behavior.
2260 */
2261 LLVMConstInt(ctx->i1, 1, false),
2262 };
2263
2264 LLVMValueRef lsb = ac_build_intrinsic(ctx, intrin_name, type,
2265 params, 2,
2266 AC_FUNC_ATTR_READNONE);
2267
2268 if (src0_bitsize == 64) {
2269 lsb = LLVMBuildTrunc(ctx->builder, lsb, ctx->i32, "");
2270 }
2271
2272 /* TODO: We need an intrinsic to skip this conditional. */
2273 /* Check for zero: */
2274 return LLVMBuildSelect(ctx->builder, LLVMBuildICmp(ctx->builder,
2275 LLVMIntEQ, src0,
2276 zero, ""),
2277 LLVMConstInt(ctx->i32, -1, 0), lsb, "");
2278 }
2279
2280 LLVMTypeRef ac_array_in_const_addr_space(LLVMTypeRef elem_type)
2281 {
2282 return LLVMPointerType(LLVMArrayType(elem_type, 0),
2283 AC_CONST_ADDR_SPACE);
2284 }
2285
2286 LLVMTypeRef ac_array_in_const32_addr_space(LLVMTypeRef elem_type)
2287 {
2288 if (!HAVE_32BIT_POINTERS)
2289 return ac_array_in_const_addr_space(elem_type);
2290
2291 return LLVMPointerType(LLVMArrayType(elem_type, 0),
2292 AC_CONST_32BIT_ADDR_SPACE);
2293 }
2294
2295 static struct ac_llvm_flow *
2296 get_current_flow(struct ac_llvm_context *ctx)
2297 {
2298 if (ctx->flow_depth > 0)
2299 return &ctx->flow[ctx->flow_depth - 1];
2300 return NULL;
2301 }
2302
2303 static struct ac_llvm_flow *
2304 get_innermost_loop(struct ac_llvm_context *ctx)
2305 {
2306 for (unsigned i = ctx->flow_depth; i > 0; --i) {
2307 if (ctx->flow[i - 1].loop_entry_block)
2308 return &ctx->flow[i - 1];
2309 }
2310 return NULL;
2311 }
2312
2313 static struct ac_llvm_flow *
2314 push_flow(struct ac_llvm_context *ctx)
2315 {
2316 struct ac_llvm_flow *flow;
2317
2318 if (ctx->flow_depth >= ctx->flow_depth_max) {
2319 unsigned new_max = MAX2(ctx->flow_depth << 1,
2320 AC_LLVM_INITIAL_CF_DEPTH);
2321
2322 ctx->flow = realloc(ctx->flow, new_max * sizeof(*ctx->flow));
2323 ctx->flow_depth_max = new_max;
2324 }
2325
2326 flow = &ctx->flow[ctx->flow_depth];
2327 ctx->flow_depth++;
2328
2329 flow->next_block = NULL;
2330 flow->loop_entry_block = NULL;
2331 return flow;
2332 }
2333
2334 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base,
2335 int label_id)
2336 {
2337 char buf[32];
2338 snprintf(buf, sizeof(buf), "%s%d", base, label_id);
2339 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
2340 }
2341
2342 /* Append a basic block at the level of the parent flow.
2343 */
2344 static LLVMBasicBlockRef append_basic_block(struct ac_llvm_context *ctx,
2345 const char *name)
2346 {
2347 assert(ctx->flow_depth >= 1);
2348
2349 if (ctx->flow_depth >= 2) {
2350 struct ac_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];
2351
2352 return LLVMInsertBasicBlockInContext(ctx->context,
2353 flow->next_block, name);
2354 }
2355
2356 LLVMValueRef main_fn =
2357 LLVMGetBasicBlockParent(LLVMGetInsertBlock(ctx->builder));
2358 return LLVMAppendBasicBlockInContext(ctx->context, main_fn, name);
2359 }
2360
2361 /* Emit a branch to the given default target for the current block if
2362 * applicable -- that is, if the current block does not already contain a
2363 * branch from a break or continue.
2364 */
2365 static void emit_default_branch(LLVMBuilderRef builder,
2366 LLVMBasicBlockRef target)
2367 {
2368 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
2369 LLVMBuildBr(builder, target);
2370 }
2371
2372 void ac_build_bgnloop(struct ac_llvm_context *ctx, int label_id)
2373 {
2374 struct ac_llvm_flow *flow = push_flow(ctx);
2375 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
2376 flow->next_block = append_basic_block(ctx, "ENDLOOP");
2377 set_basicblock_name(flow->loop_entry_block, "loop", label_id);
2378 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
2379 LLVMPositionBuilderAtEnd(ctx->builder, flow->loop_entry_block);
2380 }
2381
2382 void ac_build_break(struct ac_llvm_context *ctx)
2383 {
2384 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
2385 LLVMBuildBr(ctx->builder, flow->next_block);
2386 }
2387
2388 void ac_build_continue(struct ac_llvm_context *ctx)
2389 {
2390 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
2391 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
2392 }
2393
2394 void ac_build_else(struct ac_llvm_context *ctx, int label_id)
2395 {
2396 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
2397 LLVMBasicBlockRef endif_block;
2398
2399 assert(!current_branch->loop_entry_block);
2400
2401 endif_block = append_basic_block(ctx, "ENDIF");
2402 emit_default_branch(ctx->builder, endif_block);
2403
2404 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
2405 set_basicblock_name(current_branch->next_block, "else", label_id);
2406
2407 current_branch->next_block = endif_block;
2408 }
2409
2410 void ac_build_endif(struct ac_llvm_context *ctx, int label_id)
2411 {
2412 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
2413
2414 assert(!current_branch->loop_entry_block);
2415
2416 emit_default_branch(ctx->builder, current_branch->next_block);
2417 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
2418 set_basicblock_name(current_branch->next_block, "endif", label_id);
2419
2420 ctx->flow_depth--;
2421 }
2422
2423 void ac_build_endloop(struct ac_llvm_context *ctx, int label_id)
2424 {
2425 struct ac_llvm_flow *current_loop = get_current_flow(ctx);
2426
2427 assert(current_loop->loop_entry_block);
2428
2429 emit_default_branch(ctx->builder, current_loop->loop_entry_block);
2430
2431 LLVMPositionBuilderAtEnd(ctx->builder, current_loop->next_block);
2432 set_basicblock_name(current_loop->next_block, "endloop", label_id);
2433 ctx->flow_depth--;
2434 }
2435
2436 static void if_cond_emit(struct ac_llvm_context *ctx, LLVMValueRef cond,
2437 int label_id)
2438 {
2439 struct ac_llvm_flow *flow = push_flow(ctx);
2440 LLVMBasicBlockRef if_block;
2441
2442 if_block = append_basic_block(ctx, "IF");
2443 flow->next_block = append_basic_block(ctx, "ELSE");
2444 set_basicblock_name(if_block, "if", label_id);
2445 LLVMBuildCondBr(ctx->builder, cond, if_block, flow->next_block);
2446 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
2447 }
2448
2449 void ac_build_if(struct ac_llvm_context *ctx, LLVMValueRef value,
2450 int label_id)
2451 {
2452 LLVMValueRef cond = LLVMBuildFCmp(ctx->builder, LLVMRealUNE,
2453 value, ctx->f32_0, "");
2454 if_cond_emit(ctx, cond, label_id);
2455 }
2456
2457 void ac_build_uif(struct ac_llvm_context *ctx, LLVMValueRef value,
2458 int label_id)
2459 {
2460 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
2461 ac_to_integer(ctx, value),
2462 ctx->i32_0, "");
2463 if_cond_emit(ctx, cond, label_id);
2464 }
2465
2466 LLVMValueRef ac_build_alloca(struct ac_llvm_context *ac, LLVMTypeRef type,
2467 const char *name)
2468 {
2469 LLVMBuilderRef builder = ac->builder;
2470 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
2471 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
2472 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
2473 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
2474 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ac->context);
2475 LLVMValueRef res;
2476
2477 if (first_instr) {
2478 LLVMPositionBuilderBefore(first_builder, first_instr);
2479 } else {
2480 LLVMPositionBuilderAtEnd(first_builder, first_block);
2481 }
2482
2483 res = LLVMBuildAlloca(first_builder, type, name);
2484 LLVMBuildStore(builder, LLVMConstNull(type), res);
2485
2486 LLVMDisposeBuilder(first_builder);
2487
2488 return res;
2489 }
2490
2491 LLVMValueRef ac_build_alloca_undef(struct ac_llvm_context *ac,
2492 LLVMTypeRef type, const char *name)
2493 {
2494 LLVMValueRef ptr = ac_build_alloca(ac, type, name);
2495 LLVMBuildStore(ac->builder, LLVMGetUndef(type), ptr);
2496 return ptr;
2497 }
2498
2499 LLVMValueRef ac_cast_ptr(struct ac_llvm_context *ctx, LLVMValueRef ptr,
2500 LLVMTypeRef type)
2501 {
2502 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
2503 return LLVMBuildBitCast(ctx->builder, ptr,
2504 LLVMPointerType(type, addr_space), "");
2505 }
2506
2507 LLVMValueRef ac_trim_vector(struct ac_llvm_context *ctx, LLVMValueRef value,
2508 unsigned count)
2509 {
2510 unsigned num_components = ac_get_llvm_num_components(value);
2511 if (count == num_components)
2512 return value;
2513
2514 LLVMValueRef masks[] = {
2515 LLVMConstInt(ctx->i32, 0, false), LLVMConstInt(ctx->i32, 1, false),
2516 LLVMConstInt(ctx->i32, 2, false), LLVMConstInt(ctx->i32, 3, false)};
2517
2518 if (count == 1)
2519 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
2520 "");
2521
2522 LLVMValueRef swizzle = LLVMConstVector(masks, count);
2523 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
2524 }
2525
2526 LLVMValueRef ac_unpack_param(struct ac_llvm_context *ctx, LLVMValueRef param,
2527 unsigned rshift, unsigned bitwidth)
2528 {
2529 LLVMValueRef value = param;
2530 if (rshift)
2531 value = LLVMBuildLShr(ctx->builder, value,
2532 LLVMConstInt(ctx->i32, rshift, false), "");
2533
2534 if (rshift + bitwidth < 32) {
2535 unsigned mask = (1 << bitwidth) - 1;
2536 value = LLVMBuildAnd(ctx->builder, value,
2537 LLVMConstInt(ctx->i32, mask, false), "");
2538 }
2539 return value;
2540 }
2541
2542 /* Adjust the sample index according to FMASK.
2543 *
2544 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
2545 * which is the identity mapping. Each nibble says which physical sample
2546 * should be fetched to get that sample.
2547 *
2548 * For example, 0x11111100 means there are only 2 samples stored and
2549 * the second sample covers 3/4 of the pixel. When reading samples 0
2550 * and 1, return physical sample 0 (determined by the first two 0s
2551 * in FMASK), otherwise return physical sample 1.
2552 *
2553 * The sample index should be adjusted as follows:
2554 * addr[sample_index] = (fmask >> (addr[sample_index] * 4)) & 0xF;
2555 */
2556 void ac_apply_fmask_to_sample(struct ac_llvm_context *ac, LLVMValueRef fmask,
2557 LLVMValueRef *addr, bool is_array_tex)
2558 {
2559 struct ac_image_args fmask_load = {};
2560 fmask_load.opcode = ac_image_load;
2561 fmask_load.resource = fmask;
2562 fmask_load.dmask = 0xf;
2563 fmask_load.dim = is_array_tex ? ac_image_2darray : ac_image_2d;
2564
2565 fmask_load.coords[0] = addr[0];
2566 fmask_load.coords[1] = addr[1];
2567 if (is_array_tex)
2568 fmask_load.coords[2] = addr[2];
2569
2570 LLVMValueRef fmask_value = ac_build_image_opcode(ac, &fmask_load);
2571 fmask_value = LLVMBuildExtractElement(ac->builder, fmask_value,
2572 ac->i32_0, "");
2573
2574 /* Apply the formula. */
2575 unsigned sample_chan = is_array_tex ? 3 : 2;
2576 LLVMValueRef final_sample;
2577 final_sample = LLVMBuildMul(ac->builder, addr[sample_chan],
2578 LLVMConstInt(ac->i32, 4, 0), "");
2579 final_sample = LLVMBuildLShr(ac->builder, fmask_value, final_sample, "");
2580 final_sample = LLVMBuildAnd(ac->builder, final_sample,
2581 LLVMConstInt(ac->i32, 0xF, 0), "");
2582
2583 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
2584 * resource descriptor is 0 (invalid),
2585 */
2586 LLVMValueRef tmp;
2587 tmp = LLVMBuildBitCast(ac->builder, fmask, ac->v8i32, "");
2588 tmp = LLVMBuildExtractElement(ac->builder, tmp, ac->i32_1, "");
2589 tmp = LLVMBuildICmp(ac->builder, LLVMIntNE, tmp, ac->i32_0, "");
2590
2591 /* Replace the MSAA sample index. */
2592 addr[sample_chan] = LLVMBuildSelect(ac->builder, tmp, final_sample,
2593 addr[sample_chan], "");
2594 }
2595
2596 static LLVMValueRef
2597 _ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
2598 {
2599 ac_build_optimization_barrier(ctx, &src);
2600 return ac_build_intrinsic(ctx,
2601 lane == NULL ? "llvm.amdgcn.readfirstlane" : "llvm.amdgcn.readlane",
2602 LLVMTypeOf(src), (LLVMValueRef []) {
2603 src, lane },
2604 lane == NULL ? 1 : 2,
2605 AC_FUNC_ATTR_READNONE |
2606 AC_FUNC_ATTR_CONVERGENT);
2607 }
2608
2609 /**
2610 * Builds the "llvm.amdgcn.readlane" or "llvm.amdgcn.readfirstlane" intrinsic.
2611 * @param ctx
2612 * @param src
2613 * @param lane - id of the lane or NULL for the first active lane
2614 * @return value of the lane
2615 */
2616 LLVMValueRef
2617 ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
2618 {
2619 LLVMTypeRef src_type = LLVMTypeOf(src);
2620 src = ac_to_integer(ctx, src);
2621 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2622 LLVMValueRef ret;
2623
2624 if (bits == 32) {
2625 ret = _ac_build_readlane(ctx, src, lane);
2626 } else {
2627 assert(bits % 32 == 0);
2628 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2629 LLVMValueRef src_vector =
2630 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2631 ret = LLVMGetUndef(vec_type);
2632 for (unsigned i = 0; i < bits / 32; i++) {
2633 src = LLVMBuildExtractElement(ctx->builder, src_vector,
2634 LLVMConstInt(ctx->i32, i, 0), "");
2635 LLVMValueRef ret_comp = _ac_build_readlane(ctx, src, lane);
2636 ret = LLVMBuildInsertElement(ctx->builder, ret, ret_comp,
2637 LLVMConstInt(ctx->i32, i, 0), "");
2638 }
2639 }
2640 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2641 }
2642
2643 LLVMValueRef
2644 ac_build_writelane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef value, LLVMValueRef lane)
2645 {
2646 /* TODO: Use the actual instruction when LLVM adds an intrinsic for it.
2647 */
2648 LLVMValueRef pred = LLVMBuildICmp(ctx->builder, LLVMIntEQ, lane,
2649 ac_get_thread_id(ctx), "");
2650 return LLVMBuildSelect(ctx->builder, pred, value, src, "");
2651 }
2652
2653 LLVMValueRef
2654 ac_build_mbcnt(struct ac_llvm_context *ctx, LLVMValueRef mask)
2655 {
2656 LLVMValueRef mask_vec = LLVMBuildBitCast(ctx->builder, mask,
2657 LLVMVectorType(ctx->i32, 2),
2658 "");
2659 LLVMValueRef mask_lo = LLVMBuildExtractElement(ctx->builder, mask_vec,
2660 ctx->i32_0, "");
2661 LLVMValueRef mask_hi = LLVMBuildExtractElement(ctx->builder, mask_vec,
2662 ctx->i32_1, "");
2663 LLVMValueRef val =
2664 ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
2665 (LLVMValueRef []) { mask_lo, ctx->i32_0 },
2666 2, AC_FUNC_ATTR_READNONE);
2667 val = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi", ctx->i32,
2668 (LLVMValueRef []) { mask_hi, val },
2669 2, AC_FUNC_ATTR_READNONE);
2670 return val;
2671 }
2672
2673 enum dpp_ctrl {
2674 _dpp_quad_perm = 0x000,
2675 _dpp_row_sl = 0x100,
2676 _dpp_row_sr = 0x110,
2677 _dpp_row_rr = 0x120,
2678 dpp_wf_sl1 = 0x130,
2679 dpp_wf_rl1 = 0x134,
2680 dpp_wf_sr1 = 0x138,
2681 dpp_wf_rr1 = 0x13C,
2682 dpp_row_mirror = 0x140,
2683 dpp_row_half_mirror = 0x141,
2684 dpp_row_bcast15 = 0x142,
2685 dpp_row_bcast31 = 0x143
2686 };
2687
2688 static inline enum dpp_ctrl
2689 dpp_quad_perm(unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
2690 {
2691 assert(lane0 < 4 && lane1 < 4 && lane2 < 4 && lane3 < 4);
2692 return _dpp_quad_perm | lane0 | (lane1 << 2) | (lane2 << 4) | (lane3 << 6);
2693 }
2694
2695 static inline enum dpp_ctrl
2696 dpp_row_sl(unsigned amount)
2697 {
2698 assert(amount > 0 && amount < 16);
2699 return _dpp_row_sl | amount;
2700 }
2701
2702 static inline enum dpp_ctrl
2703 dpp_row_sr(unsigned amount)
2704 {
2705 assert(amount > 0 && amount < 16);
2706 return _dpp_row_sr | amount;
2707 }
2708
2709 static LLVMValueRef
2710 _ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
2711 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
2712 bool bound_ctrl)
2713 {
2714 return ac_build_intrinsic(ctx, "llvm.amdgcn.update.dpp.i32",
2715 LLVMTypeOf(old),
2716 (LLVMValueRef[]) {
2717 old, src,
2718 LLVMConstInt(ctx->i32, dpp_ctrl, 0),
2719 LLVMConstInt(ctx->i32, row_mask, 0),
2720 LLVMConstInt(ctx->i32, bank_mask, 0),
2721 LLVMConstInt(ctx->i1, bound_ctrl, 0) },
2722 6, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
2723 }
2724
2725 static LLVMValueRef
2726 ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
2727 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
2728 bool bound_ctrl)
2729 {
2730 LLVMTypeRef src_type = LLVMTypeOf(src);
2731 src = ac_to_integer(ctx, src);
2732 old = ac_to_integer(ctx, old);
2733 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2734 LLVMValueRef ret;
2735 if (bits == 32) {
2736 ret = _ac_build_dpp(ctx, old, src, dpp_ctrl, row_mask,
2737 bank_mask, bound_ctrl);
2738 } else {
2739 assert(bits % 32 == 0);
2740 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2741 LLVMValueRef src_vector =
2742 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2743 LLVMValueRef old_vector =
2744 LLVMBuildBitCast(ctx->builder, old, vec_type, "");
2745 ret = LLVMGetUndef(vec_type);
2746 for (unsigned i = 0; i < bits / 32; i++) {
2747 src = LLVMBuildExtractElement(ctx->builder, src_vector,
2748 LLVMConstInt(ctx->i32, i,
2749 0), "");
2750 old = LLVMBuildExtractElement(ctx->builder, old_vector,
2751 LLVMConstInt(ctx->i32, i,
2752 0), "");
2753 LLVMValueRef ret_comp = _ac_build_dpp(ctx, old, src,
2754 dpp_ctrl,
2755 row_mask,
2756 bank_mask,
2757 bound_ctrl);
2758 ret = LLVMBuildInsertElement(ctx->builder, ret,
2759 ret_comp,
2760 LLVMConstInt(ctx->i32, i,
2761 0), "");
2762 }
2763 }
2764 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2765 }
2766
2767 static inline unsigned
2768 ds_pattern_bitmode(unsigned and_mask, unsigned or_mask, unsigned xor_mask)
2769 {
2770 assert(and_mask < 32 && or_mask < 32 && xor_mask < 32);
2771 return and_mask | (or_mask << 5) | (xor_mask << 10);
2772 }
2773
2774 static LLVMValueRef
2775 _ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
2776 {
2777 return ac_build_intrinsic(ctx, "llvm.amdgcn.ds.swizzle",
2778 LLVMTypeOf(src), (LLVMValueRef []) {
2779 src, LLVMConstInt(ctx->i32, mask, 0) },
2780 2, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
2781 }
2782
2783 LLVMValueRef
2784 ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
2785 {
2786 LLVMTypeRef src_type = LLVMTypeOf(src);
2787 src = ac_to_integer(ctx, src);
2788 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
2789 LLVMValueRef ret;
2790 if (bits == 32) {
2791 ret = _ac_build_ds_swizzle(ctx, src, mask);
2792 } else {
2793 assert(bits % 32 == 0);
2794 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
2795 LLVMValueRef src_vector =
2796 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
2797 ret = LLVMGetUndef(vec_type);
2798 for (unsigned i = 0; i < bits / 32; i++) {
2799 src = LLVMBuildExtractElement(ctx->builder, src_vector,
2800 LLVMConstInt(ctx->i32, i,
2801 0), "");
2802 LLVMValueRef ret_comp = _ac_build_ds_swizzle(ctx, src,
2803 mask);
2804 ret = LLVMBuildInsertElement(ctx->builder, ret,
2805 ret_comp,
2806 LLVMConstInt(ctx->i32, i,
2807 0), "");
2808 }
2809 }
2810 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2811 }
2812
2813 static LLVMValueRef
2814 ac_build_wwm(struct ac_llvm_context *ctx, LLVMValueRef src)
2815 {
2816 char name[32], type[8];
2817 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
2818 snprintf(name, sizeof(name), "llvm.amdgcn.wwm.%s", type);
2819 return ac_build_intrinsic(ctx, name, LLVMTypeOf(src),
2820 (LLVMValueRef []) { src }, 1,
2821 AC_FUNC_ATTR_READNONE);
2822 }
2823
2824 static LLVMValueRef
2825 ac_build_set_inactive(struct ac_llvm_context *ctx, LLVMValueRef src,
2826 LLVMValueRef inactive)
2827 {
2828 char name[32], type[8];
2829 LLVMTypeRef src_type = LLVMTypeOf(src);
2830 src = ac_to_integer(ctx, src);
2831 inactive = ac_to_integer(ctx, inactive);
2832 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
2833 snprintf(name, sizeof(name), "llvm.amdgcn.set.inactive.%s", type);
2834 LLVMValueRef ret =
2835 ac_build_intrinsic(ctx, name,
2836 LLVMTypeOf(src), (LLVMValueRef []) {
2837 src, inactive }, 2,
2838 AC_FUNC_ATTR_READNONE |
2839 AC_FUNC_ATTR_CONVERGENT);
2840 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
2841 }
2842
2843 static LLVMValueRef
2844 get_reduction_identity(struct ac_llvm_context *ctx, nir_op op, unsigned type_size)
2845 {
2846 if (type_size == 4) {
2847 switch (op) {
2848 case nir_op_iadd: return ctx->i32_0;
2849 case nir_op_fadd: return ctx->f32_0;
2850 case nir_op_imul: return ctx->i32_1;
2851 case nir_op_fmul: return ctx->f32_1;
2852 case nir_op_imin: return LLVMConstInt(ctx->i32, INT32_MAX, 0);
2853 case nir_op_umin: return LLVMConstInt(ctx->i32, UINT32_MAX, 0);
2854 case nir_op_fmin: return LLVMConstReal(ctx->f32, INFINITY);
2855 case nir_op_imax: return LLVMConstInt(ctx->i32, INT32_MIN, 0);
2856 case nir_op_umax: return ctx->i32_0;
2857 case nir_op_fmax: return LLVMConstReal(ctx->f32, -INFINITY);
2858 case nir_op_iand: return LLVMConstInt(ctx->i32, -1, 0);
2859 case nir_op_ior: return ctx->i32_0;
2860 case nir_op_ixor: return ctx->i32_0;
2861 default:
2862 unreachable("bad reduction intrinsic");
2863 }
2864 } else { /* type_size == 64bit */
2865 switch (op) {
2866 case nir_op_iadd: return ctx->i64_0;
2867 case nir_op_fadd: return ctx->f64_0;
2868 case nir_op_imul: return ctx->i64_1;
2869 case nir_op_fmul: return ctx->f64_1;
2870 case nir_op_imin: return LLVMConstInt(ctx->i64, INT64_MAX, 0);
2871 case nir_op_umin: return LLVMConstInt(ctx->i64, UINT64_MAX, 0);
2872 case nir_op_fmin: return LLVMConstReal(ctx->f64, INFINITY);
2873 case nir_op_imax: return LLVMConstInt(ctx->i64, INT64_MIN, 0);
2874 case nir_op_umax: return ctx->i64_0;
2875 case nir_op_fmax: return LLVMConstReal(ctx->f64, -INFINITY);
2876 case nir_op_iand: return LLVMConstInt(ctx->i64, -1, 0);
2877 case nir_op_ior: return ctx->i64_0;
2878 case nir_op_ixor: return ctx->i64_0;
2879 default:
2880 unreachable("bad reduction intrinsic");
2881 }
2882 }
2883 }
2884
2885 static LLVMValueRef
2886 ac_build_alu_op(struct ac_llvm_context *ctx, LLVMValueRef lhs, LLVMValueRef rhs, nir_op op)
2887 {
2888 bool _64bit = ac_get_type_size(LLVMTypeOf(lhs)) == 8;
2889 switch (op) {
2890 case nir_op_iadd: return LLVMBuildAdd(ctx->builder, lhs, rhs, "");
2891 case nir_op_fadd: return LLVMBuildFAdd(ctx->builder, lhs, rhs, "");
2892 case nir_op_imul: return LLVMBuildMul(ctx->builder, lhs, rhs, "");
2893 case nir_op_fmul: return LLVMBuildFMul(ctx->builder, lhs, rhs, "");
2894 case nir_op_imin: return LLVMBuildSelect(ctx->builder,
2895 LLVMBuildICmp(ctx->builder, LLVMIntSLT, lhs, rhs, ""),
2896 lhs, rhs, "");
2897 case nir_op_umin: return LLVMBuildSelect(ctx->builder,
2898 LLVMBuildICmp(ctx->builder, LLVMIntULT, lhs, rhs, ""),
2899 lhs, rhs, "");
2900 case nir_op_fmin: return ac_build_intrinsic(ctx,
2901 _64bit ? "llvm.minnum.f64" : "llvm.minnum.f32",
2902 _64bit ? ctx->f64 : ctx->f32,
2903 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
2904 case nir_op_imax: return LLVMBuildSelect(ctx->builder,
2905 LLVMBuildICmp(ctx->builder, LLVMIntSGT, lhs, rhs, ""),
2906 lhs, rhs, "");
2907 case nir_op_umax: return LLVMBuildSelect(ctx->builder,
2908 LLVMBuildICmp(ctx->builder, LLVMIntUGT, lhs, rhs, ""),
2909 lhs, rhs, "");
2910 case nir_op_fmax: return ac_build_intrinsic(ctx,
2911 _64bit ? "llvm.maxnum.f64" : "llvm.maxnum.f32",
2912 _64bit ? ctx->f64 : ctx->f32,
2913 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
2914 case nir_op_iand: return LLVMBuildAnd(ctx->builder, lhs, rhs, "");
2915 case nir_op_ior: return LLVMBuildOr(ctx->builder, lhs, rhs, "");
2916 case nir_op_ixor: return LLVMBuildXor(ctx->builder, lhs, rhs, "");
2917 default:
2918 unreachable("bad reduction intrinsic");
2919 }
2920 }
2921
2922 /* TODO: add inclusive and excluse scan functions for SI chip class. */
2923 static LLVMValueRef
2924 ac_build_scan(struct ac_llvm_context *ctx, nir_op op, LLVMValueRef src, LLVMValueRef identity)
2925 {
2926 LLVMValueRef result, tmp;
2927 result = src;
2928 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
2929 result = ac_build_alu_op(ctx, result, tmp, op);
2930 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(2), 0xf, 0xf, false);
2931 result = ac_build_alu_op(ctx, result, tmp, op);
2932 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(3), 0xf, 0xf, false);
2933 result = ac_build_alu_op(ctx, result, tmp, op);
2934 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(4), 0xf, 0xe, false);
2935 result = ac_build_alu_op(ctx, result, tmp, op);
2936 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(8), 0xf, 0xc, false);
2937 result = ac_build_alu_op(ctx, result, tmp, op);
2938 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
2939 result = ac_build_alu_op(ctx, result, tmp, op);
2940 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
2941 result = ac_build_alu_op(ctx, result, tmp, op);
2942 return result;
2943 }
2944
2945 LLVMValueRef
2946 ac_build_inclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
2947 {
2948 ac_build_optimization_barrier(ctx, &src);
2949 LLVMValueRef result;
2950 LLVMValueRef identity = get_reduction_identity(ctx, op,
2951 ac_get_type_size(LLVMTypeOf(src)));
2952 result = LLVMBuildBitCast(ctx->builder,
2953 ac_build_set_inactive(ctx, src, identity),
2954 LLVMTypeOf(identity), "");
2955 result = ac_build_scan(ctx, op, result, identity);
2956
2957 return ac_build_wwm(ctx, result);
2958 }
2959
2960 LLVMValueRef
2961 ac_build_exclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
2962 {
2963 ac_build_optimization_barrier(ctx, &src);
2964 LLVMValueRef result;
2965 LLVMValueRef identity = get_reduction_identity(ctx, op,
2966 ac_get_type_size(LLVMTypeOf(src)));
2967 result = LLVMBuildBitCast(ctx->builder,
2968 ac_build_set_inactive(ctx, src, identity),
2969 LLVMTypeOf(identity), "");
2970 result = ac_build_dpp(ctx, identity, result, dpp_wf_sr1, 0xf, 0xf, false);
2971 result = ac_build_scan(ctx, op, result, identity);
2972
2973 return ac_build_wwm(ctx, result);
2974 }
2975
2976 LLVMValueRef
2977 ac_build_reduce(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op, unsigned cluster_size)
2978 {
2979 if (cluster_size == 1) return src;
2980 ac_build_optimization_barrier(ctx, &src);
2981 LLVMValueRef result, swap;
2982 LLVMValueRef identity = get_reduction_identity(ctx, op,
2983 ac_get_type_size(LLVMTypeOf(src)));
2984 result = LLVMBuildBitCast(ctx->builder,
2985 ac_build_set_inactive(ctx, src, identity),
2986 LLVMTypeOf(identity), "");
2987 swap = ac_build_quad_swizzle(ctx, result, 1, 0, 3, 2);
2988 result = ac_build_alu_op(ctx, result, swap, op);
2989 if (cluster_size == 2) return ac_build_wwm(ctx, result);
2990
2991 swap = ac_build_quad_swizzle(ctx, result, 2, 3, 0, 1);
2992 result = ac_build_alu_op(ctx, result, swap, op);
2993 if (cluster_size == 4) return ac_build_wwm(ctx, result);
2994
2995 if (ctx->chip_class >= VI)
2996 swap = ac_build_dpp(ctx, identity, result, dpp_row_half_mirror, 0xf, 0xf, false);
2997 else
2998 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x04));
2999 result = ac_build_alu_op(ctx, result, swap, op);
3000 if (cluster_size == 8) return ac_build_wwm(ctx, result);
3001
3002 if (ctx->chip_class >= VI)
3003 swap = ac_build_dpp(ctx, identity, result, dpp_row_mirror, 0xf, 0xf, false);
3004 else
3005 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x08));
3006 result = ac_build_alu_op(ctx, result, swap, op);
3007 if (cluster_size == 16) return ac_build_wwm(ctx, result);
3008
3009 if (ctx->chip_class >= VI && cluster_size != 32)
3010 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
3011 else
3012 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x10));
3013 result = ac_build_alu_op(ctx, result, swap, op);
3014 if (cluster_size == 32) return ac_build_wwm(ctx, result);
3015
3016 if (ctx->chip_class >= VI) {
3017 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
3018 result = ac_build_alu_op(ctx, result, swap, op);
3019 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 63, 0));
3020 return ac_build_wwm(ctx, result);
3021 } else {
3022 swap = ac_build_readlane(ctx, result, ctx->i32_0);
3023 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 32, 0));
3024 result = ac_build_alu_op(ctx, result, swap, op);
3025 return ac_build_wwm(ctx, result);
3026 }
3027 }
3028
3029 LLVMValueRef
3030 ac_build_quad_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src,
3031 unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
3032 {
3033 unsigned mask = dpp_quad_perm(lane0, lane1, lane2, lane3);
3034 if (ctx->chip_class >= VI && HAVE_LLVM >= 0x0600) {
3035 return ac_build_dpp(ctx, src, src, mask, 0xf, 0xf, false);
3036 } else {
3037 return ac_build_ds_swizzle(ctx, src, (1 << 15) | mask);
3038 }
3039 }
3040
3041 LLVMValueRef
3042 ac_build_shuffle(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef index)
3043 {
3044 index = LLVMBuildMul(ctx->builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
3045 return ac_build_intrinsic(ctx,
3046 "llvm.amdgcn.ds.bpermute", ctx->i32,
3047 (LLVMValueRef []) {index, src}, 2,
3048 AC_FUNC_ATTR_READNONE |
3049 AC_FUNC_ATTR_CONVERGENT);
3050 }