ac: add 8-bit and 16-bit supports to ac_build_permlane16()
[mesa.git] / src / amd / llvm / 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 #include <llvm/Config/llvm-config.h>
30
31 #include "c11/threads.h"
32
33 #include <assert.h>
34 #include <stdio.h>
35
36 #include "ac_llvm_util.h"
37 #include "ac_shader_util.h"
38 #include "ac_exp_param.h"
39 #include "util/bitscan.h"
40 #include "util/macros.h"
41 #include "util/u_atomic.h"
42 #include "util/u_math.h"
43 #include "sid.h"
44
45 #include "shader_enums.h"
46
47 #define AC_LLVM_INITIAL_CF_DEPTH 4
48
49 /* Data for if/else/endif and bgnloop/endloop control flow structures.
50 */
51 struct ac_llvm_flow {
52 /* Loop exit or next part of if/else/endif. */
53 LLVMBasicBlockRef next_block;
54 LLVMBasicBlockRef loop_entry_block;
55 };
56
57 /* Initialize module-independent parts of the context.
58 *
59 * The caller is responsible for initializing ctx::module and ctx::builder.
60 */
61 void
62 ac_llvm_context_init(struct ac_llvm_context *ctx,
63 struct ac_llvm_compiler *compiler,
64 enum chip_class chip_class, enum radeon_family family,
65 enum ac_float_mode float_mode, unsigned wave_size,
66 unsigned ballot_mask_bits)
67 {
68 LLVMValueRef args[1];
69
70 ctx->context = LLVMContextCreate();
71
72 ctx->chip_class = chip_class;
73 ctx->family = family;
74 ctx->wave_size = wave_size;
75 ctx->ballot_mask_bits = ballot_mask_bits;
76 ctx->float_mode = float_mode;
77 ctx->module = ac_create_module(wave_size == 32 ? compiler->tm_wave32
78 : compiler->tm,
79 ctx->context);
80 ctx->builder = ac_create_builder(ctx->context, float_mode);
81
82 ctx->voidt = LLVMVoidTypeInContext(ctx->context);
83 ctx->i1 = LLVMInt1TypeInContext(ctx->context);
84 ctx->i8 = LLVMInt8TypeInContext(ctx->context);
85 ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
86 ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
87 ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
88 ctx->intptr = ctx->i32;
89 ctx->f16 = LLVMHalfTypeInContext(ctx->context);
90 ctx->f32 = LLVMFloatTypeInContext(ctx->context);
91 ctx->f64 = LLVMDoubleTypeInContext(ctx->context);
92 ctx->v2i16 = LLVMVectorType(ctx->i16, 2);
93 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
94 ctx->v3i32 = LLVMVectorType(ctx->i32, 3);
95 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
96 ctx->v2f32 = LLVMVectorType(ctx->f32, 2);
97 ctx->v3f32 = LLVMVectorType(ctx->f32, 3);
98 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
99 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
100 ctx->iN_wavemask = LLVMIntTypeInContext(ctx->context, ctx->wave_size);
101 ctx->iN_ballotmask = LLVMIntTypeInContext(ctx->context, ballot_mask_bits);
102
103 ctx->i8_0 = LLVMConstInt(ctx->i8, 0, false);
104 ctx->i8_1 = LLVMConstInt(ctx->i8, 1, false);
105 ctx->i16_0 = LLVMConstInt(ctx->i16, 0, false);
106 ctx->i16_1 = LLVMConstInt(ctx->i16, 1, false);
107 ctx->i32_0 = LLVMConstInt(ctx->i32, 0, false);
108 ctx->i32_1 = LLVMConstInt(ctx->i32, 1, false);
109 ctx->i64_0 = LLVMConstInt(ctx->i64, 0, false);
110 ctx->i64_1 = LLVMConstInt(ctx->i64, 1, false);
111 ctx->f16_0 = LLVMConstReal(ctx->f16, 0.0);
112 ctx->f16_1 = LLVMConstReal(ctx->f16, 1.0);
113 ctx->f32_0 = LLVMConstReal(ctx->f32, 0.0);
114 ctx->f32_1 = LLVMConstReal(ctx->f32, 1.0);
115 ctx->f64_0 = LLVMConstReal(ctx->f64, 0.0);
116 ctx->f64_1 = LLVMConstReal(ctx->f64, 1.0);
117
118 ctx->i1false = LLVMConstInt(ctx->i1, 0, false);
119 ctx->i1true = LLVMConstInt(ctx->i1, 1, false);
120
121 ctx->range_md_kind = LLVMGetMDKindIDInContext(ctx->context,
122 "range", 5);
123
124 ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(ctx->context,
125 "invariant.load", 14);
126
127 ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->context, "fpmath", 6);
128
129 args[0] = LLVMConstReal(ctx->f32, 2.5);
130 ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->context, args, 1);
131
132 ctx->uniform_md_kind = LLVMGetMDKindIDInContext(ctx->context,
133 "amdgpu.uniform", 14);
134
135 ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
136 ctx->flow = calloc(1, sizeof(*ctx->flow));
137 }
138
139 void
140 ac_llvm_context_dispose(struct ac_llvm_context *ctx)
141 {
142 free(ctx->flow->stack);
143 free(ctx->flow);
144 ctx->flow = NULL;
145 }
146
147 int
148 ac_get_llvm_num_components(LLVMValueRef value)
149 {
150 LLVMTypeRef type = LLVMTypeOf(value);
151 unsigned num_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
152 ? LLVMGetVectorSize(type)
153 : 1;
154 return num_components;
155 }
156
157 LLVMValueRef
158 ac_llvm_extract_elem(struct ac_llvm_context *ac,
159 LLVMValueRef value,
160 int index)
161 {
162 if (LLVMGetTypeKind(LLVMTypeOf(value)) != LLVMVectorTypeKind) {
163 assert(index == 0);
164 return value;
165 }
166
167 return LLVMBuildExtractElement(ac->builder, value,
168 LLVMConstInt(ac->i32, index, false), "");
169 }
170
171 int
172 ac_get_elem_bits(struct ac_llvm_context *ctx, LLVMTypeRef type)
173 {
174 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
175 type = LLVMGetElementType(type);
176
177 if (LLVMGetTypeKind(type) == LLVMIntegerTypeKind)
178 return LLVMGetIntTypeWidth(type);
179
180 if (LLVMGetTypeKind(type) == LLVMPointerTypeKind) {
181 if (LLVMGetPointerAddressSpace(type) == AC_ADDR_SPACE_LDS)
182 return 32;
183 }
184
185 if (type == ctx->f16)
186 return 16;
187 if (type == ctx->f32)
188 return 32;
189 if (type == ctx->f64)
190 return 64;
191
192 unreachable("Unhandled type kind in get_elem_bits");
193 }
194
195 unsigned
196 ac_get_type_size(LLVMTypeRef type)
197 {
198 LLVMTypeKind kind = LLVMGetTypeKind(type);
199
200 switch (kind) {
201 case LLVMIntegerTypeKind:
202 return LLVMGetIntTypeWidth(type) / 8;
203 case LLVMHalfTypeKind:
204 return 2;
205 case LLVMFloatTypeKind:
206 return 4;
207 case LLVMDoubleTypeKind:
208 return 8;
209 case LLVMPointerTypeKind:
210 if (LLVMGetPointerAddressSpace(type) == AC_ADDR_SPACE_CONST_32BIT)
211 return 4;
212 return 8;
213 case LLVMVectorTypeKind:
214 return LLVMGetVectorSize(type) *
215 ac_get_type_size(LLVMGetElementType(type));
216 case LLVMArrayTypeKind:
217 return LLVMGetArrayLength(type) *
218 ac_get_type_size(LLVMGetElementType(type));
219 default:
220 assert(0);
221 return 0;
222 }
223 }
224
225 static LLVMTypeRef to_integer_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
226 {
227 if (t == ctx->i8)
228 return ctx->i8;
229 else if (t == ctx->f16 || t == ctx->i16)
230 return ctx->i16;
231 else if (t == ctx->f32 || t == ctx->i32)
232 return ctx->i32;
233 else if (t == ctx->f64 || t == ctx->i64)
234 return ctx->i64;
235 else
236 unreachable("Unhandled integer size");
237 }
238
239 LLVMTypeRef
240 ac_to_integer_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
241 {
242 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
243 LLVMTypeRef elem_type = LLVMGetElementType(t);
244 return LLVMVectorType(to_integer_type_scalar(ctx, elem_type),
245 LLVMGetVectorSize(t));
246 }
247 if (LLVMGetTypeKind(t) == LLVMPointerTypeKind) {
248 switch (LLVMGetPointerAddressSpace(t)) {
249 case AC_ADDR_SPACE_GLOBAL:
250 return ctx->i64;
251 case AC_ADDR_SPACE_CONST_32BIT:
252 case AC_ADDR_SPACE_LDS:
253 return ctx->i32;
254 default:
255 unreachable("unhandled address space");
256 }
257 }
258 return to_integer_type_scalar(ctx, t);
259 }
260
261 LLVMValueRef
262 ac_to_integer(struct ac_llvm_context *ctx, LLVMValueRef v)
263 {
264 LLVMTypeRef type = LLVMTypeOf(v);
265 if (LLVMGetTypeKind(type) == LLVMPointerTypeKind) {
266 return LLVMBuildPtrToInt(ctx->builder, v, ac_to_integer_type(ctx, type), "");
267 }
268 return LLVMBuildBitCast(ctx->builder, v, ac_to_integer_type(ctx, type), "");
269 }
270
271 LLVMValueRef
272 ac_to_integer_or_pointer(struct ac_llvm_context *ctx, LLVMValueRef v)
273 {
274 LLVMTypeRef type = LLVMTypeOf(v);
275 if (LLVMGetTypeKind(type) == LLVMPointerTypeKind)
276 return v;
277 return ac_to_integer(ctx, v);
278 }
279
280 static LLVMTypeRef to_float_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
281 {
282 if (t == ctx->i8)
283 return ctx->i8;
284 else if (t == ctx->i16 || t == ctx->f16)
285 return ctx->f16;
286 else if (t == ctx->i32 || t == ctx->f32)
287 return ctx->f32;
288 else if (t == ctx->i64 || t == ctx->f64)
289 return ctx->f64;
290 else
291 unreachable("Unhandled float size");
292 }
293
294 LLVMTypeRef
295 ac_to_float_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
296 {
297 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
298 LLVMTypeRef elem_type = LLVMGetElementType(t);
299 return LLVMVectorType(to_float_type_scalar(ctx, elem_type),
300 LLVMGetVectorSize(t));
301 }
302 return to_float_type_scalar(ctx, t);
303 }
304
305 LLVMValueRef
306 ac_to_float(struct ac_llvm_context *ctx, LLVMValueRef v)
307 {
308 LLVMTypeRef type = LLVMTypeOf(v);
309 return LLVMBuildBitCast(ctx->builder, v, ac_to_float_type(ctx, type), "");
310 }
311
312
313 LLVMValueRef
314 ac_build_intrinsic(struct ac_llvm_context *ctx, const char *name,
315 LLVMTypeRef return_type, LLVMValueRef *params,
316 unsigned param_count, unsigned attrib_mask)
317 {
318 LLVMValueRef function, call;
319 bool set_callsite_attrs = !(attrib_mask & AC_FUNC_ATTR_LEGACY);
320
321 function = LLVMGetNamedFunction(ctx->module, name);
322 if (!function) {
323 LLVMTypeRef param_types[32], function_type;
324 unsigned i;
325
326 assert(param_count <= 32);
327
328 for (i = 0; i < param_count; ++i) {
329 assert(params[i]);
330 param_types[i] = LLVMTypeOf(params[i]);
331 }
332 function_type =
333 LLVMFunctionType(return_type, param_types, param_count, 0);
334 function = LLVMAddFunction(ctx->module, name, function_type);
335
336 LLVMSetFunctionCallConv(function, LLVMCCallConv);
337 LLVMSetLinkage(function, LLVMExternalLinkage);
338
339 if (!set_callsite_attrs)
340 ac_add_func_attributes(ctx->context, function, attrib_mask);
341 }
342
343 call = LLVMBuildCall(ctx->builder, function, params, param_count, "");
344 if (set_callsite_attrs)
345 ac_add_func_attributes(ctx->context, call, attrib_mask);
346 return call;
347 }
348
349 /**
350 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
351 * intrinsic names).
352 */
353 void ac_build_type_name_for_intr(LLVMTypeRef type, char *buf, unsigned bufsize)
354 {
355 LLVMTypeRef elem_type = type;
356
357 assert(bufsize >= 8);
358
359 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
360 int ret = snprintf(buf, bufsize, "v%u",
361 LLVMGetVectorSize(type));
362 if (ret < 0) {
363 char *type_name = LLVMPrintTypeToString(type);
364 fprintf(stderr, "Error building type name for: %s\n",
365 type_name);
366 LLVMDisposeMessage(type_name);
367 return;
368 }
369 elem_type = LLVMGetElementType(type);
370 buf += ret;
371 bufsize -= ret;
372 }
373 switch (LLVMGetTypeKind(elem_type)) {
374 default: break;
375 case LLVMIntegerTypeKind:
376 snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
377 break;
378 case LLVMHalfTypeKind:
379 snprintf(buf, bufsize, "f16");
380 break;
381 case LLVMFloatTypeKind:
382 snprintf(buf, bufsize, "f32");
383 break;
384 case LLVMDoubleTypeKind:
385 snprintf(buf, bufsize, "f64");
386 break;
387 }
388 }
389
390 /**
391 * Helper function that builds an LLVM IR PHI node and immediately adds
392 * incoming edges.
393 */
394 LLVMValueRef
395 ac_build_phi(struct ac_llvm_context *ctx, LLVMTypeRef type,
396 unsigned count_incoming, LLVMValueRef *values,
397 LLVMBasicBlockRef *blocks)
398 {
399 LLVMValueRef phi = LLVMBuildPhi(ctx->builder, type, "");
400 LLVMAddIncoming(phi, values, blocks, count_incoming);
401 return phi;
402 }
403
404 void ac_build_s_barrier(struct ac_llvm_context *ctx)
405 {
406 ac_build_intrinsic(ctx, "llvm.amdgcn.s.barrier", ctx->voidt, NULL,
407 0, AC_FUNC_ATTR_CONVERGENT);
408 }
409
410 /* Prevent optimizations (at least of memory accesses) across the current
411 * point in the program by emitting empty inline assembly that is marked as
412 * having side effects.
413 *
414 * Optionally, a value can be passed through the inline assembly to prevent
415 * LLVM from hoisting calls to ReadNone functions.
416 */
417 void
418 ac_build_optimization_barrier(struct ac_llvm_context *ctx,
419 LLVMValueRef *pvgpr)
420 {
421 static int counter = 0;
422
423 LLVMBuilderRef builder = ctx->builder;
424 char code[16];
425
426 snprintf(code, sizeof(code), "; %d", p_atomic_inc_return(&counter));
427
428 if (!pvgpr) {
429 LLVMTypeRef ftype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
430 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "", true, false);
431 LLVMBuildCall(builder, inlineasm, NULL, 0, "");
432 } else {
433 LLVMTypeRef ftype = LLVMFunctionType(ctx->i32, &ctx->i32, 1, false);
434 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "=v,0", true, false);
435 LLVMTypeRef type = LLVMTypeOf(*pvgpr);
436 unsigned bitsize = ac_get_elem_bits(ctx, type);
437 LLVMValueRef vgpr = *pvgpr;
438 LLVMTypeRef vgpr_type;
439 unsigned vgpr_size;
440 LLVMValueRef vgpr0;
441
442 if (bitsize < 32)
443 vgpr = LLVMBuildZExt(ctx->builder, vgpr, ctx->i32, "");
444
445 vgpr_type = LLVMTypeOf(vgpr);
446 vgpr_size = ac_get_type_size(vgpr_type);
447
448 assert(vgpr_size % 4 == 0);
449
450 vgpr = LLVMBuildBitCast(builder, vgpr, LLVMVectorType(ctx->i32, vgpr_size / 4), "");
451 vgpr0 = LLVMBuildExtractElement(builder, vgpr, ctx->i32_0, "");
452 vgpr0 = LLVMBuildCall(builder, inlineasm, &vgpr0, 1, "");
453 vgpr = LLVMBuildInsertElement(builder, vgpr, vgpr0, ctx->i32_0, "");
454 vgpr = LLVMBuildBitCast(builder, vgpr, vgpr_type, "");
455
456 if (bitsize < 32)
457 vgpr = LLVMBuildTrunc(builder, vgpr, type, "");
458
459 *pvgpr = vgpr;
460 }
461 }
462
463 LLVMValueRef
464 ac_build_shader_clock(struct ac_llvm_context *ctx)
465 {
466 const char *intr = LLVM_VERSION_MAJOR >= 9 && ctx->chip_class >= GFX8 ?
467 "llvm.amdgcn.s.memrealtime" : "llvm.readcyclecounter";
468 LLVMValueRef tmp = ac_build_intrinsic(ctx, intr, ctx->i64, NULL, 0, 0);
469 return LLVMBuildBitCast(ctx->builder, tmp, ctx->v2i32, "");
470 }
471
472 LLVMValueRef
473 ac_build_ballot(struct ac_llvm_context *ctx,
474 LLVMValueRef value)
475 {
476 const char *name;
477
478 if (LLVM_VERSION_MAJOR >= 9) {
479 if (ctx->wave_size == 64)
480 name = "llvm.amdgcn.icmp.i64.i32";
481 else
482 name = "llvm.amdgcn.icmp.i32.i32";
483 } else {
484 name = "llvm.amdgcn.icmp.i32";
485 }
486 LLVMValueRef args[3] = {
487 value,
488 ctx->i32_0,
489 LLVMConstInt(ctx->i32, LLVMIntNE, 0)
490 };
491
492 /* We currently have no other way to prevent LLVM from lifting the icmp
493 * calls to a dominating basic block.
494 */
495 ac_build_optimization_barrier(ctx, &args[0]);
496
497 args[0] = ac_to_integer(ctx, args[0]);
498
499 return ac_build_intrinsic(ctx, name, ctx->iN_wavemask, args, 3,
500 AC_FUNC_ATTR_NOUNWIND |
501 AC_FUNC_ATTR_READNONE |
502 AC_FUNC_ATTR_CONVERGENT);
503 }
504
505 LLVMValueRef ac_get_i1_sgpr_mask(struct ac_llvm_context *ctx,
506 LLVMValueRef value)
507 {
508 const char *name = LLVM_VERSION_MAJOR >= 9 ? "llvm.amdgcn.icmp.i64.i1" : "llvm.amdgcn.icmp.i1";
509 LLVMValueRef args[3] = {
510 value,
511 ctx->i1false,
512 LLVMConstInt(ctx->i32, LLVMIntNE, 0),
513 };
514
515 return ac_build_intrinsic(ctx, name, ctx->i64, args, 3,
516 AC_FUNC_ATTR_NOUNWIND |
517 AC_FUNC_ATTR_READNONE |
518 AC_FUNC_ATTR_CONVERGENT);
519 }
520
521 LLVMValueRef
522 ac_build_vote_all(struct ac_llvm_context *ctx, LLVMValueRef value)
523 {
524 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
525 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
526 return LLVMBuildICmp(ctx->builder, LLVMIntEQ, vote_set, active_set, "");
527 }
528
529 LLVMValueRef
530 ac_build_vote_any(struct ac_llvm_context *ctx, LLVMValueRef value)
531 {
532 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
533 return LLVMBuildICmp(ctx->builder, LLVMIntNE, vote_set,
534 LLVMConstInt(ctx->iN_wavemask, 0, 0), "");
535 }
536
537 LLVMValueRef
538 ac_build_vote_eq(struct ac_llvm_context *ctx, LLVMValueRef value)
539 {
540 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
541 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
542
543 LLVMValueRef all = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
544 vote_set, active_set, "");
545 LLVMValueRef none = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
546 vote_set,
547 LLVMConstInt(ctx->iN_wavemask, 0, 0), "");
548 return LLVMBuildOr(ctx->builder, all, none, "");
549 }
550
551 LLVMValueRef
552 ac_build_varying_gather_values(struct ac_llvm_context *ctx, LLVMValueRef *values,
553 unsigned value_count, unsigned component)
554 {
555 LLVMValueRef vec = NULL;
556
557 if (value_count == 1) {
558 return values[component];
559 } else if (!value_count)
560 unreachable("value_count is 0");
561
562 for (unsigned i = component; i < value_count + component; i++) {
563 LLVMValueRef value = values[i];
564
565 if (i == component)
566 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
567 LLVMValueRef index = LLVMConstInt(ctx->i32, i - component, false);
568 vec = LLVMBuildInsertElement(ctx->builder, vec, value, index, "");
569 }
570 return vec;
571 }
572
573 LLVMValueRef
574 ac_build_gather_values_extended(struct ac_llvm_context *ctx,
575 LLVMValueRef *values,
576 unsigned value_count,
577 unsigned value_stride,
578 bool load,
579 bool always_vector)
580 {
581 LLVMBuilderRef builder = ctx->builder;
582 LLVMValueRef vec = NULL;
583 unsigned i;
584
585 if (value_count == 1 && !always_vector) {
586 if (load)
587 return LLVMBuildLoad(builder, values[0], "");
588 return values[0];
589 } else if (!value_count)
590 unreachable("value_count is 0");
591
592 for (i = 0; i < value_count; i++) {
593 LLVMValueRef value = values[i * value_stride];
594 if (load)
595 value = LLVMBuildLoad(builder, value, "");
596
597 if (!i)
598 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
599 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
600 vec = LLVMBuildInsertElement(builder, vec, value, index, "");
601 }
602 return vec;
603 }
604
605 LLVMValueRef
606 ac_build_gather_values(struct ac_llvm_context *ctx,
607 LLVMValueRef *values,
608 unsigned value_count)
609 {
610 return ac_build_gather_values_extended(ctx, values, value_count, 1, false, false);
611 }
612
613 /* Expand a scalar or vector to <dst_channels x type> by filling the remaining
614 * channels with undef. Extract at most src_channels components from the input.
615 */
616 static LLVMValueRef
617 ac_build_expand(struct ac_llvm_context *ctx,
618 LLVMValueRef value,
619 unsigned src_channels,
620 unsigned dst_channels)
621 {
622 LLVMTypeRef elemtype;
623 LLVMValueRef chan[dst_channels];
624
625 if (LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMVectorTypeKind) {
626 unsigned vec_size = LLVMGetVectorSize(LLVMTypeOf(value));
627
628 if (src_channels == dst_channels && vec_size == dst_channels)
629 return value;
630
631 src_channels = MIN2(src_channels, vec_size);
632
633 for (unsigned i = 0; i < src_channels; i++)
634 chan[i] = ac_llvm_extract_elem(ctx, value, i);
635
636 elemtype = LLVMGetElementType(LLVMTypeOf(value));
637 } else {
638 if (src_channels) {
639 assert(src_channels == 1);
640 chan[0] = value;
641 }
642 elemtype = LLVMTypeOf(value);
643 }
644
645 for (unsigned i = src_channels; i < dst_channels; i++)
646 chan[i] = LLVMGetUndef(elemtype);
647
648 return ac_build_gather_values(ctx, chan, dst_channels);
649 }
650
651 /* Extract components [start, start + channels) from a vector.
652 */
653 LLVMValueRef
654 ac_extract_components(struct ac_llvm_context *ctx,
655 LLVMValueRef value,
656 unsigned start,
657 unsigned channels)
658 {
659 LLVMValueRef chan[channels];
660
661 for (unsigned i = 0; i < channels; i++)
662 chan[i] = ac_llvm_extract_elem(ctx, value, i + start);
663
664 return ac_build_gather_values(ctx, chan, channels);
665 }
666
667 /* Expand a scalar or vector to <4 x type> by filling the remaining channels
668 * with undef. Extract at most num_channels components from the input.
669 */
670 LLVMValueRef ac_build_expand_to_vec4(struct ac_llvm_context *ctx,
671 LLVMValueRef value,
672 unsigned num_channels)
673 {
674 return ac_build_expand(ctx, value, num_channels, 4);
675 }
676
677 LLVMValueRef ac_build_round(struct ac_llvm_context *ctx, LLVMValueRef value)
678 {
679 unsigned type_size = ac_get_type_size(LLVMTypeOf(value));
680 const char *name;
681
682 if (type_size == 2)
683 name = "llvm.rint.f16";
684 else if (type_size == 4)
685 name = "llvm.rint.f32";
686 else
687 name = "llvm.rint.f64";
688
689 return ac_build_intrinsic(ctx, name, LLVMTypeOf(value), &value, 1,
690 AC_FUNC_ATTR_READNONE);
691 }
692
693 LLVMValueRef
694 ac_build_fdiv(struct ac_llvm_context *ctx,
695 LLVMValueRef num,
696 LLVMValueRef den)
697 {
698 /* If we do (num / den), LLVM >= 7.0 does:
699 * return num * v_rcp_f32(den * (fabs(den) > 0x1.0p+96f ? 0x1.0p-32f : 1.0f));
700 *
701 * If we do (num * (1 / den)), LLVM does:
702 * return num * v_rcp_f32(den);
703 */
704 LLVMValueRef one = LLVMConstReal(LLVMTypeOf(num), 1.0);
705 LLVMValueRef rcp = LLVMBuildFDiv(ctx->builder, one, den, "");
706 LLVMValueRef ret = LLVMBuildFMul(ctx->builder, num, rcp, "");
707
708 /* Use v_rcp_f32 instead of precise division. */
709 if (!LLVMIsConstant(ret))
710 LLVMSetMetadata(ret, ctx->fpmath_md_kind, ctx->fpmath_md_2p5_ulp);
711 return ret;
712 }
713
714 /* See fast_idiv_by_const.h. */
715 /* Set: increment = util_fast_udiv_info::increment ? multiplier : 0; */
716 LLVMValueRef ac_build_fast_udiv(struct ac_llvm_context *ctx,
717 LLVMValueRef num,
718 LLVMValueRef multiplier,
719 LLVMValueRef pre_shift,
720 LLVMValueRef post_shift,
721 LLVMValueRef increment)
722 {
723 LLVMBuilderRef builder = ctx->builder;
724
725 num = LLVMBuildLShr(builder, num, pre_shift, "");
726 num = LLVMBuildMul(builder,
727 LLVMBuildZExt(builder, num, ctx->i64, ""),
728 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
729 num = LLVMBuildAdd(builder, num,
730 LLVMBuildZExt(builder, increment, ctx->i64, ""), "");
731 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
732 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
733 return LLVMBuildLShr(builder, num, post_shift, "");
734 }
735
736 /* See fast_idiv_by_const.h. */
737 /* If num != UINT_MAX, this more efficient version can be used. */
738 /* Set: increment = util_fast_udiv_info::increment; */
739 LLVMValueRef ac_build_fast_udiv_nuw(struct ac_llvm_context *ctx,
740 LLVMValueRef num,
741 LLVMValueRef multiplier,
742 LLVMValueRef pre_shift,
743 LLVMValueRef post_shift,
744 LLVMValueRef increment)
745 {
746 LLVMBuilderRef builder = ctx->builder;
747
748 num = LLVMBuildLShr(builder, num, pre_shift, "");
749 num = LLVMBuildNUWAdd(builder, num, increment, "");
750 num = LLVMBuildMul(builder,
751 LLVMBuildZExt(builder, num, ctx->i64, ""),
752 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
753 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
754 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
755 return LLVMBuildLShr(builder, num, post_shift, "");
756 }
757
758 /* See fast_idiv_by_const.h. */
759 /* Both operands must fit in 31 bits and the divisor must not be 1. */
760 LLVMValueRef ac_build_fast_udiv_u31_d_not_one(struct ac_llvm_context *ctx,
761 LLVMValueRef num,
762 LLVMValueRef multiplier,
763 LLVMValueRef post_shift)
764 {
765 LLVMBuilderRef builder = ctx->builder;
766
767 num = LLVMBuildMul(builder,
768 LLVMBuildZExt(builder, num, ctx->i64, ""),
769 LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
770 num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
771 num = LLVMBuildTrunc(builder, num, ctx->i32, "");
772 return LLVMBuildLShr(builder, num, post_shift, "");
773 }
774
775 /* Coordinates for cube map selection. sc, tc, and ma are as in Table 8.27
776 * of the OpenGL 4.5 (Compatibility Profile) specification, except ma is
777 * already multiplied by two. id is the cube face number.
778 */
779 struct cube_selection_coords {
780 LLVMValueRef stc[2];
781 LLVMValueRef ma;
782 LLVMValueRef id;
783 };
784
785 static void
786 build_cube_intrinsic(struct ac_llvm_context *ctx,
787 LLVMValueRef in[3],
788 struct cube_selection_coords *out)
789 {
790 LLVMTypeRef f32 = ctx->f32;
791
792 out->stc[1] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubetc",
793 f32, in, 3, AC_FUNC_ATTR_READNONE);
794 out->stc[0] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubesc",
795 f32, in, 3, AC_FUNC_ATTR_READNONE);
796 out->ma = ac_build_intrinsic(ctx, "llvm.amdgcn.cubema",
797 f32, in, 3, AC_FUNC_ATTR_READNONE);
798 out->id = ac_build_intrinsic(ctx, "llvm.amdgcn.cubeid",
799 f32, in, 3, AC_FUNC_ATTR_READNONE);
800 }
801
802 /**
803 * Build a manual selection sequence for cube face sc/tc coordinates and
804 * major axis vector (multiplied by 2 for consistency) for the given
805 * vec3 \p coords, for the face implied by \p selcoords.
806 *
807 * For the major axis, we always adjust the sign to be in the direction of
808 * selcoords.ma; i.e., a positive out_ma means that coords is pointed towards
809 * the selcoords major axis.
810 */
811 static void build_cube_select(struct ac_llvm_context *ctx,
812 const struct cube_selection_coords *selcoords,
813 const LLVMValueRef *coords,
814 LLVMValueRef *out_st,
815 LLVMValueRef *out_ma)
816 {
817 LLVMBuilderRef builder = ctx->builder;
818 LLVMTypeRef f32 = LLVMTypeOf(coords[0]);
819 LLVMValueRef is_ma_positive;
820 LLVMValueRef sgn_ma;
821 LLVMValueRef is_ma_z, is_not_ma_z;
822 LLVMValueRef is_ma_y;
823 LLVMValueRef is_ma_x;
824 LLVMValueRef sgn;
825 LLVMValueRef tmp;
826
827 is_ma_positive = LLVMBuildFCmp(builder, LLVMRealUGE,
828 selcoords->ma, LLVMConstReal(f32, 0.0), "");
829 sgn_ma = LLVMBuildSelect(builder, is_ma_positive,
830 LLVMConstReal(f32, 1.0), LLVMConstReal(f32, -1.0), "");
831
832 is_ma_z = LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 4.0), "");
833 is_not_ma_z = LLVMBuildNot(builder, is_ma_z, "");
834 is_ma_y = LLVMBuildAnd(builder, is_not_ma_z,
835 LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 2.0), ""), "");
836 is_ma_x = LLVMBuildAnd(builder, is_not_ma_z, LLVMBuildNot(builder, is_ma_y, ""), "");
837
838 /* Select sc */
839 tmp = LLVMBuildSelect(builder, is_ma_x, coords[2], coords[0], "");
840 sgn = LLVMBuildSelect(builder, is_ma_y, LLVMConstReal(f32, 1.0),
841 LLVMBuildSelect(builder, is_ma_z, sgn_ma,
842 LLVMBuildFNeg(builder, sgn_ma, ""), ""), "");
843 out_st[0] = LLVMBuildFMul(builder, tmp, sgn, "");
844
845 /* Select tc */
846 tmp = LLVMBuildSelect(builder, is_ma_y, coords[2], coords[1], "");
847 sgn = LLVMBuildSelect(builder, is_ma_y, sgn_ma,
848 LLVMConstReal(f32, -1.0), "");
849 out_st[1] = LLVMBuildFMul(builder, tmp, sgn, "");
850
851 /* Select ma */
852 tmp = LLVMBuildSelect(builder, is_ma_z, coords[2],
853 LLVMBuildSelect(builder, is_ma_y, coords[1], coords[0], ""), "");
854 tmp = ac_build_intrinsic(ctx, "llvm.fabs.f32",
855 ctx->f32, &tmp, 1, AC_FUNC_ATTR_READNONE);
856 *out_ma = LLVMBuildFMul(builder, tmp, LLVMConstReal(f32, 2.0), "");
857 }
858
859 void
860 ac_prepare_cube_coords(struct ac_llvm_context *ctx,
861 bool is_deriv, bool is_array, bool is_lod,
862 LLVMValueRef *coords_arg,
863 LLVMValueRef *derivs_arg)
864 {
865
866 LLVMBuilderRef builder = ctx->builder;
867 struct cube_selection_coords selcoords;
868 LLVMValueRef coords[3];
869 LLVMValueRef invma;
870
871 if (is_array && !is_lod) {
872 LLVMValueRef tmp = ac_build_round(ctx, coords_arg[3]);
873
874 /* Section 8.9 (Texture Functions) of the GLSL 4.50 spec says:
875 *
876 * "For Array forms, the array layer used will be
877 *
878 * max(0, min(d−1, floor(layer+0.5)))
879 *
880 * where d is the depth of the texture array and layer
881 * comes from the component indicated in the tables below.
882 * Workaroudn for an issue where the layer is taken from a
883 * helper invocation which happens to fall on a different
884 * layer due to extrapolation."
885 *
886 * GFX8 and earlier attempt to implement this in hardware by
887 * clamping the value of coords[2] = (8 * layer) + face.
888 * Unfortunately, this means that the we end up with the wrong
889 * face when clamping occurs.
890 *
891 * Clamp the layer earlier to work around the issue.
892 */
893 if (ctx->chip_class <= GFX8) {
894 LLVMValueRef ge0;
895 ge0 = LLVMBuildFCmp(builder, LLVMRealOGE, tmp, ctx->f32_0, "");
896 tmp = LLVMBuildSelect(builder, ge0, tmp, ctx->f32_0, "");
897 }
898
899 coords_arg[3] = tmp;
900 }
901
902 build_cube_intrinsic(ctx, coords_arg, &selcoords);
903
904 invma = ac_build_intrinsic(ctx, "llvm.fabs.f32",
905 ctx->f32, &selcoords.ma, 1, AC_FUNC_ATTR_READNONE);
906 invma = ac_build_fdiv(ctx, LLVMConstReal(ctx->f32, 1.0), invma);
907
908 for (int i = 0; i < 2; ++i)
909 coords[i] = LLVMBuildFMul(builder, selcoords.stc[i], invma, "");
910
911 coords[2] = selcoords.id;
912
913 if (is_deriv && derivs_arg) {
914 LLVMValueRef derivs[4];
915 int axis;
916
917 /* Convert cube derivatives to 2D derivatives. */
918 for (axis = 0; axis < 2; axis++) {
919 LLVMValueRef deriv_st[2];
920 LLVMValueRef deriv_ma;
921
922 /* Transform the derivative alongside the texture
923 * coordinate. Mathematically, the correct formula is
924 * as follows. Assume we're projecting onto the +Z face
925 * and denote by dx/dh the derivative of the (original)
926 * X texture coordinate with respect to horizontal
927 * window coordinates. The projection onto the +Z face
928 * plane is:
929 *
930 * f(x,z) = x/z
931 *
932 * Then df/dh = df/dx * dx/dh + df/dz * dz/dh
933 * = 1/z * dx/dh - x/z * 1/z * dz/dh.
934 *
935 * This motivatives the implementation below.
936 *
937 * Whether this actually gives the expected results for
938 * apps that might feed in derivatives obtained via
939 * finite differences is anyone's guess. The OpenGL spec
940 * seems awfully quiet about how textureGrad for cube
941 * maps should be handled.
942 */
943 build_cube_select(ctx, &selcoords, &derivs_arg[axis * 3],
944 deriv_st, &deriv_ma);
945
946 deriv_ma = LLVMBuildFMul(builder, deriv_ma, invma, "");
947
948 for (int i = 0; i < 2; ++i)
949 derivs[axis * 2 + i] =
950 LLVMBuildFSub(builder,
951 LLVMBuildFMul(builder, deriv_st[i], invma, ""),
952 LLVMBuildFMul(builder, deriv_ma, coords[i], ""), "");
953 }
954
955 memcpy(derivs_arg, derivs, sizeof(derivs));
956 }
957
958 /* Shift the texture coordinate. This must be applied after the
959 * derivative calculation.
960 */
961 for (int i = 0; i < 2; ++i)
962 coords[i] = LLVMBuildFAdd(builder, coords[i], LLVMConstReal(ctx->f32, 1.5), "");
963
964 if (is_array) {
965 /* for cube arrays coord.z = coord.w(array_index) * 8 + face */
966 /* coords_arg.w component - array_index for cube arrays */
967 coords[2] = ac_build_fmad(ctx, coords_arg[3], LLVMConstReal(ctx->f32, 8.0), coords[2]);
968 }
969
970 memcpy(coords_arg, coords, sizeof(coords));
971 }
972
973
974 LLVMValueRef
975 ac_build_fs_interp(struct ac_llvm_context *ctx,
976 LLVMValueRef llvm_chan,
977 LLVMValueRef attr_number,
978 LLVMValueRef params,
979 LLVMValueRef i,
980 LLVMValueRef j)
981 {
982 LLVMValueRef args[5];
983 LLVMValueRef p1;
984
985 args[0] = i;
986 args[1] = llvm_chan;
987 args[2] = attr_number;
988 args[3] = params;
989
990 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1",
991 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
992
993 args[0] = p1;
994 args[1] = j;
995 args[2] = llvm_chan;
996 args[3] = attr_number;
997 args[4] = params;
998
999 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2",
1000 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
1001 }
1002
1003 LLVMValueRef
1004 ac_build_fs_interp_f16(struct ac_llvm_context *ctx,
1005 LLVMValueRef llvm_chan,
1006 LLVMValueRef attr_number,
1007 LLVMValueRef params,
1008 LLVMValueRef i,
1009 LLVMValueRef j)
1010 {
1011 LLVMValueRef args[6];
1012 LLVMValueRef p1;
1013
1014 args[0] = i;
1015 args[1] = llvm_chan;
1016 args[2] = attr_number;
1017 args[3] = ctx->i1false;
1018 args[4] = params;
1019
1020 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1.f16",
1021 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
1022
1023 args[0] = p1;
1024 args[1] = j;
1025 args[2] = llvm_chan;
1026 args[3] = attr_number;
1027 args[4] = ctx->i1false;
1028 args[5] = params;
1029
1030 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2.f16",
1031 ctx->f16, args, 6, AC_FUNC_ATTR_READNONE);
1032 }
1033
1034 LLVMValueRef
1035 ac_build_fs_interp_mov(struct ac_llvm_context *ctx,
1036 LLVMValueRef parameter,
1037 LLVMValueRef llvm_chan,
1038 LLVMValueRef attr_number,
1039 LLVMValueRef params)
1040 {
1041 LLVMValueRef args[4];
1042
1043 args[0] = parameter;
1044 args[1] = llvm_chan;
1045 args[2] = attr_number;
1046 args[3] = params;
1047
1048 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.mov",
1049 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
1050 }
1051
1052 LLVMValueRef
1053 ac_build_gep_ptr(struct ac_llvm_context *ctx,
1054 LLVMValueRef base_ptr,
1055 LLVMValueRef index)
1056 {
1057 return LLVMBuildGEP(ctx->builder, base_ptr, &index, 1, "");
1058 }
1059
1060 LLVMValueRef
1061 ac_build_gep0(struct ac_llvm_context *ctx,
1062 LLVMValueRef base_ptr,
1063 LLVMValueRef index)
1064 {
1065 LLVMValueRef indices[2] = {
1066 ctx->i32_0,
1067 index,
1068 };
1069 return LLVMBuildGEP(ctx->builder, base_ptr, indices, 2, "");
1070 }
1071
1072 LLVMValueRef ac_build_pointer_add(struct ac_llvm_context *ctx, LLVMValueRef ptr,
1073 LLVMValueRef index)
1074 {
1075 return LLVMBuildPointerCast(ctx->builder,
1076 LLVMBuildGEP(ctx->builder, ptr, &index, 1, ""),
1077 LLVMTypeOf(ptr), "");
1078 }
1079
1080 void
1081 ac_build_indexed_store(struct ac_llvm_context *ctx,
1082 LLVMValueRef base_ptr, LLVMValueRef index,
1083 LLVMValueRef value)
1084 {
1085 LLVMBuildStore(ctx->builder, value,
1086 ac_build_gep0(ctx, base_ptr, index));
1087 }
1088
1089 /**
1090 * Build an LLVM bytecode indexed load using LLVMBuildGEP + LLVMBuildLoad.
1091 * It's equivalent to doing a load from &base_ptr[index].
1092 *
1093 * \param base_ptr Where the array starts.
1094 * \param index The element index into the array.
1095 * \param uniform Whether the base_ptr and index can be assumed to be
1096 * dynamically uniform (i.e. load to an SGPR)
1097 * \param invariant Whether the load is invariant (no other opcodes affect it)
1098 * \param no_unsigned_wraparound
1099 * For all possible re-associations and re-distributions of an expression
1100 * "base_ptr + index * elemsize" into "addr + offset" (excluding GEPs
1101 * without inbounds in base_ptr), this parameter is true if "addr + offset"
1102 * does not result in an unsigned integer wraparound. This is used for
1103 * optimal code generation of 32-bit pointer arithmetic.
1104 *
1105 * For example, a 32-bit immediate offset that causes a 32-bit unsigned
1106 * integer wraparound can't be an imm offset in s_load_dword, because
1107 * the instruction performs "addr + offset" in 64 bits.
1108 *
1109 * Expected usage for bindless textures by chaining GEPs:
1110 * // possible unsigned wraparound, don't use InBounds:
1111 * ptr1 = LLVMBuildGEP(base_ptr, index);
1112 * image = load(ptr1); // becomes "s_load ptr1, 0"
1113 *
1114 * ptr2 = LLVMBuildInBoundsGEP(ptr1, 32 / elemsize);
1115 * sampler = load(ptr2); // becomes "s_load ptr1, 32" thanks to InBounds
1116 */
1117 static LLVMValueRef
1118 ac_build_load_custom(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
1119 LLVMValueRef index, bool uniform, bool invariant,
1120 bool no_unsigned_wraparound)
1121 {
1122 LLVMValueRef pointer, result;
1123
1124 if (no_unsigned_wraparound &&
1125 LLVMGetPointerAddressSpace(LLVMTypeOf(base_ptr)) == AC_ADDR_SPACE_CONST_32BIT)
1126 pointer = LLVMBuildInBoundsGEP(ctx->builder, base_ptr, &index, 1, "");
1127 else
1128 pointer = LLVMBuildGEP(ctx->builder, base_ptr, &index, 1, "");
1129
1130 if (uniform)
1131 LLVMSetMetadata(pointer, ctx->uniform_md_kind, ctx->empty_md);
1132 result = LLVMBuildLoad(ctx->builder, pointer, "");
1133 if (invariant)
1134 LLVMSetMetadata(result, ctx->invariant_load_md_kind, ctx->empty_md);
1135 return result;
1136 }
1137
1138 LLVMValueRef ac_build_load(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
1139 LLVMValueRef index)
1140 {
1141 return ac_build_load_custom(ctx, base_ptr, index, false, false, false);
1142 }
1143
1144 LLVMValueRef ac_build_load_invariant(struct ac_llvm_context *ctx,
1145 LLVMValueRef base_ptr, LLVMValueRef index)
1146 {
1147 return ac_build_load_custom(ctx, base_ptr, index, false, true, false);
1148 }
1149
1150 /* This assumes that there is no unsigned integer wraparound during the address
1151 * computation, excluding all GEPs within base_ptr. */
1152 LLVMValueRef ac_build_load_to_sgpr(struct ac_llvm_context *ctx,
1153 LLVMValueRef base_ptr, LLVMValueRef index)
1154 {
1155 return ac_build_load_custom(ctx, base_ptr, index, true, true, true);
1156 }
1157
1158 /* See ac_build_load_custom() documentation. */
1159 LLVMValueRef ac_build_load_to_sgpr_uint_wraparound(struct ac_llvm_context *ctx,
1160 LLVMValueRef base_ptr, LLVMValueRef index)
1161 {
1162 return ac_build_load_custom(ctx, base_ptr, index, true, true, false);
1163 }
1164
1165 static unsigned get_load_cache_policy(struct ac_llvm_context *ctx,
1166 unsigned cache_policy)
1167 {
1168 return cache_policy |
1169 (ctx->chip_class >= GFX10 && cache_policy & ac_glc ? ac_dlc : 0);
1170 }
1171
1172 static void
1173 ac_build_buffer_store_common(struct ac_llvm_context *ctx,
1174 LLVMValueRef rsrc,
1175 LLVMValueRef data,
1176 LLVMValueRef vindex,
1177 LLVMValueRef voffset,
1178 LLVMValueRef soffset,
1179 unsigned num_channels,
1180 LLVMTypeRef return_channel_type,
1181 unsigned cache_policy,
1182 bool use_format,
1183 bool structurized)
1184 {
1185 LLVMValueRef args[6];
1186 int idx = 0;
1187 args[idx++] = data;
1188 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1189 if (structurized)
1190 args[idx++] = vindex ? vindex : ctx->i32_0;
1191 args[idx++] = voffset ? voffset : ctx->i32_0;
1192 args[idx++] = soffset ? soffset : ctx->i32_0;
1193 args[idx++] = LLVMConstInt(ctx->i32, cache_policy, 0);
1194 unsigned func = !ac_has_vec3_support(ctx->chip_class, use_format) && num_channels == 3 ? 4 : num_channels;
1195 const char *indexing_kind = structurized ? "struct" : "raw";
1196 char name[256], type_name[8];
1197
1198 LLVMTypeRef type = func > 1 ? LLVMVectorType(return_channel_type, func) : return_channel_type;
1199 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1200
1201 if (use_format) {
1202 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.format.%s",
1203 indexing_kind, type_name);
1204 } else {
1205 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.%s",
1206 indexing_kind, type_name);
1207 }
1208
1209 ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
1210 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY);
1211 }
1212
1213 void
1214 ac_build_buffer_store_format(struct ac_llvm_context *ctx,
1215 LLVMValueRef rsrc,
1216 LLVMValueRef data,
1217 LLVMValueRef vindex,
1218 LLVMValueRef voffset,
1219 unsigned num_channels,
1220 unsigned cache_policy)
1221 {
1222 ac_build_buffer_store_common(ctx, rsrc, data, vindex,
1223 voffset, NULL, num_channels,
1224 ctx->f32, cache_policy,
1225 true, true);
1226 }
1227
1228 /* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
1229 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
1230 * or v4i32 (num_channels=3,4).
1231 */
1232 void
1233 ac_build_buffer_store_dword(struct ac_llvm_context *ctx,
1234 LLVMValueRef rsrc,
1235 LLVMValueRef vdata,
1236 unsigned num_channels,
1237 LLVMValueRef voffset,
1238 LLVMValueRef soffset,
1239 unsigned inst_offset,
1240 unsigned cache_policy)
1241 {
1242 /* Split 3 channel stores, because only LLVM 9+ support 3-channel
1243 * intrinsics. */
1244 if (num_channels == 3 && !ac_has_vec3_support(ctx->chip_class, false)) {
1245 LLVMValueRef v[3], v01;
1246
1247 for (int i = 0; i < 3; i++) {
1248 v[i] = LLVMBuildExtractElement(ctx->builder, vdata,
1249 LLVMConstInt(ctx->i32, i, 0), "");
1250 }
1251 v01 = ac_build_gather_values(ctx, v, 2);
1252
1253 ac_build_buffer_store_dword(ctx, rsrc, v01, 2, voffset,
1254 soffset, inst_offset, cache_policy);
1255 ac_build_buffer_store_dword(ctx, rsrc, v[2], 1, voffset,
1256 soffset, inst_offset + 8,
1257 cache_policy);
1258 return;
1259 }
1260
1261 /* SWIZZLE_ENABLE requires that soffset isn't folded into voffset
1262 * (voffset is swizzled, but soffset isn't swizzled).
1263 * llvm.amdgcn.buffer.store doesn't have a separate soffset parameter.
1264 */
1265 if (!(cache_policy & ac_swizzled)) {
1266 LLVMValueRef offset = soffset;
1267
1268 if (inst_offset)
1269 offset = LLVMBuildAdd(ctx->builder, offset,
1270 LLVMConstInt(ctx->i32, inst_offset, 0), "");
1271
1272 ac_build_buffer_store_common(ctx, rsrc, ac_to_float(ctx, vdata),
1273 ctx->i32_0, voffset, offset,
1274 num_channels, ctx->f32,
1275 cache_policy, false, false);
1276 return;
1277 }
1278
1279 static const unsigned dfmts[] = {
1280 V_008F0C_BUF_DATA_FORMAT_32,
1281 V_008F0C_BUF_DATA_FORMAT_32_32,
1282 V_008F0C_BUF_DATA_FORMAT_32_32_32,
1283 V_008F0C_BUF_DATA_FORMAT_32_32_32_32
1284 };
1285 unsigned dfmt = dfmts[num_channels - 1];
1286 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1287 LLVMValueRef immoffset = LLVMConstInt(ctx->i32, inst_offset, 0);
1288
1289 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1290 immoffset, num_channels, dfmt, nfmt, cache_policy);
1291 }
1292
1293 static LLVMValueRef
1294 ac_build_buffer_load_common(struct ac_llvm_context *ctx,
1295 LLVMValueRef rsrc,
1296 LLVMValueRef vindex,
1297 LLVMValueRef voffset,
1298 LLVMValueRef soffset,
1299 unsigned num_channels,
1300 LLVMTypeRef channel_type,
1301 unsigned cache_policy,
1302 bool can_speculate,
1303 bool use_format,
1304 bool structurized)
1305 {
1306 LLVMValueRef args[5];
1307 int idx = 0;
1308 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1309 if (structurized)
1310 args[idx++] = vindex ? vindex : ctx->i32_0;
1311 args[idx++] = voffset ? voffset : ctx->i32_0;
1312 args[idx++] = soffset ? soffset : ctx->i32_0;
1313 args[idx++] = LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0);
1314 unsigned func = !ac_has_vec3_support(ctx->chip_class, use_format) && num_channels == 3 ? 4 : num_channels;
1315 const char *indexing_kind = structurized ? "struct" : "raw";
1316 char name[256], type_name[8];
1317
1318 LLVMTypeRef type = func > 1 ? LLVMVectorType(channel_type, func) : channel_type;
1319 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1320
1321 if (use_format) {
1322 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.format.%s",
1323 indexing_kind, type_name);
1324 } else {
1325 snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.%s",
1326 indexing_kind, type_name);
1327 }
1328
1329 return ac_build_intrinsic(ctx, name, type, args, idx,
1330 ac_get_load_intr_attribs(can_speculate));
1331 }
1332
1333 LLVMValueRef
1334 ac_build_buffer_load(struct ac_llvm_context *ctx,
1335 LLVMValueRef rsrc,
1336 int num_channels,
1337 LLVMValueRef vindex,
1338 LLVMValueRef voffset,
1339 LLVMValueRef soffset,
1340 unsigned inst_offset,
1341 unsigned cache_policy,
1342 bool can_speculate,
1343 bool allow_smem)
1344 {
1345 LLVMValueRef offset = LLVMConstInt(ctx->i32, inst_offset, 0);
1346 if (voffset)
1347 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
1348 if (soffset)
1349 offset = LLVMBuildAdd(ctx->builder, offset, soffset, "");
1350
1351 if (allow_smem && !(cache_policy & ac_slc) &&
1352 (!(cache_policy & ac_glc) || ctx->chip_class >= GFX8)) {
1353 assert(vindex == NULL);
1354
1355 LLVMValueRef result[8];
1356
1357 for (int i = 0; i < num_channels; i++) {
1358 if (i) {
1359 offset = LLVMBuildAdd(ctx->builder, offset,
1360 LLVMConstInt(ctx->i32, 4, 0), "");
1361 }
1362 LLVMValueRef args[3] = {
1363 rsrc,
1364 offset,
1365 LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0),
1366 };
1367 result[i] = ac_build_intrinsic(ctx,
1368 "llvm.amdgcn.s.buffer.load.f32",
1369 ctx->f32, args, 3,
1370 AC_FUNC_ATTR_READNONE);
1371 }
1372 if (num_channels == 1)
1373 return result[0];
1374
1375 if (num_channels == 3 && !ac_has_vec3_support(ctx->chip_class, false))
1376 result[num_channels++] = LLVMGetUndef(ctx->f32);
1377 return ac_build_gather_values(ctx, result, num_channels);
1378 }
1379
1380 return ac_build_buffer_load_common(ctx, rsrc, vindex,
1381 offset, ctx->i32_0,
1382 num_channels, ctx->f32,
1383 cache_policy,
1384 can_speculate, false, false);
1385 }
1386
1387 LLVMValueRef ac_build_buffer_load_format(struct ac_llvm_context *ctx,
1388 LLVMValueRef rsrc,
1389 LLVMValueRef vindex,
1390 LLVMValueRef voffset,
1391 unsigned num_channels,
1392 unsigned cache_policy,
1393 bool can_speculate)
1394 {
1395 return ac_build_buffer_load_common(ctx, rsrc, vindex, voffset,
1396 ctx->i32_0, num_channels, ctx->f32,
1397 cache_policy, can_speculate,
1398 true, true);
1399 }
1400
1401 static LLVMValueRef
1402 ac_build_tbuffer_load(struct ac_llvm_context *ctx,
1403 LLVMValueRef rsrc,
1404 LLVMValueRef vindex,
1405 LLVMValueRef voffset,
1406 LLVMValueRef soffset,
1407 LLVMValueRef immoffset,
1408 unsigned num_channels,
1409 unsigned dfmt,
1410 unsigned nfmt,
1411 unsigned cache_policy,
1412 bool can_speculate,
1413 bool structurized)
1414 {
1415 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1416
1417 LLVMValueRef args[6];
1418 int idx = 0;
1419 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1420 if (structurized)
1421 args[idx++] = vindex ? vindex : ctx->i32_0;
1422 args[idx++] = voffset ? voffset : ctx->i32_0;
1423 args[idx++] = soffset ? soffset : ctx->i32_0;
1424 args[idx++] = LLVMConstInt(ctx->i32, ac_get_tbuffer_format(ctx->chip_class, dfmt, nfmt), 0);
1425 args[idx++] = LLVMConstInt(ctx->i32, get_load_cache_policy(ctx, cache_policy), 0);
1426 unsigned func = !ac_has_vec3_support(ctx->chip_class, true) && num_channels == 3 ? 4 : num_channels;
1427 const char *indexing_kind = structurized ? "struct" : "raw";
1428 char name[256], type_name[8];
1429
1430 LLVMTypeRef type = func > 1 ? LLVMVectorType(ctx->i32, func) : ctx->i32;
1431 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1432
1433 snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.load.%s",
1434 indexing_kind, type_name);
1435
1436 return ac_build_intrinsic(ctx, name, type, args, idx,
1437 ac_get_load_intr_attribs(can_speculate));
1438 }
1439
1440 LLVMValueRef
1441 ac_build_struct_tbuffer_load(struct ac_llvm_context *ctx,
1442 LLVMValueRef rsrc,
1443 LLVMValueRef vindex,
1444 LLVMValueRef voffset,
1445 LLVMValueRef soffset,
1446 LLVMValueRef immoffset,
1447 unsigned num_channels,
1448 unsigned dfmt,
1449 unsigned nfmt,
1450 unsigned cache_policy,
1451 bool can_speculate)
1452 {
1453 return ac_build_tbuffer_load(ctx, rsrc, vindex, voffset, soffset,
1454 immoffset, num_channels, dfmt, nfmt,
1455 cache_policy, can_speculate, true);
1456 }
1457
1458 LLVMValueRef
1459 ac_build_raw_tbuffer_load(struct ac_llvm_context *ctx,
1460 LLVMValueRef rsrc,
1461 LLVMValueRef voffset,
1462 LLVMValueRef soffset,
1463 LLVMValueRef immoffset,
1464 unsigned num_channels,
1465 unsigned dfmt,
1466 unsigned nfmt,
1467 unsigned cache_policy,
1468 bool can_speculate)
1469 {
1470 return ac_build_tbuffer_load(ctx, rsrc, NULL, voffset, soffset,
1471 immoffset, num_channels, dfmt, nfmt,
1472 cache_policy, can_speculate, false);
1473 }
1474
1475 LLVMValueRef
1476 ac_build_tbuffer_load_short(struct ac_llvm_context *ctx,
1477 LLVMValueRef rsrc,
1478 LLVMValueRef voffset,
1479 LLVMValueRef soffset,
1480 LLVMValueRef immoffset,
1481 unsigned cache_policy)
1482 {
1483 LLVMValueRef res;
1484
1485 if (LLVM_VERSION_MAJOR >= 9) {
1486 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1487
1488 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1489 res = ac_build_buffer_load_common(ctx, rsrc, NULL,
1490 voffset, soffset,
1491 1, ctx->i16, cache_policy,
1492 false, false, false);
1493 } else {
1494 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
1495 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1496
1497 res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
1498 immoffset, 1, dfmt, nfmt, cache_policy,
1499 false);
1500
1501 res = LLVMBuildTrunc(ctx->builder, res, ctx->i16, "");
1502 }
1503
1504 return res;
1505 }
1506
1507 LLVMValueRef
1508 ac_build_tbuffer_load_byte(struct ac_llvm_context *ctx,
1509 LLVMValueRef rsrc,
1510 LLVMValueRef voffset,
1511 LLVMValueRef soffset,
1512 LLVMValueRef immoffset,
1513 unsigned cache_policy)
1514 {
1515 LLVMValueRef res;
1516
1517 if (LLVM_VERSION_MAJOR >= 9) {
1518 voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");
1519
1520 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1521 res = ac_build_buffer_load_common(ctx, rsrc, NULL,
1522 voffset, soffset,
1523 1, ctx->i8, cache_policy,
1524 false, false, false);
1525 } else {
1526 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_8;
1527 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1528
1529 res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
1530 immoffset, 1, dfmt, nfmt, cache_policy,
1531 false);
1532
1533 res = LLVMBuildTrunc(ctx->builder, res, ctx->i8, "");
1534 }
1535
1536 return res;
1537 }
1538
1539 /**
1540 * Convert an 11- or 10-bit unsigned floating point number to an f32.
1541 *
1542 * The input exponent is expected to be biased analogous to IEEE-754, i.e. by
1543 * 2^(exp_bits-1) - 1 (as defined in OpenGL and other graphics APIs).
1544 */
1545 static LLVMValueRef
1546 ac_ufN_to_float(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned exp_bits, unsigned mant_bits)
1547 {
1548 assert(LLVMTypeOf(src) == ctx->i32);
1549
1550 LLVMValueRef tmp;
1551 LLVMValueRef mantissa;
1552 mantissa = LLVMBuildAnd(ctx->builder, src, LLVMConstInt(ctx->i32, (1 << mant_bits) - 1, false), "");
1553
1554 /* Converting normal numbers is just a shift + correcting the exponent bias */
1555 unsigned normal_shift = 23 - mant_bits;
1556 unsigned bias_shift = 127 - ((1 << (exp_bits - 1)) - 1);
1557 LLVMValueRef shifted, normal;
1558
1559 shifted = LLVMBuildShl(ctx->builder, src, LLVMConstInt(ctx->i32, normal_shift, false), "");
1560 normal = LLVMBuildAdd(ctx->builder, shifted, LLVMConstInt(ctx->i32, bias_shift << 23, false), "");
1561
1562 /* Converting nan/inf numbers is the same, but with a different exponent update */
1563 LLVMValueRef naninf;
1564 naninf = LLVMBuildOr(ctx->builder, normal, LLVMConstInt(ctx->i32, 0xff << 23, false), "");
1565
1566 /* Converting denormals is the complex case: determine the leading zeros of the
1567 * mantissa to obtain the correct shift for the mantissa and exponent correction.
1568 */
1569 LLVMValueRef denormal;
1570 LLVMValueRef params[2] = {
1571 mantissa,
1572 ctx->i1true, /* result can be undef when arg is 0 */
1573 };
1574 LLVMValueRef ctlz = ac_build_intrinsic(ctx, "llvm.ctlz.i32", ctx->i32,
1575 params, 2, AC_FUNC_ATTR_READNONE);
1576
1577 /* Shift such that the leading 1 ends up as the LSB of the exponent field. */
1578 tmp = LLVMBuildSub(ctx->builder, ctlz, LLVMConstInt(ctx->i32, 8, false), "");
1579 denormal = LLVMBuildShl(ctx->builder, mantissa, tmp, "");
1580
1581 unsigned denormal_exp = bias_shift + (32 - mant_bits) - 1;
1582 tmp = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, denormal_exp, false), ctlz, "");
1583 tmp = LLVMBuildShl(ctx->builder, tmp, LLVMConstInt(ctx->i32, 23, false), "");
1584 denormal = LLVMBuildAdd(ctx->builder, denormal, tmp, "");
1585
1586 /* Select the final result. */
1587 LLVMValueRef result;
1588
1589 tmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, src,
1590 LLVMConstInt(ctx->i32, ((1 << exp_bits) - 1) << mant_bits, false), "");
1591 result = LLVMBuildSelect(ctx->builder, tmp, naninf, normal, "");
1592
1593 tmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, src,
1594 LLVMConstInt(ctx->i32, 1 << mant_bits, false), "");
1595 result = LLVMBuildSelect(ctx->builder, tmp, result, denormal, "");
1596
1597 tmp = LLVMBuildICmp(ctx->builder, LLVMIntNE, src, ctx->i32_0, "");
1598 result = LLVMBuildSelect(ctx->builder, tmp, result, ctx->i32_0, "");
1599
1600 return ac_to_float(ctx, result);
1601 }
1602
1603 /**
1604 * Generate a fully general open coded buffer format fetch with all required
1605 * fixups suitable for vertex fetch, using non-format buffer loads.
1606 *
1607 * Some combinations of argument values have special interpretations:
1608 * - size = 8 bytes, format = fixed indicates PIPE_FORMAT_R11G11B10_FLOAT
1609 * - size = 8 bytes, format != {float,fixed} indicates a 2_10_10_10 data format
1610 *
1611 * \param log_size log(size of channel in bytes)
1612 * \param num_channels number of channels (1 to 4)
1613 * \param format AC_FETCH_FORMAT_xxx value
1614 * \param reverse whether XYZ channels are reversed
1615 * \param known_aligned whether the source is known to be aligned to hardware's
1616 * effective element size for loading the given format
1617 * (note: this means dword alignment for 8_8_8_8, 16_16, etc.)
1618 * \param rsrc buffer resource descriptor
1619 * \return the resulting vector of floats or integers bitcast to <4 x i32>
1620 */
1621 LLVMValueRef
1622 ac_build_opencoded_load_format(struct ac_llvm_context *ctx,
1623 unsigned log_size,
1624 unsigned num_channels,
1625 unsigned format,
1626 bool reverse,
1627 bool known_aligned,
1628 LLVMValueRef rsrc,
1629 LLVMValueRef vindex,
1630 LLVMValueRef voffset,
1631 LLVMValueRef soffset,
1632 unsigned cache_policy,
1633 bool can_speculate)
1634 {
1635 LLVMValueRef tmp;
1636 unsigned load_log_size = log_size;
1637 unsigned load_num_channels = num_channels;
1638 if (log_size == 3) {
1639 load_log_size = 2;
1640 if (format == AC_FETCH_FORMAT_FLOAT) {
1641 load_num_channels = 2 * num_channels;
1642 } else {
1643 load_num_channels = 1; /* 10_11_11 or 2_10_10_10 */
1644 }
1645 }
1646
1647 int log_recombine = 0;
1648 if (ctx->chip_class == GFX6 && !known_aligned) {
1649 /* Avoid alignment restrictions by loading one byte at a time. */
1650 load_num_channels <<= load_log_size;
1651 log_recombine = load_log_size;
1652 load_log_size = 0;
1653 } else if (load_num_channels == 2 || load_num_channels == 4) {
1654 log_recombine = -util_logbase2(load_num_channels);
1655 load_num_channels = 1;
1656 load_log_size += -log_recombine;
1657 }
1658
1659 assert(load_log_size >= 2 || LLVM_VERSION_MAJOR >= 9);
1660
1661 LLVMValueRef loads[32]; /* up to 32 bytes */
1662 for (unsigned i = 0; i < load_num_channels; ++i) {
1663 tmp = LLVMBuildAdd(ctx->builder, soffset,
1664 LLVMConstInt(ctx->i32, i << load_log_size, false), "");
1665 LLVMTypeRef channel_type = load_log_size == 0 ? ctx->i8 :
1666 load_log_size == 1 ? ctx->i16 : ctx->i32;
1667 unsigned num_channels = 1 << (MAX2(load_log_size, 2) - 2);
1668 loads[i] = ac_build_buffer_load_common(
1669 ctx, rsrc, vindex, voffset, tmp,
1670 num_channels, channel_type, cache_policy,
1671 can_speculate, false, true);
1672 if (load_log_size >= 2)
1673 loads[i] = ac_to_integer(ctx, loads[i]);
1674 }
1675
1676 if (log_recombine > 0) {
1677 /* Recombine bytes if necessary (GFX6 only) */
1678 LLVMTypeRef dst_type = log_recombine == 2 ? ctx->i32 : ctx->i16;
1679
1680 for (unsigned src = 0, dst = 0; src < load_num_channels; ++dst) {
1681 LLVMValueRef accum = NULL;
1682 for (unsigned i = 0; i < (1 << log_recombine); ++i, ++src) {
1683 tmp = LLVMBuildZExt(ctx->builder, loads[src], dst_type, "");
1684 if (i == 0) {
1685 accum = tmp;
1686 } else {
1687 tmp = LLVMBuildShl(ctx->builder, tmp,
1688 LLVMConstInt(dst_type, 8 * i, false), "");
1689 accum = LLVMBuildOr(ctx->builder, accum, tmp, "");
1690 }
1691 }
1692 loads[dst] = accum;
1693 }
1694 } else if (log_recombine < 0) {
1695 /* Split vectors of dwords */
1696 if (load_log_size > 2) {
1697 assert(load_num_channels == 1);
1698 LLVMValueRef loaded = loads[0];
1699 unsigned log_split = load_log_size - 2;
1700 log_recombine += log_split;
1701 load_num_channels = 1 << log_split;
1702 load_log_size = 2;
1703 for (unsigned i = 0; i < load_num_channels; ++i) {
1704 tmp = LLVMConstInt(ctx->i32, i, false);
1705 loads[i] = LLVMBuildExtractElement(ctx->builder, loaded, tmp, "");
1706 }
1707 }
1708
1709 /* Further split dwords and shorts if required */
1710 if (log_recombine < 0) {
1711 for (unsigned src = load_num_channels,
1712 dst = load_num_channels << -log_recombine;
1713 src > 0; --src) {
1714 unsigned dst_bits = 1 << (3 + load_log_size + log_recombine);
1715 LLVMTypeRef dst_type = LLVMIntTypeInContext(ctx->context, dst_bits);
1716 LLVMValueRef loaded = loads[src - 1];
1717 LLVMTypeRef loaded_type = LLVMTypeOf(loaded);
1718 for (unsigned i = 1 << -log_recombine; i > 0; --i, --dst) {
1719 tmp = LLVMConstInt(loaded_type, dst_bits * (i - 1), false);
1720 tmp = LLVMBuildLShr(ctx->builder, loaded, tmp, "");
1721 loads[dst - 1] = LLVMBuildTrunc(ctx->builder, tmp, dst_type, "");
1722 }
1723 }
1724 }
1725 }
1726
1727 if (log_size == 3) {
1728 if (format == AC_FETCH_FORMAT_FLOAT) {
1729 for (unsigned i = 0; i < num_channels; ++i) {
1730 tmp = ac_build_gather_values(ctx, &loads[2 * i], 2);
1731 loads[i] = LLVMBuildBitCast(ctx->builder, tmp, ctx->f64, "");
1732 }
1733 } else if (format == AC_FETCH_FORMAT_FIXED) {
1734 /* 10_11_11_FLOAT */
1735 LLVMValueRef data = loads[0];
1736 LLVMValueRef i32_2047 = LLVMConstInt(ctx->i32, 2047, false);
1737 LLVMValueRef r = LLVMBuildAnd(ctx->builder, data, i32_2047, "");
1738 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 11, false), "");
1739 LLVMValueRef g = LLVMBuildAnd(ctx->builder, tmp, i32_2047, "");
1740 LLVMValueRef b = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 22, false), "");
1741
1742 loads[0] = ac_to_integer(ctx, ac_ufN_to_float(ctx, r, 5, 6));
1743 loads[1] = ac_to_integer(ctx, ac_ufN_to_float(ctx, g, 5, 6));
1744 loads[2] = ac_to_integer(ctx, ac_ufN_to_float(ctx, b, 5, 5));
1745
1746 num_channels = 3;
1747 log_size = 2;
1748 format = AC_FETCH_FORMAT_FLOAT;
1749 } else {
1750 /* 2_10_10_10 data formats */
1751 LLVMValueRef data = loads[0];
1752 LLVMTypeRef i10 = LLVMIntTypeInContext(ctx->context, 10);
1753 LLVMTypeRef i2 = LLVMIntTypeInContext(ctx->context, 2);
1754 loads[0] = LLVMBuildTrunc(ctx->builder, data, i10, "");
1755 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 10, false), "");
1756 loads[1] = LLVMBuildTrunc(ctx->builder, tmp, i10, "");
1757 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 20, false), "");
1758 loads[2] = LLVMBuildTrunc(ctx->builder, tmp, i10, "");
1759 tmp = LLVMBuildLShr(ctx->builder, data, LLVMConstInt(ctx->i32, 30, false), "");
1760 loads[3] = LLVMBuildTrunc(ctx->builder, tmp, i2, "");
1761
1762 num_channels = 4;
1763 }
1764 }
1765
1766 if (format == AC_FETCH_FORMAT_FLOAT) {
1767 if (log_size != 2) {
1768 for (unsigned chan = 0; chan < num_channels; ++chan) {
1769 tmp = ac_to_float(ctx, loads[chan]);
1770 if (log_size == 3)
1771 tmp = LLVMBuildFPTrunc(ctx->builder, tmp, ctx->f32, "");
1772 else if (log_size == 1)
1773 tmp = LLVMBuildFPExt(ctx->builder, tmp, ctx->f32, "");
1774 loads[chan] = ac_to_integer(ctx, tmp);
1775 }
1776 }
1777 } else if (format == AC_FETCH_FORMAT_UINT) {
1778 if (log_size != 2) {
1779 for (unsigned chan = 0; chan < num_channels; ++chan)
1780 loads[chan] = LLVMBuildZExt(ctx->builder, loads[chan], ctx->i32, "");
1781 }
1782 } else if (format == AC_FETCH_FORMAT_SINT) {
1783 if (log_size != 2) {
1784 for (unsigned chan = 0; chan < num_channels; ++chan)
1785 loads[chan] = LLVMBuildSExt(ctx->builder, loads[chan], ctx->i32, "");
1786 }
1787 } else {
1788 bool unsign = format == AC_FETCH_FORMAT_UNORM ||
1789 format == AC_FETCH_FORMAT_USCALED ||
1790 format == AC_FETCH_FORMAT_UINT;
1791
1792 for (unsigned chan = 0; chan < num_channels; ++chan) {
1793 if (unsign) {
1794 tmp = LLVMBuildUIToFP(ctx->builder, loads[chan], ctx->f32, "");
1795 } else {
1796 tmp = LLVMBuildSIToFP(ctx->builder, loads[chan], ctx->f32, "");
1797 }
1798
1799 LLVMValueRef scale = NULL;
1800 if (format == AC_FETCH_FORMAT_FIXED) {
1801 assert(log_size == 2);
1802 scale = LLVMConstReal(ctx->f32, 1.0 / 0x10000);
1803 } else if (format == AC_FETCH_FORMAT_UNORM) {
1804 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(loads[chan]));
1805 scale = LLVMConstReal(ctx->f32, 1.0 / (((uint64_t)1 << bits) - 1));
1806 } else if (format == AC_FETCH_FORMAT_SNORM) {
1807 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(loads[chan]));
1808 scale = LLVMConstReal(ctx->f32, 1.0 / (((uint64_t)1 << (bits - 1)) - 1));
1809 }
1810 if (scale)
1811 tmp = LLVMBuildFMul(ctx->builder, tmp, scale, "");
1812
1813 if (format == AC_FETCH_FORMAT_SNORM) {
1814 /* Clamp to [-1, 1] */
1815 LLVMValueRef neg_one = LLVMConstReal(ctx->f32, -1.0);
1816 LLVMValueRef clamp =
1817 LLVMBuildFCmp(ctx->builder, LLVMRealULT, tmp, neg_one, "");
1818 tmp = LLVMBuildSelect(ctx->builder, clamp, neg_one, tmp, "");
1819 }
1820
1821 loads[chan] = ac_to_integer(ctx, tmp);
1822 }
1823 }
1824
1825 while (num_channels < 4) {
1826 if (format == AC_FETCH_FORMAT_UINT || format == AC_FETCH_FORMAT_SINT) {
1827 loads[num_channels] = num_channels == 3 ? ctx->i32_1 : ctx->i32_0;
1828 } else {
1829 loads[num_channels] = ac_to_integer(ctx, num_channels == 3 ? ctx->f32_1 : ctx->f32_0);
1830 }
1831 num_channels++;
1832 }
1833
1834 if (reverse) {
1835 tmp = loads[0];
1836 loads[0] = loads[2];
1837 loads[2] = tmp;
1838 }
1839
1840 return ac_build_gather_values(ctx, loads, 4);
1841 }
1842
1843 static void
1844 ac_build_tbuffer_store(struct ac_llvm_context *ctx,
1845 LLVMValueRef rsrc,
1846 LLVMValueRef vdata,
1847 LLVMValueRef vindex,
1848 LLVMValueRef voffset,
1849 LLVMValueRef soffset,
1850 LLVMValueRef immoffset,
1851 unsigned num_channels,
1852 unsigned dfmt,
1853 unsigned nfmt,
1854 unsigned cache_policy,
1855 bool structurized)
1856 {
1857 voffset = LLVMBuildAdd(ctx->builder, voffset ? voffset : ctx->i32_0,
1858 immoffset, "");
1859
1860 LLVMValueRef args[7];
1861 int idx = 0;
1862 args[idx++] = vdata;
1863 args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
1864 if (structurized)
1865 args[idx++] = vindex ? vindex : ctx->i32_0;
1866 args[idx++] = voffset ? voffset : ctx->i32_0;
1867 args[idx++] = soffset ? soffset : ctx->i32_0;
1868 args[idx++] = LLVMConstInt(ctx->i32, ac_get_tbuffer_format(ctx->chip_class, dfmt, nfmt), 0);
1869 args[idx++] = LLVMConstInt(ctx->i32, cache_policy, 0);
1870 unsigned func = !ac_has_vec3_support(ctx->chip_class, true) && num_channels == 3 ? 4 : num_channels;
1871 const char *indexing_kind = structurized ? "struct" : "raw";
1872 char name[256], type_name[8];
1873
1874 LLVMTypeRef type = func > 1 ? LLVMVectorType(ctx->i32, func) : ctx->i32;
1875 ac_build_type_name_for_intr(type, type_name, sizeof(type_name));
1876
1877 snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.store.%s",
1878 indexing_kind, type_name);
1879
1880 ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
1881 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY);
1882 }
1883
1884 void
1885 ac_build_struct_tbuffer_store(struct ac_llvm_context *ctx,
1886 LLVMValueRef rsrc,
1887 LLVMValueRef vdata,
1888 LLVMValueRef vindex,
1889 LLVMValueRef voffset,
1890 LLVMValueRef soffset,
1891 LLVMValueRef immoffset,
1892 unsigned num_channels,
1893 unsigned dfmt,
1894 unsigned nfmt,
1895 unsigned cache_policy)
1896 {
1897 ac_build_tbuffer_store(ctx, rsrc, vdata, vindex, voffset, soffset,
1898 immoffset, num_channels, dfmt, nfmt, cache_policy,
1899 true);
1900 }
1901
1902 void
1903 ac_build_raw_tbuffer_store(struct ac_llvm_context *ctx,
1904 LLVMValueRef rsrc,
1905 LLVMValueRef vdata,
1906 LLVMValueRef voffset,
1907 LLVMValueRef soffset,
1908 LLVMValueRef immoffset,
1909 unsigned num_channels,
1910 unsigned dfmt,
1911 unsigned nfmt,
1912 unsigned cache_policy)
1913 {
1914 ac_build_tbuffer_store(ctx, rsrc, vdata, NULL, voffset, soffset,
1915 immoffset, num_channels, dfmt, nfmt, cache_policy,
1916 false);
1917 }
1918
1919 void
1920 ac_build_tbuffer_store_short(struct ac_llvm_context *ctx,
1921 LLVMValueRef rsrc,
1922 LLVMValueRef vdata,
1923 LLVMValueRef voffset,
1924 LLVMValueRef soffset,
1925 unsigned cache_policy)
1926 {
1927 vdata = LLVMBuildBitCast(ctx->builder, vdata, ctx->i16, "");
1928
1929 if (LLVM_VERSION_MAJOR >= 9) {
1930 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1931 ac_build_buffer_store_common(ctx, rsrc, vdata, NULL,
1932 voffset, soffset, 1,
1933 ctx->i16, cache_policy,
1934 false, false);
1935 } else {
1936 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
1937 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1938
1939 vdata = LLVMBuildZExt(ctx->builder, vdata, ctx->i32, "");
1940
1941 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1942 ctx->i32_0, 1, dfmt, nfmt, cache_policy);
1943 }
1944 }
1945
1946 void
1947 ac_build_tbuffer_store_byte(struct ac_llvm_context *ctx,
1948 LLVMValueRef rsrc,
1949 LLVMValueRef vdata,
1950 LLVMValueRef voffset,
1951 LLVMValueRef soffset,
1952 unsigned cache_policy)
1953 {
1954 vdata = LLVMBuildBitCast(ctx->builder, vdata, ctx->i8, "");
1955
1956 if (LLVM_VERSION_MAJOR >= 9) {
1957 /* LLVM 9+ supports i8/i16 with struct/raw intrinsics. */
1958 ac_build_buffer_store_common(ctx, rsrc, vdata, NULL,
1959 voffset, soffset, 1,
1960 ctx->i8, cache_policy,
1961 false, false);
1962 } else {
1963 unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_8;
1964 unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
1965
1966 vdata = LLVMBuildZExt(ctx->builder, vdata, ctx->i32, "");
1967
1968 ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
1969 ctx->i32_0, 1, dfmt, nfmt, cache_policy);
1970 }
1971 }
1972 /**
1973 * Set range metadata on an instruction. This can only be used on load and
1974 * call instructions. If you know an instruction can only produce the values
1975 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
1976 * \p lo is the minimum value inclusive.
1977 * \p hi is the maximum value exclusive.
1978 */
1979 static void set_range_metadata(struct ac_llvm_context *ctx,
1980 LLVMValueRef value, unsigned lo, unsigned hi)
1981 {
1982 LLVMValueRef range_md, md_args[2];
1983 LLVMTypeRef type = LLVMTypeOf(value);
1984 LLVMContextRef context = LLVMGetTypeContext(type);
1985
1986 md_args[0] = LLVMConstInt(type, lo, false);
1987 md_args[1] = LLVMConstInt(type, hi, false);
1988 range_md = LLVMMDNodeInContext(context, md_args, 2);
1989 LLVMSetMetadata(value, ctx->range_md_kind, range_md);
1990 }
1991
1992 LLVMValueRef
1993 ac_get_thread_id(struct ac_llvm_context *ctx)
1994 {
1995 LLVMValueRef tid;
1996
1997 LLVMValueRef tid_args[2];
1998 tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
1999 tid_args[1] = ctx->i32_0;
2000 tid_args[1] = ac_build_intrinsic(ctx,
2001 "llvm.amdgcn.mbcnt.lo", ctx->i32,
2002 tid_args, 2, AC_FUNC_ATTR_READNONE);
2003
2004 if (ctx->wave_size == 32) {
2005 tid = tid_args[1];
2006 } else {
2007 tid = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi",
2008 ctx->i32, tid_args,
2009 2, AC_FUNC_ATTR_READNONE);
2010 }
2011 set_range_metadata(ctx, tid, 0, ctx->wave_size);
2012 return tid;
2013 }
2014
2015 /*
2016 * AMD GCN implements derivatives using the local data store (LDS)
2017 * All writes to the LDS happen in all executing threads at
2018 * the same time. TID is the Thread ID for the current
2019 * thread and is a value between 0 and 63, representing
2020 * the thread's position in the wavefront.
2021 *
2022 * For the pixel shader threads are grouped into quads of four pixels.
2023 * The TIDs of the pixels of a quad are:
2024 *
2025 * +------+------+
2026 * |4n + 0|4n + 1|
2027 * +------+------+
2028 * |4n + 2|4n + 3|
2029 * +------+------+
2030 *
2031 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
2032 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
2033 * the current pixel's column, and masking with 0xfffffffe yields the TID
2034 * of the left pixel of the current pixel's row.
2035 *
2036 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
2037 * adding 2 yields the TID of the pixel below the top pixel.
2038 */
2039 LLVMValueRef
2040 ac_build_ddxy(struct ac_llvm_context *ctx,
2041 uint32_t mask,
2042 int idx,
2043 LLVMValueRef val)
2044 {
2045 unsigned tl_lanes[4], trbl_lanes[4];
2046 char name[32], type[8];
2047 LLVMValueRef tl, trbl;
2048 LLVMTypeRef result_type;
2049 LLVMValueRef result;
2050
2051 result_type = ac_to_float_type(ctx, LLVMTypeOf(val));
2052
2053 if (result_type == ctx->f16)
2054 val = LLVMBuildZExt(ctx->builder, val, ctx->i32, "");
2055
2056 for (unsigned i = 0; i < 4; ++i) {
2057 tl_lanes[i] = i & mask;
2058 trbl_lanes[i] = (i & mask) + idx;
2059 }
2060
2061 tl = ac_build_quad_swizzle(ctx, val,
2062 tl_lanes[0], tl_lanes[1],
2063 tl_lanes[2], tl_lanes[3]);
2064 trbl = ac_build_quad_swizzle(ctx, val,
2065 trbl_lanes[0], trbl_lanes[1],
2066 trbl_lanes[2], trbl_lanes[3]);
2067
2068 if (result_type == ctx->f16) {
2069 tl = LLVMBuildTrunc(ctx->builder, tl, ctx->i16, "");
2070 trbl = LLVMBuildTrunc(ctx->builder, trbl, ctx->i16, "");
2071 }
2072
2073 tl = LLVMBuildBitCast(ctx->builder, tl, result_type, "");
2074 trbl = LLVMBuildBitCast(ctx->builder, trbl, result_type, "");
2075 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
2076
2077 ac_build_type_name_for_intr(result_type, type, sizeof(type));
2078 snprintf(name, sizeof(name), "llvm.amdgcn.wqm.%s", type);
2079
2080 return ac_build_intrinsic(ctx, name, result_type, &result, 1, 0);
2081 }
2082
2083 void
2084 ac_build_sendmsg(struct ac_llvm_context *ctx,
2085 uint32_t msg,
2086 LLVMValueRef wave_id)
2087 {
2088 LLVMValueRef args[2];
2089 args[0] = LLVMConstInt(ctx->i32, msg, false);
2090 args[1] = wave_id;
2091 ac_build_intrinsic(ctx, "llvm.amdgcn.s.sendmsg", ctx->voidt, args, 2, 0);
2092 }
2093
2094 LLVMValueRef
2095 ac_build_imsb(struct ac_llvm_context *ctx,
2096 LLVMValueRef arg,
2097 LLVMTypeRef dst_type)
2098 {
2099 LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.amdgcn.sffbh.i32",
2100 dst_type, &arg, 1,
2101 AC_FUNC_ATTR_READNONE);
2102
2103 /* The HW returns the last bit index from MSB, but NIR/TGSI wants
2104 * the index from LSB. Invert it by doing "31 - msb". */
2105 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
2106 msb, "");
2107
2108 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
2109 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
2110 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
2111 arg, ctx->i32_0, ""),
2112 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
2113 arg, all_ones, ""), "");
2114
2115 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
2116 }
2117
2118 LLVMValueRef
2119 ac_build_umsb(struct ac_llvm_context *ctx,
2120 LLVMValueRef arg,
2121 LLVMTypeRef dst_type)
2122 {
2123 const char *intrin_name;
2124 LLVMTypeRef type;
2125 LLVMValueRef highest_bit;
2126 LLVMValueRef zero;
2127 unsigned bitsize;
2128
2129 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(arg));
2130 switch (bitsize) {
2131 case 64:
2132 intrin_name = "llvm.ctlz.i64";
2133 type = ctx->i64;
2134 highest_bit = LLVMConstInt(ctx->i64, 63, false);
2135 zero = ctx->i64_0;
2136 break;
2137 case 32:
2138 intrin_name = "llvm.ctlz.i32";
2139 type = ctx->i32;
2140 highest_bit = LLVMConstInt(ctx->i32, 31, false);
2141 zero = ctx->i32_0;
2142 break;
2143 case 16:
2144 intrin_name = "llvm.ctlz.i16";
2145 type = ctx->i16;
2146 highest_bit = LLVMConstInt(ctx->i16, 15, false);
2147 zero = ctx->i16_0;
2148 break;
2149 case 8:
2150 intrin_name = "llvm.ctlz.i8";
2151 type = ctx->i8;
2152 highest_bit = LLVMConstInt(ctx->i8, 7, false);
2153 zero = ctx->i8_0;
2154 break;
2155 default:
2156 unreachable(!"invalid bitsize");
2157 break;
2158 }
2159
2160 LLVMValueRef params[2] = {
2161 arg,
2162 ctx->i1true,
2163 };
2164
2165 LLVMValueRef msb = ac_build_intrinsic(ctx, intrin_name, type,
2166 params, 2,
2167 AC_FUNC_ATTR_READNONE);
2168
2169 /* The HW returns the last bit index from MSB, but TGSI/NIR wants
2170 * the index from LSB. Invert it by doing "31 - msb". */
2171 msb = LLVMBuildSub(ctx->builder, highest_bit, msb, "");
2172
2173 if (bitsize == 64) {
2174 msb = LLVMBuildTrunc(ctx->builder, msb, ctx->i32, "");
2175 } else if (bitsize < 32) {
2176 msb = LLVMBuildSExt(ctx->builder, msb, ctx->i32, "");
2177 }
2178
2179 /* check for zero */
2180 return LLVMBuildSelect(ctx->builder,
2181 LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg, zero, ""),
2182 LLVMConstInt(ctx->i32, -1, true), msb, "");
2183 }
2184
2185 LLVMValueRef ac_build_fmin(struct ac_llvm_context *ctx, LLVMValueRef a,
2186 LLVMValueRef b)
2187 {
2188 char name[64];
2189 snprintf(name, sizeof(name), "llvm.minnum.f%d", ac_get_elem_bits(ctx, LLVMTypeOf(a)));
2190 LLVMValueRef args[2] = {a, b};
2191 return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
2192 AC_FUNC_ATTR_READNONE);
2193 }
2194
2195 LLVMValueRef ac_build_fmax(struct ac_llvm_context *ctx, LLVMValueRef a,
2196 LLVMValueRef b)
2197 {
2198 char name[64];
2199 snprintf(name, sizeof(name), "llvm.maxnum.f%d", ac_get_elem_bits(ctx, LLVMTypeOf(a)));
2200 LLVMValueRef args[2] = {a, b};
2201 return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
2202 AC_FUNC_ATTR_READNONE);
2203 }
2204
2205 LLVMValueRef ac_build_imin(struct ac_llvm_context *ctx, LLVMValueRef a,
2206 LLVMValueRef b)
2207 {
2208 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSLE, a, b, "");
2209 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2210 }
2211
2212 LLVMValueRef ac_build_imax(struct ac_llvm_context *ctx, LLVMValueRef a,
2213 LLVMValueRef b)
2214 {
2215 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, a, b, "");
2216 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2217 }
2218
2219 LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
2220 LLVMValueRef b)
2221 {
2222 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
2223 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2224 }
2225
2226 LLVMValueRef ac_build_umax(struct ac_llvm_context *ctx, LLVMValueRef a,
2227 LLVMValueRef b)
2228 {
2229 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntUGE, a, b, "");
2230 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
2231 }
2232
2233 LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
2234 {
2235 LLVMTypeRef t = LLVMTypeOf(value);
2236 return ac_build_fmin(ctx, ac_build_fmax(ctx, value, LLVMConstReal(t, 0.0)),
2237 LLVMConstReal(t, 1.0));
2238 }
2239
2240 void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
2241 {
2242 LLVMValueRef args[9];
2243
2244 args[0] = LLVMConstInt(ctx->i32, a->target, 0);
2245 args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
2246
2247 if (a->compr) {
2248 LLVMTypeRef i16 = LLVMInt16TypeInContext(ctx->context);
2249 LLVMTypeRef v2i16 = LLVMVectorType(i16, 2);
2250
2251 args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
2252 v2i16, "");
2253 args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
2254 v2i16, "");
2255 args[4] = LLVMConstInt(ctx->i1, a->done, 0);
2256 args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
2257
2258 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
2259 ctx->voidt, args, 6, 0);
2260 } else {
2261 args[2] = a->out[0];
2262 args[3] = a->out[1];
2263 args[4] = a->out[2];
2264 args[5] = a->out[3];
2265 args[6] = LLVMConstInt(ctx->i1, a->done, 0);
2266 args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
2267
2268 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
2269 ctx->voidt, args, 8, 0);
2270 }
2271 }
2272
2273 void ac_build_export_null(struct ac_llvm_context *ctx)
2274 {
2275 struct ac_export_args args;
2276
2277 args.enabled_channels = 0x0; /* enabled channels */
2278 args.valid_mask = 1; /* whether the EXEC mask is valid */
2279 args.done = 1; /* DONE bit */
2280 args.target = V_008DFC_SQ_EXP_NULL;
2281 args.compr = 0; /* COMPR flag (0 = 32-bit export) */
2282 args.out[0] = LLVMGetUndef(ctx->f32); /* R */
2283 args.out[1] = LLVMGetUndef(ctx->f32); /* G */
2284 args.out[2] = LLVMGetUndef(ctx->f32); /* B */
2285 args.out[3] = LLVMGetUndef(ctx->f32); /* A */
2286
2287 ac_build_export(ctx, &args);
2288 }
2289
2290 static unsigned ac_num_coords(enum ac_image_dim dim)
2291 {
2292 switch (dim) {
2293 case ac_image_1d:
2294 return 1;
2295 case ac_image_2d:
2296 case ac_image_1darray:
2297 return 2;
2298 case ac_image_3d:
2299 case ac_image_cube:
2300 case ac_image_2darray:
2301 case ac_image_2dmsaa:
2302 return 3;
2303 case ac_image_2darraymsaa:
2304 return 4;
2305 default:
2306 unreachable("ac_num_coords: bad dim");
2307 }
2308 }
2309
2310 static unsigned ac_num_derivs(enum ac_image_dim dim)
2311 {
2312 switch (dim) {
2313 case ac_image_1d:
2314 case ac_image_1darray:
2315 return 2;
2316 case ac_image_2d:
2317 case ac_image_2darray:
2318 case ac_image_cube:
2319 return 4;
2320 case ac_image_3d:
2321 return 6;
2322 case ac_image_2dmsaa:
2323 case ac_image_2darraymsaa:
2324 default:
2325 unreachable("derivatives not supported");
2326 }
2327 }
2328
2329 static const char *get_atomic_name(enum ac_atomic_op op)
2330 {
2331 switch (op) {
2332 case ac_atomic_swap: return "swap";
2333 case ac_atomic_add: return "add";
2334 case ac_atomic_sub: return "sub";
2335 case ac_atomic_smin: return "smin";
2336 case ac_atomic_umin: return "umin";
2337 case ac_atomic_smax: return "smax";
2338 case ac_atomic_umax: return "umax";
2339 case ac_atomic_and: return "and";
2340 case ac_atomic_or: return "or";
2341 case ac_atomic_xor: return "xor";
2342 case ac_atomic_inc_wrap: return "inc";
2343 case ac_atomic_dec_wrap: return "dec";
2344 }
2345 unreachable("bad atomic op");
2346 }
2347
2348 LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
2349 struct ac_image_args *a)
2350 {
2351 const char *overload[3] = { "", "", "" };
2352 unsigned num_overloads = 0;
2353 LLVMValueRef args[18];
2354 unsigned num_args = 0;
2355 enum ac_image_dim dim = a->dim;
2356
2357 assert(!a->lod || a->lod == ctx->i32_0 || a->lod == ctx->f32_0 ||
2358 !a->level_zero);
2359 assert((a->opcode != ac_image_get_resinfo && a->opcode != ac_image_load_mip &&
2360 a->opcode != ac_image_store_mip) ||
2361 a->lod);
2362 assert(a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
2363 (!a->compare && !a->offset));
2364 assert((a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
2365 a->opcode == ac_image_get_lod) ||
2366 !a->bias);
2367 assert((a->bias ? 1 : 0) +
2368 (a->lod ? 1 : 0) +
2369 (a->level_zero ? 1 : 0) +
2370 (a->derivs[0] ? 1 : 0) <= 1);
2371
2372 if (a->opcode == ac_image_get_lod) {
2373 switch (dim) {
2374 case ac_image_1darray:
2375 dim = ac_image_1d;
2376 break;
2377 case ac_image_2darray:
2378 case ac_image_cube:
2379 dim = ac_image_2d;
2380 break;
2381 default:
2382 break;
2383 }
2384 }
2385
2386 bool sample = a->opcode == ac_image_sample ||
2387 a->opcode == ac_image_gather4 ||
2388 a->opcode == ac_image_get_lod;
2389 bool atomic = a->opcode == ac_image_atomic ||
2390 a->opcode == ac_image_atomic_cmpswap;
2391 bool load = a->opcode == ac_image_sample ||
2392 a->opcode == ac_image_gather4 ||
2393 a->opcode == ac_image_load ||
2394 a->opcode == ac_image_load_mip;
2395 LLVMTypeRef coord_type = sample ? ctx->f32 : ctx->i32;
2396
2397 if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
2398 args[num_args++] = a->data[0];
2399 if (a->opcode == ac_image_atomic_cmpswap)
2400 args[num_args++] = a->data[1];
2401 }
2402
2403 if (!atomic)
2404 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, false);
2405
2406 if (a->offset)
2407 args[num_args++] = ac_to_integer(ctx, a->offset);
2408 if (a->bias) {
2409 args[num_args++] = ac_to_float(ctx, a->bias);
2410 overload[num_overloads++] = ".f32";
2411 }
2412 if (a->compare)
2413 args[num_args++] = ac_to_float(ctx, a->compare);
2414 if (a->derivs[0]) {
2415 unsigned count = ac_num_derivs(dim);
2416 for (unsigned i = 0; i < count; ++i)
2417 args[num_args++] = ac_to_float(ctx, a->derivs[i]);
2418 overload[num_overloads++] = ".f32";
2419 }
2420 unsigned num_coords =
2421 a->opcode != ac_image_get_resinfo ? ac_num_coords(dim) : 0;
2422 for (unsigned i = 0; i < num_coords; ++i)
2423 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->coords[i], coord_type, "");
2424 if (a->lod)
2425 args[num_args++] = LLVMBuildBitCast(ctx->builder, a->lod, coord_type, "");
2426 overload[num_overloads++] = sample ? ".f32" : ".i32";
2427
2428 args[num_args++] = a->resource;
2429 if (sample) {
2430 args[num_args++] = a->sampler;
2431 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, false);
2432 }
2433
2434 args[num_args++] = ctx->i32_0; /* texfailctrl */
2435 args[num_args++] = LLVMConstInt(ctx->i32,
2436 load ? get_load_cache_policy(ctx, a->cache_policy) :
2437 a->cache_policy, false);
2438
2439 const char *name;
2440 const char *atomic_subop = "";
2441 switch (a->opcode) {
2442 case ac_image_sample: name = "sample"; break;
2443 case ac_image_gather4: name = "gather4"; break;
2444 case ac_image_load: name = "load"; break;
2445 case ac_image_load_mip: name = "load.mip"; break;
2446 case ac_image_store: name = "store"; break;
2447 case ac_image_store_mip: name = "store.mip"; break;
2448 case ac_image_atomic:
2449 name = "atomic.";
2450 atomic_subop = get_atomic_name(a->atomic);
2451 break;
2452 case ac_image_atomic_cmpswap:
2453 name = "atomic.";
2454 atomic_subop = "cmpswap";
2455 break;
2456 case ac_image_get_lod: name = "getlod"; break;
2457 case ac_image_get_resinfo: name = "getresinfo"; break;
2458 default: unreachable("invalid image opcode");
2459 }
2460
2461 const char *dimname;
2462 switch (dim) {
2463 case ac_image_1d: dimname = "1d"; break;
2464 case ac_image_2d: dimname = "2d"; break;
2465 case ac_image_3d: dimname = "3d"; break;
2466 case ac_image_cube: dimname = "cube"; break;
2467 case ac_image_1darray: dimname = "1darray"; break;
2468 case ac_image_2darray: dimname = "2darray"; break;
2469 case ac_image_2dmsaa: dimname = "2dmsaa"; break;
2470 case ac_image_2darraymsaa: dimname = "2darraymsaa"; break;
2471 default: unreachable("invalid dim");
2472 }
2473
2474 bool lod_suffix =
2475 a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
2476 char intr_name[96];
2477 snprintf(intr_name, sizeof(intr_name),
2478 "llvm.amdgcn.image.%s%s" /* base name */
2479 "%s%s%s" /* sample/gather modifiers */
2480 ".%s.%s%s%s%s", /* dimension and type overloads */
2481 name, atomic_subop,
2482 a->compare ? ".c" : "",
2483 a->bias ? ".b" :
2484 lod_suffix ? ".l" :
2485 a->derivs[0] ? ".d" :
2486 a->level_zero ? ".lz" : "",
2487 a->offset ? ".o" : "",
2488 dimname,
2489 atomic ? "i32" : "v4f32",
2490 overload[0], overload[1], overload[2]);
2491
2492 LLVMTypeRef retty;
2493 if (atomic)
2494 retty = ctx->i32;
2495 else if (a->opcode == ac_image_store || a->opcode == ac_image_store_mip)
2496 retty = ctx->voidt;
2497 else
2498 retty = ctx->v4f32;
2499
2500 LLVMValueRef result =
2501 ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
2502 a->attributes);
2503 if (!sample && retty == ctx->v4f32) {
2504 result = LLVMBuildBitCast(ctx->builder, result,
2505 ctx->v4i32, "");
2506 }
2507 return result;
2508 }
2509
2510 LLVMValueRef ac_build_image_get_sample_count(struct ac_llvm_context *ctx,
2511 LLVMValueRef rsrc)
2512 {
2513 LLVMValueRef samples;
2514
2515 /* Read the samples from the descriptor directly.
2516 * Hardware doesn't have any instruction for this.
2517 */
2518 samples = LLVMBuildExtractElement(ctx->builder, rsrc,
2519 LLVMConstInt(ctx->i32, 3, 0), "");
2520 samples = LLVMBuildLShr(ctx->builder, samples,
2521 LLVMConstInt(ctx->i32, 16, 0), "");
2522 samples = LLVMBuildAnd(ctx->builder, samples,
2523 LLVMConstInt(ctx->i32, 0xf, 0), "");
2524 samples = LLVMBuildShl(ctx->builder, ctx->i32_1,
2525 samples, "");
2526 return samples;
2527 }
2528
2529 LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
2530 LLVMValueRef args[2])
2531 {
2532 LLVMTypeRef v2f16 =
2533 LLVMVectorType(LLVMHalfTypeInContext(ctx->context), 2);
2534
2535 return ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz", v2f16,
2536 args, 2, AC_FUNC_ATTR_READNONE);
2537 }
2538
2539 LLVMValueRef ac_build_cvt_pknorm_i16(struct ac_llvm_context *ctx,
2540 LLVMValueRef args[2])
2541 {
2542 LLVMValueRef res =
2543 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.i16",
2544 ctx->v2i16, args, 2,
2545 AC_FUNC_ATTR_READNONE);
2546 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2547 }
2548
2549 LLVMValueRef ac_build_cvt_pknorm_u16(struct ac_llvm_context *ctx,
2550 LLVMValueRef args[2])
2551 {
2552 LLVMValueRef res =
2553 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.u16",
2554 ctx->v2i16, args, 2,
2555 AC_FUNC_ATTR_READNONE);
2556 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2557 }
2558
2559 /* The 8-bit and 10-bit clamping is for HW workarounds. */
2560 LLVMValueRef ac_build_cvt_pk_i16(struct ac_llvm_context *ctx,
2561 LLVMValueRef args[2], unsigned bits, bool hi)
2562 {
2563 assert(bits == 8 || bits == 10 || bits == 16);
2564
2565 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
2566 bits == 8 ? 127 : bits == 10 ? 511 : 32767, 0);
2567 LLVMValueRef min_rgb = LLVMConstInt(ctx->i32,
2568 bits == 8 ? -128 : bits == 10 ? -512 : -32768, 0);
2569 LLVMValueRef max_alpha =
2570 bits != 10 ? max_rgb : ctx->i32_1;
2571 LLVMValueRef min_alpha =
2572 bits != 10 ? min_rgb : LLVMConstInt(ctx->i32, -2, 0);
2573
2574 /* Clamp. */
2575 if (bits != 16) {
2576 for (int i = 0; i < 2; i++) {
2577 bool alpha = hi && i == 1;
2578 args[i] = ac_build_imin(ctx, args[i],
2579 alpha ? max_alpha : max_rgb);
2580 args[i] = ac_build_imax(ctx, args[i],
2581 alpha ? min_alpha : min_rgb);
2582 }
2583 }
2584
2585 LLVMValueRef res =
2586 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.i16",
2587 ctx->v2i16, args, 2,
2588 AC_FUNC_ATTR_READNONE);
2589 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2590 }
2591
2592 /* The 8-bit and 10-bit clamping is for HW workarounds. */
2593 LLVMValueRef ac_build_cvt_pk_u16(struct ac_llvm_context *ctx,
2594 LLVMValueRef args[2], unsigned bits, bool hi)
2595 {
2596 assert(bits == 8 || bits == 10 || bits == 16);
2597
2598 LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
2599 bits == 8 ? 255 : bits == 10 ? 1023 : 65535, 0);
2600 LLVMValueRef max_alpha =
2601 bits != 10 ? max_rgb : LLVMConstInt(ctx->i32, 3, 0);
2602
2603 /* Clamp. */
2604 if (bits != 16) {
2605 for (int i = 0; i < 2; i++) {
2606 bool alpha = hi && i == 1;
2607 args[i] = ac_build_umin(ctx, args[i],
2608 alpha ? max_alpha : max_rgb);
2609 }
2610 }
2611
2612 LLVMValueRef res =
2613 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.u16",
2614 ctx->v2i16, args, 2,
2615 AC_FUNC_ATTR_READNONE);
2616 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
2617 }
2618
2619 LLVMValueRef ac_build_wqm_vote(struct ac_llvm_context *ctx, LLVMValueRef i1)
2620 {
2621 return ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.vote", ctx->i1,
2622 &i1, 1, AC_FUNC_ATTR_READNONE);
2623 }
2624
2625 void ac_build_kill_if_false(struct ac_llvm_context *ctx, LLVMValueRef i1)
2626 {
2627 ac_build_intrinsic(ctx, "llvm.amdgcn.kill", ctx->voidt,
2628 &i1, 1, 0);
2629 }
2630
2631 LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
2632 LLVMValueRef offset, LLVMValueRef width,
2633 bool is_signed)
2634 {
2635 LLVMValueRef args[] = {
2636 input,
2637 offset,
2638 width,
2639 };
2640
2641 return ac_build_intrinsic(ctx, is_signed ? "llvm.amdgcn.sbfe.i32" :
2642 "llvm.amdgcn.ubfe.i32",
2643 ctx->i32, args, 3, AC_FUNC_ATTR_READNONE);
2644
2645 }
2646
2647 LLVMValueRef ac_build_imad(struct ac_llvm_context *ctx, LLVMValueRef s0,
2648 LLVMValueRef s1, LLVMValueRef s2)
2649 {
2650 return LLVMBuildAdd(ctx->builder,
2651 LLVMBuildMul(ctx->builder, s0, s1, ""), s2, "");
2652 }
2653
2654 LLVMValueRef ac_build_fmad(struct ac_llvm_context *ctx, LLVMValueRef s0,
2655 LLVMValueRef s1, LLVMValueRef s2)
2656 {
2657 /* FMA is better on GFX10, because it has FMA units instead of MUL-ADD units. */
2658 if (ctx->chip_class >= GFX10) {
2659 return ac_build_intrinsic(ctx, "llvm.fma.f32", ctx->f32,
2660 (LLVMValueRef []) {s0, s1, s2}, 3,
2661 AC_FUNC_ATTR_READNONE);
2662 }
2663
2664 return LLVMBuildFAdd(ctx->builder,
2665 LLVMBuildFMul(ctx->builder, s0, s1, ""), s2, "");
2666 }
2667
2668 void ac_build_waitcnt(struct ac_llvm_context *ctx, unsigned wait_flags)
2669 {
2670 if (!wait_flags)
2671 return;
2672
2673 unsigned lgkmcnt = 63;
2674 unsigned vmcnt = ctx->chip_class >= GFX9 ? 63 : 15;
2675 unsigned vscnt = 63;
2676
2677 if (wait_flags & AC_WAIT_LGKM)
2678 lgkmcnt = 0;
2679 if (wait_flags & AC_WAIT_VLOAD)
2680 vmcnt = 0;
2681
2682 if (wait_flags & AC_WAIT_VSTORE) {
2683 if (ctx->chip_class >= GFX10)
2684 vscnt = 0;
2685 else
2686 vmcnt = 0;
2687 }
2688
2689 /* There is no intrinsic for vscnt(0), so use a fence. */
2690 if ((wait_flags & AC_WAIT_LGKM &&
2691 wait_flags & AC_WAIT_VLOAD &&
2692 wait_flags & AC_WAIT_VSTORE) ||
2693 vscnt == 0) {
2694 LLVMBuildFence(ctx->builder, LLVMAtomicOrderingRelease, false, "");
2695 return;
2696 }
2697
2698 unsigned simm16 = (lgkmcnt << 8) |
2699 (7 << 4) | /* expcnt */
2700 (vmcnt & 0xf) |
2701 ((vmcnt >> 4) << 14);
2702
2703 LLVMValueRef args[1] = {
2704 LLVMConstInt(ctx->i32, simm16, false),
2705 };
2706 ac_build_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
2707 ctx->voidt, args, 1, 0);
2708 }
2709
2710 LLVMValueRef ac_build_fmed3(struct ac_llvm_context *ctx, LLVMValueRef src0,
2711 LLVMValueRef src1, LLVMValueRef src2,
2712 unsigned bitsize)
2713 {
2714 LLVMTypeRef type;
2715 char *intr;
2716
2717 if (bitsize == 16) {
2718 intr = "llvm.amdgcn.fmed3.f16";
2719 type = ctx->f16;
2720 } else if (bitsize == 32) {
2721 intr = "llvm.amdgcn.fmed3.f32";
2722 type = ctx->f32;
2723 } else {
2724 intr = "llvm.amdgcn.fmed3.f64";
2725 type = ctx->f64;
2726 }
2727
2728 LLVMValueRef params[] = {
2729 src0,
2730 src1,
2731 src2,
2732 };
2733 return ac_build_intrinsic(ctx, intr, type, params, 3,
2734 AC_FUNC_ATTR_READNONE);
2735 }
2736
2737 LLVMValueRef ac_build_fract(struct ac_llvm_context *ctx, LLVMValueRef src0,
2738 unsigned bitsize)
2739 {
2740 LLVMTypeRef type;
2741 char *intr;
2742
2743 if (bitsize == 16) {
2744 intr = "llvm.amdgcn.fract.f16";
2745 type = ctx->f16;
2746 } else if (bitsize == 32) {
2747 intr = "llvm.amdgcn.fract.f32";
2748 type = ctx->f32;
2749 } else {
2750 intr = "llvm.amdgcn.fract.f64";
2751 type = ctx->f64;
2752 }
2753
2754 LLVMValueRef params[] = {
2755 src0,
2756 };
2757 return ac_build_intrinsic(ctx, intr, type, params, 1,
2758 AC_FUNC_ATTR_READNONE);
2759 }
2760
2761 LLVMValueRef ac_build_isign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2762 unsigned bitsize)
2763 {
2764 LLVMTypeRef type = LLVMIntTypeInContext(ctx->context, bitsize);
2765 LLVMValueRef zero = LLVMConstInt(type, 0, false);
2766 LLVMValueRef one = LLVMConstInt(type, 1, false);
2767
2768 LLVMValueRef cmp, val;
2769 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, zero, "");
2770 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2771 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, zero, "");
2772 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(type, -1, true), "");
2773 return val;
2774 }
2775
2776 LLVMValueRef ac_build_fsign(struct ac_llvm_context *ctx, LLVMValueRef src0,
2777 unsigned bitsize)
2778 {
2779 LLVMValueRef cmp, val, zero, one;
2780 LLVMTypeRef type;
2781
2782 if (bitsize == 16) {
2783 type = ctx->f16;
2784 zero = ctx->f16_0;
2785 one = ctx->f16_1;
2786 } else if (bitsize == 32) {
2787 type = ctx->f32;
2788 zero = ctx->f32_0;
2789 one = ctx->f32_1;
2790 } else {
2791 type = ctx->f64;
2792 zero = ctx->f64_0;
2793 one = ctx->f64_1;
2794 }
2795
2796 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, zero, "");
2797 val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
2798 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, zero, "");
2799 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(type, -1.0), "");
2800 return val;
2801 }
2802
2803 LLVMValueRef ac_build_bit_count(struct ac_llvm_context *ctx, LLVMValueRef src0)
2804 {
2805 LLVMValueRef result;
2806 unsigned bitsize;
2807
2808 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2809
2810 switch (bitsize) {
2811 case 64:
2812 result = ac_build_intrinsic(ctx, "llvm.ctpop.i64", ctx->i64,
2813 (LLVMValueRef []) { src0 }, 1,
2814 AC_FUNC_ATTR_READNONE);
2815
2816 result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
2817 break;
2818 case 32:
2819 result = ac_build_intrinsic(ctx, "llvm.ctpop.i32", ctx->i32,
2820 (LLVMValueRef []) { src0 }, 1,
2821 AC_FUNC_ATTR_READNONE);
2822 break;
2823 case 16:
2824 result = ac_build_intrinsic(ctx, "llvm.ctpop.i16", ctx->i16,
2825 (LLVMValueRef []) { src0 }, 1,
2826 AC_FUNC_ATTR_READNONE);
2827
2828 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2829 break;
2830 case 8:
2831 result = ac_build_intrinsic(ctx, "llvm.ctpop.i8", ctx->i8,
2832 (LLVMValueRef []) { src0 }, 1,
2833 AC_FUNC_ATTR_READNONE);
2834
2835 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2836 break;
2837 default:
2838 unreachable(!"invalid bitsize");
2839 break;
2840 }
2841
2842 return result;
2843 }
2844
2845 LLVMValueRef ac_build_bitfield_reverse(struct ac_llvm_context *ctx,
2846 LLVMValueRef src0)
2847 {
2848 LLVMValueRef result;
2849 unsigned bitsize;
2850
2851 bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
2852
2853 switch (bitsize) {
2854 case 64:
2855 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i64", ctx->i64,
2856 (LLVMValueRef []) { src0 }, 1,
2857 AC_FUNC_ATTR_READNONE);
2858
2859 result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
2860 break;
2861 case 32:
2862 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i32", ctx->i32,
2863 (LLVMValueRef []) { src0 }, 1,
2864 AC_FUNC_ATTR_READNONE);
2865 break;
2866 case 16:
2867 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i16", ctx->i16,
2868 (LLVMValueRef []) { src0 }, 1,
2869 AC_FUNC_ATTR_READNONE);
2870
2871 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2872 break;
2873 case 8:
2874 result = ac_build_intrinsic(ctx, "llvm.bitreverse.i8", ctx->i8,
2875 (LLVMValueRef []) { src0 }, 1,
2876 AC_FUNC_ATTR_READNONE);
2877
2878 result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
2879 break;
2880 default:
2881 unreachable(!"invalid bitsize");
2882 break;
2883 }
2884
2885 return result;
2886 }
2887
2888 #define AC_EXP_TARGET 0
2889 #define AC_EXP_ENABLED_CHANNELS 1
2890 #define AC_EXP_OUT0 2
2891
2892 enum ac_ir_type {
2893 AC_IR_UNDEF,
2894 AC_IR_CONST,
2895 AC_IR_VALUE,
2896 };
2897
2898 struct ac_vs_exp_chan
2899 {
2900 LLVMValueRef value;
2901 float const_float;
2902 enum ac_ir_type type;
2903 };
2904
2905 struct ac_vs_exp_inst {
2906 unsigned offset;
2907 LLVMValueRef inst;
2908 struct ac_vs_exp_chan chan[4];
2909 };
2910
2911 struct ac_vs_exports {
2912 unsigned num;
2913 struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
2914 };
2915
2916 /* Return true if the PARAM export has been eliminated. */
2917 static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
2918 uint32_t num_outputs,
2919 struct ac_vs_exp_inst *exp)
2920 {
2921 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
2922 bool is_zero[4] = {}, is_one[4] = {};
2923
2924 for (i = 0; i < 4; i++) {
2925 /* It's a constant expression. Undef outputs are eliminated too. */
2926 if (exp->chan[i].type == AC_IR_UNDEF) {
2927 is_zero[i] = true;
2928 is_one[i] = true;
2929 } else if (exp->chan[i].type == AC_IR_CONST) {
2930 if (exp->chan[i].const_float == 0)
2931 is_zero[i] = true;
2932 else if (exp->chan[i].const_float == 1)
2933 is_one[i] = true;
2934 else
2935 return false; /* other constant */
2936 } else
2937 return false;
2938 }
2939
2940 /* Only certain combinations of 0 and 1 can be eliminated. */
2941 if (is_zero[0] && is_zero[1] && is_zero[2])
2942 default_val = is_zero[3] ? 0 : 1;
2943 else if (is_one[0] && is_one[1] && is_one[2])
2944 default_val = is_zero[3] ? 2 : 3;
2945 else
2946 return false;
2947
2948 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
2949 LLVMInstructionEraseFromParent(exp->inst);
2950
2951 /* Change OFFSET to DEFAULT_VAL. */
2952 for (i = 0; i < num_outputs; i++) {
2953 if (vs_output_param_offset[i] == exp->offset) {
2954 vs_output_param_offset[i] =
2955 AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
2956 break;
2957 }
2958 }
2959 return true;
2960 }
2961
2962 static bool ac_eliminate_duplicated_output(struct ac_llvm_context *ctx,
2963 uint8_t *vs_output_param_offset,
2964 uint32_t num_outputs,
2965 struct ac_vs_exports *processed,
2966 struct ac_vs_exp_inst *exp)
2967 {
2968 unsigned p, copy_back_channels = 0;
2969
2970 /* See if the output is already in the list of processed outputs.
2971 * The LLVMValueRef comparison relies on SSA.
2972 */
2973 for (p = 0; p < processed->num; p++) {
2974 bool different = false;
2975
2976 for (unsigned j = 0; j < 4; j++) {
2977 struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
2978 struct ac_vs_exp_chan *c2 = &exp->chan[j];
2979
2980 /* Treat undef as a match. */
2981 if (c2->type == AC_IR_UNDEF)
2982 continue;
2983
2984 /* If c1 is undef but c2 isn't, we can copy c2 to c1
2985 * and consider the instruction duplicated.
2986 */
2987 if (c1->type == AC_IR_UNDEF) {
2988 copy_back_channels |= 1 << j;
2989 continue;
2990 }
2991
2992 /* Test whether the channels are not equal. */
2993 if (c1->type != c2->type ||
2994 (c1->type == AC_IR_CONST &&
2995 c1->const_float != c2->const_float) ||
2996 (c1->type == AC_IR_VALUE &&
2997 c1->value != c2->value)) {
2998 different = true;
2999 break;
3000 }
3001 }
3002 if (!different)
3003 break;
3004
3005 copy_back_channels = 0;
3006 }
3007 if (p == processed->num)
3008 return false;
3009
3010 /* If a match was found, but the matching export has undef where the new
3011 * one has a normal value, copy the normal value to the undef channel.
3012 */
3013 struct ac_vs_exp_inst *match = &processed->exp[p];
3014
3015 /* Get current enabled channels mask. */
3016 LLVMValueRef arg = LLVMGetOperand(match->inst, AC_EXP_ENABLED_CHANNELS);
3017 unsigned enabled_channels = LLVMConstIntGetZExtValue(arg);
3018
3019 while (copy_back_channels) {
3020 unsigned chan = u_bit_scan(&copy_back_channels);
3021
3022 assert(match->chan[chan].type == AC_IR_UNDEF);
3023 LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
3024 exp->chan[chan].value);
3025 match->chan[chan] = exp->chan[chan];
3026
3027 /* Update number of enabled channels because the original mask
3028 * is not always 0xf.
3029 */
3030 enabled_channels |= (1 << chan);
3031 LLVMSetOperand(match->inst, AC_EXP_ENABLED_CHANNELS,
3032 LLVMConstInt(ctx->i32, enabled_channels, 0));
3033 }
3034
3035 /* The PARAM export is duplicated. Kill it. */
3036 LLVMInstructionEraseFromParent(exp->inst);
3037
3038 /* Change OFFSET to the matching export. */
3039 for (unsigned i = 0; i < num_outputs; i++) {
3040 if (vs_output_param_offset[i] == exp->offset) {
3041 vs_output_param_offset[i] = match->offset;
3042 break;
3043 }
3044 }
3045 return true;
3046 }
3047
3048 void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
3049 LLVMValueRef main_fn,
3050 uint8_t *vs_output_param_offset,
3051 uint32_t num_outputs,
3052 uint8_t *num_param_exports)
3053 {
3054 LLVMBasicBlockRef bb;
3055 bool removed_any = false;
3056 struct ac_vs_exports exports;
3057
3058 exports.num = 0;
3059
3060 /* Process all LLVM instructions. */
3061 bb = LLVMGetFirstBasicBlock(main_fn);
3062 while (bb) {
3063 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
3064
3065 while (inst) {
3066 LLVMValueRef cur = inst;
3067 inst = LLVMGetNextInstruction(inst);
3068 struct ac_vs_exp_inst exp;
3069
3070 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
3071 continue;
3072
3073 LLVMValueRef callee = ac_llvm_get_called_value(cur);
3074
3075 if (!ac_llvm_is_function(callee))
3076 continue;
3077
3078 const char *name = LLVMGetValueName(callee);
3079 unsigned num_args = LLVMCountParams(callee);
3080
3081 /* Check if this is an export instruction. */
3082 if ((num_args != 9 && num_args != 8) ||
3083 (strcmp(name, "llvm.SI.export") &&
3084 strcmp(name, "llvm.amdgcn.exp.f32")))
3085 continue;
3086
3087 LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
3088 unsigned target = LLVMConstIntGetZExtValue(arg);
3089
3090 if (target < V_008DFC_SQ_EXP_PARAM)
3091 continue;
3092
3093 target -= V_008DFC_SQ_EXP_PARAM;
3094
3095 /* Parse the instruction. */
3096 memset(&exp, 0, sizeof(exp));
3097 exp.offset = target;
3098 exp.inst = cur;
3099
3100 for (unsigned i = 0; i < 4; i++) {
3101 LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);
3102
3103 exp.chan[i].value = v;
3104
3105 if (LLVMIsUndef(v)) {
3106 exp.chan[i].type = AC_IR_UNDEF;
3107 } else if (LLVMIsAConstantFP(v)) {
3108 LLVMBool loses_info;
3109 exp.chan[i].type = AC_IR_CONST;
3110 exp.chan[i].const_float =
3111 LLVMConstRealGetDouble(v, &loses_info);
3112 } else {
3113 exp.chan[i].type = AC_IR_VALUE;
3114 }
3115 }
3116
3117 /* Eliminate constant and duplicated PARAM exports. */
3118 if (ac_eliminate_const_output(vs_output_param_offset,
3119 num_outputs, &exp) ||
3120 ac_eliminate_duplicated_output(ctx,
3121 vs_output_param_offset,
3122 num_outputs, &exports,
3123 &exp)) {
3124 removed_any = true;
3125 } else {
3126 exports.exp[exports.num++] = exp;
3127 }
3128 }
3129 bb = LLVMGetNextBasicBlock(bb);
3130 }
3131
3132 /* Remove holes in export memory due to removed PARAM exports.
3133 * This is done by renumbering all PARAM exports.
3134 */
3135 if (removed_any) {
3136 uint8_t old_offset[VARYING_SLOT_MAX];
3137 unsigned out, i;
3138
3139 /* Make a copy of the offsets. We need the old version while
3140 * we are modifying some of them. */
3141 memcpy(old_offset, vs_output_param_offset,
3142 sizeof(old_offset));
3143
3144 for (i = 0; i < exports.num; i++) {
3145 unsigned offset = exports.exp[i].offset;
3146
3147 /* Update vs_output_param_offset. Multiple outputs can
3148 * have the same offset.
3149 */
3150 for (out = 0; out < num_outputs; out++) {
3151 if (old_offset[out] == offset)
3152 vs_output_param_offset[out] = i;
3153 }
3154
3155 /* Change the PARAM offset in the instruction. */
3156 LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
3157 LLVMConstInt(ctx->i32,
3158 V_008DFC_SQ_EXP_PARAM + i, 0));
3159 }
3160 *num_param_exports = exports.num;
3161 }
3162 }
3163
3164 void ac_init_exec_full_mask(struct ac_llvm_context *ctx)
3165 {
3166 LLVMValueRef full_mask = LLVMConstInt(ctx->i64, ~0ull, 0);
3167 ac_build_intrinsic(ctx,
3168 "llvm.amdgcn.init.exec", ctx->voidt,
3169 &full_mask, 1, AC_FUNC_ATTR_CONVERGENT);
3170 }
3171
3172 void ac_declare_lds_as_pointer(struct ac_llvm_context *ctx)
3173 {
3174 unsigned lds_size = ctx->chip_class >= GFX7 ? 65536 : 32768;
3175 ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32_0,
3176 LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), AC_ADDR_SPACE_LDS),
3177 "lds");
3178 }
3179
3180 LLVMValueRef ac_lds_load(struct ac_llvm_context *ctx,
3181 LLVMValueRef dw_addr)
3182 {
3183 return LLVMBuildLoad(ctx->builder, ac_build_gep0(ctx, ctx->lds, dw_addr), "");
3184 }
3185
3186 void ac_lds_store(struct ac_llvm_context *ctx,
3187 LLVMValueRef dw_addr,
3188 LLVMValueRef value)
3189 {
3190 value = ac_to_integer(ctx, value);
3191 ac_build_indexed_store(ctx, ctx->lds,
3192 dw_addr, value);
3193 }
3194
3195 LLVMValueRef ac_find_lsb(struct ac_llvm_context *ctx,
3196 LLVMTypeRef dst_type,
3197 LLVMValueRef src0)
3198 {
3199 unsigned src0_bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
3200 const char *intrin_name;
3201 LLVMTypeRef type;
3202 LLVMValueRef zero;
3203
3204 switch (src0_bitsize) {
3205 case 64:
3206 intrin_name = "llvm.cttz.i64";
3207 type = ctx->i64;
3208 zero = ctx->i64_0;
3209 break;
3210 case 32:
3211 intrin_name = "llvm.cttz.i32";
3212 type = ctx->i32;
3213 zero = ctx->i32_0;
3214 break;
3215 case 16:
3216 intrin_name = "llvm.cttz.i16";
3217 type = ctx->i16;
3218 zero = ctx->i16_0;
3219 break;
3220 case 8:
3221 intrin_name = "llvm.cttz.i8";
3222 type = ctx->i8;
3223 zero = ctx->i8_0;
3224 break;
3225 default:
3226 unreachable(!"invalid bitsize");
3227 }
3228
3229 LLVMValueRef params[2] = {
3230 src0,
3231
3232 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
3233 * add special code to check for x=0. The reason is that
3234 * the LLVM behavior for x=0 is different from what we
3235 * need here. However, LLVM also assumes that ffs(x) is
3236 * in [0, 31], but GLSL expects that ffs(0) = -1, so
3237 * a conditional assignment to handle 0 is still required.
3238 *
3239 * The hardware already implements the correct behavior.
3240 */
3241 ctx->i1true,
3242 };
3243
3244 LLVMValueRef lsb = ac_build_intrinsic(ctx, intrin_name, type,
3245 params, 2,
3246 AC_FUNC_ATTR_READNONE);
3247
3248 if (src0_bitsize == 64) {
3249 lsb = LLVMBuildTrunc(ctx->builder, lsb, ctx->i32, "");
3250 } else if (src0_bitsize < 32) {
3251 lsb = LLVMBuildSExt(ctx->builder, lsb, ctx->i32, "");
3252 }
3253
3254 /* TODO: We need an intrinsic to skip this conditional. */
3255 /* Check for zero: */
3256 return LLVMBuildSelect(ctx->builder, LLVMBuildICmp(ctx->builder,
3257 LLVMIntEQ, src0,
3258 zero, ""),
3259 LLVMConstInt(ctx->i32, -1, 0), lsb, "");
3260 }
3261
3262 LLVMTypeRef ac_array_in_const_addr_space(LLVMTypeRef elem_type)
3263 {
3264 return LLVMPointerType(elem_type, AC_ADDR_SPACE_CONST);
3265 }
3266
3267 LLVMTypeRef ac_array_in_const32_addr_space(LLVMTypeRef elem_type)
3268 {
3269 return LLVMPointerType(elem_type, AC_ADDR_SPACE_CONST_32BIT);
3270 }
3271
3272 static struct ac_llvm_flow *
3273 get_current_flow(struct ac_llvm_context *ctx)
3274 {
3275 if (ctx->flow->depth > 0)
3276 return &ctx->flow->stack[ctx->flow->depth - 1];
3277 return NULL;
3278 }
3279
3280 static struct ac_llvm_flow *
3281 get_innermost_loop(struct ac_llvm_context *ctx)
3282 {
3283 for (unsigned i = ctx->flow->depth; i > 0; --i) {
3284 if (ctx->flow->stack[i - 1].loop_entry_block)
3285 return &ctx->flow->stack[i - 1];
3286 }
3287 return NULL;
3288 }
3289
3290 static struct ac_llvm_flow *
3291 push_flow(struct ac_llvm_context *ctx)
3292 {
3293 struct ac_llvm_flow *flow;
3294
3295 if (ctx->flow->depth >= ctx->flow->depth_max) {
3296 unsigned new_max = MAX2(ctx->flow->depth << 1,
3297 AC_LLVM_INITIAL_CF_DEPTH);
3298
3299 ctx->flow->stack = realloc(ctx->flow->stack, new_max * sizeof(*ctx->flow->stack));
3300 ctx->flow->depth_max = new_max;
3301 }
3302
3303 flow = &ctx->flow->stack[ctx->flow->depth];
3304 ctx->flow->depth++;
3305
3306 flow->next_block = NULL;
3307 flow->loop_entry_block = NULL;
3308 return flow;
3309 }
3310
3311 static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base,
3312 int label_id)
3313 {
3314 char buf[32];
3315 snprintf(buf, sizeof(buf), "%s%d", base, label_id);
3316 LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
3317 }
3318
3319 /* Append a basic block at the level of the parent flow.
3320 */
3321 static LLVMBasicBlockRef append_basic_block(struct ac_llvm_context *ctx,
3322 const char *name)
3323 {
3324 assert(ctx->flow->depth >= 1);
3325
3326 if (ctx->flow->depth >= 2) {
3327 struct ac_llvm_flow *flow = &ctx->flow->stack[ctx->flow->depth - 2];
3328
3329 return LLVMInsertBasicBlockInContext(ctx->context,
3330 flow->next_block, name);
3331 }
3332
3333 LLVMValueRef main_fn =
3334 LLVMGetBasicBlockParent(LLVMGetInsertBlock(ctx->builder));
3335 return LLVMAppendBasicBlockInContext(ctx->context, main_fn, name);
3336 }
3337
3338 /* Emit a branch to the given default target for the current block if
3339 * applicable -- that is, if the current block does not already contain a
3340 * branch from a break or continue.
3341 */
3342 static void emit_default_branch(LLVMBuilderRef builder,
3343 LLVMBasicBlockRef target)
3344 {
3345 if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
3346 LLVMBuildBr(builder, target);
3347 }
3348
3349 void ac_build_bgnloop(struct ac_llvm_context *ctx, int label_id)
3350 {
3351 struct ac_llvm_flow *flow = push_flow(ctx);
3352 flow->loop_entry_block = append_basic_block(ctx, "LOOP");
3353 flow->next_block = append_basic_block(ctx, "ENDLOOP");
3354 set_basicblock_name(flow->loop_entry_block, "loop", label_id);
3355 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
3356 LLVMPositionBuilderAtEnd(ctx->builder, flow->loop_entry_block);
3357 }
3358
3359 void ac_build_break(struct ac_llvm_context *ctx)
3360 {
3361 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
3362 LLVMBuildBr(ctx->builder, flow->next_block);
3363 }
3364
3365 void ac_build_continue(struct ac_llvm_context *ctx)
3366 {
3367 struct ac_llvm_flow *flow = get_innermost_loop(ctx);
3368 LLVMBuildBr(ctx->builder, flow->loop_entry_block);
3369 }
3370
3371 void ac_build_else(struct ac_llvm_context *ctx, int label_id)
3372 {
3373 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
3374 LLVMBasicBlockRef endif_block;
3375
3376 assert(!current_branch->loop_entry_block);
3377
3378 endif_block = append_basic_block(ctx, "ENDIF");
3379 emit_default_branch(ctx->builder, endif_block);
3380
3381 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
3382 set_basicblock_name(current_branch->next_block, "else", label_id);
3383
3384 current_branch->next_block = endif_block;
3385 }
3386
3387 void ac_build_endif(struct ac_llvm_context *ctx, int label_id)
3388 {
3389 struct ac_llvm_flow *current_branch = get_current_flow(ctx);
3390
3391 assert(!current_branch->loop_entry_block);
3392
3393 emit_default_branch(ctx->builder, current_branch->next_block);
3394 LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
3395 set_basicblock_name(current_branch->next_block, "endif", label_id);
3396
3397 ctx->flow->depth--;
3398 }
3399
3400 void ac_build_endloop(struct ac_llvm_context *ctx, int label_id)
3401 {
3402 struct ac_llvm_flow *current_loop = get_current_flow(ctx);
3403
3404 assert(current_loop->loop_entry_block);
3405
3406 emit_default_branch(ctx->builder, current_loop->loop_entry_block);
3407
3408 LLVMPositionBuilderAtEnd(ctx->builder, current_loop->next_block);
3409 set_basicblock_name(current_loop->next_block, "endloop", label_id);
3410 ctx->flow->depth--;
3411 }
3412
3413 void ac_build_ifcc(struct ac_llvm_context *ctx, LLVMValueRef cond, int label_id)
3414 {
3415 struct ac_llvm_flow *flow = push_flow(ctx);
3416 LLVMBasicBlockRef if_block;
3417
3418 if_block = append_basic_block(ctx, "IF");
3419 flow->next_block = append_basic_block(ctx, "ELSE");
3420 set_basicblock_name(if_block, "if", label_id);
3421 LLVMBuildCondBr(ctx->builder, cond, if_block, flow->next_block);
3422 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
3423 }
3424
3425 void ac_build_if(struct ac_llvm_context *ctx, LLVMValueRef value,
3426 int label_id)
3427 {
3428 LLVMValueRef cond = LLVMBuildFCmp(ctx->builder, LLVMRealUNE,
3429 value, ctx->f32_0, "");
3430 ac_build_ifcc(ctx, cond, label_id);
3431 }
3432
3433 void ac_build_uif(struct ac_llvm_context *ctx, LLVMValueRef value,
3434 int label_id)
3435 {
3436 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
3437 ac_to_integer(ctx, value),
3438 ctx->i32_0, "");
3439 ac_build_ifcc(ctx, cond, label_id);
3440 }
3441
3442 LLVMValueRef ac_build_alloca_undef(struct ac_llvm_context *ac, LLVMTypeRef type,
3443 const char *name)
3444 {
3445 LLVMBuilderRef builder = ac->builder;
3446 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
3447 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
3448 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
3449 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
3450 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ac->context);
3451 LLVMValueRef res;
3452
3453 if (first_instr) {
3454 LLVMPositionBuilderBefore(first_builder, first_instr);
3455 } else {
3456 LLVMPositionBuilderAtEnd(first_builder, first_block);
3457 }
3458
3459 res = LLVMBuildAlloca(first_builder, type, name);
3460 LLVMDisposeBuilder(first_builder);
3461 return res;
3462 }
3463
3464 LLVMValueRef ac_build_alloca(struct ac_llvm_context *ac,
3465 LLVMTypeRef type, const char *name)
3466 {
3467 LLVMValueRef ptr = ac_build_alloca_undef(ac, type, name);
3468 LLVMBuildStore(ac->builder, LLVMConstNull(type), ptr);
3469 return ptr;
3470 }
3471
3472 LLVMValueRef ac_cast_ptr(struct ac_llvm_context *ctx, LLVMValueRef ptr,
3473 LLVMTypeRef type)
3474 {
3475 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
3476 return LLVMBuildBitCast(ctx->builder, ptr,
3477 LLVMPointerType(type, addr_space), "");
3478 }
3479
3480 LLVMValueRef ac_trim_vector(struct ac_llvm_context *ctx, LLVMValueRef value,
3481 unsigned count)
3482 {
3483 unsigned num_components = ac_get_llvm_num_components(value);
3484 if (count == num_components)
3485 return value;
3486
3487 LLVMValueRef masks[MAX2(count, 2)];
3488 masks[0] = ctx->i32_0;
3489 masks[1] = ctx->i32_1;
3490 for (unsigned i = 2; i < count; i++)
3491 masks[i] = LLVMConstInt(ctx->i32, i, false);
3492
3493 if (count == 1)
3494 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
3495 "");
3496
3497 LLVMValueRef swizzle = LLVMConstVector(masks, count);
3498 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
3499 }
3500
3501 LLVMValueRef ac_unpack_param(struct ac_llvm_context *ctx, LLVMValueRef param,
3502 unsigned rshift, unsigned bitwidth)
3503 {
3504 LLVMValueRef value = param;
3505 if (rshift)
3506 value = LLVMBuildLShr(ctx->builder, value,
3507 LLVMConstInt(ctx->i32, rshift, false), "");
3508
3509 if (rshift + bitwidth < 32) {
3510 unsigned mask = (1 << bitwidth) - 1;
3511 value = LLVMBuildAnd(ctx->builder, value,
3512 LLVMConstInt(ctx->i32, mask, false), "");
3513 }
3514 return value;
3515 }
3516
3517 /* Adjust the sample index according to FMASK.
3518 *
3519 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
3520 * which is the identity mapping. Each nibble says which physical sample
3521 * should be fetched to get that sample.
3522 *
3523 * For example, 0x11111100 means there are only 2 samples stored and
3524 * the second sample covers 3/4 of the pixel. When reading samples 0
3525 * and 1, return physical sample 0 (determined by the first two 0s
3526 * in FMASK), otherwise return physical sample 1.
3527 *
3528 * The sample index should be adjusted as follows:
3529 * addr[sample_index] = (fmask >> (addr[sample_index] * 4)) & 0xF;
3530 */
3531 void ac_apply_fmask_to_sample(struct ac_llvm_context *ac, LLVMValueRef fmask,
3532 LLVMValueRef *addr, bool is_array_tex)
3533 {
3534 struct ac_image_args fmask_load = {};
3535 fmask_load.opcode = ac_image_load;
3536 fmask_load.resource = fmask;
3537 fmask_load.dmask = 0xf;
3538 fmask_load.dim = is_array_tex ? ac_image_2darray : ac_image_2d;
3539 fmask_load.attributes = AC_FUNC_ATTR_READNONE;
3540
3541 fmask_load.coords[0] = addr[0];
3542 fmask_load.coords[1] = addr[1];
3543 if (is_array_tex)
3544 fmask_load.coords[2] = addr[2];
3545
3546 LLVMValueRef fmask_value = ac_build_image_opcode(ac, &fmask_load);
3547 fmask_value = LLVMBuildExtractElement(ac->builder, fmask_value,
3548 ac->i32_0, "");
3549
3550 /* Apply the formula. */
3551 unsigned sample_chan = is_array_tex ? 3 : 2;
3552 LLVMValueRef final_sample;
3553 final_sample = LLVMBuildMul(ac->builder, addr[sample_chan],
3554 LLVMConstInt(ac->i32, 4, 0), "");
3555 final_sample = LLVMBuildLShr(ac->builder, fmask_value, final_sample, "");
3556 /* Mask the sample index by 0x7, because 0x8 means an unknown value
3557 * with EQAA, so those will map to 0. */
3558 final_sample = LLVMBuildAnd(ac->builder, final_sample,
3559 LLVMConstInt(ac->i32, 0x7, 0), "");
3560
3561 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
3562 * resource descriptor is 0 (invalid).
3563 */
3564 LLVMValueRef tmp;
3565 tmp = LLVMBuildBitCast(ac->builder, fmask, ac->v8i32, "");
3566 tmp = LLVMBuildExtractElement(ac->builder, tmp, ac->i32_1, "");
3567 tmp = LLVMBuildICmp(ac->builder, LLVMIntNE, tmp, ac->i32_0, "");
3568
3569 /* Replace the MSAA sample index. */
3570 addr[sample_chan] = LLVMBuildSelect(ac->builder, tmp, final_sample,
3571 addr[sample_chan], "");
3572 }
3573
3574 static LLVMValueRef
3575 _ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
3576 {
3577 LLVMTypeRef type = LLVMTypeOf(src);
3578 LLVMValueRef result;
3579
3580 ac_build_optimization_barrier(ctx, &src);
3581
3582 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3583 if (lane)
3584 lane = LLVMBuildZExt(ctx->builder, lane, ctx->i32, "");
3585
3586 result = ac_build_intrinsic(ctx,
3587 lane == NULL ? "llvm.amdgcn.readfirstlane" : "llvm.amdgcn.readlane",
3588 ctx->i32, (LLVMValueRef []) { src, lane },
3589 lane == NULL ? 1 : 2,
3590 AC_FUNC_ATTR_READNONE |
3591 AC_FUNC_ATTR_CONVERGENT);
3592
3593 return LLVMBuildTrunc(ctx->builder, result, type, "");
3594 }
3595
3596 /**
3597 * Builds the "llvm.amdgcn.readlane" or "llvm.amdgcn.readfirstlane" intrinsic.
3598 * @param ctx
3599 * @param src
3600 * @param lane - id of the lane or NULL for the first active lane
3601 * @return value of the lane
3602 */
3603 LLVMValueRef
3604 ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
3605 {
3606 LLVMTypeRef src_type = LLVMTypeOf(src);
3607 src = ac_to_integer(ctx, src);
3608 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3609 LLVMValueRef ret;
3610
3611 if (bits > 32) {
3612 assert(bits % 32 == 0);
3613 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3614 LLVMValueRef src_vector =
3615 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3616 ret = LLVMGetUndef(vec_type);
3617 for (unsigned i = 0; i < bits / 32; i++) {
3618 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3619 LLVMConstInt(ctx->i32, i, 0), "");
3620 LLVMValueRef ret_comp = _ac_build_readlane(ctx, src, lane);
3621 ret = LLVMBuildInsertElement(ctx->builder, ret, ret_comp,
3622 LLVMConstInt(ctx->i32, i, 0), "");
3623 }
3624 } else {
3625 ret = _ac_build_readlane(ctx, src, lane);
3626 }
3627
3628 if (LLVMGetTypeKind(src_type) == LLVMPointerTypeKind)
3629 return LLVMBuildIntToPtr(ctx->builder, ret, src_type, "");
3630 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3631 }
3632
3633 LLVMValueRef
3634 ac_build_writelane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef value, LLVMValueRef lane)
3635 {
3636 return ac_build_intrinsic(ctx, "llvm.amdgcn.writelane", ctx->i32,
3637 (LLVMValueRef []) {value, lane, src}, 3,
3638 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3639 }
3640
3641 LLVMValueRef
3642 ac_build_mbcnt(struct ac_llvm_context *ctx, LLVMValueRef mask)
3643 {
3644 if (ctx->wave_size == 32) {
3645 return ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
3646 (LLVMValueRef []) { mask, ctx->i32_0 },
3647 2, AC_FUNC_ATTR_READNONE);
3648 }
3649 LLVMValueRef mask_vec = LLVMBuildBitCast(ctx->builder, mask,
3650 LLVMVectorType(ctx->i32, 2),
3651 "");
3652 LLVMValueRef mask_lo = LLVMBuildExtractElement(ctx->builder, mask_vec,
3653 ctx->i32_0, "");
3654 LLVMValueRef mask_hi = LLVMBuildExtractElement(ctx->builder, mask_vec,
3655 ctx->i32_1, "");
3656 LLVMValueRef val =
3657 ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
3658 (LLVMValueRef []) { mask_lo, ctx->i32_0 },
3659 2, AC_FUNC_ATTR_READNONE);
3660 val = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi", ctx->i32,
3661 (LLVMValueRef []) { mask_hi, val },
3662 2, AC_FUNC_ATTR_READNONE);
3663 return val;
3664 }
3665
3666 enum dpp_ctrl {
3667 _dpp_quad_perm = 0x000,
3668 _dpp_row_sl = 0x100,
3669 _dpp_row_sr = 0x110,
3670 _dpp_row_rr = 0x120,
3671 dpp_wf_sl1 = 0x130,
3672 dpp_wf_rl1 = 0x134,
3673 dpp_wf_sr1 = 0x138,
3674 dpp_wf_rr1 = 0x13C,
3675 dpp_row_mirror = 0x140,
3676 dpp_row_half_mirror = 0x141,
3677 dpp_row_bcast15 = 0x142,
3678 dpp_row_bcast31 = 0x143
3679 };
3680
3681 static inline enum dpp_ctrl
3682 dpp_quad_perm(unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
3683 {
3684 assert(lane0 < 4 && lane1 < 4 && lane2 < 4 && lane3 < 4);
3685 return _dpp_quad_perm | lane0 | (lane1 << 2) | (lane2 << 4) | (lane3 << 6);
3686 }
3687
3688 static inline enum dpp_ctrl
3689 dpp_row_sl(unsigned amount)
3690 {
3691 assert(amount > 0 && amount < 16);
3692 return _dpp_row_sl | amount;
3693 }
3694
3695 static inline enum dpp_ctrl
3696 dpp_row_sr(unsigned amount)
3697 {
3698 assert(amount > 0 && amount < 16);
3699 return _dpp_row_sr | amount;
3700 }
3701
3702 static LLVMValueRef
3703 _ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
3704 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
3705 bool bound_ctrl)
3706 {
3707 LLVMTypeRef type = LLVMTypeOf(src);
3708 LLVMValueRef res;
3709
3710 old = LLVMBuildZExt(ctx->builder, old, ctx->i32, "");
3711 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3712
3713 res = ac_build_intrinsic(ctx, "llvm.amdgcn.update.dpp.i32", ctx->i32,
3714 (LLVMValueRef[]) {
3715 old, src,
3716 LLVMConstInt(ctx->i32, dpp_ctrl, 0),
3717 LLVMConstInt(ctx->i32, row_mask, 0),
3718 LLVMConstInt(ctx->i32, bank_mask, 0),
3719 LLVMConstInt(ctx->i1, bound_ctrl, 0) },
3720 6, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3721
3722 return LLVMBuildTrunc(ctx->builder, res, type, "");
3723 }
3724
3725 static LLVMValueRef
3726 ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
3727 enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
3728 bool bound_ctrl)
3729 {
3730 LLVMTypeRef src_type = LLVMTypeOf(src);
3731 src = ac_to_integer(ctx, src);
3732 old = ac_to_integer(ctx, old);
3733 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3734 LLVMValueRef ret;
3735 if (bits > 32) {
3736 assert(bits % 32 == 0);
3737 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3738 LLVMValueRef src_vector =
3739 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3740 LLVMValueRef old_vector =
3741 LLVMBuildBitCast(ctx->builder, old, vec_type, "");
3742 ret = LLVMGetUndef(vec_type);
3743 for (unsigned i = 0; i < bits / 32; i++) {
3744 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3745 LLVMConstInt(ctx->i32, i,
3746 0), "");
3747 old = LLVMBuildExtractElement(ctx->builder, old_vector,
3748 LLVMConstInt(ctx->i32, i,
3749 0), "");
3750 LLVMValueRef ret_comp = _ac_build_dpp(ctx, old, src,
3751 dpp_ctrl,
3752 row_mask,
3753 bank_mask,
3754 bound_ctrl);
3755 ret = LLVMBuildInsertElement(ctx->builder, ret,
3756 ret_comp,
3757 LLVMConstInt(ctx->i32, i,
3758 0), "");
3759 }
3760 } else {
3761 ret = _ac_build_dpp(ctx, old, src, dpp_ctrl, row_mask,
3762 bank_mask, bound_ctrl);
3763 }
3764 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3765 }
3766
3767 static LLVMValueRef
3768 _ac_build_permlane16(struct ac_llvm_context *ctx, LLVMValueRef src, uint64_t sel,
3769 bool exchange_rows, bool bound_ctrl)
3770 {
3771 LLVMTypeRef type = LLVMTypeOf(src);
3772 LLVMValueRef result;
3773
3774 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3775
3776 LLVMValueRef args[6] = {
3777 src,
3778 src,
3779 LLVMConstInt(ctx->i32, sel, false),
3780 LLVMConstInt(ctx->i32, sel >> 32, false),
3781 ctx->i1true, /* fi */
3782 bound_ctrl ? ctx->i1true : ctx->i1false,
3783 };
3784
3785 result = ac_build_intrinsic(ctx, exchange_rows ? "llvm.amdgcn.permlanex16"
3786 : "llvm.amdgcn.permlane16",
3787 ctx->i32, args, 6,
3788 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3789
3790 return LLVMBuildTrunc(ctx->builder, result, type, "");
3791 }
3792
3793 static LLVMValueRef
3794 ac_build_permlane16(struct ac_llvm_context *ctx, LLVMValueRef src, uint64_t sel,
3795 bool exchange_rows, bool bound_ctrl)
3796 {
3797 LLVMTypeRef src_type = LLVMTypeOf(src);
3798 src = ac_to_integer(ctx, src);
3799 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3800 LLVMValueRef ret;
3801 if (bits > 32) {
3802 assert(bits % 32 == 0);
3803 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3804 LLVMValueRef src_vector =
3805 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3806 ret = LLVMGetUndef(vec_type);
3807 for (unsigned i = 0; i < bits / 32; i++) {
3808 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3809 LLVMConstInt(ctx->i32, i,
3810 0), "");
3811 LLVMValueRef ret_comp =
3812 _ac_build_permlane16(ctx, src, sel,
3813 exchange_rows,
3814 bound_ctrl);
3815 ret = LLVMBuildInsertElement(ctx->builder, ret,
3816 ret_comp,
3817 LLVMConstInt(ctx->i32, i,
3818 0), "");
3819 }
3820 } else {
3821 ret = _ac_build_permlane16(ctx, src, sel, exchange_rows,
3822 bound_ctrl);
3823 }
3824 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3825 }
3826
3827 static inline unsigned
3828 ds_pattern_bitmode(unsigned and_mask, unsigned or_mask, unsigned xor_mask)
3829 {
3830 assert(and_mask < 32 && or_mask < 32 && xor_mask < 32);
3831 return and_mask | (or_mask << 5) | (xor_mask << 10);
3832 }
3833
3834 static LLVMValueRef
3835 _ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
3836 {
3837 LLVMTypeRef src_type = LLVMTypeOf(src);
3838 LLVMValueRef ret;
3839
3840 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3841
3842 ret = ac_build_intrinsic(ctx, "llvm.amdgcn.ds.swizzle", ctx->i32,
3843 (LLVMValueRef []) {
3844 src, LLVMConstInt(ctx->i32, mask, 0) },
3845 2, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
3846
3847 return LLVMBuildTrunc(ctx->builder, ret, src_type, "");
3848 }
3849
3850 LLVMValueRef
3851 ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
3852 {
3853 LLVMTypeRef src_type = LLVMTypeOf(src);
3854 src = ac_to_integer(ctx, src);
3855 unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
3856 LLVMValueRef ret;
3857 if (bits > 32) {
3858 assert(bits % 32 == 0);
3859 LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
3860 LLVMValueRef src_vector =
3861 LLVMBuildBitCast(ctx->builder, src, vec_type, "");
3862 ret = LLVMGetUndef(vec_type);
3863 for (unsigned i = 0; i < bits / 32; i++) {
3864 src = LLVMBuildExtractElement(ctx->builder, src_vector,
3865 LLVMConstInt(ctx->i32, i,
3866 0), "");
3867 LLVMValueRef ret_comp = _ac_build_ds_swizzle(ctx, src,
3868 mask);
3869 ret = LLVMBuildInsertElement(ctx->builder, ret,
3870 ret_comp,
3871 LLVMConstInt(ctx->i32, i,
3872 0), "");
3873 }
3874 } else {
3875 ret = _ac_build_ds_swizzle(ctx, src, mask);
3876 }
3877 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3878 }
3879
3880 static LLVMValueRef
3881 ac_build_wwm(struct ac_llvm_context *ctx, LLVMValueRef src)
3882 {
3883 LLVMTypeRef src_type = LLVMTypeOf(src);
3884 unsigned bitsize = ac_get_elem_bits(ctx, src_type);
3885 char name[32], type[8];
3886 LLVMValueRef ret;
3887
3888 src = ac_to_integer(ctx, src);
3889
3890 if (bitsize < 32)
3891 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3892
3893 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3894 snprintf(name, sizeof(name), "llvm.amdgcn.wwm.%s", type);
3895 ret = ac_build_intrinsic(ctx, name, LLVMTypeOf(src),
3896 (LLVMValueRef []) { src }, 1,
3897 AC_FUNC_ATTR_READNONE);
3898
3899 if (bitsize < 32)
3900 ret = LLVMBuildTrunc(ctx->builder, ret,
3901 ac_to_integer_type(ctx, src_type), "");
3902
3903 return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
3904 }
3905
3906 static LLVMValueRef
3907 ac_build_set_inactive(struct ac_llvm_context *ctx, LLVMValueRef src,
3908 LLVMValueRef inactive)
3909 {
3910 char name[33], type[8];
3911 LLVMTypeRef src_type = LLVMTypeOf(src);
3912 unsigned bitsize = ac_get_elem_bits(ctx, src_type);
3913 src = ac_to_integer(ctx, src);
3914 inactive = ac_to_integer(ctx, inactive);
3915
3916 if (bitsize < 32) {
3917 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
3918 inactive = LLVMBuildZExt(ctx->builder, inactive, ctx->i32, "");
3919 }
3920
3921 ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
3922 snprintf(name, sizeof(name), "llvm.amdgcn.set.inactive.%s", type);
3923 LLVMValueRef ret =
3924 ac_build_intrinsic(ctx, name,
3925 LLVMTypeOf(src), (LLVMValueRef []) {
3926 src, inactive }, 2,
3927 AC_FUNC_ATTR_READNONE |
3928 AC_FUNC_ATTR_CONVERGENT);
3929 if (bitsize < 32)
3930 ret = LLVMBuildTrunc(ctx->builder, ret, src_type, "");
3931
3932 return ret;
3933 }
3934
3935 static LLVMValueRef
3936 get_reduction_identity(struct ac_llvm_context *ctx, nir_op op, unsigned type_size)
3937 {
3938 if (type_size == 1) {
3939 switch (op) {
3940 case nir_op_iadd: return ctx->i8_0;
3941 case nir_op_imul: return ctx->i8_1;
3942 case nir_op_imin: return LLVMConstInt(ctx->i8, INT8_MAX, 0);
3943 case nir_op_umin: return LLVMConstInt(ctx->i8, UINT8_MAX, 0);
3944 case nir_op_imax: return LLVMConstInt(ctx->i8, INT8_MIN, 0);
3945 case nir_op_umax: return ctx->i8_0;
3946 case nir_op_iand: return LLVMConstInt(ctx->i8, -1, 0);
3947 case nir_op_ior: return ctx->i8_0;
3948 case nir_op_ixor: return ctx->i8_0;
3949 default:
3950 unreachable("bad reduction intrinsic");
3951 }
3952 } else if (type_size == 2) {
3953 switch (op) {
3954 case nir_op_iadd: return ctx->i16_0;
3955 case nir_op_fadd: return ctx->f16_0;
3956 case nir_op_imul: return ctx->i16_1;
3957 case nir_op_fmul: return ctx->f16_1;
3958 case nir_op_imin: return LLVMConstInt(ctx->i16, INT16_MAX, 0);
3959 case nir_op_umin: return LLVMConstInt(ctx->i16, UINT16_MAX, 0);
3960 case nir_op_fmin: return LLVMConstReal(ctx->f16, INFINITY);
3961 case nir_op_imax: return LLVMConstInt(ctx->i16, INT16_MIN, 0);
3962 case nir_op_umax: return ctx->i16_0;
3963 case nir_op_fmax: return LLVMConstReal(ctx->f16, -INFINITY);
3964 case nir_op_iand: return LLVMConstInt(ctx->i16, -1, 0);
3965 case nir_op_ior: return ctx->i16_0;
3966 case nir_op_ixor: return ctx->i16_0;
3967 default:
3968 unreachable("bad reduction intrinsic");
3969 }
3970 } else if (type_size == 4) {
3971 switch (op) {
3972 case nir_op_iadd: return ctx->i32_0;
3973 case nir_op_fadd: return ctx->f32_0;
3974 case nir_op_imul: return ctx->i32_1;
3975 case nir_op_fmul: return ctx->f32_1;
3976 case nir_op_imin: return LLVMConstInt(ctx->i32, INT32_MAX, 0);
3977 case nir_op_umin: return LLVMConstInt(ctx->i32, UINT32_MAX, 0);
3978 case nir_op_fmin: return LLVMConstReal(ctx->f32, INFINITY);
3979 case nir_op_imax: return LLVMConstInt(ctx->i32, INT32_MIN, 0);
3980 case nir_op_umax: return ctx->i32_0;
3981 case nir_op_fmax: return LLVMConstReal(ctx->f32, -INFINITY);
3982 case nir_op_iand: return LLVMConstInt(ctx->i32, -1, 0);
3983 case nir_op_ior: return ctx->i32_0;
3984 case nir_op_ixor: return ctx->i32_0;
3985 default:
3986 unreachable("bad reduction intrinsic");
3987 }
3988 } else { /* type_size == 64bit */
3989 switch (op) {
3990 case nir_op_iadd: return ctx->i64_0;
3991 case nir_op_fadd: return ctx->f64_0;
3992 case nir_op_imul: return ctx->i64_1;
3993 case nir_op_fmul: return ctx->f64_1;
3994 case nir_op_imin: return LLVMConstInt(ctx->i64, INT64_MAX, 0);
3995 case nir_op_umin: return LLVMConstInt(ctx->i64, UINT64_MAX, 0);
3996 case nir_op_fmin: return LLVMConstReal(ctx->f64, INFINITY);
3997 case nir_op_imax: return LLVMConstInt(ctx->i64, INT64_MIN, 0);
3998 case nir_op_umax: return ctx->i64_0;
3999 case nir_op_fmax: return LLVMConstReal(ctx->f64, -INFINITY);
4000 case nir_op_iand: return LLVMConstInt(ctx->i64, -1, 0);
4001 case nir_op_ior: return ctx->i64_0;
4002 case nir_op_ixor: return ctx->i64_0;
4003 default:
4004 unreachable("bad reduction intrinsic");
4005 }
4006 }
4007 }
4008
4009 static LLVMValueRef
4010 ac_build_alu_op(struct ac_llvm_context *ctx, LLVMValueRef lhs, LLVMValueRef rhs, nir_op op)
4011 {
4012 bool _64bit = ac_get_type_size(LLVMTypeOf(lhs)) == 8;
4013 bool _32bit = ac_get_type_size(LLVMTypeOf(lhs)) == 4;
4014 switch (op) {
4015 case nir_op_iadd: return LLVMBuildAdd(ctx->builder, lhs, rhs, "");
4016 case nir_op_fadd: return LLVMBuildFAdd(ctx->builder, lhs, rhs, "");
4017 case nir_op_imul: return LLVMBuildMul(ctx->builder, lhs, rhs, "");
4018 case nir_op_fmul: return LLVMBuildFMul(ctx->builder, lhs, rhs, "");
4019 case nir_op_imin: return LLVMBuildSelect(ctx->builder,
4020 LLVMBuildICmp(ctx->builder, LLVMIntSLT, lhs, rhs, ""),
4021 lhs, rhs, "");
4022 case nir_op_umin: return LLVMBuildSelect(ctx->builder,
4023 LLVMBuildICmp(ctx->builder, LLVMIntULT, lhs, rhs, ""),
4024 lhs, rhs, "");
4025 case nir_op_fmin: return ac_build_intrinsic(ctx,
4026 _64bit ? "llvm.minnum.f64" : _32bit ? "llvm.minnum.f32" : "llvm.minnum.f16",
4027 _64bit ? ctx->f64 : _32bit ? ctx->f32 : ctx->f16,
4028 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
4029 case nir_op_imax: return LLVMBuildSelect(ctx->builder,
4030 LLVMBuildICmp(ctx->builder, LLVMIntSGT, lhs, rhs, ""),
4031 lhs, rhs, "");
4032 case nir_op_umax: return LLVMBuildSelect(ctx->builder,
4033 LLVMBuildICmp(ctx->builder, LLVMIntUGT, lhs, rhs, ""),
4034 lhs, rhs, "");
4035 case nir_op_fmax: return ac_build_intrinsic(ctx,
4036 _64bit ? "llvm.maxnum.f64" : _32bit ? "llvm.maxnum.f32" : "llvm.maxnum.f16",
4037 _64bit ? ctx->f64 : _32bit ? ctx->f32 : ctx->f16,
4038 (LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
4039 case nir_op_iand: return LLVMBuildAnd(ctx->builder, lhs, rhs, "");
4040 case nir_op_ior: return LLVMBuildOr(ctx->builder, lhs, rhs, "");
4041 case nir_op_ixor: return LLVMBuildXor(ctx->builder, lhs, rhs, "");
4042 default:
4043 unreachable("bad reduction intrinsic");
4044 }
4045 }
4046
4047 /**
4048 * \param maxprefix specifies that the result only needs to be correct for a
4049 * prefix of this many threads
4050 */
4051 static LLVMValueRef
4052 ac_build_scan(struct ac_llvm_context *ctx, nir_op op, LLVMValueRef src, LLVMValueRef identity,
4053 unsigned maxprefix, bool inclusive)
4054 {
4055 LLVMValueRef result, tmp;
4056
4057 if (inclusive) {
4058 result = src;
4059 } else if (ctx->chip_class >= GFX10) {
4060 /* wavefront shift_right by 1 on GFX10 (emulate dpp_wf_sr1) */
4061 LLVMValueRef active, tmp1, tmp2;
4062 LLVMValueRef tid = ac_get_thread_id(ctx);
4063
4064 tmp1 = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
4065
4066 tmp2 = ac_build_permlane16(ctx, src, (uint64_t)~0, true, false);
4067
4068 if (maxprefix > 32) {
4069 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid,
4070 LLVMConstInt(ctx->i32, 32, false), "");
4071
4072 tmp2 = LLVMBuildSelect(ctx->builder, active,
4073 ac_build_readlane(ctx, src,
4074 LLVMConstInt(ctx->i32, 31, false)),
4075 tmp2, "");
4076
4077 active = LLVMBuildOr(ctx->builder, active,
4078 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
4079 LLVMBuildAnd(ctx->builder, tid,
4080 LLVMConstInt(ctx->i32, 0x1f, false), ""),
4081 LLVMConstInt(ctx->i32, 0x10, false), ""), "");
4082 src = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4083 } else if (maxprefix > 16) {
4084 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid,
4085 LLVMConstInt(ctx->i32, 16, false), "");
4086
4087 src = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4088 }
4089
4090 result = src;
4091 } else if (ctx->chip_class >= GFX8) {
4092 src = ac_build_dpp(ctx, identity, src, dpp_wf_sr1, 0xf, 0xf, false);
4093 result = src;
4094 } else {
4095 /* wavefront shift_right by 1 on SI/CI */
4096 LLVMValueRef active, tmp1, tmp2;
4097 LLVMValueRef tid = ac_get_thread_id(ctx);
4098 tmp1 = ac_build_ds_swizzle(ctx, src, (1 << 15) | dpp_quad_perm(0, 0, 1, 2));
4099 tmp2 = ac_build_ds_swizzle(ctx, src, ds_pattern_bitmode(0x18, 0x03, 0x00));
4100 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
4101 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 0x7, 0), ""),
4102 LLVMConstInt(ctx->i32, 0x4, 0), "");
4103 tmp1 = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4104 tmp2 = ac_build_ds_swizzle(ctx, src, ds_pattern_bitmode(0x10, 0x07, 0x00));
4105 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
4106 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 0xf, 0), ""),
4107 LLVMConstInt(ctx->i32, 0x8, 0), "");
4108 tmp1 = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4109 tmp2 = ac_build_ds_swizzle(ctx, src, ds_pattern_bitmode(0x00, 0x0f, 0x00));
4110 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
4111 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 0x1f, 0), ""),
4112 LLVMConstInt(ctx->i32, 0x10, 0), "");
4113 tmp1 = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4114 tmp2 = ac_build_readlane(ctx, src, LLVMConstInt(ctx->i32, 31, 0));
4115 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid, LLVMConstInt(ctx->i32, 32, 0), "");
4116 tmp1 = LLVMBuildSelect(ctx->builder, active, tmp2, tmp1, "");
4117 active = LLVMBuildICmp(ctx->builder, LLVMIntEQ, tid, LLVMConstInt(ctx->i32, 0, 0), "");
4118 src = LLVMBuildSelect(ctx->builder, active, identity, tmp1, "");
4119 result = src;
4120 }
4121
4122 if (ctx->chip_class <= GFX7) {
4123 assert(maxprefix == 64);
4124 LLVMValueRef tid = ac_get_thread_id(ctx);
4125 LLVMValueRef active;
4126 tmp = ac_build_ds_swizzle(ctx, src, ds_pattern_bitmode(0x1e, 0x00, 0x00));
4127 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4128 LLVMBuildAnd(ctx->builder, tid, ctx->i32_1, ""),
4129 ctx->i32_0, "");
4130 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4131 result = ac_build_alu_op(ctx, result, tmp, op);
4132 tmp = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1c, 0x01, 0x00));
4133 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4134 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 2, 0), ""),
4135 ctx->i32_0, "");
4136 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4137 result = ac_build_alu_op(ctx, result, tmp, op);
4138 tmp = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x18, 0x03, 0x00));
4139 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4140 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 4, 0), ""),
4141 ctx->i32_0, "");
4142 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4143 result = ac_build_alu_op(ctx, result, tmp, op);
4144 tmp = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x10, 0x07, 0x00));
4145 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4146 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 8, 0), ""),
4147 ctx->i32_0, "");
4148 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4149 result = ac_build_alu_op(ctx, result, tmp, op);
4150 tmp = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x00, 0x0f, 0x00));
4151 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4152 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 16, 0), ""),
4153 ctx->i32_0, "");
4154 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4155 result = ac_build_alu_op(ctx, result, tmp, op);
4156 tmp = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 31, 0));
4157 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4158 LLVMBuildAnd(ctx->builder, tid, LLVMConstInt(ctx->i32, 32, 0), ""),
4159 ctx->i32_0, "");
4160 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4161 result = ac_build_alu_op(ctx, result, tmp, op);
4162 return result;
4163 }
4164
4165 if (maxprefix <= 1)
4166 return result;
4167 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
4168 result = ac_build_alu_op(ctx, result, tmp, op);
4169 if (maxprefix <= 2)
4170 return result;
4171 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(2), 0xf, 0xf, false);
4172 result = ac_build_alu_op(ctx, result, tmp, op);
4173 if (maxprefix <= 3)
4174 return result;
4175 tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(3), 0xf, 0xf, false);
4176 result = ac_build_alu_op(ctx, result, tmp, op);
4177 if (maxprefix <= 4)
4178 return result;
4179 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(4), 0xf, 0xe, false);
4180 result = ac_build_alu_op(ctx, result, tmp, op);
4181 if (maxprefix <= 8)
4182 return result;
4183 tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(8), 0xf, 0xc, false);
4184 result = ac_build_alu_op(ctx, result, tmp, op);
4185 if (maxprefix <= 16)
4186 return result;
4187
4188 if (ctx->chip_class >= GFX10) {
4189 LLVMValueRef tid = ac_get_thread_id(ctx);
4190 LLVMValueRef active;
4191
4192 tmp = ac_build_permlane16(ctx, result, ~(uint64_t)0, true, false);
4193
4194 active = LLVMBuildICmp(ctx->builder, LLVMIntNE,
4195 LLVMBuildAnd(ctx->builder, tid,
4196 LLVMConstInt(ctx->i32, 16, false), ""),
4197 ctx->i32_0, "");
4198
4199 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4200
4201 result = ac_build_alu_op(ctx, result, tmp, op);
4202
4203 if (maxprefix <= 32)
4204 return result;
4205
4206 tmp = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 31, false));
4207
4208 active = LLVMBuildICmp(ctx->builder, LLVMIntUGE, tid,
4209 LLVMConstInt(ctx->i32, 32, false), "");
4210
4211 tmp = LLVMBuildSelect(ctx->builder, active, tmp, identity, "");
4212
4213 result = ac_build_alu_op(ctx, result, tmp, op);
4214 return result;
4215 }
4216
4217 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
4218 result = ac_build_alu_op(ctx, result, tmp, op);
4219 if (maxprefix <= 32)
4220 return result;
4221 tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
4222 result = ac_build_alu_op(ctx, result, tmp, op);
4223 return result;
4224 }
4225
4226 LLVMValueRef
4227 ac_build_inclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
4228 {
4229 LLVMValueRef result;
4230
4231 if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
4232 LLVMBuilderRef builder = ctx->builder;
4233 src = LLVMBuildZExt(builder, src, ctx->i32, "");
4234 result = ac_build_ballot(ctx, src);
4235 result = ac_build_mbcnt(ctx, result);
4236 result = LLVMBuildAdd(builder, result, src, "");
4237 return result;
4238 }
4239
4240 ac_build_optimization_barrier(ctx, &src);
4241
4242 LLVMValueRef identity =
4243 get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
4244 result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
4245 LLVMTypeOf(identity), "");
4246 result = ac_build_scan(ctx, op, result, identity, ctx->wave_size, true);
4247
4248 return ac_build_wwm(ctx, result);
4249 }
4250
4251 LLVMValueRef
4252 ac_build_exclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
4253 {
4254 LLVMValueRef result;
4255
4256 if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
4257 LLVMBuilderRef builder = ctx->builder;
4258 src = LLVMBuildZExt(builder, src, ctx->i32, "");
4259 result = ac_build_ballot(ctx, src);
4260 result = ac_build_mbcnt(ctx, result);
4261 return result;
4262 }
4263
4264 ac_build_optimization_barrier(ctx, &src);
4265
4266 LLVMValueRef identity =
4267 get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
4268 result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
4269 LLVMTypeOf(identity), "");
4270 result = ac_build_scan(ctx, op, result, identity, ctx->wave_size, false);
4271
4272 return ac_build_wwm(ctx, result);
4273 }
4274
4275 LLVMValueRef
4276 ac_build_reduce(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op, unsigned cluster_size)
4277 {
4278 if (cluster_size == 1) return src;
4279 ac_build_optimization_barrier(ctx, &src);
4280 LLVMValueRef result, swap;
4281 LLVMValueRef identity = get_reduction_identity(ctx, op,
4282 ac_get_type_size(LLVMTypeOf(src)));
4283 result = LLVMBuildBitCast(ctx->builder,
4284 ac_build_set_inactive(ctx, src, identity),
4285 LLVMTypeOf(identity), "");
4286 swap = ac_build_quad_swizzle(ctx, result, 1, 0, 3, 2);
4287 result = ac_build_alu_op(ctx, result, swap, op);
4288 if (cluster_size == 2) return ac_build_wwm(ctx, result);
4289
4290 swap = ac_build_quad_swizzle(ctx, result, 2, 3, 0, 1);
4291 result = ac_build_alu_op(ctx, result, swap, op);
4292 if (cluster_size == 4) return ac_build_wwm(ctx, result);
4293
4294 if (ctx->chip_class >= GFX8)
4295 swap = ac_build_dpp(ctx, identity, result, dpp_row_half_mirror, 0xf, 0xf, false);
4296 else
4297 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x04));
4298 result = ac_build_alu_op(ctx, result, swap, op);
4299 if (cluster_size == 8) return ac_build_wwm(ctx, result);
4300
4301 if (ctx->chip_class >= GFX8)
4302 swap = ac_build_dpp(ctx, identity, result, dpp_row_mirror, 0xf, 0xf, false);
4303 else
4304 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x08));
4305 result = ac_build_alu_op(ctx, result, swap, op);
4306 if (cluster_size == 16) return ac_build_wwm(ctx, result);
4307
4308 if (ctx->chip_class >= GFX10)
4309 swap = ac_build_permlane16(ctx, result, 0, true, false);
4310 else if (ctx->chip_class >= GFX8 && cluster_size != 32)
4311 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
4312 else
4313 swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x10));
4314 result = ac_build_alu_op(ctx, result, swap, op);
4315 if (cluster_size == 32) return ac_build_wwm(ctx, result);
4316
4317 if (ctx->chip_class >= GFX8) {
4318 if (ctx->chip_class >= GFX10)
4319 swap = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 31, false));
4320 else
4321 swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
4322 result = ac_build_alu_op(ctx, result, swap, op);
4323 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 63, 0));
4324 return ac_build_wwm(ctx, result);
4325 } else {
4326 swap = ac_build_readlane(ctx, result, ctx->i32_0);
4327 result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 32, 0));
4328 result = ac_build_alu_op(ctx, result, swap, op);
4329 return ac_build_wwm(ctx, result);
4330 }
4331 }
4332
4333 /**
4334 * "Top half" of a scan that reduces per-wave values across an entire
4335 * workgroup.
4336 *
4337 * The source value must be present in the highest lane of the wave, and the
4338 * highest lane must be live.
4339 */
4340 void
4341 ac_build_wg_wavescan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4342 {
4343 if (ws->maxwaves <= 1)
4344 return;
4345
4346 const LLVMValueRef last_lane = LLVMConstInt(ctx->i32, ctx->wave_size - 1, false);
4347 LLVMBuilderRef builder = ctx->builder;
4348 LLVMValueRef tid = ac_get_thread_id(ctx);
4349 LLVMValueRef tmp;
4350
4351 tmp = LLVMBuildICmp(builder, LLVMIntEQ, tid, last_lane, "");
4352 ac_build_ifcc(ctx, tmp, 1000);
4353 LLVMBuildStore(builder, ws->src, LLVMBuildGEP(builder, ws->scratch, &ws->waveidx, 1, ""));
4354 ac_build_endif(ctx, 1000);
4355 }
4356
4357 /**
4358 * "Bottom half" of a scan that reduces per-wave values across an entire
4359 * workgroup.
4360 *
4361 * The caller must place a barrier between the top and bottom halves.
4362 */
4363 void
4364 ac_build_wg_wavescan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4365 {
4366 const LLVMTypeRef type = LLVMTypeOf(ws->src);
4367 const LLVMValueRef identity =
4368 get_reduction_identity(ctx, ws->op, ac_get_type_size(type));
4369
4370 if (ws->maxwaves <= 1) {
4371 ws->result_reduce = ws->src;
4372 ws->result_inclusive = ws->src;
4373 ws->result_exclusive = identity;
4374 return;
4375 }
4376 assert(ws->maxwaves <= 32);
4377
4378 LLVMBuilderRef builder = ctx->builder;
4379 LLVMValueRef tid = ac_get_thread_id(ctx);
4380 LLVMBasicBlockRef bbs[2];
4381 LLVMValueRef phivalues_scan[2];
4382 LLVMValueRef tmp, tmp2;
4383
4384 bbs[0] = LLVMGetInsertBlock(builder);
4385 phivalues_scan[0] = LLVMGetUndef(type);
4386
4387 if (ws->enable_reduce)
4388 tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->numwaves, "");
4389 else if (ws->enable_inclusive)
4390 tmp = LLVMBuildICmp(builder, LLVMIntULE, tid, ws->waveidx, "");
4391 else
4392 tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->waveidx, "");
4393 ac_build_ifcc(ctx, tmp, 1001);
4394 {
4395 tmp = LLVMBuildLoad(builder, LLVMBuildGEP(builder, ws->scratch, &tid, 1, ""), "");
4396
4397 ac_build_optimization_barrier(ctx, &tmp);
4398
4399 bbs[1] = LLVMGetInsertBlock(builder);
4400 phivalues_scan[1] = ac_build_scan(ctx, ws->op, tmp, identity, ws->maxwaves, true);
4401 }
4402 ac_build_endif(ctx, 1001);
4403
4404 const LLVMValueRef scan = ac_build_phi(ctx, type, 2, phivalues_scan, bbs);
4405
4406 if (ws->enable_reduce) {
4407 tmp = LLVMBuildSub(builder, ws->numwaves, ctx->i32_1, "");
4408 ws->result_reduce = ac_build_readlane(ctx, scan, tmp);
4409 }
4410 if (ws->enable_inclusive)
4411 ws->result_inclusive = ac_build_readlane(ctx, scan, ws->waveidx);
4412 if (ws->enable_exclusive) {
4413 tmp = LLVMBuildSub(builder, ws->waveidx, ctx->i32_1, "");
4414 tmp = ac_build_readlane(ctx, scan, tmp);
4415 tmp2 = LLVMBuildICmp(builder, LLVMIntEQ, ws->waveidx, ctx->i32_0, "");
4416 ws->result_exclusive = LLVMBuildSelect(builder, tmp2, identity, tmp, "");
4417 }
4418 }
4419
4420 /**
4421 * Inclusive scan of a per-wave value across an entire workgroup.
4422 *
4423 * This implies an s_barrier instruction.
4424 *
4425 * Unlike ac_build_inclusive_scan, the caller \em must ensure that all threads
4426 * of the workgroup are live. (This requirement cannot easily be relaxed in a
4427 * useful manner because of the barrier in the algorithm.)
4428 */
4429 void
4430 ac_build_wg_wavescan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4431 {
4432 ac_build_wg_wavescan_top(ctx, ws);
4433 ac_build_s_barrier(ctx);
4434 ac_build_wg_wavescan_bottom(ctx, ws);
4435 }
4436
4437 /**
4438 * "Top half" of a scan that reduces per-thread values across an entire
4439 * workgroup.
4440 *
4441 * All lanes must be active when this code runs.
4442 */
4443 void
4444 ac_build_wg_scan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4445 {
4446 if (ws->enable_exclusive) {
4447 ws->extra = ac_build_exclusive_scan(ctx, ws->src, ws->op);
4448 if (LLVMTypeOf(ws->src) == ctx->i1 && ws->op == nir_op_iadd)
4449 ws->src = LLVMBuildZExt(ctx->builder, ws->src, ctx->i32, "");
4450 ws->src = ac_build_alu_op(ctx, ws->extra, ws->src, ws->op);
4451 } else {
4452 ws->src = ac_build_inclusive_scan(ctx, ws->src, ws->op);
4453 }
4454
4455 bool enable_inclusive = ws->enable_inclusive;
4456 bool enable_exclusive = ws->enable_exclusive;
4457 ws->enable_inclusive = false;
4458 ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
4459 ac_build_wg_wavescan_top(ctx, ws);
4460 ws->enable_inclusive = enable_inclusive;
4461 ws->enable_exclusive = enable_exclusive;
4462 }
4463
4464 /**
4465 * "Bottom half" of a scan that reduces per-thread values across an entire
4466 * workgroup.
4467 *
4468 * The caller must place a barrier between the top and bottom halves.
4469 */
4470 void
4471 ac_build_wg_scan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4472 {
4473 bool enable_inclusive = ws->enable_inclusive;
4474 bool enable_exclusive = ws->enable_exclusive;
4475 ws->enable_inclusive = false;
4476 ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
4477 ac_build_wg_wavescan_bottom(ctx, ws);
4478 ws->enable_inclusive = enable_inclusive;
4479 ws->enable_exclusive = enable_exclusive;
4480
4481 /* ws->result_reduce is already the correct value */
4482 if (ws->enable_inclusive)
4483 ws->result_inclusive = ac_build_alu_op(ctx, ws->result_inclusive, ws->src, ws->op);
4484 if (ws->enable_exclusive)
4485 ws->result_exclusive = ac_build_alu_op(ctx, ws->result_exclusive, ws->extra, ws->op);
4486 }
4487
4488 /**
4489 * A scan that reduces per-thread values across an entire workgroup.
4490 *
4491 * The caller must ensure that all lanes are active when this code runs
4492 * (WWM is insufficient!), because there is an implied barrier.
4493 */
4494 void
4495 ac_build_wg_scan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
4496 {
4497 ac_build_wg_scan_top(ctx, ws);
4498 ac_build_s_barrier(ctx);
4499 ac_build_wg_scan_bottom(ctx, ws);
4500 }
4501
4502 LLVMValueRef
4503 ac_build_quad_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src,
4504 unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
4505 {
4506 unsigned mask = dpp_quad_perm(lane0, lane1, lane2, lane3);
4507 if (ctx->chip_class >= GFX8) {
4508 return ac_build_dpp(ctx, src, src, mask, 0xf, 0xf, false);
4509 } else {
4510 return ac_build_ds_swizzle(ctx, src, (1 << 15) | mask);
4511 }
4512 }
4513
4514 LLVMValueRef
4515 ac_build_shuffle(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef index)
4516 {
4517 LLVMTypeRef type = LLVMTypeOf(src);
4518 LLVMValueRef result;
4519
4520 index = LLVMBuildMul(ctx->builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
4521 src = LLVMBuildZExt(ctx->builder, src, ctx->i32, "");
4522
4523 result = ac_build_intrinsic(ctx, "llvm.amdgcn.ds.bpermute", ctx->i32,
4524 (LLVMValueRef []) {index, src}, 2,
4525 AC_FUNC_ATTR_READNONE |
4526 AC_FUNC_ATTR_CONVERGENT);
4527 return LLVMBuildTrunc(ctx->builder, result, type, "");
4528 }
4529
4530 LLVMValueRef
4531 ac_build_frexp_exp(struct ac_llvm_context *ctx, LLVMValueRef src0,
4532 unsigned bitsize)
4533 {
4534 LLVMTypeRef type;
4535 char *intr;
4536
4537 if (bitsize == 16) {
4538 intr = "llvm.amdgcn.frexp.exp.i16.f16";
4539 type = ctx->i16;
4540 } else if (bitsize == 32) {
4541 intr = "llvm.amdgcn.frexp.exp.i32.f32";
4542 type = ctx->i32;
4543 } else {
4544 intr = "llvm.amdgcn.frexp.exp.i32.f64";
4545 type = ctx->i32;
4546 }
4547
4548 LLVMValueRef params[] = {
4549 src0,
4550 };
4551 return ac_build_intrinsic(ctx, intr, type, params, 1,
4552 AC_FUNC_ATTR_READNONE);
4553 }
4554 LLVMValueRef
4555 ac_build_frexp_mant(struct ac_llvm_context *ctx, LLVMValueRef src0,
4556 unsigned bitsize)
4557 {
4558 LLVMTypeRef type;
4559 char *intr;
4560
4561 if (bitsize == 16) {
4562 intr = "llvm.amdgcn.frexp.mant.f16";
4563 type = ctx->f16;
4564 } else if (bitsize == 32) {
4565 intr = "llvm.amdgcn.frexp.mant.f32";
4566 type = ctx->f32;
4567 } else {
4568 intr = "llvm.amdgcn.frexp.mant.f64";
4569 type = ctx->f64;
4570 }
4571
4572 LLVMValueRef params[] = {
4573 src0,
4574 };
4575 return ac_build_intrinsic(ctx, intr, type, params, 1,
4576 AC_FUNC_ATTR_READNONE);
4577 }
4578
4579 LLVMValueRef
4580 ac_build_canonicalize(struct ac_llvm_context *ctx, LLVMValueRef src0,
4581 unsigned bitsize)
4582 {
4583 LLVMTypeRef type;
4584 char *intr;
4585
4586 if (bitsize == 16) {
4587 intr = "llvm.canonicalize.f16";
4588 type = ctx->f16;
4589 } else if (bitsize == 32) {
4590 intr = "llvm.canonicalize.f32";
4591 type = ctx->f32;
4592 } else {
4593 intr = "llvm.canonicalize.f64";
4594 type = ctx->f64;
4595 }
4596
4597 LLVMValueRef params[] = {
4598 src0,
4599 };
4600 return ac_build_intrinsic(ctx, intr, type, params, 1,
4601 AC_FUNC_ATTR_READNONE);
4602 }
4603
4604 /*
4605 * this takes an I,J coordinate pair,
4606 * and works out the X and Y derivatives.
4607 * it returns DDX(I), DDX(J), DDY(I), DDY(J).
4608 */
4609 LLVMValueRef
4610 ac_build_ddxy_interp(struct ac_llvm_context *ctx, LLVMValueRef interp_ij)
4611 {
4612 LLVMValueRef result[4], a;
4613 unsigned i;
4614
4615 for (i = 0; i < 2; i++) {
4616 a = LLVMBuildExtractElement(ctx->builder, interp_ij,
4617 LLVMConstInt(ctx->i32, i, false), "");
4618 result[i] = ac_build_ddxy(ctx, AC_TID_MASK_TOP_LEFT, 1, a);
4619 result[2+i] = ac_build_ddxy(ctx, AC_TID_MASK_TOP_LEFT, 2, a);
4620 }
4621 return ac_build_gather_values(ctx, result, 4);
4622 }
4623
4624 LLVMValueRef
4625 ac_build_load_helper_invocation(struct ac_llvm_context *ctx)
4626 {
4627 LLVMValueRef result = ac_build_intrinsic(ctx, "llvm.amdgcn.ps.live",
4628 ctx->i1, NULL, 0,
4629 AC_FUNC_ATTR_READNONE);
4630 result = LLVMBuildNot(ctx->builder, result, "");
4631 return LLVMBuildSExt(ctx->builder, result, ctx->i32, "");
4632 }
4633
4634 LLVMValueRef ac_build_call(struct ac_llvm_context *ctx, LLVMValueRef func,
4635 LLVMValueRef *args, unsigned num_args)
4636 {
4637 LLVMValueRef ret = LLVMBuildCall(ctx->builder, func, args, num_args, "");
4638 LLVMSetInstructionCallConv(ret, LLVMGetFunctionCallConv(func));
4639 return ret;
4640 }
4641
4642 void
4643 ac_export_mrt_z(struct ac_llvm_context *ctx, LLVMValueRef depth,
4644 LLVMValueRef stencil, LLVMValueRef samplemask,
4645 struct ac_export_args *args)
4646 {
4647 unsigned mask = 0;
4648 unsigned format = ac_get_spi_shader_z_format(depth != NULL,
4649 stencil != NULL,
4650 samplemask != NULL);
4651
4652 assert(depth || stencil || samplemask);
4653
4654 memset(args, 0, sizeof(*args));
4655
4656 args->valid_mask = 1; /* whether the EXEC mask is valid */
4657 args->done = 1; /* DONE bit */
4658
4659 /* Specify the target we are exporting */
4660 args->target = V_008DFC_SQ_EXP_MRTZ;
4661
4662 args->compr = 0; /* COMP flag */
4663 args->out[0] = LLVMGetUndef(ctx->f32); /* R, depth */
4664 args->out[1] = LLVMGetUndef(ctx->f32); /* G, stencil test val[0:7], stencil op val[8:15] */
4665 args->out[2] = LLVMGetUndef(ctx->f32); /* B, sample mask */
4666 args->out[3] = LLVMGetUndef(ctx->f32); /* A, alpha to mask */
4667
4668 if (format == V_028710_SPI_SHADER_UINT16_ABGR) {
4669 assert(!depth);
4670 args->compr = 1; /* COMPR flag */
4671
4672 if (stencil) {
4673 /* Stencil should be in X[23:16]. */
4674 stencil = ac_to_integer(ctx, stencil);
4675 stencil = LLVMBuildShl(ctx->builder, stencil,
4676 LLVMConstInt(ctx->i32, 16, 0), "");
4677 args->out[0] = ac_to_float(ctx, stencil);
4678 mask |= 0x3;
4679 }
4680 if (samplemask) {
4681 /* SampleMask should be in Y[15:0]. */
4682 args->out[1] = samplemask;
4683 mask |= 0xc;
4684 }
4685 } else {
4686 if (depth) {
4687 args->out[0] = depth;
4688 mask |= 0x1;
4689 }
4690 if (stencil) {
4691 args->out[1] = stencil;
4692 mask |= 0x2;
4693 }
4694 if (samplemask) {
4695 args->out[2] = samplemask;
4696 mask |= 0x4;
4697 }
4698 }
4699
4700 /* GFX6 (except OLAND and HAINAN) has a bug that it only looks
4701 * at the X writemask component. */
4702 if (ctx->chip_class == GFX6 &&
4703 ctx->family != CHIP_OLAND &&
4704 ctx->family != CHIP_HAINAN)
4705 mask |= 0x1;
4706
4707 /* Specify which components to enable */
4708 args->enabled_channels = mask;
4709 }
4710
4711 static LLVMTypeRef
4712 arg_llvm_type(enum ac_arg_type type, unsigned size, struct ac_llvm_context *ctx)
4713 {
4714 if (type == AC_ARG_FLOAT) {
4715 return size == 1 ? ctx->f32 : LLVMVectorType(ctx->f32, size);
4716 } else if (type == AC_ARG_INT) {
4717 return size == 1 ? ctx->i32 : LLVMVectorType(ctx->i32, size);
4718 } else {
4719 LLVMTypeRef ptr_type;
4720 switch (type) {
4721 case AC_ARG_CONST_PTR:
4722 ptr_type = ctx->i8;
4723 break;
4724 case AC_ARG_CONST_FLOAT_PTR:
4725 ptr_type = ctx->f32;
4726 break;
4727 case AC_ARG_CONST_PTR_PTR:
4728 ptr_type = ac_array_in_const32_addr_space(ctx->i8);
4729 break;
4730 case AC_ARG_CONST_DESC_PTR:
4731 ptr_type = ctx->v4i32;
4732 break;
4733 case AC_ARG_CONST_IMAGE_PTR:
4734 ptr_type = ctx->v8i32;
4735 break;
4736 default:
4737 unreachable("unknown arg type");
4738 }
4739 if (size == 1) {
4740 return ac_array_in_const32_addr_space(ptr_type);
4741 } else {
4742 assert(size == 2);
4743 return ac_array_in_const_addr_space(ptr_type);
4744 }
4745 }
4746 }
4747
4748 LLVMValueRef
4749 ac_build_main(const struct ac_shader_args *args,
4750 struct ac_llvm_context *ctx,
4751 enum ac_llvm_calling_convention convention,
4752 const char *name, LLVMTypeRef ret_type,
4753 LLVMModuleRef module)
4754 {
4755 LLVMTypeRef arg_types[AC_MAX_ARGS];
4756
4757 for (unsigned i = 0; i < args->arg_count; i++) {
4758 arg_types[i] = arg_llvm_type(args->args[i].type,
4759 args->args[i].size, ctx);
4760 }
4761
4762 LLVMTypeRef main_function_type =
4763 LLVMFunctionType(ret_type, arg_types, args->arg_count, 0);
4764
4765 LLVMValueRef main_function =
4766 LLVMAddFunction(module, name, main_function_type);
4767 LLVMBasicBlockRef main_function_body =
4768 LLVMAppendBasicBlockInContext(ctx->context, main_function, "main_body");
4769 LLVMPositionBuilderAtEnd(ctx->builder, main_function_body);
4770
4771 LLVMSetFunctionCallConv(main_function, convention);
4772 for (unsigned i = 0; i < args->arg_count; ++i) {
4773 LLVMValueRef P = LLVMGetParam(main_function, i);
4774
4775 if (args->args[i].file != AC_ARG_SGPR)
4776 continue;
4777
4778 ac_add_function_attr(ctx->context, main_function, i + 1, AC_FUNC_ATTR_INREG);
4779
4780 if (LLVMGetTypeKind(LLVMTypeOf(P)) == LLVMPointerTypeKind) {
4781 ac_add_function_attr(ctx->context, main_function, i + 1, AC_FUNC_ATTR_NOALIAS);
4782 ac_add_attr_dereferenceable(P, UINT64_MAX);
4783 }
4784 }
4785
4786 ctx->main_function = main_function;
4787 return main_function;
4788 }
4789