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