amd/common: save an instruction in the build_cube_select sequence
[mesa.git] / src / amd / common / ac_llvm_build.c
1 /*
2 * Copyright 2014 Advanced Micro Devices, Inc.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sub license, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
15 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
16 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
18 * USE OR OTHER DEALINGS IN THE SOFTWARE.
19 *
20 * The above copyright notice and this permission notice (including the
21 * next paragraph) shall be included in all copies or substantial portions
22 * of the Software.
23 *
24 */
25 /* based on pieces from si_pipe.c and radeon_llvm_emit.c */
26 #include "ac_llvm_build.h"
27
28 #include <llvm-c/Core.h>
29
30 #include "c11/threads.h"
31
32 #include <assert.h>
33 #include <stdio.h>
34
35 #include "ac_llvm_util.h"
36 #include "ac_exp_param.h"
37 #include "util/bitscan.h"
38 #include "util/macros.h"
39 #include "util/u_atomic.h"
40 #include "sid.h"
41
42 #include "shader_enums.h"
43
44 /* Initialize module-independent parts of the context.
45 *
46 * The caller is responsible for initializing ctx::module and ctx::builder.
47 */
48 void
49 ac_llvm_context_init(struct ac_llvm_context *ctx, LLVMContextRef context,
50 enum chip_class chip_class)
51 {
52 LLVMValueRef args[1];
53
54 ctx->chip_class = chip_class;
55
56 ctx->context = context;
57 ctx->module = NULL;
58 ctx->builder = NULL;
59
60 ctx->voidt = LLVMVoidTypeInContext(ctx->context);
61 ctx->i1 = LLVMInt1TypeInContext(ctx->context);
62 ctx->i8 = LLVMInt8TypeInContext(ctx->context);
63 ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
64 ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
65 ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
66 ctx->f16 = LLVMHalfTypeInContext(ctx->context);
67 ctx->f32 = LLVMFloatTypeInContext(ctx->context);
68 ctx->f64 = LLVMDoubleTypeInContext(ctx->context);
69 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
70 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
71 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
72
73 ctx->i32_0 = LLVMConstInt(ctx->i32, 0, false);
74 ctx->i32_1 = LLVMConstInt(ctx->i32, 1, false);
75 ctx->f32_0 = LLVMConstReal(ctx->f32, 0.0);
76 ctx->f32_1 = LLVMConstReal(ctx->f32, 1.0);
77
78 ctx->range_md_kind = LLVMGetMDKindIDInContext(ctx->context,
79 "range", 5);
80
81 ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(ctx->context,
82 "invariant.load", 14);
83
84 ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->context, "fpmath", 6);
85
86 args[0] = LLVMConstReal(ctx->f32, 2.5);
87 ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->context, args, 1);
88
89 ctx->uniform_md_kind = LLVMGetMDKindIDInContext(ctx->context,
90 "amdgpu.uniform", 14);
91
92 ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
93 }
94
95 unsigned
96 ac_get_type_size(LLVMTypeRef type)
97 {
98 LLVMTypeKind kind = LLVMGetTypeKind(type);
99
100 switch (kind) {
101 case LLVMIntegerTypeKind:
102 return LLVMGetIntTypeWidth(type) / 8;
103 case LLVMFloatTypeKind:
104 return 4;
105 case LLVMDoubleTypeKind:
106 case LLVMPointerTypeKind:
107 return 8;
108 case LLVMVectorTypeKind:
109 return LLVMGetVectorSize(type) *
110 ac_get_type_size(LLVMGetElementType(type));
111 case LLVMArrayTypeKind:
112 return LLVMGetArrayLength(type) *
113 ac_get_type_size(LLVMGetElementType(type));
114 default:
115 assert(0);
116 return 0;
117 }
118 }
119
120 static LLVMTypeRef to_integer_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
121 {
122 if (t == ctx->f16 || t == ctx->i16)
123 return ctx->i16;
124 else if (t == ctx->f32 || t == ctx->i32)
125 return ctx->i32;
126 else if (t == ctx->f64 || t == ctx->i64)
127 return ctx->i64;
128 else
129 unreachable("Unhandled integer size");
130 }
131
132 LLVMTypeRef
133 ac_to_integer_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
134 {
135 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
136 LLVMTypeRef elem_type = LLVMGetElementType(t);
137 return LLVMVectorType(to_integer_type_scalar(ctx, elem_type),
138 LLVMGetVectorSize(t));
139 }
140 return to_integer_type_scalar(ctx, t);
141 }
142
143 LLVMValueRef
144 ac_to_integer(struct ac_llvm_context *ctx, LLVMValueRef v)
145 {
146 LLVMTypeRef type = LLVMTypeOf(v);
147 return LLVMBuildBitCast(ctx->builder, v, ac_to_integer_type(ctx, type), "");
148 }
149
150 static LLVMTypeRef to_float_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
151 {
152 if (t == ctx->i16 || t == ctx->f16)
153 return ctx->f16;
154 else if (t == ctx->i32 || t == ctx->f32)
155 return ctx->f32;
156 else if (t == ctx->i64 || t == ctx->f64)
157 return ctx->f64;
158 else
159 unreachable("Unhandled float size");
160 }
161
162 LLVMTypeRef
163 ac_to_float_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
164 {
165 if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
166 LLVMTypeRef elem_type = LLVMGetElementType(t);
167 return LLVMVectorType(to_float_type_scalar(ctx, elem_type),
168 LLVMGetVectorSize(t));
169 }
170 return to_float_type_scalar(ctx, t);
171 }
172
173 LLVMValueRef
174 ac_to_float(struct ac_llvm_context *ctx, LLVMValueRef v)
175 {
176 LLVMTypeRef type = LLVMTypeOf(v);
177 return LLVMBuildBitCast(ctx->builder, v, ac_to_float_type(ctx, type), "");
178 }
179
180
181 LLVMValueRef
182 ac_build_intrinsic(struct ac_llvm_context *ctx, const char *name,
183 LLVMTypeRef return_type, LLVMValueRef *params,
184 unsigned param_count, unsigned attrib_mask)
185 {
186 LLVMValueRef function, call;
187 bool set_callsite_attrs = HAVE_LLVM >= 0x0400 &&
188 !(attrib_mask & AC_FUNC_ATTR_LEGACY);
189
190 function = LLVMGetNamedFunction(ctx->module, name);
191 if (!function) {
192 LLVMTypeRef param_types[32], function_type;
193 unsigned i;
194
195 assert(param_count <= 32);
196
197 for (i = 0; i < param_count; ++i) {
198 assert(params[i]);
199 param_types[i] = LLVMTypeOf(params[i]);
200 }
201 function_type =
202 LLVMFunctionType(return_type, param_types, param_count, 0);
203 function = LLVMAddFunction(ctx->module, name, function_type);
204
205 LLVMSetFunctionCallConv(function, LLVMCCallConv);
206 LLVMSetLinkage(function, LLVMExternalLinkage);
207
208 if (!set_callsite_attrs)
209 ac_add_func_attributes(ctx->context, function, attrib_mask);
210 }
211
212 call = LLVMBuildCall(ctx->builder, function, params, param_count, "");
213 if (set_callsite_attrs)
214 ac_add_func_attributes(ctx->context, call, attrib_mask);
215 return call;
216 }
217
218 /**
219 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
220 * intrinsic names).
221 */
222 void ac_build_type_name_for_intr(LLVMTypeRef type, char *buf, unsigned bufsize)
223 {
224 LLVMTypeRef elem_type = type;
225
226 assert(bufsize >= 8);
227
228 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
229 int ret = snprintf(buf, bufsize, "v%u",
230 LLVMGetVectorSize(type));
231 if (ret < 0) {
232 char *type_name = LLVMPrintTypeToString(type);
233 fprintf(stderr, "Error building type name for: %s\n",
234 type_name);
235 return;
236 }
237 elem_type = LLVMGetElementType(type);
238 buf += ret;
239 bufsize -= ret;
240 }
241 switch (LLVMGetTypeKind(elem_type)) {
242 default: break;
243 case LLVMIntegerTypeKind:
244 snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
245 break;
246 case LLVMFloatTypeKind:
247 snprintf(buf, bufsize, "f32");
248 break;
249 case LLVMDoubleTypeKind:
250 snprintf(buf, bufsize, "f64");
251 break;
252 }
253 }
254
255 /* Prevent optimizations (at least of memory accesses) across the current
256 * point in the program by emitting empty inline assembly that is marked as
257 * having side effects.
258 *
259 * Optionally, a value can be passed through the inline assembly to prevent
260 * LLVM from hoisting calls to ReadNone functions.
261 */
262 void
263 ac_build_optimization_barrier(struct ac_llvm_context *ctx,
264 LLVMValueRef *pvgpr)
265 {
266 static int counter = 0;
267
268 LLVMBuilderRef builder = ctx->builder;
269 char code[16];
270
271 snprintf(code, sizeof(code), "; %d", p_atomic_inc_return(&counter));
272
273 if (!pvgpr) {
274 LLVMTypeRef ftype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
275 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "", true, false);
276 LLVMBuildCall(builder, inlineasm, NULL, 0, "");
277 } else {
278 LLVMTypeRef ftype = LLVMFunctionType(ctx->i32, &ctx->i32, 1, false);
279 LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "=v,0", true, false);
280 LLVMValueRef vgpr = *pvgpr;
281 LLVMTypeRef vgpr_type = LLVMTypeOf(vgpr);
282 unsigned vgpr_size = ac_get_type_size(vgpr_type);
283 LLVMValueRef vgpr0;
284
285 assert(vgpr_size % 4 == 0);
286
287 vgpr = LLVMBuildBitCast(builder, vgpr, LLVMVectorType(ctx->i32, vgpr_size / 4), "");
288 vgpr0 = LLVMBuildExtractElement(builder, vgpr, ctx->i32_0, "");
289 vgpr0 = LLVMBuildCall(builder, inlineasm, &vgpr0, 1, "");
290 vgpr = LLVMBuildInsertElement(builder, vgpr, vgpr0, ctx->i32_0, "");
291 vgpr = LLVMBuildBitCast(builder, vgpr, vgpr_type, "");
292
293 *pvgpr = vgpr;
294 }
295 }
296
297 LLVMValueRef
298 ac_build_ballot(struct ac_llvm_context *ctx,
299 LLVMValueRef value)
300 {
301 LLVMValueRef args[3] = {
302 value,
303 ctx->i32_0,
304 LLVMConstInt(ctx->i32, LLVMIntNE, 0)
305 };
306
307 /* We currently have no other way to prevent LLVM from lifting the icmp
308 * calls to a dominating basic block.
309 */
310 ac_build_optimization_barrier(ctx, &args[0]);
311
312 if (LLVMTypeOf(args[0]) != ctx->i32)
313 args[0] = LLVMBuildBitCast(ctx->builder, args[0], ctx->i32, "");
314
315 return ac_build_intrinsic(ctx,
316 "llvm.amdgcn.icmp.i32",
317 ctx->i64, args, 3,
318 AC_FUNC_ATTR_NOUNWIND |
319 AC_FUNC_ATTR_READNONE |
320 AC_FUNC_ATTR_CONVERGENT);
321 }
322
323 LLVMValueRef
324 ac_build_vote_all(struct ac_llvm_context *ctx, LLVMValueRef value)
325 {
326 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
327 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
328 return LLVMBuildICmp(ctx->builder, LLVMIntEQ, vote_set, active_set, "");
329 }
330
331 LLVMValueRef
332 ac_build_vote_any(struct ac_llvm_context *ctx, LLVMValueRef value)
333 {
334 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
335 return LLVMBuildICmp(ctx->builder, LLVMIntNE, vote_set,
336 LLVMConstInt(ctx->i64, 0, 0), "");
337 }
338
339 LLVMValueRef
340 ac_build_vote_eq(struct ac_llvm_context *ctx, LLVMValueRef value)
341 {
342 LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
343 LLVMValueRef vote_set = ac_build_ballot(ctx, value);
344
345 LLVMValueRef all = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
346 vote_set, active_set, "");
347 LLVMValueRef none = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
348 vote_set,
349 LLVMConstInt(ctx->i64, 0, 0), "");
350 return LLVMBuildOr(ctx->builder, all, none, "");
351 }
352
353 LLVMValueRef
354 ac_build_gather_values_extended(struct ac_llvm_context *ctx,
355 LLVMValueRef *values,
356 unsigned value_count,
357 unsigned value_stride,
358 bool load,
359 bool always_vector)
360 {
361 LLVMBuilderRef builder = ctx->builder;
362 LLVMValueRef vec = NULL;
363 unsigned i;
364
365 if (value_count == 1 && !always_vector) {
366 if (load)
367 return LLVMBuildLoad(builder, values[0], "");
368 return values[0];
369 } else if (!value_count)
370 unreachable("value_count is 0");
371
372 for (i = 0; i < value_count; i++) {
373 LLVMValueRef value = values[i * value_stride];
374 if (load)
375 value = LLVMBuildLoad(builder, value, "");
376
377 if (!i)
378 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
379 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
380 vec = LLVMBuildInsertElement(builder, vec, value, index, "");
381 }
382 return vec;
383 }
384
385 LLVMValueRef
386 ac_build_gather_values(struct ac_llvm_context *ctx,
387 LLVMValueRef *values,
388 unsigned value_count)
389 {
390 return ac_build_gather_values_extended(ctx, values, value_count, 1, false, false);
391 }
392
393 LLVMValueRef
394 ac_build_fdiv(struct ac_llvm_context *ctx,
395 LLVMValueRef num,
396 LLVMValueRef den)
397 {
398 LLVMValueRef ret = LLVMBuildFDiv(ctx->builder, num, den, "");
399
400 if (!LLVMIsConstant(ret))
401 LLVMSetMetadata(ret, ctx->fpmath_md_kind, ctx->fpmath_md_2p5_ulp);
402 return ret;
403 }
404
405 /* Coordinates for cube map selection. sc, tc, and ma are as in Table 8.27
406 * of the OpenGL 4.5 (Compatibility Profile) specification, except ma is
407 * already multiplied by two. id is the cube face number.
408 */
409 struct cube_selection_coords {
410 LLVMValueRef stc[2];
411 LLVMValueRef ma;
412 LLVMValueRef id;
413 };
414
415 static void
416 build_cube_intrinsic(struct ac_llvm_context *ctx,
417 LLVMValueRef in[3],
418 struct cube_selection_coords *out)
419 {
420 LLVMTypeRef f32 = ctx->f32;
421
422 out->stc[1] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubetc",
423 f32, in, 3, AC_FUNC_ATTR_READNONE);
424 out->stc[0] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubesc",
425 f32, in, 3, AC_FUNC_ATTR_READNONE);
426 out->ma = ac_build_intrinsic(ctx, "llvm.amdgcn.cubema",
427 f32, in, 3, AC_FUNC_ATTR_READNONE);
428 out->id = ac_build_intrinsic(ctx, "llvm.amdgcn.cubeid",
429 f32, in, 3, AC_FUNC_ATTR_READNONE);
430 }
431
432 /**
433 * Build a manual selection sequence for cube face sc/tc coordinates and
434 * major axis vector (multiplied by 2 for consistency) for the given
435 * vec3 \p coords, for the face implied by \p selcoords.
436 *
437 * For the major axis, we always adjust the sign to be in the direction of
438 * selcoords.ma; i.e., a positive out_ma means that coords is pointed towards
439 * the selcoords major axis.
440 */
441 static void build_cube_select(struct ac_llvm_context *ctx,
442 const struct cube_selection_coords *selcoords,
443 const LLVMValueRef *coords,
444 LLVMValueRef *out_st,
445 LLVMValueRef *out_ma)
446 {
447 LLVMBuilderRef builder = ctx->builder;
448 LLVMTypeRef f32 = LLVMTypeOf(coords[0]);
449 LLVMValueRef is_ma_positive;
450 LLVMValueRef sgn_ma;
451 LLVMValueRef is_ma_z, is_not_ma_z;
452 LLVMValueRef is_ma_y;
453 LLVMValueRef is_ma_x;
454 LLVMValueRef sgn;
455 LLVMValueRef tmp;
456
457 is_ma_positive = LLVMBuildFCmp(builder, LLVMRealUGE,
458 selcoords->ma, LLVMConstReal(f32, 0.0), "");
459 sgn_ma = LLVMBuildSelect(builder, is_ma_positive,
460 LLVMConstReal(f32, 1.0), LLVMConstReal(f32, -1.0), "");
461
462 is_ma_z = LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 4.0), "");
463 is_not_ma_z = LLVMBuildNot(builder, is_ma_z, "");
464 is_ma_y = LLVMBuildAnd(builder, is_not_ma_z,
465 LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 2.0), ""), "");
466 is_ma_x = LLVMBuildAnd(builder, is_not_ma_z, LLVMBuildNot(builder, is_ma_y, ""), "");
467
468 /* Select sc */
469 tmp = LLVMBuildSelect(builder, is_ma_x, coords[2], coords[0], "");
470 sgn = LLVMBuildSelect(builder, is_ma_y, LLVMConstReal(f32, 1.0),
471 LLVMBuildSelect(builder, is_ma_z, sgn_ma,
472 LLVMBuildFNeg(builder, sgn_ma, ""), ""), "");
473 out_st[0] = LLVMBuildFMul(builder, tmp, sgn, "");
474
475 /* Select tc */
476 tmp = LLVMBuildSelect(builder, is_ma_y, coords[2], coords[1], "");
477 sgn = LLVMBuildSelect(builder, is_ma_y, sgn_ma,
478 LLVMConstReal(f32, -1.0), "");
479 out_st[1] = LLVMBuildFMul(builder, tmp, sgn, "");
480
481 /* Select ma */
482 tmp = LLVMBuildSelect(builder, is_ma_z, coords[2],
483 LLVMBuildSelect(builder, is_ma_y, coords[1], coords[0], ""), "");
484 tmp = ac_build_intrinsic(ctx, "llvm.fabs.f32",
485 ctx->f32, &tmp, 1, AC_FUNC_ATTR_READNONE);
486 *out_ma = LLVMBuildFMul(builder, tmp, LLVMConstReal(f32, 2.0), "");
487 }
488
489 void
490 ac_prepare_cube_coords(struct ac_llvm_context *ctx,
491 bool is_deriv, bool is_array, bool is_lod,
492 LLVMValueRef *coords_arg,
493 LLVMValueRef *derivs_arg)
494 {
495
496 LLVMBuilderRef builder = ctx->builder;
497 struct cube_selection_coords selcoords;
498 LLVMValueRef coords[3];
499 LLVMValueRef invma;
500
501 if (is_array && !is_lod) {
502 LLVMValueRef tmp = coords_arg[3];
503 tmp = ac_build_intrinsic(ctx, "llvm.rint.f32", ctx->f32, &tmp, 1, 0);
504
505 /* Section 8.9 (Texture Functions) of the GLSL 4.50 spec says:
506 *
507 * "For Array forms, the array layer used will be
508 *
509 * max(0, min(d−1, floor(layer+0.5)))
510 *
511 * where d is the depth of the texture array and layer
512 * comes from the component indicated in the tables below.
513 * Workaroudn for an issue where the layer is taken from a
514 * helper invocation which happens to fall on a different
515 * layer due to extrapolation."
516 *
517 * VI and earlier attempt to implement this in hardware by
518 * clamping the value of coords[2] = (8 * layer) + face.
519 * Unfortunately, this means that the we end up with the wrong
520 * face when clamping occurs.
521 *
522 * Clamp the layer earlier to work around the issue.
523 */
524 if (ctx->chip_class <= VI) {
525 LLVMValueRef ge0;
526 ge0 = LLVMBuildFCmp(builder, LLVMRealOGE, tmp, ctx->f32_0, "");
527 tmp = LLVMBuildSelect(builder, ge0, tmp, ctx->f32_0, "");
528 }
529
530 coords_arg[3] = tmp;
531 }
532
533 build_cube_intrinsic(ctx, coords_arg, &selcoords);
534
535 invma = ac_build_intrinsic(ctx, "llvm.fabs.f32",
536 ctx->f32, &selcoords.ma, 1, AC_FUNC_ATTR_READNONE);
537 invma = ac_build_fdiv(ctx, LLVMConstReal(ctx->f32, 1.0), invma);
538
539 for (int i = 0; i < 2; ++i)
540 coords[i] = LLVMBuildFMul(builder, selcoords.stc[i], invma, "");
541
542 coords[2] = selcoords.id;
543
544 if (is_deriv && derivs_arg) {
545 LLVMValueRef derivs[4];
546 int axis;
547
548 /* Convert cube derivatives to 2D derivatives. */
549 for (axis = 0; axis < 2; axis++) {
550 LLVMValueRef deriv_st[2];
551 LLVMValueRef deriv_ma;
552
553 /* Transform the derivative alongside the texture
554 * coordinate. Mathematically, the correct formula is
555 * as follows. Assume we're projecting onto the +Z face
556 * and denote by dx/dh the derivative of the (original)
557 * X texture coordinate with respect to horizontal
558 * window coordinates. The projection onto the +Z face
559 * plane is:
560 *
561 * f(x,z) = x/z
562 *
563 * Then df/dh = df/dx * dx/dh + df/dz * dz/dh
564 * = 1/z * dx/dh - x/z * 1/z * dz/dh.
565 *
566 * This motivatives the implementation below.
567 *
568 * Whether this actually gives the expected results for
569 * apps that might feed in derivatives obtained via
570 * finite differences is anyone's guess. The OpenGL spec
571 * seems awfully quiet about how textureGrad for cube
572 * maps should be handled.
573 */
574 build_cube_select(ctx, &selcoords, &derivs_arg[axis * 3],
575 deriv_st, &deriv_ma);
576
577 deriv_ma = LLVMBuildFMul(builder, deriv_ma, invma, "");
578
579 for (int i = 0; i < 2; ++i)
580 derivs[axis * 2 + i] =
581 LLVMBuildFSub(builder,
582 LLVMBuildFMul(builder, deriv_st[i], invma, ""),
583 LLVMBuildFMul(builder, deriv_ma, coords[i], ""), "");
584 }
585
586 memcpy(derivs_arg, derivs, sizeof(derivs));
587 }
588
589 /* Shift the texture coordinate. This must be applied after the
590 * derivative calculation.
591 */
592 for (int i = 0; i < 2; ++i)
593 coords[i] = LLVMBuildFAdd(builder, coords[i], LLVMConstReal(ctx->f32, 1.5), "");
594
595 if (is_array) {
596 /* for cube arrays coord.z = coord.w(array_index) * 8 + face */
597 /* coords_arg.w component - array_index for cube arrays */
598 LLVMValueRef tmp = LLVMBuildFMul(ctx->builder, coords_arg[3], LLVMConstReal(ctx->f32, 8.0), "");
599 coords[2] = LLVMBuildFAdd(ctx->builder, tmp, coords[2], "");
600 }
601
602 memcpy(coords_arg, coords, sizeof(coords));
603 }
604
605
606 LLVMValueRef
607 ac_build_fs_interp(struct ac_llvm_context *ctx,
608 LLVMValueRef llvm_chan,
609 LLVMValueRef attr_number,
610 LLVMValueRef params,
611 LLVMValueRef i,
612 LLVMValueRef j)
613 {
614 LLVMValueRef args[5];
615 LLVMValueRef p1;
616
617 if (HAVE_LLVM < 0x0400) {
618 LLVMValueRef ij[2];
619 ij[0] = LLVMBuildBitCast(ctx->builder, i, ctx->i32, "");
620 ij[1] = LLVMBuildBitCast(ctx->builder, j, ctx->i32, "");
621
622 args[0] = llvm_chan;
623 args[1] = attr_number;
624 args[2] = params;
625 args[3] = ac_build_gather_values(ctx, ij, 2);
626 return ac_build_intrinsic(ctx, "llvm.SI.fs.interp",
627 ctx->f32, args, 4,
628 AC_FUNC_ATTR_READNONE);
629 }
630
631 args[0] = i;
632 args[1] = llvm_chan;
633 args[2] = attr_number;
634 args[3] = params;
635
636 p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1",
637 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
638
639 args[0] = p1;
640 args[1] = j;
641 args[2] = llvm_chan;
642 args[3] = attr_number;
643 args[4] = params;
644
645 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2",
646 ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
647 }
648
649 LLVMValueRef
650 ac_build_fs_interp_mov(struct ac_llvm_context *ctx,
651 LLVMValueRef parameter,
652 LLVMValueRef llvm_chan,
653 LLVMValueRef attr_number,
654 LLVMValueRef params)
655 {
656 LLVMValueRef args[4];
657 if (HAVE_LLVM < 0x0400) {
658 args[0] = llvm_chan;
659 args[1] = attr_number;
660 args[2] = params;
661
662 return ac_build_intrinsic(ctx,
663 "llvm.SI.fs.constant",
664 ctx->f32, args, 3,
665 AC_FUNC_ATTR_READNONE);
666 }
667
668 args[0] = parameter;
669 args[1] = llvm_chan;
670 args[2] = attr_number;
671 args[3] = params;
672
673 return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.mov",
674 ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
675 }
676
677 LLVMValueRef
678 ac_build_gep0(struct ac_llvm_context *ctx,
679 LLVMValueRef base_ptr,
680 LLVMValueRef index)
681 {
682 LLVMValueRef indices[2] = {
683 LLVMConstInt(ctx->i32, 0, 0),
684 index,
685 };
686 return LLVMBuildGEP(ctx->builder, base_ptr,
687 indices, 2, "");
688 }
689
690 void
691 ac_build_indexed_store(struct ac_llvm_context *ctx,
692 LLVMValueRef base_ptr, LLVMValueRef index,
693 LLVMValueRef value)
694 {
695 LLVMBuildStore(ctx->builder, value,
696 ac_build_gep0(ctx, base_ptr, index));
697 }
698
699 /**
700 * Build an LLVM bytecode indexed load using LLVMBuildGEP + LLVMBuildLoad.
701 * It's equivalent to doing a load from &base_ptr[index].
702 *
703 * \param base_ptr Where the array starts.
704 * \param index The element index into the array.
705 * \param uniform Whether the base_ptr and index can be assumed to be
706 * dynamically uniform
707 */
708 LLVMValueRef
709 ac_build_indexed_load(struct ac_llvm_context *ctx,
710 LLVMValueRef base_ptr, LLVMValueRef index,
711 bool uniform)
712 {
713 LLVMValueRef pointer;
714
715 pointer = ac_build_gep0(ctx, base_ptr, index);
716 if (uniform)
717 LLVMSetMetadata(pointer, ctx->uniform_md_kind, ctx->empty_md);
718 return LLVMBuildLoad(ctx->builder, pointer, "");
719 }
720
721 /**
722 * Do a load from &base_ptr[index], but also add a flag that it's loading
723 * a constant from a dynamically uniform index.
724 */
725 LLVMValueRef
726 ac_build_indexed_load_const(struct ac_llvm_context *ctx,
727 LLVMValueRef base_ptr, LLVMValueRef index)
728 {
729 LLVMValueRef result = ac_build_indexed_load(ctx, base_ptr, index, true);
730 LLVMSetMetadata(result, ctx->invariant_load_md_kind, ctx->empty_md);
731 return result;
732 }
733
734 /* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
735 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
736 * or v4i32 (num_channels=3,4).
737 */
738 void
739 ac_build_buffer_store_dword(struct ac_llvm_context *ctx,
740 LLVMValueRef rsrc,
741 LLVMValueRef vdata,
742 unsigned num_channels,
743 LLVMValueRef voffset,
744 LLVMValueRef soffset,
745 unsigned inst_offset,
746 bool glc,
747 bool slc,
748 bool writeonly_memory,
749 bool has_add_tid)
750 {
751 /* TODO: Fix stores with ADD_TID and remove the "has_add_tid" flag. */
752 if (!has_add_tid) {
753 /* Split 3 channel stores, becase LLVM doesn't support 3-channel
754 * intrinsics. */
755 if (num_channels == 3) {
756 LLVMValueRef v[3], v01;
757
758 for (int i = 0; i < 3; i++) {
759 v[i] = LLVMBuildExtractElement(ctx->builder, vdata,
760 LLVMConstInt(ctx->i32, i, 0), "");
761 }
762 v01 = ac_build_gather_values(ctx, v, 2);
763
764 ac_build_buffer_store_dword(ctx, rsrc, v01, 2, voffset,
765 soffset, inst_offset, glc, slc,
766 writeonly_memory, has_add_tid);
767 ac_build_buffer_store_dword(ctx, rsrc, v[2], 1, voffset,
768 soffset, inst_offset + 8,
769 glc, slc,
770 writeonly_memory, has_add_tid);
771 return;
772 }
773
774 unsigned func = CLAMP(num_channels, 1, 3) - 1;
775 static const char *types[] = {"f32", "v2f32", "v4f32"};
776 char name[256];
777 LLVMValueRef offset = soffset;
778
779 if (inst_offset)
780 offset = LLVMBuildAdd(ctx->builder, offset,
781 LLVMConstInt(ctx->i32, inst_offset, 0), "");
782 if (voffset)
783 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
784
785 LLVMValueRef args[] = {
786 ac_to_float(ctx, vdata),
787 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
788 LLVMConstInt(ctx->i32, 0, 0),
789 offset,
790 LLVMConstInt(ctx->i1, glc, 0),
791 LLVMConstInt(ctx->i1, slc, 0),
792 };
793
794 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.store.%s",
795 types[func]);
796
797 ac_build_intrinsic(ctx, name, ctx->voidt,
798 args, ARRAY_SIZE(args),
799 writeonly_memory ?
800 AC_FUNC_ATTR_INACCESSIBLE_MEM_ONLY :
801 AC_FUNC_ATTR_WRITEONLY);
802 return;
803 }
804
805 static unsigned dfmt[] = {
806 V_008F0C_BUF_DATA_FORMAT_32,
807 V_008F0C_BUF_DATA_FORMAT_32_32,
808 V_008F0C_BUF_DATA_FORMAT_32_32_32,
809 V_008F0C_BUF_DATA_FORMAT_32_32_32_32
810 };
811 assert(num_channels >= 1 && num_channels <= 4);
812
813 LLVMValueRef args[] = {
814 rsrc,
815 vdata,
816 LLVMConstInt(ctx->i32, num_channels, 0),
817 voffset ? voffset : LLVMGetUndef(ctx->i32),
818 soffset,
819 LLVMConstInt(ctx->i32, inst_offset, 0),
820 LLVMConstInt(ctx->i32, dfmt[num_channels - 1], 0),
821 LLVMConstInt(ctx->i32, V_008F0C_BUF_NUM_FORMAT_UINT, 0),
822 LLVMConstInt(ctx->i32, voffset != NULL, 0),
823 LLVMConstInt(ctx->i32, 0, 0), /* idxen */
824 LLVMConstInt(ctx->i32, glc, 0),
825 LLVMConstInt(ctx->i32, slc, 0),
826 LLVMConstInt(ctx->i32, 0, 0), /* tfe*/
827 };
828
829 /* The instruction offset field has 12 bits */
830 assert(voffset || inst_offset < (1 << 12));
831
832 /* The intrinsic is overloaded, we need to add a type suffix for overloading to work. */
833 unsigned func = CLAMP(num_channels, 1, 3) - 1;
834 const char *types[] = {"i32", "v2i32", "v4i32"};
835 char name[256];
836 snprintf(name, sizeof(name), "llvm.SI.tbuffer.store.%s", types[func]);
837
838 ac_build_intrinsic(ctx, name, ctx->voidt,
839 args, ARRAY_SIZE(args),
840 AC_FUNC_ATTR_LEGACY);
841 }
842
843 LLVMValueRef
844 ac_build_buffer_load(struct ac_llvm_context *ctx,
845 LLVMValueRef rsrc,
846 int num_channels,
847 LLVMValueRef vindex,
848 LLVMValueRef voffset,
849 LLVMValueRef soffset,
850 unsigned inst_offset,
851 unsigned glc,
852 unsigned slc,
853 bool can_speculate,
854 bool allow_smem)
855 {
856 LLVMValueRef offset = LLVMConstInt(ctx->i32, inst_offset, 0);
857 if (voffset)
858 offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
859 if (soffset)
860 offset = LLVMBuildAdd(ctx->builder, offset, soffset, "");
861
862 /* TODO: VI and later generations can use SMEM with GLC=1.*/
863 if (allow_smem && !glc && !slc) {
864 assert(vindex == NULL);
865
866 LLVMValueRef result[4];
867
868 for (int i = 0; i < num_channels; i++) {
869 if (i) {
870 offset = LLVMBuildAdd(ctx->builder, offset,
871 LLVMConstInt(ctx->i32, 4, 0), "");
872 }
873 LLVMValueRef args[2] = {rsrc, offset};
874 result[i] = ac_build_intrinsic(ctx, "llvm.SI.load.const.v4i32",
875 ctx->f32, args, 2,
876 AC_FUNC_ATTR_READNONE |
877 AC_FUNC_ATTR_LEGACY);
878 }
879 if (num_channels == 1)
880 return result[0];
881
882 if (num_channels == 3)
883 result[num_channels++] = LLVMGetUndef(ctx->f32);
884 return ac_build_gather_values(ctx, result, num_channels);
885 }
886
887 unsigned func = CLAMP(num_channels, 1, 3) - 1;
888
889 LLVMValueRef args[] = {
890 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
891 vindex ? vindex : LLVMConstInt(ctx->i32, 0, 0),
892 offset,
893 LLVMConstInt(ctx->i1, glc, 0),
894 LLVMConstInt(ctx->i1, slc, 0)
895 };
896
897 LLVMTypeRef types[] = {ctx->f32, LLVMVectorType(ctx->f32, 2),
898 ctx->v4f32};
899 const char *type_names[] = {"f32", "v2f32", "v4f32"};
900 char name[256];
901
902 snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.%s",
903 type_names[func]);
904
905 return ac_build_intrinsic(ctx, name, types[func], args,
906 ARRAY_SIZE(args),
907 /* READNONE means writes can't affect it, while
908 * READONLY means that writes can affect it. */
909 can_speculate && HAVE_LLVM >= 0x0400 ?
910 AC_FUNC_ATTR_READNONE :
911 AC_FUNC_ATTR_READONLY);
912 }
913
914 LLVMValueRef ac_build_buffer_load_format(struct ac_llvm_context *ctx,
915 LLVMValueRef rsrc,
916 LLVMValueRef vindex,
917 LLVMValueRef voffset,
918 bool can_speculate)
919 {
920 LLVMValueRef args [] = {
921 LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
922 vindex,
923 voffset,
924 LLVMConstInt(ctx->i1, 0, 0), /* glc */
925 LLVMConstInt(ctx->i1, 0, 0), /* slc */
926 };
927
928 return ac_build_intrinsic(ctx,
929 "llvm.amdgcn.buffer.load.format.v4f32",
930 ctx->v4f32, args, ARRAY_SIZE(args),
931 /* READNONE means writes can't affect it, while
932 * READONLY means that writes can affect it. */
933 can_speculate && HAVE_LLVM >= 0x0400 ?
934 AC_FUNC_ATTR_READNONE :
935 AC_FUNC_ATTR_READONLY);
936 }
937
938 /**
939 * Set range metadata on an instruction. This can only be used on load and
940 * call instructions. If you know an instruction can only produce the values
941 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
942 * \p lo is the minimum value inclusive.
943 * \p hi is the maximum value exclusive.
944 */
945 static void set_range_metadata(struct ac_llvm_context *ctx,
946 LLVMValueRef value, unsigned lo, unsigned hi)
947 {
948 LLVMValueRef range_md, md_args[2];
949 LLVMTypeRef type = LLVMTypeOf(value);
950 LLVMContextRef context = LLVMGetTypeContext(type);
951
952 md_args[0] = LLVMConstInt(type, lo, false);
953 md_args[1] = LLVMConstInt(type, hi, false);
954 range_md = LLVMMDNodeInContext(context, md_args, 2);
955 LLVMSetMetadata(value, ctx->range_md_kind, range_md);
956 }
957
958 LLVMValueRef
959 ac_get_thread_id(struct ac_llvm_context *ctx)
960 {
961 LLVMValueRef tid;
962
963 LLVMValueRef tid_args[2];
964 tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
965 tid_args[1] = LLVMConstInt(ctx->i32, 0, false);
966 tid_args[1] = ac_build_intrinsic(ctx,
967 "llvm.amdgcn.mbcnt.lo", ctx->i32,
968 tid_args, 2, AC_FUNC_ATTR_READNONE);
969
970 tid = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi",
971 ctx->i32, tid_args,
972 2, AC_FUNC_ATTR_READNONE);
973 set_range_metadata(ctx, tid, 0, 64);
974 return tid;
975 }
976
977 /*
978 * SI implements derivatives using the local data store (LDS)
979 * All writes to the LDS happen in all executing threads at
980 * the same time. TID is the Thread ID for the current
981 * thread and is a value between 0 and 63, representing
982 * the thread's position in the wavefront.
983 *
984 * For the pixel shader threads are grouped into quads of four pixels.
985 * The TIDs of the pixels of a quad are:
986 *
987 * +------+------+
988 * |4n + 0|4n + 1|
989 * +------+------+
990 * |4n + 2|4n + 3|
991 * +------+------+
992 *
993 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
994 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
995 * the current pixel's column, and masking with 0xfffffffe yields the TID
996 * of the left pixel of the current pixel's row.
997 *
998 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
999 * adding 2 yields the TID of the pixel below the top pixel.
1000 */
1001 LLVMValueRef
1002 ac_build_ddxy(struct ac_llvm_context *ctx,
1003 uint32_t mask,
1004 int idx,
1005 LLVMValueRef val)
1006 {
1007 LLVMValueRef tl, trbl, args[2];
1008 LLVMValueRef result;
1009
1010 if (ctx->chip_class >= VI) {
1011 LLVMValueRef thread_id, tl_tid, trbl_tid;
1012 thread_id = ac_get_thread_id(ctx);
1013
1014 tl_tid = LLVMBuildAnd(ctx->builder, thread_id,
1015 LLVMConstInt(ctx->i32, mask, false), "");
1016
1017 trbl_tid = LLVMBuildAdd(ctx->builder, tl_tid,
1018 LLVMConstInt(ctx->i32, idx, false), "");
1019
1020 args[0] = LLVMBuildMul(ctx->builder, tl_tid,
1021 LLVMConstInt(ctx->i32, 4, false), "");
1022 args[1] = val;
1023 tl = ac_build_intrinsic(ctx,
1024 "llvm.amdgcn.ds.bpermute", ctx->i32,
1025 args, 2,
1026 AC_FUNC_ATTR_READNONE |
1027 AC_FUNC_ATTR_CONVERGENT);
1028
1029 args[0] = LLVMBuildMul(ctx->builder, trbl_tid,
1030 LLVMConstInt(ctx->i32, 4, false), "");
1031 trbl = ac_build_intrinsic(ctx,
1032 "llvm.amdgcn.ds.bpermute", ctx->i32,
1033 args, 2,
1034 AC_FUNC_ATTR_READNONE |
1035 AC_FUNC_ATTR_CONVERGENT);
1036 } else {
1037 uint32_t masks[2];
1038
1039 switch (mask) {
1040 case AC_TID_MASK_TOP_LEFT:
1041 masks[0] = 0x8000;
1042 if (idx == 1)
1043 masks[1] = 0x8055;
1044 else
1045 masks[1] = 0x80aa;
1046
1047 break;
1048 case AC_TID_MASK_TOP:
1049 masks[0] = 0x8044;
1050 masks[1] = 0x80ee;
1051 break;
1052 case AC_TID_MASK_LEFT:
1053 masks[0] = 0x80a0;
1054 masks[1] = 0x80f5;
1055 break;
1056 }
1057
1058 args[0] = val;
1059 args[1] = LLVMConstInt(ctx->i32, masks[0], false);
1060
1061 tl = ac_build_intrinsic(ctx,
1062 "llvm.amdgcn.ds.swizzle", ctx->i32,
1063 args, 2,
1064 AC_FUNC_ATTR_READNONE |
1065 AC_FUNC_ATTR_CONVERGENT);
1066
1067 args[1] = LLVMConstInt(ctx->i32, masks[1], false);
1068 trbl = ac_build_intrinsic(ctx,
1069 "llvm.amdgcn.ds.swizzle", ctx->i32,
1070 args, 2,
1071 AC_FUNC_ATTR_READNONE |
1072 AC_FUNC_ATTR_CONVERGENT);
1073 }
1074
1075 tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
1076 trbl = LLVMBuildBitCast(ctx->builder, trbl, ctx->f32, "");
1077 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
1078 return result;
1079 }
1080
1081 void
1082 ac_build_sendmsg(struct ac_llvm_context *ctx,
1083 uint32_t msg,
1084 LLVMValueRef wave_id)
1085 {
1086 LLVMValueRef args[2];
1087 const char *intr_name = (HAVE_LLVM < 0x0400) ? "llvm.SI.sendmsg" : "llvm.amdgcn.s.sendmsg";
1088 args[0] = LLVMConstInt(ctx->i32, msg, false);
1089 args[1] = wave_id;
1090 ac_build_intrinsic(ctx, intr_name, ctx->voidt, args, 2, 0);
1091 }
1092
1093 LLVMValueRef
1094 ac_build_imsb(struct ac_llvm_context *ctx,
1095 LLVMValueRef arg,
1096 LLVMTypeRef dst_type)
1097 {
1098 const char *intr_name = (HAVE_LLVM < 0x0400) ? "llvm.AMDGPU.flbit.i32" :
1099 "llvm.amdgcn.sffbh.i32";
1100 LLVMValueRef msb = ac_build_intrinsic(ctx, intr_name,
1101 dst_type, &arg, 1,
1102 AC_FUNC_ATTR_READNONE);
1103
1104 /* The HW returns the last bit index from MSB, but NIR/TGSI wants
1105 * the index from LSB. Invert it by doing "31 - msb". */
1106 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
1107 msb, "");
1108
1109 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
1110 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
1111 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1112 arg, LLVMConstInt(ctx->i32, 0, 0), ""),
1113 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
1114 arg, all_ones, ""), "");
1115
1116 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
1117 }
1118
1119 LLVMValueRef
1120 ac_build_umsb(struct ac_llvm_context *ctx,
1121 LLVMValueRef arg,
1122 LLVMTypeRef dst_type)
1123 {
1124 LLVMValueRef args[2] = {
1125 arg,
1126 LLVMConstInt(ctx->i1, 1, 0),
1127 };
1128 LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.ctlz.i32",
1129 dst_type, args, ARRAY_SIZE(args),
1130 AC_FUNC_ATTR_READNONE);
1131
1132 /* The HW returns the last bit index from MSB, but TGSI/NIR wants
1133 * the index from LSB. Invert it by doing "31 - msb". */
1134 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
1135 msb, "");
1136
1137 /* check for zero */
1138 return LLVMBuildSelect(ctx->builder,
1139 LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg,
1140 LLVMConstInt(ctx->i32, 0, 0), ""),
1141 LLVMConstInt(ctx->i32, -1, true), msb, "");
1142 }
1143
1144 LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
1145 LLVMValueRef b)
1146 {
1147 LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
1148 return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
1149 }
1150
1151 LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
1152 {
1153 if (HAVE_LLVM >= 0x0500) {
1154 LLVMValueRef max[2] = {
1155 value,
1156 LLVMConstReal(ctx->f32, 0),
1157 };
1158 LLVMValueRef min[2] = {
1159 LLVMConstReal(ctx->f32, 1),
1160 };
1161
1162 min[1] = ac_build_intrinsic(ctx, "llvm.maxnum.f32",
1163 ctx->f32, max, 2,
1164 AC_FUNC_ATTR_READNONE);
1165 return ac_build_intrinsic(ctx, "llvm.minnum.f32",
1166 ctx->f32, min, 2,
1167 AC_FUNC_ATTR_READNONE);
1168 }
1169
1170 LLVMValueRef args[3] = {
1171 value,
1172 LLVMConstReal(ctx->f32, 0),
1173 LLVMConstReal(ctx->f32, 1),
1174 };
1175
1176 return ac_build_intrinsic(ctx, "llvm.AMDGPU.clamp.", ctx->f32, args, 3,
1177 AC_FUNC_ATTR_READNONE |
1178 AC_FUNC_ATTR_LEGACY);
1179 }
1180
1181 void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
1182 {
1183 LLVMValueRef args[9];
1184
1185 if (HAVE_LLVM >= 0x0500) {
1186 args[0] = LLVMConstInt(ctx->i32, a->target, 0);
1187 args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
1188
1189 if (a->compr) {
1190 LLVMTypeRef i16 = LLVMInt16TypeInContext(ctx->context);
1191 LLVMTypeRef v2i16 = LLVMVectorType(i16, 2);
1192
1193 args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
1194 v2i16, "");
1195 args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
1196 v2i16, "");
1197 args[4] = LLVMConstInt(ctx->i1, a->done, 0);
1198 args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1199
1200 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
1201 ctx->voidt, args, 6, 0);
1202 } else {
1203 args[2] = a->out[0];
1204 args[3] = a->out[1];
1205 args[4] = a->out[2];
1206 args[5] = a->out[3];
1207 args[6] = LLVMConstInt(ctx->i1, a->done, 0);
1208 args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);
1209
1210 ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
1211 ctx->voidt, args, 8, 0);
1212 }
1213 return;
1214 }
1215
1216 args[0] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);
1217 args[1] = LLVMConstInt(ctx->i32, a->valid_mask, 0);
1218 args[2] = LLVMConstInt(ctx->i32, a->done, 0);
1219 args[3] = LLVMConstInt(ctx->i32, a->target, 0);
1220 args[4] = LLVMConstInt(ctx->i32, a->compr, 0);
1221 memcpy(args + 5, a->out, sizeof(a->out[0]) * 4);
1222
1223 ac_build_intrinsic(ctx, "llvm.SI.export", ctx->voidt, args, 9,
1224 AC_FUNC_ATTR_LEGACY);
1225 }
1226
1227 LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
1228 struct ac_image_args *a)
1229 {
1230 LLVMTypeRef dst_type;
1231 LLVMValueRef args[11];
1232 unsigned num_args = 0;
1233 const char *name;
1234 char intr_name[128], type[64];
1235
1236 if (HAVE_LLVM >= 0x0400) {
1237 bool sample = a->opcode == ac_image_sample ||
1238 a->opcode == ac_image_gather4 ||
1239 a->opcode == ac_image_get_lod;
1240
1241 if (sample)
1242 args[num_args++] = ac_to_float(ctx, a->addr);
1243 else
1244 args[num_args++] = a->addr;
1245
1246 args[num_args++] = a->resource;
1247 if (sample)
1248 args[num_args++] = a->sampler;
1249 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, 0);
1250 if (sample)
1251 args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, 0);
1252 args[num_args++] = LLVMConstInt(ctx->i1, 0, 0); /* glc */
1253 args[num_args++] = LLVMConstInt(ctx->i1, 0, 0); /* slc */
1254 args[num_args++] = LLVMConstInt(ctx->i1, 0, 0); /* lwe */
1255 args[num_args++] = LLVMConstInt(ctx->i1, a->da, 0);
1256
1257 switch (a->opcode) {
1258 case ac_image_sample:
1259 name = "llvm.amdgcn.image.sample";
1260 break;
1261 case ac_image_gather4:
1262 name = "llvm.amdgcn.image.gather4";
1263 break;
1264 case ac_image_load:
1265 name = "llvm.amdgcn.image.load";
1266 break;
1267 case ac_image_load_mip:
1268 name = "llvm.amdgcn.image.load.mip";
1269 break;
1270 case ac_image_get_lod:
1271 name = "llvm.amdgcn.image.getlod";
1272 break;
1273 case ac_image_get_resinfo:
1274 name = "llvm.amdgcn.image.getresinfo";
1275 break;
1276 default:
1277 unreachable("invalid image opcode");
1278 }
1279
1280 ac_build_type_name_for_intr(LLVMTypeOf(args[0]), type,
1281 sizeof(type));
1282
1283 snprintf(intr_name, sizeof(intr_name), "%s%s%s%s.v4f32.%s.v8i32",
1284 name,
1285 a->compare ? ".c" : "",
1286 a->bias ? ".b" :
1287 a->lod ? ".l" :
1288 a->deriv ? ".d" :
1289 a->level_zero ? ".lz" : "",
1290 a->offset ? ".o" : "",
1291 type);
1292
1293 LLVMValueRef result =
1294 ac_build_intrinsic(ctx, intr_name,
1295 ctx->v4f32, args, num_args,
1296 AC_FUNC_ATTR_READNONE);
1297 if (!sample) {
1298 result = LLVMBuildBitCast(ctx->builder, result,
1299 ctx->v4i32, "");
1300 }
1301 return result;
1302 }
1303
1304 args[num_args++] = a->addr;
1305 args[num_args++] = a->resource;
1306
1307 if (a->opcode == ac_image_load ||
1308 a->opcode == ac_image_load_mip ||
1309 a->opcode == ac_image_get_resinfo) {
1310 dst_type = ctx->v4i32;
1311 } else {
1312 dst_type = ctx->v4f32;
1313 args[num_args++] = a->sampler;
1314 }
1315
1316 args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, 0);
1317 args[num_args++] = LLVMConstInt(ctx->i32, a->unorm, 0);
1318 args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* r128 */
1319 args[num_args++] = LLVMConstInt(ctx->i32, a->da, 0);
1320 args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* glc */
1321 args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* slc */
1322 args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* tfe */
1323 args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* lwe */
1324
1325 switch (a->opcode) {
1326 case ac_image_sample:
1327 name = "llvm.SI.image.sample";
1328 break;
1329 case ac_image_gather4:
1330 name = "llvm.SI.gather4";
1331 break;
1332 case ac_image_load:
1333 name = "llvm.SI.image.load";
1334 break;
1335 case ac_image_load_mip:
1336 name = "llvm.SI.image.load.mip";
1337 break;
1338 case ac_image_get_lod:
1339 name = "llvm.SI.getlod";
1340 break;
1341 case ac_image_get_resinfo:
1342 name = "llvm.SI.getresinfo";
1343 break;
1344 }
1345
1346 ac_build_type_name_for_intr(LLVMTypeOf(a->addr), type, sizeof(type));
1347 snprintf(intr_name, sizeof(intr_name), "%s%s%s%s.%s",
1348 name,
1349 a->compare ? ".c" : "",
1350 a->bias ? ".b" :
1351 a->lod ? ".l" :
1352 a->deriv ? ".d" :
1353 a->level_zero ? ".lz" : "",
1354 a->offset ? ".o" : "",
1355 type);
1356
1357 return ac_build_intrinsic(ctx, intr_name,
1358 dst_type, args, num_args,
1359 AC_FUNC_ATTR_READNONE |
1360 AC_FUNC_ATTR_LEGACY);
1361 }
1362
1363 LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
1364 LLVMValueRef args[2])
1365 {
1366 if (HAVE_LLVM >= 0x0500) {
1367 LLVMTypeRef v2f16 =
1368 LLVMVectorType(LLVMHalfTypeInContext(ctx->context), 2);
1369 LLVMValueRef res =
1370 ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz",
1371 v2f16, args, 2,
1372 AC_FUNC_ATTR_READNONE);
1373 return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
1374 }
1375
1376 return ac_build_intrinsic(ctx, "llvm.SI.packf16", ctx->i32, args, 2,
1377 AC_FUNC_ATTR_READNONE |
1378 AC_FUNC_ATTR_LEGACY);
1379 }
1380
1381 /**
1382 * KILL, AKA discard in GLSL.
1383 *
1384 * \param value kill if value < 0.0 or value == NULL.
1385 */
1386 void ac_build_kill(struct ac_llvm_context *ctx, LLVMValueRef value)
1387 {
1388 if (value) {
1389 ac_build_intrinsic(ctx, "llvm.AMDGPU.kill", ctx->voidt,
1390 &value, 1, AC_FUNC_ATTR_LEGACY);
1391 } else {
1392 ac_build_intrinsic(ctx, "llvm.AMDGPU.kilp", ctx->voidt,
1393 NULL, 0, AC_FUNC_ATTR_LEGACY);
1394 }
1395 }
1396
1397 LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
1398 LLVMValueRef offset, LLVMValueRef width,
1399 bool is_signed)
1400 {
1401 LLVMValueRef args[] = {
1402 input,
1403 offset,
1404 width,
1405 };
1406
1407 if (HAVE_LLVM >= 0x0500) {
1408 return ac_build_intrinsic(ctx,
1409 is_signed ? "llvm.amdgcn.sbfe.i32" :
1410 "llvm.amdgcn.ubfe.i32",
1411 ctx->i32, args, 3,
1412 AC_FUNC_ATTR_READNONE);
1413 }
1414
1415 return ac_build_intrinsic(ctx,
1416 is_signed ? "llvm.AMDGPU.bfe.i32" :
1417 "llvm.AMDGPU.bfe.u32",
1418 ctx->i32, args, 3,
1419 AC_FUNC_ATTR_READNONE |
1420 AC_FUNC_ATTR_LEGACY);
1421 }
1422
1423 void ac_get_image_intr_name(const char *base_name,
1424 LLVMTypeRef data_type,
1425 LLVMTypeRef coords_type,
1426 LLVMTypeRef rsrc_type,
1427 char *out_name, unsigned out_len)
1428 {
1429 char coords_type_name[8];
1430
1431 ac_build_type_name_for_intr(coords_type, coords_type_name,
1432 sizeof(coords_type_name));
1433
1434 if (HAVE_LLVM <= 0x0309) {
1435 snprintf(out_name, out_len, "%s.%s", base_name, coords_type_name);
1436 } else {
1437 char data_type_name[8];
1438 char rsrc_type_name[8];
1439
1440 ac_build_type_name_for_intr(data_type, data_type_name,
1441 sizeof(data_type_name));
1442 ac_build_type_name_for_intr(rsrc_type, rsrc_type_name,
1443 sizeof(rsrc_type_name));
1444 snprintf(out_name, out_len, "%s.%s.%s.%s", base_name,
1445 data_type_name, coords_type_name, rsrc_type_name);
1446 }
1447 }
1448
1449 #define AC_EXP_TARGET (HAVE_LLVM >= 0x0500 ? 0 : 3)
1450 #define AC_EXP_OUT0 (HAVE_LLVM >= 0x0500 ? 2 : 5)
1451
1452 enum ac_ir_type {
1453 AC_IR_UNDEF,
1454 AC_IR_CONST,
1455 AC_IR_VALUE,
1456 };
1457
1458 struct ac_vs_exp_chan
1459 {
1460 LLVMValueRef value;
1461 float const_float;
1462 enum ac_ir_type type;
1463 };
1464
1465 struct ac_vs_exp_inst {
1466 unsigned offset;
1467 LLVMValueRef inst;
1468 struct ac_vs_exp_chan chan[4];
1469 };
1470
1471 struct ac_vs_exports {
1472 unsigned num;
1473 struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
1474 };
1475
1476 /* Return true if the PARAM export has been eliminated. */
1477 static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
1478 uint32_t num_outputs,
1479 struct ac_vs_exp_inst *exp)
1480 {
1481 unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
1482 bool is_zero[4] = {}, is_one[4] = {};
1483
1484 for (i = 0; i < 4; i++) {
1485 /* It's a constant expression. Undef outputs are eliminated too. */
1486 if (exp->chan[i].type == AC_IR_UNDEF) {
1487 is_zero[i] = true;
1488 is_one[i] = true;
1489 } else if (exp->chan[i].type == AC_IR_CONST) {
1490 if (exp->chan[i].const_float == 0)
1491 is_zero[i] = true;
1492 else if (exp->chan[i].const_float == 1)
1493 is_one[i] = true;
1494 else
1495 return false; /* other constant */
1496 } else
1497 return false;
1498 }
1499
1500 /* Only certain combinations of 0 and 1 can be eliminated. */
1501 if (is_zero[0] && is_zero[1] && is_zero[2])
1502 default_val = is_zero[3] ? 0 : 1;
1503 else if (is_one[0] && is_one[1] && is_one[2])
1504 default_val = is_zero[3] ? 2 : 3;
1505 else
1506 return false;
1507
1508 /* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
1509 LLVMInstructionEraseFromParent(exp->inst);
1510
1511 /* Change OFFSET to DEFAULT_VAL. */
1512 for (i = 0; i < num_outputs; i++) {
1513 if (vs_output_param_offset[i] == exp->offset) {
1514 vs_output_param_offset[i] =
1515 AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
1516 break;
1517 }
1518 }
1519 return true;
1520 }
1521
1522 static bool ac_eliminate_duplicated_output(uint8_t *vs_output_param_offset,
1523 uint32_t num_outputs,
1524 struct ac_vs_exports *processed,
1525 struct ac_vs_exp_inst *exp)
1526 {
1527 unsigned p, copy_back_channels = 0;
1528
1529 /* See if the output is already in the list of processed outputs.
1530 * The LLVMValueRef comparison relies on SSA.
1531 */
1532 for (p = 0; p < processed->num; p++) {
1533 bool different = false;
1534
1535 for (unsigned j = 0; j < 4; j++) {
1536 struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
1537 struct ac_vs_exp_chan *c2 = &exp->chan[j];
1538
1539 /* Treat undef as a match. */
1540 if (c2->type == AC_IR_UNDEF)
1541 continue;
1542
1543 /* If c1 is undef but c2 isn't, we can copy c2 to c1
1544 * and consider the instruction duplicated.
1545 */
1546 if (c1->type == AC_IR_UNDEF) {
1547 copy_back_channels |= 1 << j;
1548 continue;
1549 }
1550
1551 /* Test whether the channels are not equal. */
1552 if (c1->type != c2->type ||
1553 (c1->type == AC_IR_CONST &&
1554 c1->const_float != c2->const_float) ||
1555 (c1->type == AC_IR_VALUE &&
1556 c1->value != c2->value)) {
1557 different = true;
1558 break;
1559 }
1560 }
1561 if (!different)
1562 break;
1563
1564 copy_back_channels = 0;
1565 }
1566 if (p == processed->num)
1567 return false;
1568
1569 /* If a match was found, but the matching export has undef where the new
1570 * one has a normal value, copy the normal value to the undef channel.
1571 */
1572 struct ac_vs_exp_inst *match = &processed->exp[p];
1573
1574 while (copy_back_channels) {
1575 unsigned chan = u_bit_scan(&copy_back_channels);
1576
1577 assert(match->chan[chan].type == AC_IR_UNDEF);
1578 LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
1579 exp->chan[chan].value);
1580 match->chan[chan] = exp->chan[chan];
1581 }
1582
1583 /* The PARAM export is duplicated. Kill it. */
1584 LLVMInstructionEraseFromParent(exp->inst);
1585
1586 /* Change OFFSET to the matching export. */
1587 for (unsigned i = 0; i < num_outputs; i++) {
1588 if (vs_output_param_offset[i] == exp->offset) {
1589 vs_output_param_offset[i] = match->offset;
1590 break;
1591 }
1592 }
1593 return true;
1594 }
1595
1596 void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
1597 LLVMValueRef main_fn,
1598 uint8_t *vs_output_param_offset,
1599 uint32_t num_outputs,
1600 uint8_t *num_param_exports)
1601 {
1602 LLVMBasicBlockRef bb;
1603 bool removed_any = false;
1604 struct ac_vs_exports exports;
1605
1606 exports.num = 0;
1607
1608 /* Process all LLVM instructions. */
1609 bb = LLVMGetFirstBasicBlock(main_fn);
1610 while (bb) {
1611 LLVMValueRef inst = LLVMGetFirstInstruction(bb);
1612
1613 while (inst) {
1614 LLVMValueRef cur = inst;
1615 inst = LLVMGetNextInstruction(inst);
1616 struct ac_vs_exp_inst exp;
1617
1618 if (LLVMGetInstructionOpcode(cur) != LLVMCall)
1619 continue;
1620
1621 LLVMValueRef callee = ac_llvm_get_called_value(cur);
1622
1623 if (!ac_llvm_is_function(callee))
1624 continue;
1625
1626 const char *name = LLVMGetValueName(callee);
1627 unsigned num_args = LLVMCountParams(callee);
1628
1629 /* Check if this is an export instruction. */
1630 if ((num_args != 9 && num_args != 8) ||
1631 (strcmp(name, "llvm.SI.export") &&
1632 strcmp(name, "llvm.amdgcn.exp.f32")))
1633 continue;
1634
1635 LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
1636 unsigned target = LLVMConstIntGetZExtValue(arg);
1637
1638 if (target < V_008DFC_SQ_EXP_PARAM)
1639 continue;
1640
1641 target -= V_008DFC_SQ_EXP_PARAM;
1642
1643 /* Parse the instruction. */
1644 memset(&exp, 0, sizeof(exp));
1645 exp.offset = target;
1646 exp.inst = cur;
1647
1648 for (unsigned i = 0; i < 4; i++) {
1649 LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);
1650
1651 exp.chan[i].value = v;
1652
1653 if (LLVMIsUndef(v)) {
1654 exp.chan[i].type = AC_IR_UNDEF;
1655 } else if (LLVMIsAConstantFP(v)) {
1656 LLVMBool loses_info;
1657 exp.chan[i].type = AC_IR_CONST;
1658 exp.chan[i].const_float =
1659 LLVMConstRealGetDouble(v, &loses_info);
1660 } else {
1661 exp.chan[i].type = AC_IR_VALUE;
1662 }
1663 }
1664
1665 /* Eliminate constant and duplicated PARAM exports. */
1666 if (ac_eliminate_const_output(vs_output_param_offset,
1667 num_outputs, &exp) ||
1668 ac_eliminate_duplicated_output(vs_output_param_offset,
1669 num_outputs, &exports,
1670 &exp)) {
1671 removed_any = true;
1672 } else {
1673 exports.exp[exports.num++] = exp;
1674 }
1675 }
1676 bb = LLVMGetNextBasicBlock(bb);
1677 }
1678
1679 /* Remove holes in export memory due to removed PARAM exports.
1680 * This is done by renumbering all PARAM exports.
1681 */
1682 if (removed_any) {
1683 uint8_t old_offset[VARYING_SLOT_MAX];
1684 unsigned out, i;
1685
1686 /* Make a copy of the offsets. We need the old version while
1687 * we are modifying some of them. */
1688 memcpy(old_offset, vs_output_param_offset,
1689 sizeof(old_offset));
1690
1691 for (i = 0; i < exports.num; i++) {
1692 unsigned offset = exports.exp[i].offset;
1693
1694 /* Update vs_output_param_offset. Multiple outputs can
1695 * have the same offset.
1696 */
1697 for (out = 0; out < num_outputs; out++) {
1698 if (old_offset[out] == offset)
1699 vs_output_param_offset[out] = i;
1700 }
1701
1702 /* Change the PARAM offset in the instruction. */
1703 LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
1704 LLVMConstInt(ctx->i32,
1705 V_008DFC_SQ_EXP_PARAM + i, 0));
1706 }
1707 *num_param_exports = exports.num;
1708 }
1709 }