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