ac: add ac_build_buffer_store_format() helper
[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 static void
1086 ac_build_buffer_store_common(struct ac_llvm_context *ctx,
1087 LLVMValueRef rsrc,
1088 LLVMValueRef data,
1089 LLVMValueRef vindex,
1090 LLVMValueRef voffset,
1091 unsigned num_channels,
1092 bool glc,
1093 bool slc,
1094 bool writeonly_memory,
1095 bool use_format)
1096 {
1097 LLVMValueRef args[] = {
1098 data,
1099 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
1100 vindex ? vindex : ctx->i32_0,
1101 voffset,
1102 LLVMConstInt(ctx->i1, glc, 0),
1103 LLVMConstInt(ctx->i1, slc, 0)
1104 };
1105 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1106
1107 const char *type_names[] = {"f32", "v2f32", "v4f32"};
1108 char name[256];
1109
1110 if (use_format) {
1111 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.store.format.%s",
1112 type_names[func]);
1113 } else {
1114 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.store.%s",
1115 type_names[func]);
1116 }
1117
1118 ac_build_intrinsic(ctx, name, ctx->voidt, args, ARRAY_SIZE(args),
1119 ac_get_store_intr_attribs(writeonly_memory));
1120 }
1121
1122 static void
1123 ac_build_llvm8_buffer_store_common(struct ac_llvm_context *ctx,
1124 LLVMValueRef rsrc,
1125 LLVMValueRef data,
1126 LLVMValueRef vindex,
1127 LLVMValueRef voffset,
1128 LLVMValueRef soffset,
1129 unsigned num_channels,
1130 bool glc,
1131 bool slc,
1132 bool writeonly_memory,
1133 bool use_format,
1134 bool structurized)
1135 {
1136 LLVMValueRef args[6];
1137 int idx = 0;
1138 args[idx++] = data;
1139 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1140 if (structurized)
1141 args[idx++] = vindex ? vindex : ctx->i32_0;
1142 args[idx++] = voffset ? voffset : ctx->i32_0;
1143 args[idx++] = soffset ? soffset : ctx->i32_0;
1144 args[idx++] = LLVMConstInt(ctx->i32, (glc ? 1 : 0) + (slc ? 2 : 0), 0);
1145 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1146
1147 const char *type_names[] = {"f32", "v2f32", "v4f32"};
1148 const char *indexing_kind = structurized ? "struct" : "raw";
1149 char name[256];
1150
1151 if (use_format) {
1152 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.format.%s",
1153 indexing_kind, type_names[func]);
1154 } else {
1155 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.%s",
1156 indexing_kind, type_names[func]);
1157 }
1158
1159 ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
1160 ac_get_store_intr_attribs(writeonly_memory));
1161 }
1162
1163 void
1164 ac_build_buffer_store_format(struct ac_llvm_context *ctx,
1165 LLVMValueRef rsrc,
1166 LLVMValueRef data,
1167 LLVMValueRef vindex,
1168 LLVMValueRef voffset,
1169 unsigned num_channels,
1170 bool glc,
1171 bool writeonly_memory)
1172 {
1173 if (HAVE_LLVM >= 0x800) {
1174 ac_build_llvm8_buffer_store_common(ctx, rsrc, data, vindex,
1175 voffset, NULL, num_channels,
1176 glc, false, writeonly_memory,
1177 true, true);
1178 } else {
1179 ac_build_buffer_store_common(ctx, rsrc, data, vindex, voffset,
1180 num_channels, glc, false,
1181 writeonly_memory, true);
1182 }
1183 }
1184
1185 /* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
1186 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
1187 * or v4i32 (num_channels=3,4).
1188 */
1189 void
1190 ac_build_buffer_store_dword(struct ac_llvm_context *ctx,
1191 LLVMValueRef rsrc,
1192 LLVMValueRef vdata,
1193 unsigned num_channels,
1194 LLVMValueRef voffset,
1195 LLVMValueRef soffset,
1196 unsigned inst_offset,
1197 bool glc,
1198 bool slc,
1199 bool writeonly_memory,
1200 bool swizzle_enable_hint)
1201 {
1202 /* Split 3 channel stores, becase LLVM doesn't support 3-channel
1203 * intrinsics. */
1204 if (num_channels == 3) {
1205 LLVMValueRef v[3], v01;
1206
1207 for (int i = 0; i < 3; i++) {
1208 v[i] = LLVMBuildExtractElement(ctx->builder, vdata,
1209 LLVMConstInt(ctx->i32, i, 0), "");
1210 }
1211 v01 = ac_build_gather_values(ctx, v, 2);
1212
1213 ac_build_buffer_store_dword(ctx, rsrc, v01, 2, voffset,
1214 soffset, inst_offset, glc, slc,
1215 writeonly_memory, swizzle_enable_hint);
1216 ac_build_buffer_store_dword(ctx, rsrc, v[2], 1, voffset,
1217 soffset, inst_offset + 8,
1218 glc, slc,
1219 writeonly_memory, swizzle_enable_hint);
1220 return;
1221 }
1222
1223 /* SWIZZLE_ENABLE requires that soffset isn't folded into voffset
1224 * (voffset is swizzled, but soffset isn't swizzled).
1225 * llvm.amdgcn.buffer.store doesn't have a separate soffset parameter.
1226 */
1227 if (!swizzle_enable_hint) {
1228 LLVMValueRef offset = soffset;
1229
1230 static const char *types[] = {"f32", "v2f32", "v4f32"};
1231
1232 if (inst_offset)
1233 offset = LLVMBuildAdd(ctx->builder, offset,
1234 LLVMConstInt(ctx->i32, inst_offset, 0), "");
1235 if (voffset)
1236 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
1237
1238 LLVMValueRef args[] = {
1239 ac_to_float(ctx, vdata),
1240 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
1241 ctx->i32_0,
1242 offset,
1243 LLVMConstInt(ctx->i1, glc, 0),
1244 LLVMConstInt(ctx->i1, slc, 0),
1245 };
1246
1247 char name[256];
1248 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.store.%s",
1249 types[CLAMP(num_channels, 1, 3) - 1]);
1250
1251 ac_build_intrinsic(ctx, name, ctx->voidt,
1252 args, ARRAY_SIZE(args),
1253 ac_get_store_intr_attribs(writeonly_memory));
1254 return;
1255 }
1256
1257 static const unsigned dfmt[] = {
1258 V_008F0C_BUF_DATA_FORMAT_32,
1259 V_008F0C_BUF_DATA_FORMAT_32_32,
1260 V_008F0C_BUF_DATA_FORMAT_32_32_32,
1261 V_008F0C_BUF_DATA_FORMAT_32_32_32_32
1262 };
1263 static const char *types[] = {"i32", "v2i32", "v4i32"};
1264 LLVMValueRef args[] = {
1265 vdata,
1266 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
1267 ctx->i32_0,
1268 voffset ? voffset : ctx->i32_0,
1269 soffset,
1270 LLVMConstInt(ctx->i32, inst_offset, 0),
1271 LLVMConstInt(ctx->i32, dfmt[num_channels - 1], 0),
1272 LLVMConstInt(ctx->i32, V_008F0C_BUF_NUM_FORMAT_UINT, 0),
1273 LLVMConstInt(ctx->i1, glc, 0),
1274 LLVMConstInt(ctx->i1, slc, 0),
1275 };
1276 char name[256];
1277 snprintf(name, sizeof(name), "llvm.amdgcn.tbuffer.store.%s",
1278 types[CLAMP(num_channels, 1, 3) - 1]);
1279
1280 ac_build_intrinsic(ctx, name, ctx->voidt,
1281 args, ARRAY_SIZE(args),
1282 ac_get_store_intr_attribs(writeonly_memory));
1283 }
1284
1285 static LLVMValueRef
1286 ac_build_buffer_load_common(struct ac_llvm_context *ctx,
1287 LLVMValueRef rsrc,
1288 LLVMValueRef vindex,
1289 LLVMValueRef voffset,
1290 unsigned num_channels,
1291 bool glc,
1292 bool slc,
1293 bool can_speculate,
1294 bool use_format)
1295 {
1296 LLVMValueRef args[] = {
1297 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
1298 vindex ? vindex : ctx->i32_0,
1299 voffset,
1300 LLVMConstInt(ctx->i1, glc, 0),
1301 LLVMConstInt(ctx->i1, slc, 0)
1302 };
1303 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1304
1305 LLVMTypeRef types[] = {ctx->f32, ctx->v2f32, ctx->v4f32};
1306 const char *type_names[] = {"f32", "v2f32", "v4f32"};
1307 char name[256];
1308
1309 if (use_format) {
1310 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.format.%s",
1311 type_names[func]);
1312 } else {
1313 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.%s",
1314 type_names[func]);
1315 }
1316
1317 return ac_build_intrinsic(ctx, name, types[func], args,
1318 ARRAY_SIZE(args),
1319 ac_get_load_intr_attribs(can_speculate));
1320 }
1321
1322 static LLVMValueRef
1323 ac_build_llvm8_buffer_load_common(struct ac_llvm_context *ctx,
1324 LLVMValueRef rsrc,
1325 LLVMValueRef vindex,
1326 LLVMValueRef voffset,
1327 LLVMValueRef soffset,
1328 unsigned num_channels,
1329 bool glc,
1330 bool slc,
1331 bool can_speculate,
1332 bool use_format,
1333 bool structurized)
1334 {
1335 LLVMValueRef args[5];
1336 int idx = 0;
1337 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1338 if (structurized)
1339 args[idx++] = vindex ? vindex : ctx->i32_0;
1340 args[idx++] = voffset ? voffset : ctx->i32_0;
1341 args[idx++] = soffset ? soffset : ctx->i32_0;
1342 args[idx++] = LLVMConstInt(ctx->i32, (glc ? 1 : 0) + (slc ? 2 : 0), 0);
1343 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1344
1345 LLVMTypeRef types[] = {ctx->f32, ctx->v2f32, ctx->v4f32};
1346 const char *type_names[] = {"f32", "v2f32", "v4f32"};
1347 const char *indexing_kind = structurized ? "struct" : "raw";
1348 char name[256];
1349
1350 if (use_format) {
1351 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.format.%s",
1352 indexing_kind, type_names[func]);
1353 } else {
1354 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.%s",
1355 indexing_kind, type_names[func]);
1356 }
1357
1358 return ac_build_intrinsic(ctx, name, types[func], args,
1359 idx,
1360 ac_get_load_intr_attribs(can_speculate));
1361 }
1362
1363 LLVMValueRef
1364 ac_build_buffer_load(struct ac_llvm_context *ctx,
1365 LLVMValueRef rsrc,
1366 int num_channels,
1367 LLVMValueRef vindex,
1368 LLVMValueRef voffset,
1369 LLVMValueRef soffset,
1370 unsigned inst_offset,
1371 unsigned glc,
1372 unsigned slc,
1373 bool can_speculate,
1374 bool allow_smem)
1375 {
1376 LLVMValueRef offset = LLVMConstInt(ctx->i32, inst_offset, 0);
1377 if (voffset)
1378 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
1379 if (soffset)
1380 offset = LLVMBuildAdd(ctx->builder, offset, soffset, "");
1381
1382 if (allow_smem && !slc &&
1383 (!glc || (HAVE_LLVM >= 0x0800 && ctx->chip_class >= VI))) {
1384 assert(vindex == NULL);
1385
1386 LLVMValueRef result[8];
1387
1388 for (int i = 0; i < num_channels; i++) {
1389 if (i) {
1390 offset = LLVMBuildAdd(ctx->builder, offset,
1391 LLVMConstInt(ctx->i32, 4, 0), "");
1392 }
1393 const char *intrname =
1394 HAVE_LLVM >= 0x0800 ? "llvm.amdgcn.s.buffer.load.f32"
1395 : "llvm.SI.load.const.v4i32";
1396 unsigned num_args = HAVE_LLVM >= 0x0800 ? 3 : 2;
1397 LLVMValueRef args[3] = {
1398 rsrc,
1399 offset,
1400 glc ? ctx->i32_1 : ctx->i32_0,
1401 };
1402 result[i] = ac_build_intrinsic(ctx, intrname,
1403 ctx->f32, args, num_args,
1404 AC_FUNC_ATTR_READNONE |
1405 (HAVE_LLVM < 0x0800 ? AC_FUNC_ATTR_LEGACY : 0));
1406 }
1407 if (num_channels == 1)
1408 return result[0];
1409
1410 if (num_channels == 3)
1411 result[num_channels++] = LLVMGetUndef(ctx->f32);
1412 return ac_build_gather_values(ctx, result, num_channels);
1413 }
1414
1415 return ac_build_buffer_load_common(ctx, rsrc, vindex, offset,
1416 num_channels, glc, slc,
1417 can_speculate, false);
1418 }
1419
1420 LLVMValueRef ac_build_buffer_load_format(struct ac_llvm_context *ctx,
1421 LLVMValueRef rsrc,
1422 LLVMValueRef vindex,
1423 LLVMValueRef voffset,
1424 unsigned num_channels,
1425 bool glc,
1426 bool can_speculate)
1427 {
1428 if (HAVE_LLVM >= 0x800) {
1429 return ac_build_llvm8_buffer_load_common(ctx, rsrc, vindex, voffset, ctx->i32_0,
1430 num_channels, glc, false,
1431 can_speculate, true, true);
1432 }
1433 return ac_build_buffer_load_common(ctx, rsrc, vindex, voffset,
1434 num_channels, glc, false,
1435 can_speculate, true);
1436 }
1437
1438 LLVMValueRef ac_build_buffer_load_format_gfx9_safe(struct ac_llvm_context *ctx,
1439 LLVMValueRef rsrc,
1440 LLVMValueRef vindex,
1441 LLVMValueRef voffset,
1442 unsigned num_channels,
1443 bool glc,
1444 bool can_speculate)
1445 {
1446 if (HAVE_LLVM >= 0x800) {
1447 return ac_build_llvm8_buffer_load_common(ctx, rsrc, vindex, voffset, ctx->i32_0,
1448 num_channels, glc, false,
1449 can_speculate, true, true);
1450 }
1451
1452 LLVMValueRef elem_count = LLVMBuildExtractElement(ctx->builder, rsrc, LLVMConstInt(ctx->i32, 2, 0), "");
1453 LLVMValueRef stride = LLVMBuildExtractElement(ctx->builder, rsrc, ctx->i32_1, "");
1454 stride = LLVMBuildLShr(ctx->builder, stride, LLVMConstInt(ctx->i32, 16, 0), "");
1455
1456 LLVMValueRef new_elem_count = LLVMBuildSelect(ctx->builder,
1457 LLVMBuildICmp(ctx->builder, LLVMIntUGT, elem_count, stride, ""),
1458 elem_count, stride, "");
1459
1460 LLVMValueRef new_rsrc = LLVMBuildInsertElement(ctx->builder, rsrc, new_elem_count,
1461 LLVMConstInt(ctx->i32, 2, 0), "");
1462
1463 return ac_build_buffer_load_common(ctx, new_rsrc, vindex, voffset,
1464 num_channels, glc, false,
1465 can_speculate, true);
1466 }
1467
1468 static LLVMValueRef
1469 ac_build_llvm8_tbuffer_load(struct ac_llvm_context *ctx,
1470 LLVMValueRef rsrc,
1471 LLVMValueRef vindex,
1472 LLVMValueRef voffset,
1473 LLVMValueRef soffset,
1474 unsigned num_channels,
1475 unsigned dfmt,
1476 unsigned nfmt,
1477 bool glc,
1478 bool slc,
1479 bool can_speculate,
1480 bool structurized)
1481 {
1482 LLVMValueRef args[6];
1483 int idx = 0;
1484 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1485 if (structurized)
1486 args[idx++] = vindex ? vindex : ctx->i32_0;
1487 args[idx++] = voffset ? voffset : ctx->i32_0;
1488 args[idx++] = soffset ? soffset : ctx->i32_0;
1489 args[idx++] = LLVMConstInt(ctx->i32, dfmt | (nfmt << 4), 0);
1490 args[idx++] = LLVMConstInt(ctx->i32, (glc ? 1 : 0) + (slc ? 2 : 0), 0);
1491 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1492
1493 LLVMTypeRef types[] = {ctx->i32, ctx->v2i32, ctx->v4i32};
1494 const char *type_names[] = {"i32", "v2i32", "v4i32"};
1495 const char *indexing_kind = structurized ? "struct" : "raw";
1496 char name[256];
1497
1498 snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.load.%s",
1499 indexing_kind, type_names[func]);
1500
1501 return ac_build_intrinsic(ctx, name, types[func], args,
1502 idx,
1503 ac_get_load_intr_attribs(can_speculate));
1504 }
1505
1506 static LLVMValueRef
1507 ac_build_tbuffer_load(struct ac_llvm_context *ctx,
1508 LLVMValueRef rsrc,
1509 LLVMValueRef vindex,
1510 LLVMValueRef voffset,
1511 LLVMValueRef soffset,
1512 LLVMValueRef immoffset,
1513 unsigned num_channels,
1514 unsigned dfmt,
1515 unsigned nfmt,
1516 bool glc,
1517 bool slc,
1518 bool can_speculate,
1519 bool structurized) /* only matters for LLVM 8+ */
1520 {
1521 if (HAVE_LLVM >= 0x800) {
1522 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1523
1524 return ac_build_llvm8_tbuffer_load(ctx, rsrc, vindex, voffset,
1525 soffset, num_channels,
1526 dfmt, nfmt, glc, slc,
1527 can_speculate, structurized);
1528 }
1529
1530 LLVMValueRef args[] = {
1531 rsrc,
1532 vindex ? vindex : ctx->i32_0,
1533 voffset,
1534 soffset,
1535 immoffset,
1536 LLVMConstInt(ctx->i32, dfmt, false),
1537 LLVMConstInt(ctx->i32, nfmt, false),
1538 LLVMConstInt(ctx->i32, glc, false),
1539 LLVMConstInt(ctx->i32, slc, false),
1540 };
1541 unsigned func = CLAMP(num_channels, 1, 3) - 1;
1542 LLVMTypeRef types[] = {ctx->i32, ctx->v2i32, ctx->v4i32};
1543 const char *type_names[] = {"i32", "v2i32", "v4i32"};
1544 char name[256];
1545
1546 snprintf(name, sizeof(name), "llvm.amdgcn.tbuffer.load.%s",
1547 type_names[func]);
1548
1549 return ac_build_intrinsic(ctx, name, types[func], args, 9,
1550 ac_get_load_intr_attribs(can_speculate));
1551 }
1552
1553 LLVMValueRef
1554 ac_build_struct_tbuffer_load(struct ac_llvm_context *ctx,
1555 LLVMValueRef rsrc,
1556 LLVMValueRef vindex,
1557 LLVMValueRef voffset,
1558 LLVMValueRef soffset,
1559 LLVMValueRef immoffset,
1560 unsigned num_channels,
1561 unsigned dfmt,
1562 unsigned nfmt,
1563 bool glc,
1564 bool slc,
1565 bool can_speculate)
1566 {
1567 return ac_build_tbuffer_load(ctx, rsrc, vindex, voffset, soffset,
1568 immoffset, num_channels, dfmt, nfmt, glc,
1569 slc, can_speculate, true);
1570 }
1571
1572 LLVMValueRef
1573 ac_build_raw_tbuffer_load(struct ac_llvm_context *ctx,
1574 LLVMValueRef rsrc,
1575 LLVMValueRef voffset,
1576 LLVMValueRef soffset,
1577 LLVMValueRef immoffset,
1578 unsigned num_channels,
1579 unsigned dfmt,
1580 unsigned nfmt,
1581 bool glc,
1582 bool slc,
1583 bool can_speculate)
1584 {
1585 return ac_build_tbuffer_load(ctx, rsrc, NULL, voffset, soffset,
1586 immoffset, num_channels, dfmt, nfmt, glc,
1587 slc, can_speculate, false);
1588 }
1589
1590 LLVMValueRef
1591 ac_build_tbuffer_load_short(struct ac_llvm_context *ctx,
1592 LLVMValueRef rsrc,
1593 LLVMValueRef voffset,
1594 LLVMValueRef soffset,
1595 LLVMValueRef immoffset,
1596 bool glc)
1597 {
1598 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
1599 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1600 LLVMValueRef res;
1601
1602 res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
1603 immoffset, 1, dfmt, nfmt, glc, false,
1604 false);
1605
1606 return LLVMBuildTrunc(ctx->builder, res, ctx->i16, "");
1607 }
1608
1609 /**
1610 * Set range metadata on an instruction. This can only be used on load and
1611 * call instructions. If you know an instruction can only produce the values
1612 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
1613 * \p lo is the minimum value inclusive.
1614 * \p hi is the maximum value exclusive.
1615 */
1616 static void set_range_metadata(struct ac_llvm_context *ctx,
1617 LLVMValueRef value, unsigned lo, unsigned hi)
1618 {
1619 LLVMValueRef range_md, md_args[2];
1620 LLVMTypeRef type = LLVMTypeOf(value);
1621 LLVMContextRef context = LLVMGetTypeContext(type);
1622
1623 md_args[0] = LLVMConstInt(type, lo, false);
1624 md_args[1] = LLVMConstInt(type, hi, false);
1625 range_md = LLVMMDNodeInContext(context, md_args, 2);
1626 LLVMSetMetadata(value, ctx->range_md_kind, range_md);
1627 }
1628
1629 LLVMValueRef
1630 ac_get_thread_id(struct ac_llvm_context *ctx)
1631 {
1632 LLVMValueRef tid;
1633
1634 LLVMValueRef tid_args[2];
1635 tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
1636 tid_args[1] = ctx->i32_0;
1637 tid_args[1] = ac_build_intrinsic(ctx,
1638 "llvm.amdgcn.mbcnt.lo", ctx->i32,
1639 tid_args, 2, AC_FUNC_ATTR_READNONE);
1640
1641 tid = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi",
1642 ctx->i32, tid_args,
1643 2, AC_FUNC_ATTR_READNONE);
1644 set_range_metadata(ctx, tid, 0, 64);
1645 return tid;
1646 }
1647
1648 /*
1649 * SI implements derivatives using the local data store (LDS)
1650 * All writes to the LDS happen in all executing threads at
1651 * the same time. TID is the Thread ID for the current
1652 * thread and is a value between 0 and 63, representing
1653 * the thread's position in the wavefront.
1654 *
1655 * For the pixel shader threads are grouped into quads of four pixels.
1656 * The TIDs of the pixels of a quad are:
1657 *
1658 * +------+------+
1659 * |4n + 0|4n + 1|
1660 * +------+------+
1661 * |4n + 2|4n + 3|
1662 * +------+------+
1663 *
1664 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
1665 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
1666 * the current pixel's column, and masking with 0xfffffffe yields the TID
1667 * of the left pixel of the current pixel's row.
1668 *
1669 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
1670 * adding 2 yields the TID of the pixel below the top pixel.
1671 */
1672 LLVMValueRef
1673 ac_build_ddxy(struct ac_llvm_context *ctx,
1674 uint32_t mask,
1675 int idx,
1676 LLVMValueRef val)
1677 {
1678 unsigned tl_lanes[4], trbl_lanes[4];
1679 LLVMValueRef tl, trbl;
1680 LLVMValueRef result;
1681
1682 for (unsigned i = 0; i < 4; ++i) {
1683 tl_lanes[i] = i & mask;
1684 trbl_lanes[i] = (i & mask) + idx;
1685 }
1686
1687 tl = ac_build_quad_swizzle(ctx, val,
1688 tl_lanes[0], tl_lanes[1],
1689 tl_lanes[2], tl_lanes[3]);
1690 trbl = ac_build_quad_swizzle(ctx, val,
1691 trbl_lanes[0], trbl_lanes[1],
1692 trbl_lanes[2], trbl_lanes[3]);
1693
1694 tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
1695 trbl = LLVMBuildBitCast(ctx->builder, trbl, ctx->f32, "");
1696 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
1697
1698 result = ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.f32", ctx->f32,
1699 &result, 1, 0);
1700
1701 return result;
1702 }
1703
1704 void
1705 ac_build_sendmsg(struct ac_llvm_context *ctx,
1706 uint32_t msg,
1707 LLVMValueRef wave_id)
1708 {
1709 LLVMValueRef args[2];
1710 args[0] = LLVMConstInt(ctx->i32, msg, false);
1711 args[1] = wave_id;
1712 ac_build_intrinsic(ctx, "llvm.amdgcn.s.sendmsg", ctx->voidt, args, 2, 0);
1713 }
1714
1715 LLVMValueRef
1716 ac_build_imsb(struct ac_llvm_context *ctx,
1717 LLVMValueRef arg,
1718 LLVMTypeRef dst_type)
1719 {
1720 LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.amdgcn.sffbh.i32",
1721 dst_type, &arg, 1,
1722 AC_FUNC_ATTR_READNONE);
1723
1724 /* The HW returns the last bit index from MSB, but NIR/TGSI wants
1725 * the index from LSB. Invert it by doing "31 - msb". */
1726 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
1727 msb, "");
1728
1729 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
1730 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
1731 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1732 arg, ctx->i32_0, ""),
1733 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1734 arg, all_ones, ""), "");
1735
1736 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
1737 }
1738
1739 LLVMValueRef
1740 ac_build_umsb(struct ac_llvm_context *ctx,
1741 LLVMValueRef arg,
1742 LLVMTypeRef dst_type)
1743 {
1744 const char *intrin_name;
1745 LLVMTypeRef type;
1746 LLVMValueRef highest_bit;
1747 LLVMValueRef zero;
1748 unsigned bitsize;
1749
1750 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(arg));
1751 switch (bitsize) {
1752 case 64:
1753 intrin_name = "llvm.ctlz.i64";
1754 type = ctx->i64;
1755 highest_bit = LLVMConstInt(ctx->i64, 63, false);
1756 zero = ctx->i64_0;
1757 break;
1758 case 32:
1759 intrin_name = "llvm.ctlz.i32";
1760 type = ctx->i32;
1761 highest_bit = LLVMConstInt(ctx->i32, 31, false);
1762 zero = ctx->i32_0;
1763 break;
1764 case 16:
1765 intrin_name = "llvm.ctlz.i16";
1766 type = ctx->i16;
1767 highest_bit = LLVMConstInt(ctx->i16, 15, false);
1768 zero = ctx->i16_0;
1769 break;
1770 default:
1771 unreachable(!"invalid bitsize");
1772 break;
1773 }
1774
1775 LLVMValueRef params[2] = {
1776 arg,
1777 ctx->i1true,
1778 };
1779
1780 LLVMValueRef msb = ac_build_intrinsic(ctx, intrin_name, type,
1781 params, 2,
1782 AC_FUNC_ATTR_READNONE);
1783
1784 /* The HW returns the last bit index from MSB, but TGSI/NIR wants
1785 * the index from LSB. Invert it by doing "31 - msb". */
1786 msb = LLVMBuildSub(ctx->builder, highest_bit, msb, "");
1787 msb = LLVMBuildTruncOrBitCast(ctx->builder, msb, ctx->i32, "");
1788
1789 /* check for zero */
1790 return LLVMBuildSelect(ctx->builder,
1791 LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg, zero, ""),
1792 LLVMConstInt(ctx->i32, -1, true), msb, "");
1793 }
1794
1795 LLVMValueRef ac_build_fmin(struct ac_llvm_context *ctx, LLVMValueRef a,
1796 LLVMValueRef b)
1797 {
1798 char name[64];
1799 snprintf(name, sizeof(name), "llvm.minnum.f%d", ac_get_elem_bits(ctx, LLVMTypeOf(a)));
1800 LLVMValueRef args[2] = {a, b};
1801 return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
1802 AC_FUNC_ATTR_READNONE);
1803 }
1804
1805 LLVMValueRef ac_build_fmax(struct ac_llvm_context *ctx, LLVMValueRef a,
1806 LLVMValueRef b)
1807 {
1808 char name[64];
1809 snprintf(name, sizeof(name), "llvm.maxnum.f%d", ac_get_elem_bits(ctx, LLVMTypeOf(a)));
1810 LLVMValueRef args[2] = {a, b};
1811 return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
1812 AC_FUNC_ATTR_READNONE);
1813 }
1814
1815 LLVMValueRef ac_build_imin(struct ac_llvm_context *ctx, LLVMValueRef a,
1816 LLVMValueRef b)
1817 {
1818 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSLE, a, b, "");
1819 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1820 }
1821
1822 LLVMValueRef ac_build_imax(struct ac_llvm_context *ctx, LLVMValueRef a,
1823 LLVMValueRef b)
1824 {
1825 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, a, b, "");
1826 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1827 }
1828
1829 LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
1830 LLVMValueRef b)
1831 {
1832 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
1833 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1834 }
1835
1836 LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
1837 {
1838 LLVMTypeRef t = LLVMTypeOf(value);
1839 return ac_build_fmin(ctx, ac_build_fmax(ctx, value, LLVMConstReal(t, 0.0)),
1840 LLVMConstReal(t, 1.0));
1841 }
1842
1843 void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
1844 {
1845 LLVMValueRef args[9];
1846
1847 args[0] = LLVMConstInt(ctx->i32, a->target, 0);
1848 args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
1849
1850 if (a->compr) {
1851 LLVMTypeRef i16 = LLVMInt16TypeInContext(ctx->context);
1852 LLVMTypeRef v2i16 = LLVMVectorType(i16, 2);
1853
1854 args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
1855 v2i16, "");
1856 args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
1857 v2i16, "");
1858 args[4] = LLVMConstInt(ctx->i1, a->done, 0);
1859 args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1860
1861 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
1862 ctx->voidt, args, 6, 0);
1863 } else {
1864 args[2] = a->out[0];
1865 args[3] = a->out[1];
1866 args[4] = a->out[2];
1867 args[5] = a->out[3];
1868 args[6] = LLVMConstInt(ctx->i1, a->done, 0);
1869 args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1870
1871 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
1872 ctx->voidt, args, 8, 0);
1873 }
1874 }
1875
1876 void ac_build_export_null(struct ac_llvm_context *ctx)
1877 {
1878 struct ac_export_args args;
1879
1880 args.enabled_channels = 0x0; /* enabled channels */
1881 args.valid_mask = 1; /* whether the EXEC mask is valid */
1882 args.done = 1; /* DONE bit */
1883 args.target = V_008DFC_SQ_EXP_NULL;
1884 args.compr = 0; /* COMPR flag (0 = 32-bit export) */
1885 args.out[0] = LLVMGetUndef(ctx->f32); /* R */
1886 args.out[1] = LLVMGetUndef(ctx->f32); /* G */
1887 args.out[2] = LLVMGetUndef(ctx->f32); /* B */
1888 args.out[3] = LLVMGetUndef(ctx->f32); /* A */
1889
1890 ac_build_export(ctx, &args);
1891 }
1892
1893 static unsigned ac_num_coords(enum ac_image_dim dim)
1894 {
1895 switch (dim) {
1896 case ac_image_1d:
1897 return 1;
1898 case ac_image_2d:
1899 case ac_image_1darray:
1900 return 2;
1901 case ac_image_3d:
1902 case ac_image_cube:
1903 case ac_image_2darray:
1904 case ac_image_2dmsaa:
1905 return 3;
1906 case ac_image_2darraymsaa:
1907 return 4;
1908 default:
1909 unreachable("ac_num_coords: bad dim");
1910 }
1911 }
1912
1913 static unsigned ac_num_derivs(enum ac_image_dim dim)
1914 {
1915 switch (dim) {
1916 case ac_image_1d:
1917 case ac_image_1darray:
1918 return 2;
1919 case ac_image_2d:
1920 case ac_image_2darray:
1921 case ac_image_cube:
1922 return 4;
1923 case ac_image_3d:
1924 return 6;
1925 case ac_image_2dmsaa:
1926 case ac_image_2darraymsaa:
1927 default:
1928 unreachable("derivatives not supported");
1929 }
1930 }
1931
1932 static const char *get_atomic_name(enum ac_atomic_op op)
1933 {
1934 switch (op) {
1935 case ac_atomic_swap: return "swap";
1936 case ac_atomic_add: return "add";
1937 case ac_atomic_sub: return "sub";
1938 case ac_atomic_smin: return "smin";
1939 case ac_atomic_umin: return "umin";
1940 case ac_atomic_smax: return "smax";
1941 case ac_atomic_umax: return "umax";
1942 case ac_atomic_and: return "and";
1943 case ac_atomic_or: return "or";
1944 case ac_atomic_xor: return "xor";
1945 }
1946 unreachable("bad atomic op");
1947 }
1948
1949 LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
1950 struct ac_image_args *a)
1951 {
1952 const char *overload[3] = { "", "", "" };
1953 unsigned num_overloads = 0;
1954 LLVMValueRef args[18];
1955 unsigned num_args = 0;
1956 enum ac_image_dim dim = a->dim;
1957
1958 assert(!a->lod || a->lod == ctx->i32_0 || a->lod == ctx->f32_0 ||
1959 !a->level_zero);
1960 assert((a->opcode != ac_image_get_resinfo && a->opcode != ac_image_load_mip &&
1961 a->opcode != ac_image_store_mip) ||
1962 a->lod);
1963 assert(a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
1964 (!a->compare && !a->offset));
1965 assert((a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
1966 a->opcode == ac_image_get_lod) ||
1967 !a->bias);
1968 assert((a->bias ? 1 : 0) +
1969 (a->lod ? 1 : 0) +
1970 (a->level_zero ? 1 : 0) +
1971 (a->derivs[0] ? 1 : 0) <= 1);
1972
1973 if (a->opcode == ac_image_get_lod) {
1974 switch (dim) {
1975 case ac_image_1darray:
1976 dim = ac_image_1d;
1977 break;
1978 case ac_image_2darray:
1979 case ac_image_cube:
1980 dim = ac_image_2d;
1981 break;
1982 default:
1983 break;
1984 }
1985 }
1986
1987 bool sample = a->opcode == ac_image_sample ||
1988 a->opcode == ac_image_gather4 ||
1989 a->opcode == ac_image_get_lod;
1990 bool atomic = a->opcode == ac_image_atomic ||
1991 a->opcode == ac_image_atomic_cmpswap;
1992 LLVMTypeRef coord_type = sample ? ctx->f32 : ctx->i32;
1993
1994 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
1995 args[num_args++] = a->data[0];
1996 if (a->opcode == ac_image_atomic_cmpswap)
1997 args[num_args++] = a->data[1];
1998 }
1999
2000 if (!atomic)
2001 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, false);
2002
2003 if (a->offset)
2004 args[num_args++] = ac_to_integer(ctx, a->offset);
2005 if (a->bias) {
2006 args[num_args++] = ac_to_float(ctx, a->bias);
2007 overload[num_overloads++] = ".f32";
2008 }
2009 if (a->compare)
2010 args[num_args++] = ac_to_float(ctx, a->compare);
2011 if (a->derivs[0]) {
2012 unsigned count = ac_num_derivs(dim);
2013 for (unsigned i = 0; i < count; ++i)
2014 args[num_args++] = ac_to_float(ctx, a->derivs[i]);
2015 overload[num_overloads++] = ".f32";
2016 }
2017 unsigned num_coords =
2018 a->opcode != ac_image_get_resinfo ? ac_num_coords(dim) : 0;
2019 for (unsigned i = 0; i < num_coords; ++i)
2020 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->coords[i], coord_type, "");
2021 if (a->lod)
2022 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->lod, coord_type, "");
2023 overload[num_overloads++] = sample ? ".f32" : ".i32";
2024
2025 args[num_args++] = a->resource;
2026 if (sample) {
2027 args[num_args++] = a->sampler;
2028 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, false);
2029 }
2030
2031 args[num_args++] = ctx->i32_0; /* texfailctrl */
2032 args[num_args++] = LLVMConstInt(ctx->i32, a->cache_policy, false);
2033
2034 const char *name;
2035 const char *atomic_subop = "";
2036 switch (a->opcode) {
2037 case ac_image_sample: name = "sample"; break;
2038 case ac_image_gather4: name = "gather4"; break;
2039 case ac_image_load: name = "load"; break;
2040 case ac_image_load_mip: name = "load.mip"; break;
2041 case ac_image_store: name = "store"; break;
2042 case ac_image_store_mip: name = "store.mip"; break;
2043 case ac_image_atomic:
2044 name = "atomic.";
2045 atomic_subop = get_atomic_name(a->atomic);
2046 break;
2047 case ac_image_atomic_cmpswap:
2048 name = "atomic.";
2049 atomic_subop = "cmpswap";
2050 break;
2051 case ac_image_get_lod: name = "getlod"; break;
2052 case ac_image_get_resinfo: name = "getresinfo"; break;
2053 default: unreachable("invalid image opcode");
2054 }
2055
2056 const char *dimname;
2057 switch (dim) {
2058 case ac_image_1d: dimname = "1d"; break;
2059 case ac_image_2d: dimname = "2d"; break;
2060 case ac_image_3d: dimname = "3d"; break;
2061 case ac_image_cube: dimname = "cube"; break;
2062 case ac_image_1darray: dimname = "1darray"; break;
2063 case ac_image_2darray: dimname = "2darray"; break;
2064 case ac_image_2dmsaa: dimname = "2dmsaa"; break;
2065 case ac_image_2darraymsaa: dimname = "2darraymsaa"; break;
2066 default: unreachable("invalid dim");
2067 }
2068
2069 bool lod_suffix =
2070 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
2071 char intr_name[96];
2072 snprintf(intr_name, sizeof(intr_name),
2073 "llvm.amdgcn.image.%s%s" /* base name */
2074 "%s%s%s" /* sample/gather modifiers */
2075 ".%s.%s%s%s%s", /* dimension and type overloads */
2076 name, atomic_subop,
2077 a->compare ? ".c" : "",
2078 a->bias ? ".b" :
2079 lod_suffix ? ".l" :
2080 a->derivs[0] ? ".d" :
2081 a->level_zero ? ".lz" : "",
2082 a->offset ? ".o" : "",
2083 dimname,
2084 atomic ? "i32" : "v4f32",
2085 overload[0], overload[1], overload[2]);
2086
2087 LLVMTypeRef retty;
2088 if (atomic)
2089 retty = ctx->i32;
2090 else if (a->opcode == ac_image_store || a->opcode == ac_image_store_mip)
2091 retty = ctx->voidt;
2092 else
2093 retty = ctx->v4f32;
2094
2095 LLVMValueRef result =
2096 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
2097 a->attributes);
2098 if (!sample && retty == ctx->v4f32) {
2099 result = LLVMBuildBitCast(ctx->builder, result,
2100 ctx->v4i32, "");
2101 }
2102 return result;
2103 }
2104
2105 LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
2106 LLVMValueRef args[2])
2107 {
2108 LLVMTypeRef v2f16 =
2109 LLVMVectorType(LLVMHalfTypeInContext(ctx->context), 2);
2110
2111 return ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz", v2f16,
2112 args, 2, AC_FUNC_ATTR_READNONE);
2113 }
2114
2115 LLVMValueRef ac_build_cvt_pknorm_i16(struct ac_llvm_context *ctx,
2116 LLVMValueRef args[2])
2117 {
2118 LLVMValueRef res =
2119 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.i16",
2120 ctx->v2i16, args, 2,
2121 AC_FUNC_ATTR_READNONE);
2122 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2123 }
2124
2125 LLVMValueRef ac_build_cvt_pknorm_u16(struct ac_llvm_context *ctx,
2126 LLVMValueRef args[2])
2127 {
2128 LLVMValueRef res =
2129 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.u16",
2130 ctx->v2i16, args, 2,
2131 AC_FUNC_ATTR_READNONE);
2132 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2133 }
2134
2135 /* The 8-bit and 10-bit clamping is for HW workarounds. */
2136 LLVMValueRef ac_build_cvt_pk_i16(struct ac_llvm_context *ctx,
2137 LLVMValueRef args[2], unsigned bits, bool hi)
2138 {
2139 assert(bits == 8 || bits == 10 || bits == 16);
2140
2141 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
2142 bits == 8 ? 127 : bits == 10 ? 511 : 32767, 0);
2143 LLVMValueRef min_rgb = LLVMConstInt(ctx->i32,
2144 bits == 8 ? -128 : bits == 10 ? -512 : -32768, 0);
2145 LLVMValueRef max_alpha =
2146 bits != 10 ? max_rgb : ctx->i32_1;
2147 LLVMValueRef min_alpha =
2148 bits != 10 ? min_rgb : LLVMConstInt(ctx->i32, -2, 0);
2149
2150 /* Clamp. */
2151 if (bits != 16) {
2152 for (int i = 0; i < 2; i++) {
2153 bool alpha = hi && i == 1;
2154 args[i] = ac_build_imin(ctx, args[i],
2155 alpha ? max_alpha : max_rgb);
2156 args[i] = ac_build_imax(ctx, args[i],
2157 alpha ? min_alpha : min_rgb);
2158 }
2159 }
2160
2161 LLVMValueRef res =
2162 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.i16",
2163 ctx->v2i16, args, 2,
2164 AC_FUNC_ATTR_READNONE);
2165 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2166 }
2167
2168 /* The 8-bit and 10-bit clamping is for HW workarounds. */
2169 LLVMValueRef ac_build_cvt_pk_u16(struct ac_llvm_context *ctx,
2170 LLVMValueRef args[2], unsigned bits, bool hi)
2171 {
2172 assert(bits == 8 || bits == 10 || bits == 16);
2173
2174 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
2175 bits == 8 ? 255 : bits == 10 ? 1023 : 65535, 0);
2176 LLVMValueRef max_alpha =
2177 bits != 10 ? max_rgb : LLVMConstInt(ctx->i32, 3, 0);
2178
2179 /* Clamp. */
2180 if (bits != 16) {
2181 for (int i = 0; i < 2; i++) {
2182 bool alpha = hi && i == 1;
2183 args[i] = ac_build_umin(ctx, args[i],
2184 alpha ? max_alpha : max_rgb);
2185 }
2186 }
2187
2188 LLVMValueRef res =
2189 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.u16",
2190 ctx->v2i16, args, 2,
2191 AC_FUNC_ATTR_READNONE);
2192 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2193 }
2194
2195 LLVMValueRef ac_build_wqm_vote(struct ac_llvm_context *ctx, LLVMValueRef i1)
2196 {
2197 return ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.vote", ctx->i1,
2198 &i1, 1, AC_FUNC_ATTR_READNONE);
2199 }
2200
2201 void ac_build_kill_if_false(struct ac_llvm_context *ctx, LLVMValueRef i1)
2202 {
2203 ac_build_intrinsic(ctx, "llvm.amdgcn.kill", ctx->voidt,
2204 &i1, 1, 0);
2205 }
2206
2207 LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
2208 LLVMValueRef offset, LLVMValueRef width,
2209 bool is_signed)
2210 {
2211 LLVMValueRef args[] = {
2212 input,
2213 offset,
2214 width,
2215 };
2216
2217 return ac_build_intrinsic(ctx,
2218 is_signed ? "llvm.amdgcn.sbfe.i32" :
2219 "llvm.amdgcn.ubfe.i32",
2220 ctx->i32, args, 3,
2221 AC_FUNC_ATTR_READNONE);
2222 }
2223
2224 LLVMValueRef ac_build_imad(struct ac_llvm_context *ctx, LLVMValueRef s0,
2225 LLVMValueRef s1, LLVMValueRef s2)
2226 {
2227 return LLVMBuildAdd(ctx->builder,
2228 LLVMBuildMul(ctx->builder, s0, s1, ""), s2, "");
2229 }
2230
2231 LLVMValueRef ac_build_fmad(struct ac_llvm_context *ctx, LLVMValueRef s0,
2232 LLVMValueRef s1, LLVMValueRef s2)
2233 {
2234 return LLVMBuildFAdd(ctx->builder,
2235 LLVMBuildFMul(ctx->builder, s0, s1, ""), s2, "");
2236 }
2237
2238 void ac_build_waitcnt(struct ac_llvm_context *ctx, unsigned simm16)
2239 {
2240 LLVMValueRef args[1] = {
2241 LLVMConstInt(ctx->i32, simm16, false),
2242 };
2243 ac_build_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
2244 ctx->voidt, args, 1, 0);
2245 }
2246
2247 LLVMValueRef ac_build_fract(struct ac_llvm_context *ctx, LLVMValueRef src0,
2248 unsigned bitsize)
2249 {
2250 LLVMTypeRef type;
2251 char *intr;
2252
2253 if (bitsize == 32) {
2254 intr = "llvm.amdgcn.fract.f32";
2255 type = ctx->f32;
2256 } else {
2257 intr = "llvm.amdgcn.fract.f64";
2258 type = ctx->f64;
2259 }
2260
2261 LLVMValueRef params[] = {
2262 src0,
2263 };
2264 return ac_build_intrinsic(ctx, intr, type, params, 1,
2265 AC_FUNC_ATTR_READNONE);
2266 }
2267
2268 LLVMValueRef ac_build_isign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2269 unsigned bitsize)
2270 {
2271 LLVMTypeRef type = LLVMIntTypeInContext(ctx->context, bitsize);
2272 LLVMValueRef zero = LLVMConstInt(type, 0, false);
2273 LLVMValueRef one = LLVMConstInt(type, 1, false);
2274
2275 LLVMValueRef cmp, val;
2276 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, zero, "");
2277 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2278 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, zero, "");
2279 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(type, -1, true), "");
2280 return val;
2281 }
2282
2283 LLVMValueRef ac_build_fsign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2284 unsigned bitsize)
2285 {
2286 LLVMValueRef cmp, val, zero, one;
2287 LLVMTypeRef type;
2288
2289 if (bitsize == 32) {
2290 type = ctx->f32;
2291 zero = ctx->f32_0;
2292 one = ctx->f32_1;
2293 } else {
2294 type = ctx->f64;
2295 zero = ctx->f64_0;
2296 one = ctx->f64_1;
2297 }
2298
2299 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, zero, "");
2300 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2301 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, zero, "");
2302 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(type, -1.0), "");
2303 return val;
2304 }
2305
2306 LLVMValueRef ac_build_bit_count(struct ac_llvm_context *ctx, LLVMValueRef src0)
2307 {
2308 LLVMValueRef result;
2309 unsigned bitsize;
2310
2311 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2312
2313 switch (bitsize) {
2314 case 64:
2315 result = ac_build_intrinsic(ctx, "llvm.ctpop.i64", ctx->i64,
2316 (LLVMValueRef []) { src0 }, 1,
2317 AC_FUNC_ATTR_READNONE);
2318
2319 result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
2320 break;
2321 case 32:
2322 result = ac_build_intrinsic(ctx, "llvm.ctpop.i32", ctx->i32,
2323 (LLVMValueRef []) { src0 }, 1,
2324 AC_FUNC_ATTR_READNONE);
2325 break;
2326 case 16:
2327 result = ac_build_intrinsic(ctx, "llvm.ctpop.i16", ctx->i16,
2328 (LLVMValueRef []) { src0 }, 1,
2329 AC_FUNC_ATTR_READNONE);
2330 break;
2331 default:
2332 unreachable(!"invalid bitsize");
2333 break;
2334 }
2335
2336 return result;
2337 }
2338
2339 LLVMValueRef ac_build_bitfield_reverse(struct ac_llvm_context *ctx,
2340 LLVMValueRef src0)
2341 {
2342 LLVMValueRef result;
2343 unsigned bitsize;
2344
2345 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2346
2347 switch (bitsize) {
2348 case 32:
2349 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i32", ctx->i32,
2350 (LLVMValueRef []) { src0 }, 1,
2351 AC_FUNC_ATTR_READNONE);
2352 break;
2353 case 16:
2354 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i16", ctx->i16,
2355 (LLVMValueRef []) { src0 }, 1,
2356 AC_FUNC_ATTR_READNONE);
2357 break;
2358 default:
2359 unreachable(!"invalid bitsize");
2360 break;
2361 }
2362
2363 return result;
2364 }
2365
2366 #define AC_EXP_TARGET 0
2367 #define AC_EXP_ENABLED_CHANNELS 1
2368 #define AC_EXP_OUT0 2
2369
2370 enum ac_ir_type {
2371 AC_IR_UNDEF,
2372 AC_IR_CONST,
2373 AC_IR_VALUE,
2374 };
2375
2376 struct ac_vs_exp_chan
2377 {
2378 LLVMValueRef value;
2379 float const_float;
2380 enum ac_ir_type type;
2381 };
2382
2383 struct ac_vs_exp_inst {
2384 unsigned offset;
2385 LLVMValueRef inst;
2386 struct ac_vs_exp_chan chan[4];
2387 };
2388
2389 struct ac_vs_exports {
2390 unsigned num;
2391 struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
2392 };
2393
2394 /* Return true if the PARAM export has been eliminated. */
2395 static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
2396 uint32_t num_outputs,
2397 struct ac_vs_exp_inst *exp)
2398 {
2399 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
2400 bool is_zero[4] = {}, is_one[4] = {};
2401
2402 for (i = 0; i < 4; i++) {
2403 /* It's a constant expression. Undef outputs are eliminated too. */
2404 if (exp->chan[i].type == AC_IR_UNDEF) {
2405 is_zero[i] = true;
2406 is_one[i] = true;
2407 } else if (exp->chan[i].type == AC_IR_CONST) {
2408 if (exp->chan[i].const_float == 0)
2409 is_zero[i] = true;
2410 else if (exp->chan[i].const_float == 1)
2411 is_one[i] = true;
2412 else
2413 return false; /* other constant */
2414 } else
2415 return false;
2416 }
2417
2418 /* Only certain combinations of 0 and 1 can be eliminated. */
2419 if (is_zero[0] && is_zero[1] && is_zero[2])
2420 default_val = is_zero[3] ? 0 : 1;
2421 else if (is_one[0] && is_one[1] && is_one[2])
2422 default_val = is_zero[3] ? 2 : 3;
2423 else
2424 return false;
2425
2426 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
2427 LLVMInstructionEraseFromParent(exp->inst);
2428
2429 /* Change OFFSET to DEFAULT_VAL. */
2430 for (i = 0; i < num_outputs; i++) {
2431 if (vs_output_param_offset[i] == exp->offset) {
2432 vs_output_param_offset[i] =
2433 AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
2434 break;
2435 }
2436 }
2437 return true;
2438 }
2439
2440 static bool ac_eliminate_duplicated_output(struct ac_llvm_context *ctx,
2441 uint8_t *vs_output_param_offset,
2442 uint32_t num_outputs,
2443 struct ac_vs_exports *processed,
2444 struct ac_vs_exp_inst *exp)
2445 {
2446 unsigned p, copy_back_channels = 0;
2447
2448 /* See if the output is already in the list of processed outputs.
2449 * The LLVMValueRef comparison relies on SSA.
2450 */
2451 for (p = 0; p < processed->num; p++) {
2452 bool different = false;
2453
2454 for (unsigned j = 0; j < 4; j++) {
2455 struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
2456 struct ac_vs_exp_chan *c2 = &exp->chan[j];
2457
2458 /* Treat undef as a match. */
2459 if (c2->type == AC_IR_UNDEF)
2460 continue;
2461
2462 /* If c1 is undef but c2 isn't, we can copy c2 to c1
2463 * and consider the instruction duplicated.
2464 */
2465 if (c1->type == AC_IR_UNDEF) {
2466 copy_back_channels |= 1 << j;
2467 continue;
2468 }
2469
2470 /* Test whether the channels are not equal. */
2471 if (c1->type != c2->type ||
2472 (c1->type == AC_IR_CONST &&
2473 c1->const_float != c2->const_float) ||
2474 (c1->type == AC_IR_VALUE &&
2475 c1->value != c2->value)) {
2476 different = true;
2477 break;
2478 }
2479 }
2480 if (!different)
2481 break;
2482
2483 copy_back_channels = 0;
2484 }
2485 if (p == processed->num)
2486 return false;
2487
2488 /* If a match was found, but the matching export has undef where the new
2489 * one has a normal value, copy the normal value to the undef channel.
2490 */
2491 struct ac_vs_exp_inst *match = &processed->exp[p];
2492
2493 /* Get current enabled channels mask. */
2494 LLVMValueRef arg = LLVMGetOperand(match->inst, AC_EXP_ENABLED_CHANNELS);
2495 unsigned enabled_channels = LLVMConstIntGetZExtValue(arg);
2496
2497 while (copy_back_channels) {
2498 unsigned chan = u_bit_scan(&copy_back_channels);
2499
2500 assert(match->chan[chan].type == AC_IR_UNDEF);
2501 LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
2502 exp->chan[chan].value);
2503 match->chan[chan] = exp->chan[chan];
2504
2505 /* Update number of enabled channels because the original mask
2506 * is not always 0xf.
2507 */
2508 enabled_channels |= (1 << chan);
2509 LLVMSetOperand(match->inst, AC_EXP_ENABLED_CHANNELS,
2510 LLVMConstInt(ctx->i32, enabled_channels, 0));
2511 }
2512
2513 /* The PARAM export is duplicated. Kill it. */
2514 LLVMInstructionEraseFromParent(exp->inst);
2515
2516 /* Change OFFSET to the matching export. */
2517 for (unsigned i = 0; i < num_outputs; i++) {
2518 if (vs_output_param_offset[i] == exp->offset) {
2519 vs_output_param_offset[i] = match->offset;
2520 break;
2521 }
2522 }
2523 return true;
2524 }
2525
2526 void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
2527 LLVMValueRef main_fn,
2528 uint8_t *vs_output_param_offset,
2529 uint32_t num_outputs,
2530 uint8_t *num_param_exports)
2531 {
2532 LLVMBasicBlockRef bb;
2533 bool removed_any = false;
2534 struct ac_vs_exports exports;
2535
2536 exports.num = 0;
2537
2538 /* Process all LLVM instructions. */
2539 bb = LLVMGetFirstBasicBlock(main_fn);
2540 while (bb) {
2541 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
2542
2543 while (inst) {
2544 LLVMValueRef cur = inst;
2545 inst = LLVMGetNextInstruction(inst);
2546 struct ac_vs_exp_inst exp;
2547
2548 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
2549 continue;
2550
2551 LLVMValueRef callee = ac_llvm_get_called_value(cur);
2552
2553 if (!ac_llvm_is_function(callee))
2554 continue;
2555
2556 const char *name = LLVMGetValueName(callee);
2557 unsigned num_args = LLVMCountParams(callee);
2558
2559 /* Check if this is an export instruction. */
2560 if ((num_args != 9 && num_args != 8) ||
2561 (strcmp(name, "llvm.SI.export") &&
2562 strcmp(name, "llvm.amdgcn.exp.f32")))
2563 continue;
2564
2565 LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
2566 unsigned target = LLVMConstIntGetZExtValue(arg);
2567
2568 if (target < V_008DFC_SQ_EXP_PARAM)
2569 continue;
2570
2571 target -= V_008DFC_SQ_EXP_PARAM;
2572
2573 /* Parse the instruction. */
2574 memset(&exp, 0, sizeof(exp));
2575 exp.offset = target;
2576 exp.inst = cur;
2577
2578 for (unsigned i = 0; i < 4; i++) {
2579 LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);
2580
2581 exp.chan[i].value = v;
2582
2583 if (LLVMIsUndef(v)) {
2584 exp.chan[i].type = AC_IR_UNDEF;
2585 } else if (LLVMIsAConstantFP(v)) {
2586 LLVMBool loses_info;
2587 exp.chan[i].type = AC_IR_CONST;
2588 exp.chan[i].const_float =
2589 LLVMConstRealGetDouble(v, &loses_info);
2590 } else {
2591 exp.chan[i].type = AC_IR_VALUE;
2592 }
2593 }
2594
2595 /* Eliminate constant and duplicated PARAM exports. */
2596 if (ac_eliminate_const_output(vs_output_param_offset,
2597 num_outputs, &exp) ||
2598 ac_eliminate_duplicated_output(ctx,
2599 vs_output_param_offset,
2600 num_outputs, &exports,
2601 &exp)) {
2602 removed_any = true;
2603 } else {
2604 exports.exp[exports.num++] = exp;
2605 }
2606 }
2607 bb = LLVMGetNextBasicBlock(bb);
2608 }
2609
2610 /* Remove holes in export memory due to removed PARAM exports.
2611 * This is done by renumbering all PARAM exports.
2612 */
2613 if (removed_any) {
2614 uint8_t old_offset[VARYING_SLOT_MAX];
2615 unsigned out, i;
2616
2617 /* Make a copy of the offsets. We need the old version while
2618 * we are modifying some of them. */
2619 memcpy(old_offset, vs_output_param_offset,
2620 sizeof(old_offset));
2621
2622 for (i = 0; i < exports.num; i++) {
2623 unsigned offset = exports.exp[i].offset;
2624
2625 /* Update vs_output_param_offset. Multiple outputs can
2626 * have the same offset.
2627 */
2628 for (out = 0; out < num_outputs; out++) {
2629 if (old_offset[out] == offset)
2630 vs_output_param_offset[out] = i;
2631 }
2632
2633 /* Change the PARAM offset in the instruction. */
2634 LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
2635 LLVMConstInt(ctx->i32,
2636 V_008DFC_SQ_EXP_PARAM + i, 0));
2637 }
2638 *num_param_exports = exports.num;
2639 }
2640 }
2641
2642 void ac_init_exec_full_mask(struct ac_llvm_context *ctx)
2643 {
2644 LLVMValueRef full_mask = LLVMConstInt(ctx->i64, ~0ull, 0);
2645 ac_build_intrinsic(ctx,
2646 "llvm.amdgcn.init.exec", ctx->voidt,
2647 &full_mask, 1, AC_FUNC_ATTR_CONVERGENT);
2648 }
2649
2650 void ac_declare_lds_as_pointer(struct ac_llvm_context *ctx)
2651 {
2652 unsigned lds_size = ctx->chip_class >= CIK ? 65536 : 32768;
2653 ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32_0,
2654 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), AC_ADDR_SPACE_LDS),
2655 "lds");
2656 }
2657
2658 LLVMValueRef ac_lds_load(struct ac_llvm_context *ctx,
2659 LLVMValueRef dw_addr)
2660 {
2661 return ac_build_load(ctx, ctx->lds, dw_addr);
2662 }
2663
2664 void ac_lds_store(struct ac_llvm_context *ctx,
2665 LLVMValueRef dw_addr,
2666 LLVMValueRef value)
2667 {
2668 value = ac_to_integer(ctx, value);
2669 ac_build_indexed_store(ctx, ctx->lds,
2670 dw_addr, value);
2671 }
2672
2673 LLVMValueRef ac_find_lsb(struct ac_llvm_context *ctx,
2674 LLVMTypeRef dst_type,
2675 LLVMValueRef src0)
2676 {
2677 unsigned src0_bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2678 const char *intrin_name;
2679 LLVMTypeRef type;
2680 LLVMValueRef zero;
2681
2682 switch (src0_bitsize) {
2683 case 64:
2684 intrin_name = "llvm.cttz.i64";
2685 type = ctx->i64;
2686 zero = ctx->i64_0;
2687 break;
2688 case 32:
2689 intrin_name = "llvm.cttz.i32";
2690 type = ctx->i32;
2691 zero = ctx->i32_0;
2692 break;
2693 case 16:
2694 intrin_name = "llvm.cttz.i16";
2695 type = ctx->i16;
2696 zero = ctx->i16_0;
2697 break;
2698 default:
2699 unreachable(!"invalid bitsize");
2700 }
2701
2702 LLVMValueRef params[2] = {
2703 src0,
2704
2705 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
2706 * add special code to check for x=0. The reason is that
2707 * the LLVM behavior for x=0 is different from what we
2708 * need here. However, LLVM also assumes that ffs(x) is
2709 * in [0, 31], but GLSL expects that ffs(0) = -1, so
2710 * a conditional assignment to handle 0 is still required.
2711 *
2712 * The hardware already implements the correct behavior.
2713 */
2714 ctx->i1true,
2715 };
2716
2717 LLVMValueRef lsb = ac_build_intrinsic(ctx, intrin_name, type,
2718 params, 2,
2719 AC_FUNC_ATTR_READNONE);
2720
2721 if (src0_bitsize == 64) {
2722 lsb = LLVMBuildTrunc(ctx->builder, lsb, ctx->i32, "");
2723 }
2724
2725 /* TODO: We need an intrinsic to skip this conditional. */
2726 /* Check for zero: */
2727 return LLVMBuildSelect(ctx->builder, LLVMBuildICmp(ctx->builder,
2728 LLVMIntEQ, src0,
2729 zero, ""),
2730 LLVMConstInt(ctx->i32, -1, 0), lsb, "");
2731 }
2732
2733 LLVMTypeRef ac_array_in_const_addr_space(LLVMTypeRef elem_type)
2734 {
2735 return LLVMPointerType(LLVMArrayType(elem_type, 0),
2736 AC_ADDR_SPACE_CONST);
2737 }
2738
2739 LLVMTypeRef ac_array_in_const32_addr_space(LLVMTypeRef elem_type)
2740 {
2741 return LLVMPointerType(LLVMArrayType(elem_type, 0),
2742 AC_ADDR_SPACE_CONST_32BIT);
2743 }
2744
2745 static struct ac_llvm_flow *
2746 get_current_flow(struct ac_llvm_context *ctx)
2747 {
2748 if (ctx->flow_depth > 0)
2749 return &ctx->flow[ctx->flow_depth - 1];
2750 return NULL;
2751 }
2752
2753 static struct ac_llvm_flow *
2754 get_innermost_loop(struct ac_llvm_context *ctx)
2755 {
2756 for (unsigned i = ctx->flow_depth; i > 0; --i) {
2757 if (ctx->flow[i - 1].loop_entry_block)
2758 return &ctx->flow[i - 1];
2759 }
2760 return NULL;
2761 }
2762
2763 static struct ac_llvm_flow *
2764 push_flow(struct ac_llvm_context *ctx)
2765 {
2766 struct ac_llvm_flow *flow;
2767
2768 if (ctx->flow_depth >= ctx->flow_depth_max) {
2769 unsigned new_max = MAX2(ctx->flow_depth << 1,
2770 AC_LLVM_INITIAL_CF_DEPTH);
2771
2772 ctx->flow = realloc(ctx->flow, new_max * sizeof(*ctx->flow));
2773 ctx->flow_depth_max = new_max;
2774 }
2775
2776 flow = &ctx->flow[ctx->flow_depth];
2777 ctx->flow_depth++;
2778
2779 flow->next_block = NULL;
2780 flow->loop_entry_block = NULL;
2781 return flow;
2782 }
2783
2784 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base,
2785 int label_id)
2786 {
2787 char buf[32];
2788 snprintf(buf, sizeof(buf), "%s%d", base, label_id);
2789 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
2790 }
2791
2792 /* Append a basic block at the level of the parent flow.
2793 */
2794 static LLVMBasicBlockRef append_basic_block(struct ac_llvm_context *ctx,
2795 const char *name)
2796 {
2797 assert(ctx->flow_depth >= 1);
2798
2799 if (ctx->flow_depth >= 2) {
2800 struct ac_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];
2801
2802 return LLVMInsertBasicBlockInContext(ctx->context,
2803 flow->next_block, name);
2804 }
2805
2806 LLVMValueRef main_fn =
2807 LLVMGetBasicBlockParent(LLVMGetInsertBlock(ctx->builder));
2808 return LLVMAppendBasicBlockInContext(ctx->context, main_fn, name);
2809 }
2810
2811 /* Emit a branch to the given default target for the current block if
2812 * applicable -- that is, if the current block does not already contain a
2813 * branch from a break or continue.
2814 */
2815 static void emit_default_branch(LLVMBuilderRef builder,
2816 LLVMBasicBlockRef target)
2817 {
2818 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
2819 LLVMBuildBr(builder, target);
2820 }
2821
2822 void ac_build_bgnloop(struct ac_llvm_context *ctx, int label_id)
2823 {
2824 struct ac_llvm_flow *flow = push_flow(ctx);
2825 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
2826 flow->next_block = append_basic_block(ctx, "ENDLOOP");
2827 set_basicblock_name(flow->loop_entry_block, "loop", label_id);
2828 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
2829 LLVMPositionBuilderAtEnd(ctx->builder, flow->loop_entry_block);
2830 }
2831
2832 void ac_build_break(struct ac_llvm_context *ctx)
2833 {
2834 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
2835 LLVMBuildBr(ctx->builder, flow->next_block);
2836 }
2837
2838 void ac_build_continue(struct ac_llvm_context *ctx)
2839 {
2840 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
2841 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
2842 }
2843
2844 void ac_build_else(struct ac_llvm_context *ctx, int label_id)
2845 {
2846 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
2847 LLVMBasicBlockRef endif_block;
2848
2849 assert(!current_branch->loop_entry_block);
2850
2851 endif_block = append_basic_block(ctx, "ENDIF");
2852 emit_default_branch(ctx->builder, endif_block);
2853
2854 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
2855 set_basicblock_name(current_branch->next_block, "else", label_id);
2856
2857 current_branch->next_block = endif_block;
2858 }
2859
2860 void ac_build_endif(struct ac_llvm_context *ctx, int label_id)
2861 {
2862 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
2863
2864 assert(!current_branch->loop_entry_block);
2865
2866 emit_default_branch(ctx->builder, current_branch->next_block);
2867 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
2868 set_basicblock_name(current_branch->next_block, "endif", label_id);
2869
2870 ctx->flow_depth--;
2871 }
2872
2873 void ac_build_endloop(struct ac_llvm_context *ctx, int label_id)
2874 {
2875 struct ac_llvm_flow *current_loop = get_current_flow(ctx);
2876
2877 assert(current_loop->loop_entry_block);
2878
2879 emit_default_branch(ctx->builder, current_loop->loop_entry_block);
2880
2881 LLVMPositionBuilderAtEnd(ctx->builder, current_loop->next_block);
2882 set_basicblock_name(current_loop->next_block, "endloop", label_id);
2883 ctx->flow_depth--;
2884 }
2885
2886 void ac_build_ifcc(struct ac_llvm_context *ctx, LLVMValueRef cond, int label_id)
2887 {
2888 struct ac_llvm_flow *flow = push_flow(ctx);
2889 LLVMBasicBlockRef if_block;
2890
2891 if_block = append_basic_block(ctx, "IF");
2892 flow->next_block = append_basic_block(ctx, "ELSE");
2893 set_basicblock_name(if_block, "if", label_id);
2894 LLVMBuildCondBr(ctx->builder, cond, if_block, flow->next_block);
2895 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
2896 }
2897
2898 void ac_build_if(struct ac_llvm_context *ctx, LLVMValueRef value,
2899 int label_id)
2900 {
2901 LLVMValueRef cond = LLVMBuildFCmp(ctx->builder, LLVMRealUNE,
2902 value, ctx->f32_0, "");
2903 ac_build_ifcc(ctx, cond, label_id);
2904 }
2905
2906 void ac_build_uif(struct ac_llvm_context *ctx, LLVMValueRef value,
2907 int label_id)
2908 {
2909 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
2910 ac_to_integer(ctx, value),
2911 ctx->i32_0, "");
2912 ac_build_ifcc(ctx, cond, label_id);
2913 }
2914
2915 LLVMValueRef ac_build_alloca_undef(struct ac_llvm_context *ac, LLVMTypeRef type,
2916 const char *name)
2917 {
2918 LLVMBuilderRef builder = ac->builder;
2919 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
2920 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
2921 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
2922 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
2923 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ac->context);
2924 LLVMValueRef res;
2925
2926 if (first_instr) {
2927 LLVMPositionBuilderBefore(first_builder, first_instr);
2928 } else {
2929 LLVMPositionBuilderAtEnd(first_builder, first_block);
2930 }
2931
2932 res = LLVMBuildAlloca(first_builder, type, name);
2933 LLVMDisposeBuilder(first_builder);
2934 return res;
2935 }
2936
2937 LLVMValueRef ac_build_alloca(struct ac_llvm_context *ac,
2938 LLVMTypeRef type, const char *name)
2939 {
2940 LLVMValueRef ptr = ac_build_alloca_undef(ac, type, name);
2941 LLVMBuildStore(ac->builder, LLVMConstNull(type), ptr);
2942 return ptr;
2943 }
2944
2945 LLVMValueRef ac_cast_ptr(struct ac_llvm_context *ctx, LLVMValueRef ptr,
2946 LLVMTypeRef type)
2947 {
2948 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
2949 return LLVMBuildBitCast(ctx->builder, ptr,
2950 LLVMPointerType(type, addr_space), "");
2951 }
2952
2953 LLVMValueRef ac_trim_vector(struct ac_llvm_context *ctx, LLVMValueRef value,
2954 unsigned count)
2955 {
2956 unsigned num_components = ac_get_llvm_num_components(value);
2957 if (count == num_components)
2958 return value;
2959
2960 LLVMValueRef masks[MAX2(count, 2)];
2961 masks[0] = ctx->i32_0;
2962 masks[1] = ctx->i32_1;
2963 for (unsigned i = 2; i < count; i++)
2964 masks[i] = LLVMConstInt(ctx->i32, i, false);
2965
2966 if (count == 1)
2967 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
2968 "");
2969
2970 LLVMValueRef swizzle = LLVMConstVector(masks, count);
2971 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
2972 }
2973
2974 LLVMValueRef ac_unpack_param(struct ac_llvm_context *ctx, LLVMValueRef param,
2975 unsigned rshift, unsigned bitwidth)
2976 {
2977 LLVMValueRef value = param;
2978 if (rshift)
2979 value = LLVMBuildLShr(ctx->builder, value,
2980 LLVMConstInt(ctx->i32, rshift, false), "");
2981
2982 if (rshift + bitwidth < 32) {
2983 unsigned mask = (1 << bitwidth) - 1;
2984 value = LLVMBuildAnd(ctx->builder, value,
2985 LLVMConstInt(ctx->i32, mask, false), "");
2986 }
2987 return value;
2988 }
2989
2990 /* Adjust the sample index according to FMASK.
2991 *
2992 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
2993 * which is the identity mapping. Each nibble says which physical sample
2994 * should be fetched to get that sample.
2995 *
2996 * For example, 0x11111100 means there are only 2 samples stored and
2997 * the second sample covers 3/4 of the pixel. When reading samples 0
2998 * and 1, return physical sample 0 (determined by the first two 0s
2999 * in FMASK), otherwise return physical sample 1.
3000 *
3001 * The sample index should be adjusted as follows:
3002 * addr[sample_index] = (fmask >> (addr[sample_index] * 4)) & 0xF;
3003 */
3004 void ac_apply_fmask_to_sample(struct ac_llvm_context *ac, LLVMValueRef fmask,
3005 LLVMValueRef *addr, bool is_array_tex)
3006 {
3007 struct ac_image_args fmask_load = {};
3008 fmask_load.opcode = ac_image_load;
3009 fmask_load.resource = fmask;
3010 fmask_load.dmask = 0xf;
3011 fmask_load.dim = is_array_tex ? ac_image_2darray : ac_image_2d;
3012
3013 fmask_load.coords[0] = addr[0];
3014 fmask_load.coords[1] = addr[1];
3015 if (is_array_tex)
3016 fmask_load.coords[2] = addr[2];
3017
3018 LLVMValueRef fmask_value = ac_build_image_opcode(ac, &fmask_load);
3019 fmask_value = LLVMBuildExtractElement(ac->builder, fmask_value,
3020 ac->i32_0, "");
3021
3022 /* Apply the formula. */
3023 unsigned sample_chan = is_array_tex ? 3 : 2;
3024 LLVMValueRef final_sample;
3025 final_sample = LLVMBuildMul(ac->builder, addr[sample_chan],
3026 LLVMConstInt(ac->i32, 4, 0), "");
3027 final_sample = LLVMBuildLShr(ac->builder, fmask_value, final_sample, "");
3028 /* Mask the sample index by 0x7, because 0x8 means an unknown value
3029 * with EQAA, so those will map to 0. */
3030 final_sample = LLVMBuildAnd(ac->builder, final_sample,
3031 LLVMConstInt(ac->i32, 0x7, 0), "");
3032
3033 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
3034 * resource descriptor is 0 (invalid).
3035 */
3036 LLVMValueRef tmp;
3037 tmp = LLVMBuildBitCast(ac->builder, fmask, ac->v8i32, "");
3038 tmp = LLVMBuildExtractElement(ac->builder, tmp, ac->i32_1, "");
3039 tmp = LLVMBuildICmp(ac->builder, LLVMIntNE, tmp, ac->i32_0, "");
3040
3041 /* Replace the MSAA sample index. */
3042 addr[sample_chan] = LLVMBuildSelect(ac->builder, tmp, final_sample,
3043 addr[sample_chan], "");
3044 }
3045
3046 static LLVMValueRef
3047 _ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
3048 {
3049 ac_build_optimization_barrier(ctx, &src);
3050 return ac_build_intrinsic(ctx,
3051 lane == NULL ? "llvm.amdgcn.readfirstlane" : "llvm.amdgcn.readlane",
3052 LLVMTypeOf(src), (LLVMValueRef []) {
3053 src, lane },
3054 lane == NULL ? 1 : 2,
3055 AC_FUNC_ATTR_READNONE |
3056 AC_FUNC_ATTR_CONVERGENT);
3057 }
3058
3059 /**
3060 * Builds the "llvm.amdgcn.readlane" or "llvm.amdgcn.readfirstlane" intrinsic.
3061 * @param ctx
3062 * @param src
3063 * @param lane - id of the lane or NULL for the first active lane
3064 * @return value of the lane
3065 */
3066 LLVMValueRef
3067 ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
3068 {
3069 LLVMTypeRef src_type = LLVMTypeOf(src);
3070 src = ac_to_integer(ctx, src);
3071 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3072 LLVMValueRef ret;
3073
3074 if (bits == 32) {
3075 ret = _ac_build_readlane(ctx, src, lane);
3076 } else {
3077 assert(bits % 32 == 0);
3078 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3079 LLVMValueRef src_vector =
3080 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3081 ret = LLVMGetUndef(vec_type);
3082 for (unsigned i = 0; i < bits / 32; i++) {
3083 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3084 LLVMConstInt(ctx->i32, i, 0), "");
3085 LLVMValueRef ret_comp = _ac_build_readlane(ctx, src, lane);
3086 ret = LLVMBuildInsertElement(ctx->builder, ret, ret_comp,
3087 LLVMConstInt(ctx->i32, i, 0), "");
3088 }
3089 }
3090 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3091 }
3092
3093 LLVMValueRef
3094 ac_build_writelane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef value, LLVMValueRef lane)
3095 {
3096 /* TODO: Use the actual instruction when LLVM adds an intrinsic for it.
3097 */
3098 LLVMValueRef pred = LLVMBuildICmp(ctx->builder, LLVMIntEQ, lane,
3099 ac_get_thread_id(ctx), "");
3100 return LLVMBuildSelect(ctx->builder, pred, value, src, "");
3101 }
3102
3103 LLVMValueRef
3104 ac_build_mbcnt(struct ac_llvm_context *ctx, LLVMValueRef mask)
3105 {
3106 LLVMValueRef mask_vec = LLVMBuildBitCast(ctx->builder, mask,
3107 LLVMVectorType(ctx->i32, 2),
3108 "");
3109 LLVMValueRef mask_lo = LLVMBuildExtractElement(ctx->builder, mask_vec,
3110 ctx->i32_0, "");
3111 LLVMValueRef mask_hi = LLVMBuildExtractElement(ctx->builder, mask_vec,
3112 ctx->i32_1, "");
3113 LLVMValueRef val =
3114 ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
3115 (LLVMValueRef []) { mask_lo, ctx->i32_0 },
3116 2, AC_FUNC_ATTR_READNONE);
3117 val = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi", ctx->i32,
3118 (LLVMValueRef []) { mask_hi, val },
3119 2, AC_FUNC_ATTR_READNONE);
3120 return val;
3121 }
3122
3123 enum dpp_ctrl {
3124 _dpp_quad_perm = 0x000,
3125 _dpp_row_sl = 0x100,
3126 _dpp_row_sr = 0x110,
3127 _dpp_row_rr = 0x120,
3128 dpp_wf_sl1 = 0x130,
3129 dpp_wf_rl1 = 0x134,
3130 dpp_wf_sr1 = 0x138,
3131 dpp_wf_rr1 = 0x13C,
3132 dpp_row_mirror = 0x140,
3133 dpp_row_half_mirror = 0x141,
3134 dpp_row_bcast15 = 0x142,
3135 dpp_row_bcast31 = 0x143
3136 };
3137
3138 static inline enum dpp_ctrl
3139 dpp_quad_perm(unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
3140 {
3141 assert(lane0 < 4 && lane1 < 4 && lane2 < 4 && lane3 < 4);
3142 return _dpp_quad_perm | lane0 | (lane1 << 2) | (lane2 << 4) | (lane3 << 6);
3143 }
3144
3145 static inline enum dpp_ctrl
3146 dpp_row_sl(unsigned amount)
3147 {
3148 assert(amount > 0 && amount < 16);
3149 return _dpp_row_sl | amount;
3150 }
3151
3152 static inline enum dpp_ctrl
3153 dpp_row_sr(unsigned amount)
3154 {
3155 assert(amount > 0 && amount < 16);
3156 return _dpp_row_sr | amount;
3157 }
3158
3159 static LLVMValueRef
3160 _ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
3161 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
3162 bool bound_ctrl)
3163 {
3164 return ac_build_intrinsic(ctx, "llvm.amdgcn.update.dpp.i32",
3165 LLVMTypeOf(old),
3166 (LLVMValueRef[]) {
3167 old, src,
3168 LLVMConstInt(ctx->i32, dpp_ctrl, 0),
3169 LLVMConstInt(ctx->i32, row_mask, 0),
3170 LLVMConstInt(ctx->i32, bank_mask, 0),
3171 LLVMConstInt(ctx->i1, bound_ctrl, 0) },
3172 6, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3173 }
3174
3175 static LLVMValueRef
3176 ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
3177 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
3178 bool bound_ctrl)
3179 {
3180 LLVMTypeRef src_type = LLVMTypeOf(src);
3181 src = ac_to_integer(ctx, src);
3182 old = ac_to_integer(ctx, old);
3183 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3184 LLVMValueRef ret;
3185 if (bits == 32) {
3186 ret = _ac_build_dpp(ctx, old, src, dpp_ctrl, row_mask,
3187 bank_mask, bound_ctrl);
3188 } else {
3189 assert(bits % 32 == 0);
3190 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3191 LLVMValueRef src_vector =
3192 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3193 LLVMValueRef old_vector =
3194 LLVMBuildBitCast(ctx->builder, old, vec_type, "");
3195 ret = LLVMGetUndef(vec_type);
3196 for (unsigned i = 0; i < bits / 32; i++) {
3197 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3198 LLVMConstInt(ctx->i32, i,
3199 0), "");
3200 old = LLVMBuildExtractElement(ctx->builder, old_vector,
3201 LLVMConstInt(ctx->i32, i,
3202 0), "");
3203 LLVMValueRef ret_comp = _ac_build_dpp(ctx, old, src,
3204 dpp_ctrl,
3205 row_mask,
3206 bank_mask,
3207 bound_ctrl);
3208 ret = LLVMBuildInsertElement(ctx->builder, ret,
3209 ret_comp,
3210 LLVMConstInt(ctx->i32, i,
3211 0), "");
3212 }
3213 }
3214 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3215 }
3216
3217 static inline unsigned
3218 ds_pattern_bitmode(unsigned and_mask, unsigned or_mask, unsigned xor_mask)
3219 {
3220 assert(and_mask < 32 && or_mask < 32 && xor_mask < 32);
3221 return and_mask | (or_mask << 5) | (xor_mask << 10);
3222 }
3223
3224 static LLVMValueRef
3225 _ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
3226 {
3227 return ac_build_intrinsic(ctx, "llvm.amdgcn.ds.swizzle",
3228 LLVMTypeOf(src), (LLVMValueRef []) {
3229 src, LLVMConstInt(ctx->i32, mask, 0) },
3230 2, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3231 }
3232
3233 LLVMValueRef
3234 ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
3235 {
3236 LLVMTypeRef src_type = LLVMTypeOf(src);
3237 src = ac_to_integer(ctx, src);
3238 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3239 LLVMValueRef ret;
3240 if (bits == 32) {
3241 ret = _ac_build_ds_swizzle(ctx, src, mask);
3242 } else {
3243 assert(bits % 32 == 0);
3244 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3245 LLVMValueRef src_vector =
3246 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3247 ret = LLVMGetUndef(vec_type);
3248 for (unsigned i = 0; i < bits / 32; i++) {
3249 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3250 LLVMConstInt(ctx->i32, i,
3251 0), "");
3252 LLVMValueRef ret_comp = _ac_build_ds_swizzle(ctx, src,
3253 mask);
3254 ret = LLVMBuildInsertElement(ctx->builder, ret,
3255 ret_comp,
3256 LLVMConstInt(ctx->i32, i,
3257 0), "");
3258 }
3259 }
3260 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3261 }
3262
3263 static LLVMValueRef
3264 ac_build_wwm(struct ac_llvm_context *ctx, LLVMValueRef src)
3265 {
3266 char name[32], type[8];
3267 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3268 snprintf(name, sizeof(name), "llvm.amdgcn.wwm.%s", type);
3269 return ac_build_intrinsic(ctx, name, LLVMTypeOf(src),
3270 (LLVMValueRef []) { src }, 1,
3271 AC_FUNC_ATTR_READNONE);
3272 }
3273
3274 static LLVMValueRef
3275 ac_build_set_inactive(struct ac_llvm_context *ctx, LLVMValueRef src,
3276 LLVMValueRef inactive)
3277 {
3278 char name[33], type[8];
3279 LLVMTypeRef src_type = LLVMTypeOf(src);
3280 src = ac_to_integer(ctx, src);
3281 inactive = ac_to_integer(ctx, inactive);
3282 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3283 snprintf(name, sizeof(name), "llvm.amdgcn.set.inactive.%s", type);
3284 LLVMValueRef ret =
3285 ac_build_intrinsic(ctx, name,
3286 LLVMTypeOf(src), (LLVMValueRef []) {
3287 src, inactive }, 2,
3288 AC_FUNC_ATTR_READNONE |
3289 AC_FUNC_ATTR_CONVERGENT);
3290 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3291 }
3292
3293 static LLVMValueRef
3294 get_reduction_identity(struct ac_llvm_context *ctx, nir_op op, unsigned type_size)
3295 {
3296 if (type_size == 4) {
3297 switch (op) {
3298 case nir_op_iadd: return ctx->i32_0;
3299 case nir_op_fadd: return ctx->f32_0;
3300 case nir_op_imul: return ctx->i32_1;
3301 case nir_op_fmul: return ctx->f32_1;
3302 case nir_op_imin: return LLVMConstInt(ctx->i32, INT32_MAX, 0);
3303 case nir_op_umin: return LLVMConstInt(ctx->i32, UINT32_MAX, 0);
3304 case nir_op_fmin: return LLVMConstReal(ctx->f32, INFINITY);
3305 case nir_op_imax: return LLVMConstInt(ctx->i32, INT32_MIN, 0);
3306 case nir_op_umax: return ctx->i32_0;
3307 case nir_op_fmax: return LLVMConstReal(ctx->f32, -INFINITY);
3308 case nir_op_iand: return LLVMConstInt(ctx->i32, -1, 0);
3309 case nir_op_ior: return ctx->i32_0;
3310 case nir_op_ixor: return ctx->i32_0;
3311 default:
3312 unreachable("bad reduction intrinsic");
3313 }
3314 } else { /* type_size == 64bit */
3315 switch (op) {
3316 case nir_op_iadd: return ctx->i64_0;
3317 case nir_op_fadd: return ctx->f64_0;
3318 case nir_op_imul: return ctx->i64_1;
3319 case nir_op_fmul: return ctx->f64_1;
3320 case nir_op_imin: return LLVMConstInt(ctx->i64, INT64_MAX, 0);
3321 case nir_op_umin: return LLVMConstInt(ctx->i64, UINT64_MAX, 0);
3322 case nir_op_fmin: return LLVMConstReal(ctx->f64, INFINITY);
3323 case nir_op_imax: return LLVMConstInt(ctx->i64, INT64_MIN, 0);
3324 case nir_op_umax: return ctx->i64_0;
3325 case nir_op_fmax: return LLVMConstReal(ctx->f64, -INFINITY);
3326 case nir_op_iand: return LLVMConstInt(ctx->i64, -1, 0);
3327 case nir_op_ior: return ctx->i64_0;
3328 case nir_op_ixor: return ctx->i64_0;
3329 default:
3330 unreachable("bad reduction intrinsic");
3331 }
3332 }
3333 }
3334
3335 static LLVMValueRef
3336 ac_build_alu_op(struct ac_llvm_context *ctx, LLVMValueRef lhs, LLVMValueRef rhs, nir_op op)
3337 {
3338 bool _64bit = ac_get_type_size(LLVMTypeOf(lhs)) == 8;
3339 switch (op) {
3340 case nir_op_iadd: return LLVMBuildAdd(ctx->builder, lhs, rhs, "");
3341 case nir_op_fadd: return LLVMBuildFAdd(ctx->builder, lhs, rhs, "");
3342 case nir_op_imul: return LLVMBuildMul(ctx->builder, lhs, rhs, "");
3343 case nir_op_fmul: return LLVMBuildFMul(ctx->builder, lhs, rhs, "");
3344 case nir_op_imin: return LLVMBuildSelect(ctx->builder,
3345 LLVMBuildICmp(ctx->builder, LLVMIntSLT, lhs, rhs, ""),
3346 lhs, rhs, "");
3347 case nir_op_umin: return LLVMBuildSelect(ctx->builder,
3348 LLVMBuildICmp(ctx->builder, LLVMIntULT, lhs, rhs, ""),
3349 lhs, rhs, "");
3350 case nir_op_fmin: return ac_build_intrinsic(ctx,
3351 _64bit ? "llvm.minnum.f64" : "llvm.minnum.f32",
3352 _64bit ? ctx->f64 : ctx->f32,
3353 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
3354 case nir_op_imax: return LLVMBuildSelect(ctx->builder,
3355 LLVMBuildICmp(ctx->builder, LLVMIntSGT, lhs, rhs, ""),
3356 lhs, rhs, "");
3357 case nir_op_umax: return LLVMBuildSelect(ctx->builder,
3358 LLVMBuildICmp(ctx->builder, LLVMIntUGT, lhs, rhs, ""),
3359 lhs, rhs, "");
3360 case nir_op_fmax: return ac_build_intrinsic(ctx,
3361 _64bit ? "llvm.maxnum.f64" : "llvm.maxnum.f32",
3362 _64bit ? ctx->f64 : ctx->f32,
3363 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
3364 case nir_op_iand: return LLVMBuildAnd(ctx->builder, lhs, rhs, "");
3365 case nir_op_ior: return LLVMBuildOr(ctx->builder, lhs, rhs, "");
3366 case nir_op_ixor: return LLVMBuildXor(ctx->builder, lhs, rhs, "");
3367 default:
3368 unreachable("bad reduction intrinsic");
3369 }
3370 }
3371
3372 /**
3373 * \param maxprefix specifies that the result only needs to be correct for a
3374 * prefix of this many threads
3375 *
3376 * TODO: add inclusive and excluse scan functions for SI chip class.
3377 */
3378 static LLVMValueRef
3379 ac_build_scan(struct ac_llvm_context *ctx, nir_op op, LLVMValueRef src, LLVMValueRef identity,
3380 unsigned maxprefix)
3381 {
3382 LLVMValueRef result, tmp;
3383 result = src;
3384 if (maxprefix <= 1)
3385 return result;
3386 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
3387 result = ac_build_alu_op(ctx, result, tmp, op);
3388 if (maxprefix <= 2)
3389 return result;
3390 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(2), 0xf, 0xf, false);
3391 result = ac_build_alu_op(ctx, result, tmp, op);
3392 if (maxprefix <= 3)
3393 return result;
3394 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(3), 0xf, 0xf, false);
3395 result = ac_build_alu_op(ctx, result, tmp, op);
3396 if (maxprefix <= 4)
3397 return result;
3398 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(4), 0xf, 0xe, false);
3399 result = ac_build_alu_op(ctx, result, tmp, op);
3400 if (maxprefix <= 8)
3401 return result;
3402 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(8), 0xf, 0xc, false);
3403 result = ac_build_alu_op(ctx, result, tmp, op);
3404 if (maxprefix <= 16)
3405 return result;
3406 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
3407 result = ac_build_alu_op(ctx, result, tmp, op);
3408 if (maxprefix <= 32)
3409 return result;
3410 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
3411 result = ac_build_alu_op(ctx, result, tmp, op);
3412 return result;
3413 }
3414
3415 LLVMValueRef
3416 ac_build_inclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
3417 {
3418 LLVMValueRef result;
3419
3420 if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
3421 LLVMBuilderRef builder = ctx->builder;
3422 src = LLVMBuildZExt(builder, src, ctx->i32, "");
3423 result = ac_build_ballot(ctx, src);
3424 result = ac_build_mbcnt(ctx, result);
3425 result = LLVMBuildAdd(builder, result, src, "");
3426 return result;
3427 }
3428
3429 ac_build_optimization_barrier(ctx, &src);
3430
3431 LLVMValueRef identity =
3432 get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
3433 result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
3434 LLVMTypeOf(identity), "");
3435 result = ac_build_scan(ctx, op, result, identity, 64);
3436
3437 return ac_build_wwm(ctx, result);
3438 }
3439
3440 LLVMValueRef
3441 ac_build_exclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
3442 {
3443 LLVMValueRef result;
3444
3445 if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
3446 LLVMBuilderRef builder = ctx->builder;
3447 src = LLVMBuildZExt(builder, src, ctx->i32, "");
3448 result = ac_build_ballot(ctx, src);
3449 result = ac_build_mbcnt(ctx, result);
3450 return result;
3451 }
3452
3453 ac_build_optimization_barrier(ctx, &src);
3454
3455 LLVMValueRef identity =
3456 get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
3457 result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
3458 LLVMTypeOf(identity), "");
3459 result = ac_build_dpp(ctx, identity, result, dpp_wf_sr1, 0xf, 0xf, false);
3460 result = ac_build_scan(ctx, op, result, identity, 64);
3461
3462 return ac_build_wwm(ctx, result);
3463 }
3464
3465 LLVMValueRef
3466 ac_build_reduce(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op, unsigned cluster_size)
3467 {
3468 if (cluster_size == 1) return src;
3469 ac_build_optimization_barrier(ctx, &src);
3470 LLVMValueRef result, swap;
3471 LLVMValueRef identity = get_reduction_identity(ctx, op,
3472 ac_get_type_size(LLVMTypeOf(src)));
3473 result = LLVMBuildBitCast(ctx->builder,
3474 ac_build_set_inactive(ctx, src, identity),
3475 LLVMTypeOf(identity), "");
3476 swap = ac_build_quad_swizzle(ctx, result, 1, 0, 3, 2);
3477 result = ac_build_alu_op(ctx, result, swap, op);
3478 if (cluster_size == 2) return ac_build_wwm(ctx, result);
3479
3480 swap = ac_build_quad_swizzle(ctx, result, 2, 3, 0, 1);
3481 result = ac_build_alu_op(ctx, result, swap, op);
3482 if (cluster_size == 4) return ac_build_wwm(ctx, result);
3483
3484 if (ctx->chip_class >= VI)
3485 swap = ac_build_dpp(ctx, identity, result, dpp_row_half_mirror, 0xf, 0xf, false);
3486 else
3487 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x04));
3488 result = ac_build_alu_op(ctx, result, swap, op);
3489 if (cluster_size == 8) return ac_build_wwm(ctx, result);
3490
3491 if (ctx->chip_class >= VI)
3492 swap = ac_build_dpp(ctx, identity, result, dpp_row_mirror, 0xf, 0xf, false);
3493 else
3494 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x08));
3495 result = ac_build_alu_op(ctx, result, swap, op);
3496 if (cluster_size == 16) return ac_build_wwm(ctx, result);
3497
3498 if (ctx->chip_class >= VI && cluster_size != 32)
3499 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
3500 else
3501 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x10));
3502 result = ac_build_alu_op(ctx, result, swap, op);
3503 if (cluster_size == 32) return ac_build_wwm(ctx, result);
3504
3505 if (ctx->chip_class >= VI) {
3506 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
3507 result = ac_build_alu_op(ctx, result, swap, op);
3508 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 63, 0));
3509 return ac_build_wwm(ctx, result);
3510 } else {
3511 swap = ac_build_readlane(ctx, result, ctx->i32_0);
3512 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 32, 0));
3513 result = ac_build_alu_op(ctx, result, swap, op);
3514 return ac_build_wwm(ctx, result);
3515 }
3516 }
3517
3518 /**
3519 * "Top half" of a scan that reduces per-wave values across an entire
3520 * workgroup.
3521 *
3522 * The source value must be present in the highest lane of the wave, and the
3523 * highest lane must be live.
3524 */
3525 void
3526 ac_build_wg_wavescan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
3527 {
3528 if (ws->maxwaves <= 1)
3529 return;
3530
3531 const LLVMValueRef i32_63 = LLVMConstInt(ctx->i32, 63, false);
3532 LLVMBuilderRef builder = ctx->builder;
3533 LLVMValueRef tid = ac_get_thread_id(ctx);
3534 LLVMValueRef tmp;
3535
3536 tmp = LLVMBuildICmp(builder, LLVMIntEQ, tid, i32_63, "");
3537 ac_build_ifcc(ctx, tmp, 1000);
3538 LLVMBuildStore(builder, ws->src, LLVMBuildGEP(builder, ws->scratch, &ws->waveidx, 1, ""));
3539 ac_build_endif(ctx, 1000);
3540 }
3541
3542 /**
3543 * "Bottom half" of a scan that reduces per-wave values across an entire
3544 * workgroup.
3545 *
3546 * The caller must place a barrier between the top and bottom halves.
3547 */
3548 void
3549 ac_build_wg_wavescan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
3550 {
3551 const LLVMTypeRef type = LLVMTypeOf(ws->src);
3552 const LLVMValueRef identity =
3553 get_reduction_identity(ctx, ws->op, ac_get_type_size(type));
3554
3555 if (ws->maxwaves <= 1) {
3556 ws->result_reduce = ws->src;
3557 ws->result_inclusive = ws->src;
3558 ws->result_exclusive = identity;
3559 return;
3560 }
3561 assert(ws->maxwaves <= 32);
3562
3563 LLVMBuilderRef builder = ctx->builder;
3564 LLVMValueRef tid = ac_get_thread_id(ctx);
3565 LLVMBasicBlockRef bbs[2];
3566 LLVMValueRef phivalues_scan[2];
3567 LLVMValueRef tmp, tmp2;
3568
3569 bbs[0] = LLVMGetInsertBlock(builder);
3570 phivalues_scan[0] = LLVMGetUndef(type);
3571
3572 if (ws->enable_reduce)
3573 tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->numwaves, "");
3574 else if (ws->enable_inclusive)
3575 tmp = LLVMBuildICmp(builder, LLVMIntULE, tid, ws->waveidx, "");
3576 else
3577 tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->waveidx, "");
3578 ac_build_ifcc(ctx, tmp, 1001);
3579 {
3580 tmp = LLVMBuildLoad(builder, LLVMBuildGEP(builder, ws->scratch, &tid, 1, ""), "");
3581
3582 ac_build_optimization_barrier(ctx, &tmp);
3583
3584 bbs[1] = LLVMGetInsertBlock(builder);
3585 phivalues_scan[1] = ac_build_scan(ctx, ws->op, tmp, identity, ws->maxwaves);
3586 }
3587 ac_build_endif(ctx, 1001);
3588
3589 const LLVMValueRef scan = ac_build_phi(ctx, type, 2, phivalues_scan, bbs);
3590
3591 if (ws->enable_reduce) {
3592 tmp = LLVMBuildSub(builder, ws->numwaves, ctx->i32_1, "");
3593 ws->result_reduce = ac_build_readlane(ctx, scan, tmp);
3594 }
3595 if (ws->enable_inclusive)
3596 ws->result_inclusive = ac_build_readlane(ctx, scan, ws->waveidx);
3597 if (ws->enable_exclusive) {
3598 tmp = LLVMBuildSub(builder, ws->waveidx, ctx->i32_1, "");
3599 tmp = ac_build_readlane(ctx, scan, tmp);
3600 tmp2 = LLVMBuildICmp(builder, LLVMIntEQ, ws->waveidx, ctx->i32_0, "");
3601 ws->result_exclusive = LLVMBuildSelect(builder, tmp2, identity, tmp, "");
3602 }
3603 }
3604
3605 /**
3606 * Inclusive scan of a per-wave value across an entire workgroup.
3607 *
3608 * This implies an s_barrier instruction.
3609 *
3610 * Unlike ac_build_inclusive_scan, the caller \em must ensure that all threads
3611 * of the workgroup are live. (This requirement cannot easily be relaxed in a
3612 * useful manner because of the barrier in the algorithm.)
3613 */
3614 void
3615 ac_build_wg_wavescan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
3616 {
3617 ac_build_wg_wavescan_top(ctx, ws);
3618 ac_build_s_barrier(ctx);
3619 ac_build_wg_wavescan_bottom(ctx, ws);
3620 }
3621
3622 /**
3623 * "Top half" of a scan that reduces per-thread values across an entire
3624 * workgroup.
3625 *
3626 * All lanes must be active when this code runs.
3627 */
3628 void
3629 ac_build_wg_scan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
3630 {
3631 if (ws->enable_exclusive) {
3632 ws->extra = ac_build_exclusive_scan(ctx, ws->src, ws->op);
3633 if (LLVMTypeOf(ws->src) == ctx->i1 && ws->op == nir_op_iadd)
3634 ws->src = LLVMBuildZExt(ctx->builder, ws->src, ctx->i32, "");
3635 ws->src = ac_build_alu_op(ctx, ws->extra, ws->src, ws->op);
3636 } else {
3637 ws->src = ac_build_inclusive_scan(ctx, ws->src, ws->op);
3638 }
3639
3640 bool enable_inclusive = ws->enable_inclusive;
3641 bool enable_exclusive = ws->enable_exclusive;
3642 ws->enable_inclusive = false;
3643 ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
3644 ac_build_wg_wavescan_top(ctx, ws);
3645 ws->enable_inclusive = enable_inclusive;
3646 ws->enable_exclusive = enable_exclusive;
3647 }
3648
3649 /**
3650 * "Bottom half" of a scan that reduces per-thread values across an entire
3651 * workgroup.
3652 *
3653 * The caller must place a barrier between the top and bottom halves.
3654 */
3655 void
3656 ac_build_wg_scan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
3657 {
3658 bool enable_inclusive = ws->enable_inclusive;
3659 bool enable_exclusive = ws->enable_exclusive;
3660 ws->enable_inclusive = false;
3661 ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
3662 ac_build_wg_wavescan_bottom(ctx, ws);
3663 ws->enable_inclusive = enable_inclusive;
3664 ws->enable_exclusive = enable_exclusive;
3665
3666 /* ws->result_reduce is already the correct value */
3667 if (ws->enable_inclusive)
3668 ws->result_inclusive = ac_build_alu_op(ctx, ws->result_exclusive, ws->src, ws->op);
3669 if (ws->enable_exclusive)
3670 ws->result_exclusive = ac_build_alu_op(ctx, ws->result_exclusive, ws->extra, ws->op);
3671 }
3672
3673 /**
3674 * A scan that reduces per-thread values across an entire workgroup.
3675 *
3676 * The caller must ensure that all lanes are active when this code runs
3677 * (WWM is insufficient!), because there is an implied barrier.
3678 */
3679 void
3680 ac_build_wg_scan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
3681 {
3682 ac_build_wg_scan_top(ctx, ws);
3683 ac_build_s_barrier(ctx);
3684 ac_build_wg_scan_bottom(ctx, ws);
3685 }
3686
3687 LLVMValueRef
3688 ac_build_quad_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src,
3689 unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
3690 {
3691 unsigned mask = dpp_quad_perm(lane0, lane1, lane2, lane3);
3692 if (ctx->chip_class >= VI) {
3693 return ac_build_dpp(ctx, src, src, mask, 0xf, 0xf, false);
3694 } else {
3695 return ac_build_ds_swizzle(ctx, src, (1 << 15) | mask);
3696 }
3697 }
3698
3699 LLVMValueRef
3700 ac_build_shuffle(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef index)
3701 {
3702 index = LLVMBuildMul(ctx->builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
3703 return ac_build_intrinsic(ctx,
3704 "llvm.amdgcn.ds.bpermute", ctx->i32,
3705 (LLVMValueRef []) {index, src}, 2,
3706 AC_FUNC_ATTR_READNONE |
3707 AC_FUNC_ATTR_CONVERGENT);
3708 }