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