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