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