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