ac/nir/llvm: fix channel in texture gather lowering code.
[mesa.git] / src / amd / common / ac_nir_to_llvm.c
1 /*
2 * Copyright © 2016 Bas Nieuwenhuizen
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include "ac_nir_to_llvm.h"
25 #include "ac_llvm_util.h"
26 #include "ac_binary.h"
27 #include "sid.h"
28 #include "nir/nir.h"
29 #include "../vulkan/radv_descriptor_set.h"
30 #include "util/bitscan.h"
31 #include <llvm-c/Transforms/Scalar.h>
32
33 enum radeon_llvm_calling_convention {
34 RADEON_LLVM_AMDGPU_VS = 87,
35 RADEON_LLVM_AMDGPU_GS = 88,
36 RADEON_LLVM_AMDGPU_PS = 89,
37 RADEON_LLVM_AMDGPU_CS = 90,
38 };
39
40 #define CONST_ADDR_SPACE 2
41 #define LOCAL_ADDR_SPACE 3
42
43 #define RADEON_LLVM_MAX_INPUTS (VARYING_SLOT_VAR31 + 1)
44 #define RADEON_LLVM_MAX_OUTPUTS (VARYING_SLOT_VAR31 + 1)
45
46 enum desc_type {
47 DESC_IMAGE,
48 DESC_FMASK,
49 DESC_SAMPLER,
50 DESC_BUFFER,
51 };
52
53 struct nir_to_llvm_context {
54 const struct ac_nir_compiler_options *options;
55 struct ac_shader_variant_info *shader_info;
56
57 LLVMContextRef context;
58 LLVMModuleRef module;
59 LLVMBuilderRef builder;
60 LLVMValueRef main_function;
61
62 struct hash_table *defs;
63 struct hash_table *phis;
64
65 LLVMValueRef descriptor_sets[4];
66 LLVMValueRef push_constants;
67 LLVMValueRef num_work_groups;
68 LLVMValueRef workgroup_ids;
69 LLVMValueRef local_invocation_ids;
70 LLVMValueRef tg_size;
71
72 LLVMValueRef vertex_buffers;
73 LLVMValueRef base_vertex;
74 LLVMValueRef start_instance;
75 LLVMValueRef vertex_id;
76 LLVMValueRef rel_auto_id;
77 LLVMValueRef vs_prim_id;
78 LLVMValueRef instance_id;
79
80 LLVMValueRef prim_mask;
81 LLVMValueRef sample_positions;
82 LLVMValueRef persp_sample, persp_center, persp_centroid;
83 LLVMValueRef linear_sample, linear_center, linear_centroid;
84 LLVMValueRef front_face;
85 LLVMValueRef ancillary;
86 LLVMValueRef frag_pos[4];
87
88 LLVMBasicBlockRef continue_block;
89 LLVMBasicBlockRef break_block;
90
91 LLVMTypeRef i1;
92 LLVMTypeRef i8;
93 LLVMTypeRef i16;
94 LLVMTypeRef i32;
95 LLVMTypeRef i64;
96 LLVMTypeRef v2i32;
97 LLVMTypeRef v3i32;
98 LLVMTypeRef v4i32;
99 LLVMTypeRef v8i32;
100 LLVMTypeRef f32;
101 LLVMTypeRef f16;
102 LLVMTypeRef v2f32;
103 LLVMTypeRef v4f32;
104 LLVMTypeRef v16i8;
105 LLVMTypeRef voidt;
106
107 LLVMValueRef i32zero;
108 LLVMValueRef i32one;
109 LLVMValueRef f32zero;
110 LLVMValueRef f32one;
111 LLVMValueRef v4f32empty;
112
113 unsigned range_md_kind;
114 unsigned uniform_md_kind;
115 unsigned fpmath_md_kind;
116 unsigned invariant_load_md_kind;
117 LLVMValueRef empty_md;
118 LLVMValueRef fpmath_md_2p5_ulp;
119 gl_shader_stage stage;
120
121 LLVMValueRef lds;
122 LLVMValueRef inputs[RADEON_LLVM_MAX_INPUTS * 4];
123 LLVMValueRef outputs[RADEON_LLVM_MAX_OUTPUTS * 4];
124
125 LLVMValueRef shared_memory;
126 uint64_t input_mask;
127 uint64_t output_mask;
128 int num_locals;
129 LLVMValueRef *locals;
130 bool has_ddxy;
131 unsigned num_clips;
132 unsigned num_culls;
133 };
134
135 struct ac_tex_info {
136 LLVMValueRef args[12];
137 int arg_count;
138 LLVMTypeRef dst_type;
139 bool has_offset;
140 };
141
142 enum ac_func_attr {
143 AC_FUNC_ATTR_ALWAYSINLINE = (1 << 0),
144 AC_FUNC_ATTR_BYVAL = (1 << 1),
145 AC_FUNC_ATTR_INREG = (1 << 2),
146 AC_FUNC_ATTR_NOALIAS = (1 << 3),
147 AC_FUNC_ATTR_NOUNWIND = (1 << 4),
148 AC_FUNC_ATTR_READNONE = (1 << 5),
149 AC_FUNC_ATTR_READONLY = (1 << 6),
150 AC_FUNC_ATTR_LAST = (1 << 7)
151 };
152
153 #if HAVE_LLVM < 0x0400
154 static LLVMAttribute ac_attr_to_llvm_attr(enum ac_func_attr attr)
155 {
156 switch (attr) {
157 case AC_FUNC_ATTR_ALWAYSINLINE: return LLVMAlwaysInlineAttribute;
158 case AC_FUNC_ATTR_BYVAL: return LLVMByValAttribute;
159 case AC_FUNC_ATTR_INREG: return LLVMInRegAttribute;
160 case AC_FUNC_ATTR_NOALIAS: return LLVMNoAliasAttribute;
161 case AC_FUNC_ATTR_NOUNWIND: return LLVMNoUnwindAttribute;
162 case AC_FUNC_ATTR_READNONE: return LLVMReadNoneAttribute;
163 case AC_FUNC_ATTR_READONLY: return LLVMReadOnlyAttribute;
164 default:
165 fprintf(stderr, "Unhandled function attribute: %x\n", attr);
166 return 0;
167 }
168 }
169
170 #else
171
172 static const char *attr_to_str(enum ac_func_attr attr)
173 {
174 switch (attr) {
175 case AC_FUNC_ATTR_ALWAYSINLINE: return "alwaysinline";
176 case AC_FUNC_ATTR_BYVAL: return "byval";
177 case AC_FUNC_ATTR_INREG: return "inreg";
178 case AC_FUNC_ATTR_NOALIAS: return "noalias";
179 case AC_FUNC_ATTR_NOUNWIND: return "nounwind";
180 case AC_FUNC_ATTR_READNONE: return "readnone";
181 case AC_FUNC_ATTR_READONLY: return "readonly";
182 default:
183 fprintf(stderr, "Unhandled function attribute: %x\n", attr);
184 return 0;
185 }
186 }
187
188 #endif
189
190 static void
191 ac_add_function_attr(LLVMValueRef function,
192 int attr_idx,
193 enum ac_func_attr attr)
194 {
195
196 #if HAVE_LLVM < 0x0400
197 LLVMAttribute llvm_attr = ac_attr_to_llvm_attr(attr);
198 if (attr_idx == -1) {
199 LLVMAddFunctionAttr(function, llvm_attr);
200 } else {
201 LLVMAddAttribute(LLVMGetParam(function, attr_idx - 1), llvm_attr);
202 }
203 #else
204 LLVMContextRef context = LLVMGetModuleContext(LLVMGetGlobalParent(function));
205 const char *attr_name = attr_to_str(attr);
206 unsigned kind_id = LLVMGetEnumAttributeKindForName(attr_name,
207 strlen(attr_name));
208 LLVMAttributeRef llvm_attr = LLVMCreateEnumAttribute(context, kind_id, 0);
209 LLVMAddAttributeAtIndex(function, attr_idx, llvm_attr);
210 #endif
211 }
212
213 static LLVMValueRef
214 emit_llvm_intrinsic(struct nir_to_llvm_context *ctx, const char *name,
215 LLVMTypeRef return_type, LLVMValueRef *params,
216 unsigned param_count, unsigned attr_mask);
217 static LLVMValueRef get_sampler_desc(struct nir_to_llvm_context *ctx,
218 nir_deref_var *deref,
219 enum desc_type desc_type);
220 static unsigned radeon_llvm_reg_index_soa(unsigned index, unsigned chan)
221 {
222 return (index * 4) + chan;
223 }
224
225 static unsigned llvm_get_type_size(LLVMTypeRef type)
226 {
227 LLVMTypeKind kind = LLVMGetTypeKind(type);
228
229 switch (kind) {
230 case LLVMIntegerTypeKind:
231 return LLVMGetIntTypeWidth(type) / 8;
232 case LLVMFloatTypeKind:
233 return 4;
234 case LLVMPointerTypeKind:
235 return 8;
236 case LLVMVectorTypeKind:
237 return LLVMGetVectorSize(type) *
238 llvm_get_type_size(LLVMGetElementType(type));
239 default:
240 assert(0);
241 return 0;
242 }
243 }
244
245 static void set_llvm_calling_convention(LLVMValueRef func,
246 gl_shader_stage stage)
247 {
248 enum radeon_llvm_calling_convention calling_conv;
249
250 switch (stage) {
251 case MESA_SHADER_VERTEX:
252 case MESA_SHADER_TESS_CTRL:
253 case MESA_SHADER_TESS_EVAL:
254 calling_conv = RADEON_LLVM_AMDGPU_VS;
255 break;
256 case MESA_SHADER_GEOMETRY:
257 calling_conv = RADEON_LLVM_AMDGPU_GS;
258 break;
259 case MESA_SHADER_FRAGMENT:
260 calling_conv = RADEON_LLVM_AMDGPU_PS;
261 break;
262 case MESA_SHADER_COMPUTE:
263 calling_conv = RADEON_LLVM_AMDGPU_CS;
264 break;
265 default:
266 unreachable("Unhandle shader type");
267 }
268
269 LLVMSetFunctionCallConv(func, calling_conv);
270 }
271
272 static LLVMValueRef
273 create_llvm_function(LLVMContextRef ctx, LLVMModuleRef module,
274 LLVMBuilderRef builder, LLVMTypeRef *return_types,
275 unsigned num_return_elems, LLVMTypeRef *param_types,
276 unsigned param_count, unsigned array_params,
277 unsigned sgpr_params, bool unsafe_math)
278 {
279 LLVMTypeRef main_function_type, ret_type;
280 LLVMBasicBlockRef main_function_body;
281
282 if (num_return_elems)
283 ret_type = LLVMStructTypeInContext(ctx, return_types,
284 num_return_elems, true);
285 else
286 ret_type = LLVMVoidTypeInContext(ctx);
287
288 /* Setup the function */
289 main_function_type =
290 LLVMFunctionType(ret_type, param_types, param_count, 0);
291 LLVMValueRef main_function =
292 LLVMAddFunction(module, "main", main_function_type);
293 main_function_body =
294 LLVMAppendBasicBlockInContext(ctx, main_function, "main_body");
295 LLVMPositionBuilderAtEnd(builder, main_function_body);
296
297 LLVMSetFunctionCallConv(main_function, RADEON_LLVM_AMDGPU_CS);
298 for (unsigned i = 0; i < sgpr_params; ++i) {
299 if (i < array_params) {
300 LLVMValueRef P = LLVMGetParam(main_function, i);
301 ac_add_function_attr(main_function, i + 1, AC_FUNC_ATTR_BYVAL);
302 ac_add_attr_dereferenceable(P, UINT64_MAX);
303 }
304 else {
305 ac_add_function_attr(main_function, i + 1, AC_FUNC_ATTR_INREG);
306 }
307 }
308
309 if (unsafe_math) {
310 /* These were copied from some LLVM test. */
311 LLVMAddTargetDependentFunctionAttr(main_function,
312 "less-precise-fpmad",
313 "true");
314 LLVMAddTargetDependentFunctionAttr(main_function,
315 "no-infs-fp-math",
316 "true");
317 LLVMAddTargetDependentFunctionAttr(main_function,
318 "no-nans-fp-math",
319 "true");
320 LLVMAddTargetDependentFunctionAttr(main_function,
321 "unsafe-fp-math",
322 "true");
323 }
324 return main_function;
325 }
326
327 static LLVMTypeRef const_array(LLVMTypeRef elem_type, int num_elements)
328 {
329 return LLVMPointerType(LLVMArrayType(elem_type, num_elements),
330 CONST_ADDR_SPACE);
331 }
332
333 static LLVMValueRef get_shared_memory_ptr(struct nir_to_llvm_context *ctx,
334 int idx,
335 LLVMTypeRef type)
336 {
337 LLVMValueRef offset;
338 LLVMValueRef ptr;
339 int addr_space;
340
341 offset = LLVMConstInt(ctx->i32, idx, false);
342
343 ptr = ctx->shared_memory;
344 ptr = LLVMBuildGEP(ctx->builder, ptr, &offset, 1, "");
345 addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
346 ptr = LLVMBuildBitCast(ctx->builder, ptr, LLVMPointerType(type, addr_space), "");
347 return ptr;
348 }
349
350 static LLVMValueRef to_integer(struct nir_to_llvm_context *ctx, LLVMValueRef v)
351 {
352 LLVMTypeRef type = LLVMTypeOf(v);
353 if (type == ctx->f32) {
354 return LLVMBuildBitCast(ctx->builder, v, ctx->i32, "");
355 } else if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
356 LLVMTypeRef elem_type = LLVMGetElementType(type);
357 if (elem_type == ctx->f32) {
358 LLVMTypeRef nt = LLVMVectorType(ctx->i32, LLVMGetVectorSize(type));
359 return LLVMBuildBitCast(ctx->builder, v, nt, "");
360 }
361 }
362 return v;
363 }
364
365 static LLVMValueRef to_float(struct nir_to_llvm_context *ctx, LLVMValueRef v)
366 {
367 LLVMTypeRef type = LLVMTypeOf(v);
368 if (type == ctx->i32) {
369 return LLVMBuildBitCast(ctx->builder, v, ctx->f32, "");
370 } else if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
371 LLVMTypeRef elem_type = LLVMGetElementType(type);
372 if (elem_type == ctx->i32) {
373 LLVMTypeRef nt = LLVMVectorType(ctx->f32, LLVMGetVectorSize(type));
374 return LLVMBuildBitCast(ctx->builder, v, nt, "");
375 }
376 }
377 return v;
378 }
379
380 static LLVMValueRef build_indexed_load(struct nir_to_llvm_context *ctx,
381 LLVMValueRef base_ptr, LLVMValueRef index,
382 bool uniform)
383 {
384 LLVMValueRef pointer;
385 LLVMValueRef indices[] = {ctx->i32zero, index};
386
387 pointer = LLVMBuildGEP(ctx->builder, base_ptr, indices, 2, "");
388 if (uniform)
389 LLVMSetMetadata(pointer, ctx->uniform_md_kind, ctx->empty_md);
390 return LLVMBuildLoad(ctx->builder, pointer, "");
391 }
392
393 static LLVMValueRef build_indexed_load_const(struct nir_to_llvm_context *ctx,
394 LLVMValueRef base_ptr, LLVMValueRef index)
395 {
396 LLVMValueRef result = build_indexed_load(ctx, base_ptr, index, true);
397 LLVMSetMetadata(result, ctx->invariant_load_md_kind, ctx->empty_md);
398 return result;
399 }
400
401 static void create_function(struct nir_to_llvm_context *ctx,
402 struct nir_shader *nir)
403 {
404 LLVMTypeRef arg_types[23];
405 unsigned arg_idx = 0;
406 unsigned array_count = 0;
407 unsigned sgpr_count = 0, user_sgpr_count;
408 unsigned i;
409
410 /* 1 for each descriptor set */
411 for (unsigned i = 0; i < 4; ++i)
412 arg_types[arg_idx++] = const_array(ctx->i8, 1024 * 1024);
413
414 /* 1 for push constants and dynamic descriptors */
415 arg_types[arg_idx++] = const_array(ctx->i8, 1024 * 1024);
416
417 array_count = arg_idx;
418 switch (nir->stage) {
419 case MESA_SHADER_COMPUTE:
420 arg_types[arg_idx++] = LLVMVectorType(ctx->i32, 3); /* grid size */
421 user_sgpr_count = arg_idx;
422 arg_types[arg_idx++] = LLVMVectorType(ctx->i32, 3);
423 arg_types[arg_idx++] = ctx->i32;
424 sgpr_count = arg_idx;
425
426 arg_types[arg_idx++] = LLVMVectorType(ctx->i32, 3);
427 break;
428 case MESA_SHADER_VERTEX:
429 arg_types[arg_idx++] = const_array(ctx->v16i8, 16); /* vertex buffers */
430 arg_types[arg_idx++] = ctx->i32; // base vertex
431 arg_types[arg_idx++] = ctx->i32; // start instance
432 user_sgpr_count = sgpr_count = arg_idx;
433 arg_types[arg_idx++] = ctx->i32; // vertex id
434 arg_types[arg_idx++] = ctx->i32; // rel auto id
435 arg_types[arg_idx++] = ctx->i32; // vs prim id
436 arg_types[arg_idx++] = ctx->i32; // instance id
437 break;
438 case MESA_SHADER_FRAGMENT:
439 arg_types[arg_idx++] = const_array(ctx->f32, 32); /* sample positions */
440 user_sgpr_count = arg_idx;
441 arg_types[arg_idx++] = ctx->i32; /* prim mask */
442 sgpr_count = arg_idx;
443 arg_types[arg_idx++] = ctx->v2i32; /* persp sample */
444 arg_types[arg_idx++] = ctx->v2i32; /* persp center */
445 arg_types[arg_idx++] = ctx->v2i32; /* persp centroid */
446 arg_types[arg_idx++] = ctx->v3i32; /* persp pull model */
447 arg_types[arg_idx++] = ctx->v2i32; /* linear sample */
448 arg_types[arg_idx++] = ctx->v2i32; /* linear center */
449 arg_types[arg_idx++] = ctx->v2i32; /* linear centroid */
450 arg_types[arg_idx++] = ctx->f32; /* line stipple tex */
451 arg_types[arg_idx++] = ctx->f32; /* pos x float */
452 arg_types[arg_idx++] = ctx->f32; /* pos y float */
453 arg_types[arg_idx++] = ctx->f32; /* pos z float */
454 arg_types[arg_idx++] = ctx->f32; /* pos w float */
455 arg_types[arg_idx++] = ctx->i32; /* front face */
456 arg_types[arg_idx++] = ctx->i32; /* ancillary */
457 arg_types[arg_idx++] = ctx->f32; /* sample coverage */
458 arg_types[arg_idx++] = ctx->i32; /* fixed pt */
459 break;
460 default:
461 unreachable("Shader stage not implemented");
462 }
463
464 ctx->main_function = create_llvm_function(
465 ctx->context, ctx->module, ctx->builder, NULL, 0, arg_types,
466 arg_idx, array_count, sgpr_count, ctx->options->unsafe_math);
467 set_llvm_calling_convention(ctx->main_function, nir->stage);
468
469
470 ctx->shader_info->num_input_sgprs = 0;
471 ctx->shader_info->num_input_vgprs = 0;
472
473 for (i = 0; i < user_sgpr_count; i++)
474 ctx->shader_info->num_user_sgprs += llvm_get_type_size(arg_types[i]) / 4;
475
476 ctx->shader_info->num_input_sgprs = ctx->shader_info->num_user_sgprs;
477 for (; i < sgpr_count; i++)
478 ctx->shader_info->num_input_sgprs += llvm_get_type_size(arg_types[i]) / 4;
479
480 if (nir->stage != MESA_SHADER_FRAGMENT)
481 for (; i < arg_idx; ++i)
482 ctx->shader_info->num_input_vgprs += llvm_get_type_size(arg_types[i]) / 4;
483
484 arg_idx = 0;
485 for (unsigned i = 0; i < 4; ++i)
486 ctx->descriptor_sets[i] =
487 LLVMGetParam(ctx->main_function, arg_idx++);
488
489 ctx->push_constants = LLVMGetParam(ctx->main_function, arg_idx++);
490
491 switch (nir->stage) {
492 case MESA_SHADER_COMPUTE:
493 ctx->num_work_groups =
494 LLVMGetParam(ctx->main_function, arg_idx++);
495 ctx->workgroup_ids =
496 LLVMGetParam(ctx->main_function, arg_idx++);
497 ctx->tg_size =
498 LLVMGetParam(ctx->main_function, arg_idx++);
499 ctx->local_invocation_ids =
500 LLVMGetParam(ctx->main_function, arg_idx++);
501 break;
502 case MESA_SHADER_VERTEX:
503 ctx->vertex_buffers = LLVMGetParam(ctx->main_function, arg_idx++);
504 ctx->base_vertex = LLVMGetParam(ctx->main_function, arg_idx++);
505 ctx->start_instance = LLVMGetParam(ctx->main_function, arg_idx++);
506 ctx->vertex_id = LLVMGetParam(ctx->main_function, arg_idx++);
507 ctx->rel_auto_id = LLVMGetParam(ctx->main_function, arg_idx++);
508 ctx->vs_prim_id = LLVMGetParam(ctx->main_function, arg_idx++);
509 ctx->instance_id = LLVMGetParam(ctx->main_function, arg_idx++);
510 break;
511 case MESA_SHADER_FRAGMENT:
512 ctx->sample_positions = LLVMGetParam(ctx->main_function, arg_idx++);
513 ctx->prim_mask = LLVMGetParam(ctx->main_function, arg_idx++);
514 ctx->persp_sample = LLVMGetParam(ctx->main_function, arg_idx++);
515 ctx->persp_center = LLVMGetParam(ctx->main_function, arg_idx++);
516 ctx->persp_centroid = LLVMGetParam(ctx->main_function, arg_idx++);
517 arg_idx++;
518 ctx->linear_sample = LLVMGetParam(ctx->main_function, arg_idx++);
519 ctx->linear_center = LLVMGetParam(ctx->main_function, arg_idx++);
520 ctx->linear_centroid = LLVMGetParam(ctx->main_function, arg_idx++);
521 arg_idx++; /* line stipple */
522 ctx->frag_pos[0] = LLVMGetParam(ctx->main_function, arg_idx++);
523 ctx->frag_pos[1] = LLVMGetParam(ctx->main_function, arg_idx++);
524 ctx->frag_pos[2] = LLVMGetParam(ctx->main_function, arg_idx++);
525 ctx->frag_pos[3] = LLVMGetParam(ctx->main_function, arg_idx++);
526 ctx->front_face = LLVMGetParam(ctx->main_function, arg_idx++);
527 ctx->ancillary = LLVMGetParam(ctx->main_function, arg_idx++);
528 break;
529 default:
530 unreachable("Shader stage not implemented");
531 }
532 }
533
534 static void setup_types(struct nir_to_llvm_context *ctx)
535 {
536 LLVMValueRef args[4];
537
538 ctx->voidt = LLVMVoidTypeInContext(ctx->context);
539 ctx->i1 = LLVMIntTypeInContext(ctx->context, 1);
540 ctx->i8 = LLVMIntTypeInContext(ctx->context, 8);
541 ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
542 ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
543 ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
544 ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
545 ctx->v3i32 = LLVMVectorType(ctx->i32, 3);
546 ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
547 ctx->v8i32 = LLVMVectorType(ctx->i32, 8);
548 ctx->f32 = LLVMFloatTypeInContext(ctx->context);
549 ctx->f16 = LLVMHalfTypeInContext(ctx->context);
550 ctx->v2f32 = LLVMVectorType(ctx->f32, 2);
551 ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
552 ctx->v16i8 = LLVMVectorType(ctx->i8, 16);
553
554 ctx->i32zero = LLVMConstInt(ctx->i32, 0, false);
555 ctx->i32one = LLVMConstInt(ctx->i32, 1, false);
556 ctx->f32zero = LLVMConstReal(ctx->f32, 0.0);
557 ctx->f32one = LLVMConstReal(ctx->f32, 1.0);
558
559 args[0] = ctx->f32zero;
560 args[1] = ctx->f32zero;
561 args[2] = ctx->f32zero;
562 args[3] = ctx->f32one;
563 ctx->v4f32empty = LLVMConstVector(args, 4);
564
565 ctx->range_md_kind = LLVMGetMDKindIDInContext(ctx->context,
566 "range", 5);
567 ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(ctx->context,
568 "invariant.load", 14);
569 ctx->uniform_md_kind =
570 LLVMGetMDKindIDInContext(ctx->context, "amdgpu.uniform", 14);
571 ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
572
573 ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->context, "fpmath", 6);
574
575 args[0] = LLVMConstReal(ctx->f32, 2.5);
576 ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->context, args, 1);
577 }
578
579 static int get_llvm_num_components(LLVMValueRef value)
580 {
581 LLVMTypeRef type = LLVMTypeOf(value);
582 unsigned num_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
583 ? LLVMGetVectorSize(type)
584 : 1;
585 return num_components;
586 }
587
588 static LLVMValueRef llvm_extract_elem(struct nir_to_llvm_context *ctx,
589 LLVMValueRef value,
590 int index)
591 {
592 int count = get_llvm_num_components(value);
593
594 assert(index < count);
595 if (count == 1)
596 return value;
597
598 return LLVMBuildExtractElement(ctx->builder, value,
599 LLVMConstInt(ctx->i32, index, false), "");
600 }
601
602 static LLVMValueRef trim_vector(struct nir_to_llvm_context *ctx,
603 LLVMValueRef value, unsigned count)
604 {
605 unsigned num_components = get_llvm_num_components(value);
606 if (count == num_components)
607 return value;
608
609 LLVMValueRef masks[] = {
610 LLVMConstInt(ctx->i32, 0, false), LLVMConstInt(ctx->i32, 1, false),
611 LLVMConstInt(ctx->i32, 2, false), LLVMConstInt(ctx->i32, 3, false)};
612
613 if (count == 1)
614 return LLVMBuildExtractElement(ctx->builder, value, masks[0],
615 "");
616
617 LLVMValueRef swizzle = LLVMConstVector(masks, count);
618 return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
619 }
620
621 static LLVMValueRef
622 build_gather_values_extended(struct nir_to_llvm_context *ctx,
623 LLVMValueRef *values,
624 unsigned value_count,
625 unsigned value_stride,
626 bool load)
627 {
628 LLVMBuilderRef builder = ctx->builder;
629 LLVMValueRef vec;
630 unsigned i;
631
632
633 if (value_count == 1) {
634 if (load)
635 return LLVMBuildLoad(builder, values[0], "");
636 return values[0];
637 }
638
639 for (i = 0; i < value_count; i++) {
640 LLVMValueRef value = values[i * value_stride];
641 if (load)
642 value = LLVMBuildLoad(builder, value, "");
643
644 if (!i)
645 vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
646 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
647 vec = LLVMBuildInsertElement(builder, vec, value, index, "");
648 }
649 return vec;
650 }
651
652
653 static void
654 build_store_values_extended(struct nir_to_llvm_context *ctx,
655 LLVMValueRef *values,
656 unsigned value_count,
657 unsigned value_stride,
658 LLVMValueRef vec)
659 {
660 LLVMBuilderRef builder = ctx->builder;
661 unsigned i;
662
663 if (value_count == 1) {
664 LLVMBuildStore(builder, vec, values[0]);
665 return;
666 }
667
668 for (i = 0; i < value_count; i++) {
669 LLVMValueRef ptr = values[i * value_stride];
670 LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
671 LLVMValueRef value = LLVMBuildExtractElement(builder, vec, index, "");
672 LLVMBuildStore(builder, value, ptr);
673 }
674 }
675
676 static LLVMValueRef
677 build_gather_values(struct nir_to_llvm_context *ctx,
678 LLVMValueRef *values,
679 unsigned value_count)
680 {
681 return build_gather_values_extended(ctx, values, value_count, 1, false);
682 }
683
684 static LLVMTypeRef get_def_type(struct nir_to_llvm_context *ctx,
685 nir_ssa_def *def)
686 {
687 LLVMTypeRef type = LLVMIntTypeInContext(ctx->context, def->bit_size);
688 if (def->num_components > 1) {
689 type = LLVMVectorType(type, def->num_components);
690 }
691 return type;
692 }
693
694 static LLVMValueRef get_src(struct nir_to_llvm_context *ctx, nir_src src)
695 {
696 assert(src.is_ssa);
697 struct hash_entry *entry = _mesa_hash_table_search(ctx->defs, src.ssa);
698 return (LLVMValueRef)entry->data;
699 }
700
701
702 static LLVMBasicBlockRef get_block(struct nir_to_llvm_context *ctx,
703 struct nir_block *b)
704 {
705 struct hash_entry *entry = _mesa_hash_table_search(ctx->defs, b);
706 return (LLVMBasicBlockRef)entry->data;
707 }
708
709 static LLVMValueRef get_alu_src(struct nir_to_llvm_context *ctx,
710 nir_alu_src src,
711 unsigned num_components)
712 {
713 LLVMValueRef value = get_src(ctx, src.src);
714 bool need_swizzle = false;
715
716 assert(value);
717 LLVMTypeRef type = LLVMTypeOf(value);
718 unsigned src_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
719 ? LLVMGetVectorSize(type)
720 : 1;
721
722 for (unsigned i = 0; i < num_components; ++i) {
723 assert(src.swizzle[i] < src_components);
724 if (src.swizzle[i] != i)
725 need_swizzle = true;
726 }
727
728 if (need_swizzle || num_components != src_components) {
729 LLVMValueRef masks[] = {
730 LLVMConstInt(ctx->i32, src.swizzle[0], false),
731 LLVMConstInt(ctx->i32, src.swizzle[1], false),
732 LLVMConstInt(ctx->i32, src.swizzle[2], false),
733 LLVMConstInt(ctx->i32, src.swizzle[3], false)};
734
735 if (src_components > 1 && num_components == 1) {
736 value = LLVMBuildExtractElement(ctx->builder, value,
737 masks[0], "");
738 } else if (src_components == 1 && num_components > 1) {
739 LLVMValueRef values[] = {value, value, value, value};
740 value = build_gather_values(ctx, values, num_components);
741 } else {
742 LLVMValueRef swizzle = LLVMConstVector(masks, num_components);
743 value = LLVMBuildShuffleVector(ctx->builder, value, value,
744 swizzle, "");
745 }
746 }
747 assert(!src.negate);
748 assert(!src.abs);
749 return value;
750 }
751
752 static LLVMValueRef emit_int_cmp(struct nir_to_llvm_context *ctx,
753 LLVMIntPredicate pred, LLVMValueRef src0,
754 LLVMValueRef src1)
755 {
756 LLVMValueRef result = LLVMBuildICmp(ctx->builder, pred, src0, src1, "");
757 return LLVMBuildSelect(ctx->builder, result,
758 LLVMConstInt(ctx->i32, 0xFFFFFFFF, false),
759 LLVMConstInt(ctx->i32, 0, false), "");
760 }
761
762 static LLVMValueRef emit_float_cmp(struct nir_to_llvm_context *ctx,
763 LLVMRealPredicate pred, LLVMValueRef src0,
764 LLVMValueRef src1)
765 {
766 LLVMValueRef result;
767 src0 = to_float(ctx, src0);
768 src1 = to_float(ctx, src1);
769 result = LLVMBuildFCmp(ctx->builder, pred, src0, src1, "");
770 return LLVMBuildSelect(ctx->builder, result,
771 LLVMConstInt(ctx->i32, 0xFFFFFFFF, false),
772 LLVMConstInt(ctx->i32, 0, false), "");
773 }
774
775 static LLVMValueRef emit_intrin_1f_param(struct nir_to_llvm_context *ctx,
776 const char *intrin,
777 LLVMValueRef src0)
778 {
779 LLVMValueRef params[] = {
780 to_float(ctx, src0),
781 };
782 return emit_llvm_intrinsic(ctx, intrin, ctx->f32, params, 1, AC_FUNC_ATTR_READNONE);
783 }
784
785 static LLVMValueRef emit_intrin_2f_param(struct nir_to_llvm_context *ctx,
786 const char *intrin,
787 LLVMValueRef src0, LLVMValueRef src1)
788 {
789 LLVMValueRef params[] = {
790 to_float(ctx, src0),
791 to_float(ctx, src1),
792 };
793 return emit_llvm_intrinsic(ctx, intrin, ctx->f32, params, 2, AC_FUNC_ATTR_READNONE);
794 }
795
796 static LLVMValueRef emit_intrin_3f_param(struct nir_to_llvm_context *ctx,
797 const char *intrin,
798 LLVMValueRef src0, LLVMValueRef src1, LLVMValueRef src2)
799 {
800 LLVMValueRef params[] = {
801 to_float(ctx, src0),
802 to_float(ctx, src1),
803 to_float(ctx, src2),
804 };
805 return emit_llvm_intrinsic(ctx, intrin, ctx->f32, params, 3, AC_FUNC_ATTR_READNONE);
806 }
807
808 static LLVMValueRef emit_bcsel(struct nir_to_llvm_context *ctx,
809 LLVMValueRef src0, LLVMValueRef src1, LLVMValueRef src2)
810 {
811 LLVMValueRef v = LLVMBuildICmp(ctx->builder, LLVMIntNE, src0,
812 ctx->i32zero, "");
813 return LLVMBuildSelect(ctx->builder, v, src1, src2, "");
814 }
815
816 static LLVMValueRef emit_find_lsb(struct nir_to_llvm_context *ctx,
817 LLVMValueRef src0)
818 {
819 LLVMValueRef params[2] = {
820 src0,
821
822 /* The value of 1 means that ffs(x=0) = undef, so LLVM won't
823 * add special code to check for x=0. The reason is that
824 * the LLVM behavior for x=0 is different from what we
825 * need here.
826 *
827 * The hardware already implements the correct behavior.
828 */
829 LLVMConstInt(ctx->i32, 1, false),
830 };
831 return emit_llvm_intrinsic(ctx, "llvm.cttz.i32", ctx->i32, params, 2, AC_FUNC_ATTR_READNONE);
832 }
833
834 static LLVMValueRef emit_ifind_msb(struct nir_to_llvm_context *ctx,
835 LLVMValueRef src0)
836 {
837 LLVMValueRef msb = emit_llvm_intrinsic(ctx, "llvm.AMDGPU.flbit.i32",
838 ctx->i32, &src0, 1,
839 AC_FUNC_ATTR_READNONE);
840
841 /* The HW returns the last bit index from MSB, but NIR wants
842 * the index from LSB. Invert it by doing "31 - msb". */
843 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
844 msb, "");
845
846 LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
847 LLVMValueRef cond = LLVMBuildOr(ctx->builder,
848 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
849 src0, ctx->i32zero, ""),
850 LLVMBuildICmp(ctx->builder, LLVMIntEQ,
851 src0, all_ones, ""), "");
852
853 return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
854 }
855
856 static LLVMValueRef emit_ufind_msb(struct nir_to_llvm_context *ctx,
857 LLVMValueRef src0)
858 {
859 LLVMValueRef args[2] = {
860 src0,
861 ctx->i32one,
862 };
863 LLVMValueRef msb = emit_llvm_intrinsic(ctx, "llvm.ctlz.i32",
864 ctx->i32, args, ARRAY_SIZE(args),
865 AC_FUNC_ATTR_READNONE);
866
867 /* The HW returns the last bit index from MSB, but NIR wants
868 * the index from LSB. Invert it by doing "31 - msb". */
869 msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
870 msb, "");
871
872 return LLVMBuildSelect(ctx->builder,
873 LLVMBuildICmp(ctx->builder, LLVMIntEQ, src0,
874 ctx->i32zero, ""),
875 LLVMConstInt(ctx->i32, -1, true), msb, "");
876 }
877
878 static LLVMValueRef emit_minmax_int(struct nir_to_llvm_context *ctx,
879 LLVMIntPredicate pred,
880 LLVMValueRef src0, LLVMValueRef src1)
881 {
882 return LLVMBuildSelect(ctx->builder,
883 LLVMBuildICmp(ctx->builder, pred, src0, src1, ""),
884 src0,
885 src1, "");
886
887 }
888 static LLVMValueRef emit_iabs(struct nir_to_llvm_context *ctx,
889 LLVMValueRef src0)
890 {
891 return emit_minmax_int(ctx, LLVMIntSGT, src0,
892 LLVMBuildNeg(ctx->builder, src0, ""));
893 }
894
895 static LLVMValueRef emit_fsign(struct nir_to_llvm_context *ctx,
896 LLVMValueRef src0)
897 {
898 LLVMValueRef cmp, val;
899
900 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, ctx->f32zero, "");
901 val = LLVMBuildSelect(ctx->builder, cmp, ctx->f32one, src0, "");
902 cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, ctx->f32zero, "");
903 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(ctx->f32, -1.0), "");
904 return val;
905 }
906
907 static LLVMValueRef emit_isign(struct nir_to_llvm_context *ctx,
908 LLVMValueRef src0)
909 {
910 LLVMValueRef cmp, val;
911
912 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, ctx->i32zero, "");
913 val = LLVMBuildSelect(ctx->builder, cmp, ctx->i32one, src0, "");
914 cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, ctx->i32zero, "");
915 val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(ctx->i32, -1, true), "");
916 return val;
917 }
918
919 static LLVMValueRef emit_ffract(struct nir_to_llvm_context *ctx,
920 LLVMValueRef src0)
921 {
922 const char *intr = "llvm.floor.f32";
923 LLVMValueRef fsrc0 = to_float(ctx, src0);
924 LLVMValueRef params[] = {
925 fsrc0,
926 };
927 LLVMValueRef floor = emit_llvm_intrinsic(ctx, intr,
928 ctx->f32, params, 1,
929 AC_FUNC_ATTR_READNONE);
930 return LLVMBuildFSub(ctx->builder, fsrc0, floor, "");
931 }
932
933 static LLVMValueRef emit_uint_carry(struct nir_to_llvm_context *ctx,
934 const char *intrin,
935 LLVMValueRef src0, LLVMValueRef src1)
936 {
937 LLVMTypeRef ret_type;
938 LLVMTypeRef types[] = { ctx->i32, ctx->i1 };
939 LLVMValueRef res;
940 LLVMValueRef params[] = { src0, src1 };
941 ret_type = LLVMStructTypeInContext(ctx->context, types,
942 2, true);
943
944 res = emit_llvm_intrinsic(ctx, intrin, ret_type,
945 params, 2, AC_FUNC_ATTR_READNONE);
946
947 res = LLVMBuildExtractValue(ctx->builder, res, 1, "");
948 res = LLVMBuildZExt(ctx->builder, res, ctx->i32, "");
949 return res;
950 }
951
952 static LLVMValueRef emit_b2f(struct nir_to_llvm_context *ctx,
953 LLVMValueRef src0)
954 {
955 return LLVMBuildAnd(ctx->builder, src0, LLVMBuildBitCast(ctx->builder, LLVMConstReal(ctx->f32, 1.0), ctx->i32, ""), "");
956 }
957
958 static LLVMValueRef emit_umul_high(struct nir_to_llvm_context *ctx,
959 LLVMValueRef src0, LLVMValueRef src1)
960 {
961 LLVMValueRef dst64, result;
962 src0 = LLVMBuildZExt(ctx->builder, src0, ctx->i64, "");
963 src1 = LLVMBuildZExt(ctx->builder, src1, ctx->i64, "");
964
965 dst64 = LLVMBuildMul(ctx->builder, src0, src1, "");
966 dst64 = LLVMBuildLShr(ctx->builder, dst64, LLVMConstInt(ctx->i64, 32, false), "");
967 result = LLVMBuildTrunc(ctx->builder, dst64, ctx->i32, "");
968 return result;
969 }
970
971 static LLVMValueRef emit_imul_high(struct nir_to_llvm_context *ctx,
972 LLVMValueRef src0, LLVMValueRef src1)
973 {
974 LLVMValueRef dst64, result;
975 src0 = LLVMBuildSExt(ctx->builder, src0, ctx->i64, "");
976 src1 = LLVMBuildSExt(ctx->builder, src1, ctx->i64, "");
977
978 dst64 = LLVMBuildMul(ctx->builder, src0, src1, "");
979 dst64 = LLVMBuildAShr(ctx->builder, dst64, LLVMConstInt(ctx->i64, 32, false), "");
980 result = LLVMBuildTrunc(ctx->builder, dst64, ctx->i32, "");
981 return result;
982 }
983
984 static LLVMValueRef emit_bitfield_extract(struct nir_to_llvm_context *ctx,
985 const char *intrin,
986 LLVMValueRef srcs[3])
987 {
988 LLVMValueRef result;
989 LLVMValueRef icond = LLVMBuildICmp(ctx->builder, LLVMIntEQ, srcs[2], LLVMConstInt(ctx->i32, 32, false), "");
990 result = emit_llvm_intrinsic(ctx, intrin, ctx->i32, srcs, 3, AC_FUNC_ATTR_READNONE);
991
992 result = LLVMBuildSelect(ctx->builder, icond, srcs[0], result, "");
993 return result;
994 }
995
996 static LLVMValueRef emit_bitfield_insert(struct nir_to_llvm_context *ctx,
997 LLVMValueRef src0, LLVMValueRef src1,
998 LLVMValueRef src2, LLVMValueRef src3)
999 {
1000 LLVMValueRef bfi_args[3], result;
1001
1002 bfi_args[0] = LLVMBuildShl(ctx->builder,
1003 LLVMBuildSub(ctx->builder,
1004 LLVMBuildShl(ctx->builder,
1005 ctx->i32one,
1006 src3, ""),
1007 ctx->i32one, ""),
1008 src2, "");
1009 bfi_args[1] = LLVMBuildShl(ctx->builder, src1, src2, "");
1010 bfi_args[2] = src0;
1011
1012 LLVMValueRef icond = LLVMBuildICmp(ctx->builder, LLVMIntEQ, src3, LLVMConstInt(ctx->i32, 32, false), "");
1013
1014 /* Calculate:
1015 * (arg0 & arg1) | (~arg0 & arg2) = arg2 ^ (arg0 & (arg1 ^ arg2)
1016 * Use the right-hand side, which the LLVM backend can convert to V_BFI.
1017 */
1018 result = LLVMBuildXor(ctx->builder, bfi_args[2],
1019 LLVMBuildAnd(ctx->builder, bfi_args[0],
1020 LLVMBuildXor(ctx->builder, bfi_args[1], bfi_args[2], ""), ""), "");
1021
1022 result = LLVMBuildSelect(ctx->builder, icond, src1, result, "");
1023 return result;
1024 }
1025
1026 static LLVMValueRef emit_pack_half_2x16(struct nir_to_llvm_context *ctx,
1027 LLVMValueRef src0)
1028 {
1029 LLVMValueRef const16 = LLVMConstInt(ctx->i32, 16, false);
1030 int i;
1031 LLVMValueRef comp[2];
1032
1033 src0 = to_float(ctx, src0);
1034 comp[0] = LLVMBuildExtractElement(ctx->builder, src0, ctx->i32zero, "");
1035 comp[1] = LLVMBuildExtractElement(ctx->builder, src0, ctx->i32one, "");
1036 for (i = 0; i < 2; i++) {
1037 comp[i] = LLVMBuildFPTrunc(ctx->builder, comp[i], ctx->f16, "");
1038 comp[i] = LLVMBuildBitCast(ctx->builder, comp[i], ctx->i16, "");
1039 comp[i] = LLVMBuildZExt(ctx->builder, comp[i], ctx->i32, "");
1040 }
1041
1042 comp[1] = LLVMBuildShl(ctx->builder, comp[1], const16, "");
1043 comp[0] = LLVMBuildOr(ctx->builder, comp[0], comp[1], "");
1044
1045 return comp[0];
1046 }
1047
1048 static LLVMValueRef emit_unpack_half_2x16(struct nir_to_llvm_context *ctx,
1049 LLVMValueRef src0)
1050 {
1051 LLVMValueRef const16 = LLVMConstInt(ctx->i32, 16, false);
1052 LLVMValueRef temps[2], result, val;
1053 int i;
1054
1055 for (i = 0; i < 2; i++) {
1056 val = i == 1 ? LLVMBuildLShr(ctx->builder, src0, const16, "") : src0;
1057 val = LLVMBuildTrunc(ctx->builder, val, ctx->i16, "");
1058 val = LLVMBuildBitCast(ctx->builder, val, ctx->f16, "");
1059 temps[i] = LLVMBuildFPExt(ctx->builder, val, ctx->f32, "");
1060 }
1061
1062 result = LLVMBuildInsertElement(ctx->builder, LLVMGetUndef(ctx->v2f32), temps[0],
1063 ctx->i32zero, "");
1064 result = LLVMBuildInsertElement(ctx->builder, result, temps[1],
1065 ctx->i32one, "");
1066 return result;
1067 }
1068
1069 /**
1070 * Set range metadata on an instruction. This can only be used on load and
1071 * call instructions. If you know an instruction can only produce the values
1072 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
1073 * \p lo is the minimum value inclusive.
1074 * \p hi is the maximum value exclusive.
1075 */
1076 static void set_range_metadata(struct nir_to_llvm_context *ctx,
1077 LLVMValueRef value, unsigned lo, unsigned hi)
1078 {
1079 LLVMValueRef range_md, md_args[2];
1080 LLVMTypeRef type = LLVMTypeOf(value);
1081 LLVMContextRef context = LLVMGetTypeContext(type);
1082
1083 md_args[0] = LLVMConstInt(type, lo, false);
1084 md_args[1] = LLVMConstInt(type, hi, false);
1085 range_md = LLVMMDNodeInContext(context, md_args, 2);
1086 LLVMSetMetadata(value, ctx->range_md_kind, range_md);
1087 }
1088
1089 static LLVMValueRef get_thread_id(struct nir_to_llvm_context *ctx)
1090 {
1091 LLVMValueRef tid;
1092 LLVMValueRef tid_args[2];
1093 tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
1094 tid_args[1] = ctx->i32zero;
1095 tid_args[1] = emit_llvm_intrinsic(ctx,
1096 "llvm.amdgcn.mbcnt.lo", ctx->i32,
1097 tid_args, 2, AC_FUNC_ATTR_READNONE);
1098
1099 tid = emit_llvm_intrinsic(ctx,
1100 "llvm.amdgcn.mbcnt.hi", ctx->i32,
1101 tid_args, 2, AC_FUNC_ATTR_READNONE);
1102 set_range_metadata(ctx, tid, 0, 64);
1103 return tid;
1104 }
1105
1106 /*
1107 * SI implements derivatives using the local data store (LDS)
1108 * All writes to the LDS happen in all executing threads at
1109 * the same time. TID is the Thread ID for the current
1110 * thread and is a value between 0 and 63, representing
1111 * the thread's position in the wavefront.
1112 *
1113 * For the pixel shader threads are grouped into quads of four pixels.
1114 * The TIDs of the pixels of a quad are:
1115 *
1116 * +------+------+
1117 * |4n + 0|4n + 1|
1118 * +------+------+
1119 * |4n + 2|4n + 3|
1120 * +------+------+
1121 *
1122 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
1123 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
1124 * the current pixel's column, and masking with 0xfffffffe yields the TID
1125 * of the left pixel of the current pixel's row.
1126 *
1127 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
1128 * adding 2 yields the TID of the pixel below the top pixel.
1129 */
1130 /* masks for thread ID. */
1131 #define TID_MASK_TOP_LEFT 0xfffffffc
1132 #define TID_MASK_TOP 0xfffffffd
1133 #define TID_MASK_LEFT 0xfffffffe
1134 static LLVMValueRef emit_ddxy(struct nir_to_llvm_context *ctx,
1135 nir_alu_instr *instr,
1136 LLVMValueRef src0)
1137 {
1138 LLVMValueRef indices[2];
1139 LLVMValueRef store_ptr, load_ptr0, load_ptr1;
1140 LLVMValueRef tl, trbl, result;
1141 LLVMValueRef tl_tid, trbl_tid;
1142 LLVMValueRef args[2];
1143 unsigned mask;
1144 int idx;
1145 ctx->has_ddxy = true;
1146 if (!ctx->lds)
1147 ctx->lds = LLVMAddGlobalInAddressSpace(ctx->module,
1148 LLVMArrayType(ctx->i32, 64),
1149 "ddxy_lds", LOCAL_ADDR_SPACE);
1150
1151 indices[0] = ctx->i32zero;
1152 indices[1] = get_thread_id(ctx);
1153 store_ptr = LLVMBuildGEP(ctx->builder, ctx->lds,
1154 indices, 2, "");
1155
1156 if (instr->op == nir_op_fddx_fine || instr->op == nir_op_fddx)
1157 mask = TID_MASK_LEFT;
1158 else if (instr->op == nir_op_fddy_fine || instr->op == nir_op_fddy)
1159 mask = TID_MASK_TOP;
1160 else
1161 mask = TID_MASK_TOP_LEFT;
1162
1163 tl_tid = LLVMBuildAnd(ctx->builder, indices[1],
1164 LLVMConstInt(ctx->i32, mask, false), "");
1165 indices[1] = tl_tid;
1166 load_ptr0 = LLVMBuildGEP(ctx->builder, ctx->lds,
1167 indices, 2, "");
1168
1169 /* for DDX we want to next X pixel, DDY next Y pixel. */
1170 if (instr->op == nir_op_fddx_fine ||
1171 instr->op == nir_op_fddx_coarse ||
1172 instr->op == nir_op_fddx)
1173 idx = 1;
1174 else
1175 idx = 2;
1176
1177 trbl_tid = LLVMBuildAdd(ctx->builder, indices[1],
1178 LLVMConstInt(ctx->i32, idx, false), "");
1179 indices[1] = trbl_tid;
1180 load_ptr1 = LLVMBuildGEP(ctx->builder, ctx->lds,
1181 indices, 2, "");
1182
1183 if (ctx->options->family >= CHIP_TONGA) {
1184 args[0] = LLVMBuildMul(ctx->builder, tl_tid,
1185 LLVMConstInt(ctx->i32, 4, false), "");
1186 args[1] = src0;
1187 tl = emit_llvm_intrinsic(ctx, "llvm.amdgcn.ds.bpermute",
1188 ctx->i32, args, 2,
1189 AC_FUNC_ATTR_READNONE);
1190
1191 args[0] = LLVMBuildMul(ctx->builder, trbl_tid,
1192 LLVMConstInt(ctx->i32, 4, false), "");
1193 trbl = emit_llvm_intrinsic(ctx, "llvm.amdgcn.ds.bpermute",
1194 ctx->i32, args, 2,
1195 AC_FUNC_ATTR_READNONE);
1196 } else {
1197 LLVMBuildStore(ctx->builder, src0, store_ptr);
1198
1199 tl = LLVMBuildLoad(ctx->builder, load_ptr0, "");
1200 trbl = LLVMBuildLoad(ctx->builder, load_ptr1, "");
1201 }
1202 tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
1203 trbl = LLVMBuildBitCast(ctx->builder, trbl, ctx->f32, "");
1204 result = LLVMBuildFSub(ctx->builder, trbl, tl, "");
1205 return result;
1206 }
1207
1208 /*
1209 * this takes an I,J coordinate pair,
1210 * and works out the X and Y derivatives.
1211 * it returns DDX(I), DDX(J), DDY(I), DDY(J).
1212 */
1213 static LLVMValueRef emit_ddxy_interp(
1214 struct nir_to_llvm_context *ctx,
1215 LLVMValueRef interp_ij)
1216 {
1217 LLVMValueRef indices[2];
1218 LLVMValueRef store_ptr, load_ptr_x, load_ptr_y, load_ptr_ddx, load_ptr_ddy, temp, temp2;
1219 LLVMValueRef tl, tr, bl, result[4];
1220 unsigned c;
1221
1222 if (!ctx->lds)
1223 ctx->lds = LLVMAddGlobalInAddressSpace(ctx->module,
1224 LLVMArrayType(ctx->i32, 64),
1225 "ddxy_lds", LOCAL_ADDR_SPACE);
1226
1227 indices[0] = ctx->i32zero;
1228 indices[1] = get_thread_id(ctx);
1229 store_ptr = LLVMBuildGEP(ctx->builder, ctx->lds,
1230 indices, 2, "");
1231
1232 temp = LLVMBuildAnd(ctx->builder, indices[1],
1233 LLVMConstInt(ctx->i32, TID_MASK_LEFT, false), "");
1234
1235 temp2 = LLVMBuildAnd(ctx->builder, indices[1],
1236 LLVMConstInt(ctx->i32, TID_MASK_TOP, false), "");
1237
1238 indices[1] = temp;
1239 load_ptr_x = LLVMBuildGEP(ctx->builder, ctx->lds,
1240 indices, 2, "");
1241
1242 indices[1] = temp2;
1243 load_ptr_y = LLVMBuildGEP(ctx->builder, ctx->lds,
1244 indices, 2, "");
1245
1246 indices[1] = LLVMBuildAdd(ctx->builder, temp,
1247 LLVMConstInt(ctx->i32, 1, false), "");
1248 load_ptr_ddx = LLVMBuildGEP(ctx->builder, ctx->lds,
1249 indices, 2, "");
1250
1251 indices[1] = LLVMBuildAdd(ctx->builder, temp2,
1252 LLVMConstInt(ctx->i32, 2, false), "");
1253 load_ptr_ddy = LLVMBuildGEP(ctx->builder, ctx->lds,
1254 indices, 2, "");
1255
1256 for (c = 0; c < 2; ++c) {
1257 LLVMValueRef store_val;
1258 LLVMValueRef c_ll = LLVMConstInt(ctx->i32, c, false);
1259
1260 store_val = LLVMBuildExtractElement(ctx->builder,
1261 interp_ij, c_ll, "");
1262 LLVMBuildStore(ctx->builder,
1263 store_val,
1264 store_ptr);
1265
1266 tl = LLVMBuildLoad(ctx->builder, load_ptr_x, "");
1267 tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
1268
1269 tr = LLVMBuildLoad(ctx->builder, load_ptr_ddx, "");
1270 tr = LLVMBuildBitCast(ctx->builder, tr, ctx->f32, "");
1271
1272 result[c] = LLVMBuildFSub(ctx->builder, tr, tl, "");
1273
1274 tl = LLVMBuildLoad(ctx->builder, load_ptr_y, "");
1275 tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
1276
1277 bl = LLVMBuildLoad(ctx->builder, load_ptr_ddy, "");
1278 bl = LLVMBuildBitCast(ctx->builder, bl, ctx->f32, "");
1279
1280 result[c + 2] = LLVMBuildFSub(ctx->builder, bl, tl, "");
1281 }
1282
1283 return build_gather_values(ctx, result, 4);
1284 }
1285
1286 static LLVMValueRef emit_fdiv(struct nir_to_llvm_context *ctx,
1287 LLVMValueRef num,
1288 LLVMValueRef den)
1289 {
1290 LLVMValueRef ret = LLVMBuildFDiv(ctx->builder, num, den, "");
1291
1292 if (!LLVMIsConstant(ret))
1293 LLVMSetMetadata(ret, ctx->fpmath_md_kind, ctx->fpmath_md_2p5_ulp);
1294 return ret;
1295 }
1296
1297 static void visit_alu(struct nir_to_llvm_context *ctx, nir_alu_instr *instr)
1298 {
1299 LLVMValueRef src[4], result = NULL;
1300 unsigned num_components = instr->dest.dest.ssa.num_components;
1301 unsigned src_components;
1302
1303 assert(nir_op_infos[instr->op].num_inputs <= ARRAY_SIZE(src));
1304 switch (instr->op) {
1305 case nir_op_vec2:
1306 case nir_op_vec3:
1307 case nir_op_vec4:
1308 src_components = 1;
1309 break;
1310 case nir_op_pack_half_2x16:
1311 src_components = 2;
1312 break;
1313 case nir_op_unpack_half_2x16:
1314 src_components = 1;
1315 break;
1316 default:
1317 src_components = num_components;
1318 break;
1319 }
1320 for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
1321 src[i] = get_alu_src(ctx, instr->src[i], src_components);
1322
1323 switch (instr->op) {
1324 case nir_op_fmov:
1325 case nir_op_imov:
1326 result = src[0];
1327 break;
1328 case nir_op_fneg:
1329 src[0] = to_float(ctx, src[0]);
1330 result = LLVMBuildFNeg(ctx->builder, src[0], "");
1331 break;
1332 case nir_op_ineg:
1333 result = LLVMBuildNeg(ctx->builder, src[0], "");
1334 break;
1335 case nir_op_inot:
1336 result = LLVMBuildNot(ctx->builder, src[0], "");
1337 break;
1338 case nir_op_iadd:
1339 result = LLVMBuildAdd(ctx->builder, src[0], src[1], "");
1340 break;
1341 case nir_op_fadd:
1342 src[0] = to_float(ctx, src[0]);
1343 src[1] = to_float(ctx, src[1]);
1344 result = LLVMBuildFAdd(ctx->builder, src[0], src[1], "");
1345 break;
1346 case nir_op_fsub:
1347 src[0] = to_float(ctx, src[0]);
1348 src[1] = to_float(ctx, src[1]);
1349 result = LLVMBuildFSub(ctx->builder, src[0], src[1], "");
1350 break;
1351 case nir_op_isub:
1352 result = LLVMBuildSub(ctx->builder, src[0], src[1], "");
1353 break;
1354 case nir_op_imul:
1355 result = LLVMBuildMul(ctx->builder, src[0], src[1], "");
1356 break;
1357 case nir_op_imod:
1358 result = LLVMBuildSRem(ctx->builder, src[0], src[1], "");
1359 break;
1360 case nir_op_umod:
1361 result = LLVMBuildURem(ctx->builder, src[0], src[1], "");
1362 break;
1363 case nir_op_fmod:
1364 src[0] = to_float(ctx, src[0]);
1365 src[1] = to_float(ctx, src[1]);
1366 result = emit_fdiv(ctx, src[0], src[1]);
1367 result = emit_intrin_1f_param(ctx, "llvm.floor.f32", result);
1368 result = LLVMBuildFMul(ctx->builder, src[1] , result, "");
1369 result = LLVMBuildFSub(ctx->builder, src[0], result, "");
1370 break;
1371 case nir_op_frem:
1372 src[0] = to_float(ctx, src[0]);
1373 src[1] = to_float(ctx, src[1]);
1374 result = LLVMBuildFRem(ctx->builder, src[0], src[1], "");
1375 break;
1376 case nir_op_idiv:
1377 result = LLVMBuildSDiv(ctx->builder, src[0], src[1], "");
1378 break;
1379 case nir_op_udiv:
1380 result = LLVMBuildUDiv(ctx->builder, src[0], src[1], "");
1381 break;
1382 case nir_op_fmul:
1383 src[0] = to_float(ctx, src[0]);
1384 src[1] = to_float(ctx, src[1]);
1385 result = LLVMBuildFMul(ctx->builder, src[0], src[1], "");
1386 break;
1387 case nir_op_fdiv:
1388 src[0] = to_float(ctx, src[0]);
1389 src[1] = to_float(ctx, src[1]);
1390 result = emit_fdiv(ctx, src[0], src[1]);
1391 break;
1392 case nir_op_frcp:
1393 src[0] = to_float(ctx, src[0]);
1394 result = emit_fdiv(ctx, ctx->f32one, src[0]);
1395 break;
1396 case nir_op_iand:
1397 result = LLVMBuildAnd(ctx->builder, src[0], src[1], "");
1398 break;
1399 case nir_op_ior:
1400 result = LLVMBuildOr(ctx->builder, src[0], src[1], "");
1401 break;
1402 case nir_op_ixor:
1403 result = LLVMBuildXor(ctx->builder, src[0], src[1], "");
1404 break;
1405 case nir_op_ishl:
1406 result = LLVMBuildShl(ctx->builder, src[0], src[1], "");
1407 break;
1408 case nir_op_ishr:
1409 result = LLVMBuildAShr(ctx->builder, src[0], src[1], "");
1410 break;
1411 case nir_op_ushr:
1412 result = LLVMBuildLShr(ctx->builder, src[0], src[1], "");
1413 break;
1414 case nir_op_ilt:
1415 result = emit_int_cmp(ctx, LLVMIntSLT, src[0], src[1]);
1416 break;
1417 case nir_op_ine:
1418 result = emit_int_cmp(ctx, LLVMIntNE, src[0], src[1]);
1419 break;
1420 case nir_op_ieq:
1421 result = emit_int_cmp(ctx, LLVMIntEQ, src[0], src[1]);
1422 break;
1423 case nir_op_ige:
1424 result = emit_int_cmp(ctx, LLVMIntSGE, src[0], src[1]);
1425 break;
1426 case nir_op_ult:
1427 result = emit_int_cmp(ctx, LLVMIntULT, src[0], src[1]);
1428 break;
1429 case nir_op_uge:
1430 result = emit_int_cmp(ctx, LLVMIntUGE, src[0], src[1]);
1431 break;
1432 case nir_op_feq:
1433 result = emit_float_cmp(ctx, LLVMRealUEQ, src[0], src[1]);
1434 break;
1435 case nir_op_fne:
1436 result = emit_float_cmp(ctx, LLVMRealUNE, src[0], src[1]);
1437 break;
1438 case nir_op_flt:
1439 result = emit_float_cmp(ctx, LLVMRealULT, src[0], src[1]);
1440 break;
1441 case nir_op_fge:
1442 result = emit_float_cmp(ctx, LLVMRealUGE, src[0], src[1]);
1443 break;
1444 case nir_op_fabs:
1445 result = emit_intrin_1f_param(ctx, "llvm.fabs.f32", src[0]);
1446 break;
1447 case nir_op_iabs:
1448 result = emit_iabs(ctx, src[0]);
1449 break;
1450 case nir_op_imax:
1451 result = emit_minmax_int(ctx, LLVMIntSGT, src[0], src[1]);
1452 break;
1453 case nir_op_imin:
1454 result = emit_minmax_int(ctx, LLVMIntSLT, src[0], src[1]);
1455 break;
1456 case nir_op_umax:
1457 result = emit_minmax_int(ctx, LLVMIntUGT, src[0], src[1]);
1458 break;
1459 case nir_op_umin:
1460 result = emit_minmax_int(ctx, LLVMIntULT, src[0], src[1]);
1461 break;
1462 case nir_op_isign:
1463 result = emit_isign(ctx, src[0]);
1464 break;
1465 case nir_op_fsign:
1466 src[0] = to_float(ctx, src[0]);
1467 result = emit_fsign(ctx, src[0]);
1468 break;
1469 case nir_op_ffloor:
1470 result = emit_intrin_1f_param(ctx, "llvm.floor.f32", src[0]);
1471 break;
1472 case nir_op_ftrunc:
1473 result = emit_intrin_1f_param(ctx, "llvm.trunc.f32", src[0]);
1474 break;
1475 case nir_op_fceil:
1476 result = emit_intrin_1f_param(ctx, "llvm.ceil.f32", src[0]);
1477 break;
1478 case nir_op_fround_even:
1479 result = emit_intrin_1f_param(ctx, "llvm.rint.f32", src[0]);
1480 break;
1481 case nir_op_ffract:
1482 result = emit_ffract(ctx, src[0]);
1483 break;
1484 case nir_op_fsin:
1485 result = emit_intrin_1f_param(ctx, "llvm.sin.f32", src[0]);
1486 break;
1487 case nir_op_fcos:
1488 result = emit_intrin_1f_param(ctx, "llvm.cos.f32", src[0]);
1489 break;
1490 case nir_op_fsqrt:
1491 result = emit_intrin_1f_param(ctx, "llvm.sqrt.f32", src[0]);
1492 break;
1493 case nir_op_fexp2:
1494 result = emit_intrin_1f_param(ctx, "llvm.exp2.f32", src[0]);
1495 break;
1496 case nir_op_flog2:
1497 result = emit_intrin_1f_param(ctx, "llvm.log2.f32", src[0]);
1498 break;
1499 case nir_op_frsq:
1500 result = emit_intrin_1f_param(ctx, "llvm.sqrt.f32", src[0]);
1501 result = emit_fdiv(ctx, ctx->f32one, result);
1502 break;
1503 case nir_op_fpow:
1504 result = emit_intrin_2f_param(ctx, "llvm.pow.f32", src[0], src[1]);
1505 break;
1506 case nir_op_fmax:
1507 result = emit_intrin_2f_param(ctx, "llvm.maxnum.f32", src[0], src[1]);
1508 break;
1509 case nir_op_fmin:
1510 result = emit_intrin_2f_param(ctx, "llvm.minnum.f32", src[0], src[1]);
1511 break;
1512 case nir_op_ffma:
1513 result = emit_intrin_3f_param(ctx, "llvm.fma.f32", src[0], src[1], src[2]);
1514 break;
1515 case nir_op_ibitfield_extract:
1516 result = emit_bitfield_extract(ctx, "llvm.AMDGPU.bfe.i32", src);
1517 break;
1518 case nir_op_ubitfield_extract:
1519 result = emit_bitfield_extract(ctx, "llvm.AMDGPU.bfe.u32", src);
1520 break;
1521 case nir_op_bitfield_insert:
1522 result = emit_bitfield_insert(ctx, src[0], src[1], src[2], src[3]);
1523 break;
1524 case nir_op_bitfield_reverse:
1525 result = emit_llvm_intrinsic(ctx, "llvm.bitreverse.i32", ctx->i32, src, 1, AC_FUNC_ATTR_READNONE);
1526 break;
1527 case nir_op_bit_count:
1528 result = emit_llvm_intrinsic(ctx, "llvm.ctpop.i32", ctx->i32, src, 1, AC_FUNC_ATTR_READNONE);
1529 break;
1530 case nir_op_vec2:
1531 case nir_op_vec3:
1532 case nir_op_vec4:
1533 for (unsigned i = 0; i < nir_op_infos[instr->op].num_inputs; i++)
1534 src[i] = to_integer(ctx, src[i]);
1535 result = build_gather_values(ctx, src, num_components);
1536 break;
1537 case nir_op_f2i:
1538 src[0] = to_float(ctx, src[0]);
1539 result = LLVMBuildFPToSI(ctx->builder, src[0], ctx->i32, "");
1540 break;
1541 case nir_op_f2u:
1542 src[0] = to_float(ctx, src[0]);
1543 result = LLVMBuildFPToUI(ctx->builder, src[0], ctx->i32, "");
1544 break;
1545 case nir_op_i2f:
1546 result = LLVMBuildSIToFP(ctx->builder, src[0], ctx->f32, "");
1547 break;
1548 case nir_op_u2f:
1549 result = LLVMBuildUIToFP(ctx->builder, src[0], ctx->f32, "");
1550 break;
1551 case nir_op_bcsel:
1552 result = emit_bcsel(ctx, src[0], src[1], src[2]);
1553 break;
1554 case nir_op_find_lsb:
1555 result = emit_find_lsb(ctx, src[0]);
1556 break;
1557 case nir_op_ufind_msb:
1558 result = emit_ufind_msb(ctx, src[0]);
1559 break;
1560 case nir_op_ifind_msb:
1561 result = emit_ifind_msb(ctx, src[0]);
1562 break;
1563 case nir_op_uadd_carry:
1564 result = emit_uint_carry(ctx, "llvm.uadd.with.overflow.i32", src[0], src[1]);
1565 break;
1566 case nir_op_usub_borrow:
1567 result = emit_uint_carry(ctx, "llvm.usub.with.overflow.i32", src[0], src[1]);
1568 break;
1569 case nir_op_b2f:
1570 result = emit_b2f(ctx, src[0]);
1571 break;
1572 case nir_op_fquantize2f16:
1573 src[0] = to_float(ctx, src[0]);
1574 result = LLVMBuildFPTrunc(ctx->builder, src[0], ctx->f16, "");
1575 /* need to convert back up to f32 */
1576 result = LLVMBuildFPExt(ctx->builder, result, ctx->f32, "");
1577 break;
1578 case nir_op_umul_high:
1579 result = emit_umul_high(ctx, src[0], src[1]);
1580 break;
1581 case nir_op_imul_high:
1582 result = emit_imul_high(ctx, src[0], src[1]);
1583 break;
1584 case nir_op_pack_half_2x16:
1585 result = emit_pack_half_2x16(ctx, src[0]);
1586 break;
1587 case nir_op_unpack_half_2x16:
1588 result = emit_unpack_half_2x16(ctx, src[0]);
1589 break;
1590 case nir_op_fddx:
1591 case nir_op_fddy:
1592 case nir_op_fddx_fine:
1593 case nir_op_fddy_fine:
1594 case nir_op_fddx_coarse:
1595 case nir_op_fddy_coarse:
1596 result = emit_ddxy(ctx, instr, src[0]);
1597 break;
1598 default:
1599 fprintf(stderr, "Unknown NIR alu instr: ");
1600 nir_print_instr(&instr->instr, stderr);
1601 fprintf(stderr, "\n");
1602 abort();
1603 }
1604
1605 if (result) {
1606 assert(instr->dest.dest.is_ssa);
1607 result = to_integer(ctx, result);
1608 _mesa_hash_table_insert(ctx->defs, &instr->dest.dest.ssa,
1609 result);
1610 }
1611 }
1612
1613 static void visit_load_const(struct nir_to_llvm_context *ctx,
1614 nir_load_const_instr *instr)
1615 {
1616 LLVMValueRef values[4], value = NULL;
1617 LLVMTypeRef element_type =
1618 LLVMIntTypeInContext(ctx->context, instr->def.bit_size);
1619
1620 for (unsigned i = 0; i < instr->def.num_components; ++i) {
1621 switch (instr->def.bit_size) {
1622 case 32:
1623 values[i] = LLVMConstInt(element_type,
1624 instr->value.u32[i], false);
1625 break;
1626 case 64:
1627 values[i] = LLVMConstInt(element_type,
1628 instr->value.u64[i], false);
1629 break;
1630 default:
1631 fprintf(stderr,
1632 "unsupported nir load_const bit_size: %d\n",
1633 instr->def.bit_size);
1634 abort();
1635 }
1636 }
1637 if (instr->def.num_components > 1) {
1638 value = LLVMConstVector(values, instr->def.num_components);
1639 } else
1640 value = values[0];
1641
1642 _mesa_hash_table_insert(ctx->defs, &instr->def, value);
1643 }
1644
1645 static LLVMValueRef cast_ptr(struct nir_to_llvm_context *ctx, LLVMValueRef ptr,
1646 LLVMTypeRef type)
1647 {
1648 int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
1649 return LLVMBuildBitCast(ctx->builder, ptr,
1650 LLVMPointerType(type, addr_space), "");
1651 }
1652
1653 static LLVMValueRef
1654 emit_llvm_intrinsic(struct nir_to_llvm_context *ctx, const char *name,
1655 LLVMTypeRef return_type, LLVMValueRef *params,
1656 unsigned param_count, unsigned attrib_mask)
1657 {
1658 LLVMValueRef function;
1659
1660 function = LLVMGetNamedFunction(ctx->module, name);
1661 if (!function) {
1662 LLVMTypeRef param_types[32], function_type;
1663 unsigned i;
1664
1665 assert(param_count <= 32);
1666
1667 for (i = 0; i < param_count; ++i) {
1668 assert(params[i]);
1669 param_types[i] = LLVMTypeOf(params[i]);
1670 }
1671 function_type =
1672 LLVMFunctionType(return_type, param_types, param_count, 0);
1673 function = LLVMAddFunction(ctx->module, name, function_type);
1674
1675 LLVMSetFunctionCallConv(function, LLVMCCallConv);
1676 LLVMSetLinkage(function, LLVMExternalLinkage);
1677
1678 attrib_mask |= AC_FUNC_ATTR_NOUNWIND;
1679 while (attrib_mask) {
1680 enum ac_func_attr attr = 1u << u_bit_scan(&attrib_mask);
1681 ac_add_function_attr(function, -1, attr);
1682 }
1683 }
1684 return LLVMBuildCall(ctx->builder, function, params, param_count, "");
1685 }
1686
1687 static LLVMValueRef
1688 get_buffer_size(struct nir_to_llvm_context *ctx, LLVMValueRef descriptor, bool in_elements)
1689 {
1690 LLVMValueRef size =
1691 LLVMBuildExtractElement(ctx->builder, descriptor,
1692 LLVMConstInt(ctx->i32, 2, false), "");
1693
1694 /* VI only */
1695 if (ctx->options->chip_class >= VI && in_elements) {
1696 /* On VI, the descriptor contains the size in bytes,
1697 * but TXQ must return the size in elements.
1698 * The stride is always non-zero for resources using TXQ.
1699 */
1700 LLVMValueRef stride =
1701 LLVMBuildExtractElement(ctx->builder, descriptor,
1702 LLVMConstInt(ctx->i32, 1, false), "");
1703 stride = LLVMBuildLShr(ctx->builder, stride,
1704 LLVMConstInt(ctx->i32, 16, false), "");
1705 stride = LLVMBuildAnd(ctx->builder, stride,
1706 LLVMConstInt(ctx->i32, 0x3fff, false), "");
1707
1708 size = LLVMBuildUDiv(ctx->builder, size, stride, "");
1709 }
1710 return size;
1711 }
1712
1713 /**
1714 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
1715 * intrinsic names).
1716 */
1717 static void build_int_type_name(
1718 LLVMTypeRef type,
1719 char *buf, unsigned bufsize)
1720 {
1721 assert(bufsize >= 6);
1722
1723 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
1724 snprintf(buf, bufsize, "v%ui32",
1725 LLVMGetVectorSize(type));
1726 else
1727 strcpy(buf, "i32");
1728 }
1729
1730 static LLVMValueRef radv_lower_gather4_integer(struct nir_to_llvm_context *ctx,
1731 struct ac_tex_info *tinfo,
1732 nir_tex_instr *instr,
1733 const char *intr_name,
1734 unsigned coord_vgpr_index)
1735 {
1736 LLVMValueRef coord = tinfo->args[0];
1737 LLVMValueRef half_texel[2];
1738 int c;
1739
1740 //TODO Rect
1741 {
1742 LLVMValueRef txq_args[10];
1743 int txq_arg_count = 0;
1744 LLVMValueRef size;
1745 bool da = instr->is_array || instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE;
1746 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, 0, false);
1747 txq_args[txq_arg_count++] = tinfo->args[1];
1748 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, 0xf, 0); /* dmask */
1749 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, 0, 0); /* unorm */
1750 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, 0, 0); /* r128 */
1751 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, da ? 1 : 0, 0);
1752 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, 0, 0); /* glc */
1753 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, 0, 0); /* slc */
1754 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, 0, 0); /* tfe */
1755 txq_args[txq_arg_count++] = LLVMConstInt(ctx->i32, 0, 0); /* lwe */
1756 size = emit_llvm_intrinsic(ctx, "llvm.SI.getresinfo.i32", ctx->v4i32,
1757 txq_args, txq_arg_count,
1758 AC_FUNC_ATTR_READNONE);
1759
1760 for (c = 0; c < 2; c++) {
1761 half_texel[c] = LLVMBuildExtractElement(ctx->builder, size,
1762 LLVMConstInt(ctx->i32, c, false), "");
1763 half_texel[c] = LLVMBuildUIToFP(ctx->builder, half_texel[c], ctx->f32, "");
1764 half_texel[c] = emit_fdiv(ctx, ctx->f32one, half_texel[c]);
1765 half_texel[c] = LLVMBuildFMul(ctx->builder, half_texel[c],
1766 LLVMConstReal(ctx->f32, -0.5), "");
1767 }
1768 }
1769
1770 for (c = 0; c < 2; c++) {
1771 LLVMValueRef tmp;
1772 LLVMValueRef index = LLVMConstInt(ctx->i32, coord_vgpr_index + c, 0);
1773 tmp = LLVMBuildExtractElement(ctx->builder, coord, index, "");
1774 tmp = LLVMBuildBitCast(ctx->builder, tmp, ctx->f32, "");
1775 tmp = LLVMBuildFAdd(ctx->builder, tmp, half_texel[c], "");
1776 tmp = LLVMBuildBitCast(ctx->builder, tmp, ctx->i32, "");
1777 coord = LLVMBuildInsertElement(ctx->builder, coord, tmp, index, "");
1778 }
1779
1780 tinfo->args[0] = coord;
1781 return emit_llvm_intrinsic(ctx, intr_name, tinfo->dst_type, tinfo->args, tinfo->arg_count,
1782 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_NOUNWIND);
1783
1784 }
1785
1786 static LLVMValueRef build_tex_intrinsic(struct nir_to_llvm_context *ctx,
1787 nir_tex_instr *instr,
1788 struct ac_tex_info *tinfo)
1789 {
1790 const char *name = "llvm.SI.image.sample";
1791 const char *infix = "";
1792 char intr_name[127];
1793 char type[64];
1794 bool is_shadow = instr->is_shadow;
1795 bool has_offset = tinfo->has_offset;
1796 switch (instr->op) {
1797 case nir_texop_txf:
1798 case nir_texop_txf_ms:
1799 case nir_texop_samples_identical:
1800 name = instr->sampler_dim == GLSL_SAMPLER_DIM_MS ? "llvm.SI.image.load" :
1801 instr->sampler_dim == GLSL_SAMPLER_DIM_BUF ? "llvm.SI.vs.load.input" :
1802 "llvm.SI.image.load.mip";
1803 is_shadow = false;
1804 has_offset = false;
1805 break;
1806 case nir_texop_txb:
1807 infix = ".b";
1808 break;
1809 case nir_texop_txl:
1810 infix = ".l";
1811 break;
1812 case nir_texop_txs:
1813 name = "llvm.SI.getresinfo";
1814 break;
1815 case nir_texop_query_levels:
1816 name = "llvm.SI.getresinfo";
1817 break;
1818 case nir_texop_tex:
1819 if (ctx->stage != MESA_SHADER_FRAGMENT)
1820 infix = ".lz";
1821 break;
1822 case nir_texop_txd:
1823 infix = ".d";
1824 break;
1825 case nir_texop_tg4:
1826 name = "llvm.SI.gather4";
1827 infix = ".lz";
1828 break;
1829 case nir_texop_lod:
1830 name = "llvm.SI.getlod";
1831 is_shadow = false;
1832 has_offset = false;
1833 break;
1834 default:
1835 break;
1836 }
1837
1838 build_int_type_name(LLVMTypeOf(tinfo->args[0]), type, sizeof(type));
1839 sprintf(intr_name, "%s%s%s%s.%s", name, is_shadow ? ".c" : "", infix,
1840 has_offset ? ".o" : "", type);
1841
1842 if (instr->op == nir_texop_tg4) {
1843 enum glsl_base_type stype = glsl_get_sampler_result_type(instr->texture->var->type);
1844 if (stype == GLSL_TYPE_UINT || stype == GLSL_TYPE_INT) {
1845 return radv_lower_gather4_integer(ctx, tinfo, instr, intr_name,
1846 (int)has_offset + (int)is_shadow);
1847 }
1848 }
1849 return emit_llvm_intrinsic(ctx, intr_name, tinfo->dst_type, tinfo->args, tinfo->arg_count,
1850 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_NOUNWIND);
1851
1852 }
1853
1854 static LLVMValueRef visit_vulkan_resource_index(struct nir_to_llvm_context *ctx,
1855 nir_intrinsic_instr *instr)
1856 {
1857 LLVMValueRef index = get_src(ctx, instr->src[0]);
1858 unsigned desc_set = nir_intrinsic_desc_set(instr);
1859 unsigned binding = nir_intrinsic_binding(instr);
1860 LLVMValueRef desc_ptr = ctx->descriptor_sets[desc_set];
1861 struct radv_descriptor_set_layout *layout = ctx->options->layout->set[desc_set].layout;
1862 unsigned base_offset = layout->binding[binding].offset;
1863 LLVMValueRef offset, stride;
1864
1865 if (layout->binding[binding].type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC ||
1866 layout->binding[binding].type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
1867 desc_ptr = ctx->push_constants;
1868 base_offset = ctx->options->layout->push_constant_size;
1869 base_offset += 16 * layout->binding[binding].dynamic_offset_offset;
1870 stride = LLVMConstInt(ctx->i32, 16, false);
1871 } else
1872 stride = LLVMConstInt(ctx->i32, layout->binding[binding].size, false);
1873
1874 offset = LLVMConstInt(ctx->i32, base_offset, false);
1875 index = LLVMBuildMul(ctx->builder, index, stride, "");
1876 offset = LLVMBuildAdd(ctx->builder, offset, index, "");
1877
1878 LLVMValueRef indices[] = {ctx->i32zero, offset};
1879 desc_ptr = LLVMBuildGEP(ctx->builder, desc_ptr, indices, 2, "");
1880 desc_ptr = cast_ptr(ctx, desc_ptr, ctx->v4i32);
1881 LLVMSetMetadata(desc_ptr, ctx->uniform_md_kind, ctx->empty_md);
1882
1883 return LLVMBuildLoad(ctx->builder, desc_ptr, "");
1884 }
1885
1886 static LLVMValueRef visit_load_push_constant(struct nir_to_llvm_context *ctx,
1887 nir_intrinsic_instr *instr)
1888 {
1889 LLVMValueRef ptr;
1890
1891 LLVMValueRef indices[] = {ctx->i32zero, get_src(ctx, instr->src[0])};
1892 ptr = LLVMBuildGEP(ctx->builder, ctx->push_constants, indices, 2, "");
1893 ptr = cast_ptr(ctx, ptr, get_def_type(ctx, &instr->dest.ssa));
1894
1895 return LLVMBuildLoad(ctx->builder, ptr, "");
1896 }
1897
1898 static LLVMValueRef visit_get_buffer_size(struct nir_to_llvm_context *ctx,
1899 nir_intrinsic_instr *instr)
1900 {
1901 LLVMValueRef desc = get_src(ctx, instr->src[0]);
1902
1903 return get_buffer_size(ctx, desc, false);
1904 }
1905 static void visit_store_ssbo(struct nir_to_llvm_context *ctx,
1906 nir_intrinsic_instr *instr)
1907 {
1908 const char *store_name;
1909 LLVMTypeRef data_type = ctx->f32;
1910 unsigned writemask = nir_intrinsic_write_mask(instr);
1911 LLVMValueRef base_data, base_offset;
1912 LLVMValueRef params[6];
1913
1914 if (ctx->stage == MESA_SHADER_FRAGMENT)
1915 ctx->shader_info->fs.writes_memory = true;
1916
1917 params[1] = get_src(ctx, instr->src[1]);
1918 params[2] = LLVMConstInt(ctx->i32, 0, false); /* vindex */
1919 params[4] = LLVMConstInt(ctx->i1, 0, false); /* glc */
1920 params[5] = LLVMConstInt(ctx->i1, 0, false); /* slc */
1921
1922 if (instr->num_components > 1)
1923 data_type = LLVMVectorType(ctx->f32, instr->num_components);
1924
1925 base_data = to_float(ctx, get_src(ctx, instr->src[0]));
1926 base_data = trim_vector(ctx, base_data, instr->num_components);
1927 base_data = LLVMBuildBitCast(ctx->builder, base_data,
1928 data_type, "");
1929 base_offset = get_src(ctx, instr->src[2]); /* voffset */
1930 while (writemask) {
1931 int start, count;
1932 LLVMValueRef data;
1933 LLVMValueRef offset;
1934 LLVMValueRef tmp;
1935 u_bit_scan_consecutive_range(&writemask, &start, &count);
1936
1937 /* Due to an LLVM limitation, split 3-element writes
1938 * into a 2-element and a 1-element write. */
1939 if (count == 3) {
1940 writemask |= 1 << (start + 2);
1941 count = 2;
1942 }
1943
1944 if (count == 4) {
1945 store_name = "llvm.amdgcn.buffer.store.v4f32";
1946 data = base_data;
1947 } else if (count == 2) {
1948 tmp = LLVMBuildExtractElement(ctx->builder,
1949 base_data, LLVMConstInt(ctx->i32, start, false), "");
1950 data = LLVMBuildInsertElement(ctx->builder, LLVMGetUndef(ctx->v2f32), tmp,
1951 ctx->i32zero, "");
1952
1953 tmp = LLVMBuildExtractElement(ctx->builder,
1954 base_data, LLVMConstInt(ctx->i32, start + 1, false), "");
1955 data = LLVMBuildInsertElement(ctx->builder, data, tmp,
1956 ctx->i32one, "");
1957 store_name = "llvm.amdgcn.buffer.store.v2f32";
1958
1959 } else {
1960 assert(count == 1);
1961 if (get_llvm_num_components(base_data) > 1)
1962 data = LLVMBuildExtractElement(ctx->builder, base_data,
1963 LLVMConstInt(ctx->i32, start, false), "");
1964 else
1965 data = base_data;
1966 store_name = "llvm.amdgcn.buffer.store.f32";
1967 }
1968
1969 offset = base_offset;
1970 if (start != 0) {
1971 offset = LLVMBuildAdd(ctx->builder, offset, LLVMConstInt(ctx->i32, start * 4, false), "");
1972 }
1973 params[0] = data;
1974 params[3] = offset;
1975 emit_llvm_intrinsic(ctx, store_name,
1976 LLVMVoidTypeInContext(ctx->context), params, 6, 0);
1977 }
1978 }
1979
1980 static LLVMValueRef visit_atomic_ssbo(struct nir_to_llvm_context *ctx,
1981 nir_intrinsic_instr *instr)
1982 {
1983 const char *name;
1984 LLVMValueRef params[5];
1985 int arg_count = 0;
1986 if (ctx->stage == MESA_SHADER_FRAGMENT)
1987 ctx->shader_info->fs.writes_memory = true;
1988
1989 if (instr->intrinsic == nir_intrinsic_ssbo_atomic_comp_swap) {
1990 params[arg_count++] = get_src(ctx, instr->src[3]);
1991 }
1992 params[arg_count++] = get_src(ctx, instr->src[2]);
1993 params[arg_count++] = get_src(ctx, instr->src[0]);
1994 params[arg_count++] = LLVMConstInt(ctx->i32, 0, false); /* vindex */
1995 params[arg_count++] = get_src(ctx, instr->src[1]); /* voffset */
1996 params[arg_count++] = LLVMConstInt(ctx->i1, 0, false); /* slc */
1997
1998 switch (instr->intrinsic) {
1999 case nir_intrinsic_ssbo_atomic_add:
2000 name = "llvm.amdgcn.buffer.atomic.add";
2001 break;
2002 case nir_intrinsic_ssbo_atomic_imin:
2003 name = "llvm.amdgcn.buffer.atomic.smin";
2004 break;
2005 case nir_intrinsic_ssbo_atomic_umin:
2006 name = "llvm.amdgcn.buffer.atomic.umin";
2007 break;
2008 case nir_intrinsic_ssbo_atomic_imax:
2009 name = "llvm.amdgcn.buffer.atomic.smax";
2010 break;
2011 case nir_intrinsic_ssbo_atomic_umax:
2012 name = "llvm.amdgcn.buffer.atomic.umax";
2013 break;
2014 case nir_intrinsic_ssbo_atomic_and:
2015 name = "llvm.amdgcn.buffer.atomic.and";
2016 break;
2017 case nir_intrinsic_ssbo_atomic_or:
2018 name = "llvm.amdgcn.buffer.atomic.or";
2019 break;
2020 case nir_intrinsic_ssbo_atomic_xor:
2021 name = "llvm.amdgcn.buffer.atomic.xor";
2022 break;
2023 case nir_intrinsic_ssbo_atomic_exchange:
2024 name = "llvm.amdgcn.buffer.atomic.swap";
2025 break;
2026 case nir_intrinsic_ssbo_atomic_comp_swap:
2027 name = "llvm.amdgcn.buffer.atomic.cmpswap";
2028 break;
2029 default:
2030 abort();
2031 }
2032
2033 return emit_llvm_intrinsic(ctx, name, ctx->i32, params, arg_count, 0);
2034 }
2035
2036 static LLVMValueRef visit_load_buffer(struct nir_to_llvm_context *ctx,
2037 nir_intrinsic_instr *instr)
2038 {
2039 const char *load_name;
2040 LLVMTypeRef data_type = ctx->f32;
2041 if (instr->num_components == 3)
2042 data_type = LLVMVectorType(ctx->f32, 4);
2043 else if (instr->num_components > 1)
2044 data_type = LLVMVectorType(ctx->f32, instr->num_components);
2045
2046 if (instr->num_components == 4 || instr->num_components == 3)
2047 load_name = "llvm.amdgcn.buffer.load.v4f32";
2048 else if (instr->num_components == 2)
2049 load_name = "llvm.amdgcn.buffer.load.v2f32";
2050 else if (instr->num_components == 1)
2051 load_name = "llvm.amdgcn.buffer.load.f32";
2052 else
2053 abort();
2054
2055 LLVMValueRef params[] = {
2056 get_src(ctx, instr->src[0]),
2057 LLVMConstInt(ctx->i32, 0, false),
2058 get_src(ctx, instr->src[1]),
2059 LLVMConstInt(ctx->i1, 0, false),
2060 LLVMConstInt(ctx->i1, 0, false),
2061 };
2062
2063 LLVMValueRef ret =
2064 emit_llvm_intrinsic(ctx, load_name, data_type, params, 5, 0);
2065
2066 if (instr->num_components == 3)
2067 ret = trim_vector(ctx, ret, 3);
2068
2069 return LLVMBuildBitCast(ctx->builder, ret,
2070 get_def_type(ctx, &instr->dest.ssa), "");
2071 }
2072
2073 static void
2074 radv_get_deref_offset(struct nir_to_llvm_context *ctx, nir_deref *tail,
2075 bool vs_in, unsigned *const_out, LLVMValueRef *indir_out)
2076 {
2077 unsigned const_offset = 0;
2078 LLVMValueRef offset = NULL;
2079
2080
2081 while (tail->child != NULL) {
2082 const struct glsl_type *parent_type = tail->type;
2083 tail = tail->child;
2084
2085 if (tail->deref_type == nir_deref_type_array) {
2086 nir_deref_array *deref_array = nir_deref_as_array(tail);
2087 LLVMValueRef index, stride, local_offset;
2088 unsigned size = glsl_count_attribute_slots(tail->type, vs_in);
2089
2090 const_offset += size * deref_array->base_offset;
2091 if (deref_array->deref_array_type == nir_deref_array_type_direct)
2092 continue;
2093
2094 assert(deref_array->deref_array_type == nir_deref_array_type_indirect);
2095 index = get_src(ctx, deref_array->indirect);
2096 stride = LLVMConstInt(ctx->i32, size, 0);
2097 local_offset = LLVMBuildMul(ctx->builder, stride, index, "");
2098
2099 if (offset)
2100 offset = LLVMBuildAdd(ctx->builder, offset, local_offset, "");
2101 else
2102 offset = local_offset;
2103 } else if (tail->deref_type == nir_deref_type_struct) {
2104 nir_deref_struct *deref_struct = nir_deref_as_struct(tail);
2105
2106 for (unsigned i = 0; i < deref_struct->index; i++) {
2107 const struct glsl_type *ft = glsl_get_struct_field(parent_type, i);
2108 const_offset += glsl_count_attribute_slots(ft, vs_in);
2109 }
2110 } else
2111 unreachable("unsupported deref type");
2112
2113 }
2114
2115 if (const_offset && offset)
2116 offset = LLVMBuildAdd(ctx->builder, offset,
2117 LLVMConstInt(ctx->i32, const_offset, 0),
2118 "");
2119
2120 *const_out = const_offset;
2121 *indir_out = offset;
2122 }
2123
2124 static LLVMValueRef visit_load_var(struct nir_to_llvm_context *ctx,
2125 nir_intrinsic_instr *instr)
2126 {
2127 LLVMValueRef values[4];
2128 int idx = instr->variables[0]->var->data.driver_location;
2129 int ve = instr->dest.ssa.num_components;
2130 LLVMValueRef indir_index;
2131 unsigned const_index;
2132 switch (instr->variables[0]->var->data.mode) {
2133 case nir_var_shader_in:
2134 radv_get_deref_offset(ctx, &instr->variables[0]->deref,
2135 ctx->stage == MESA_SHADER_VERTEX,
2136 &const_index, &indir_index);
2137 for (unsigned chan = 0; chan < ve; chan++) {
2138 if (indir_index) {
2139 unsigned count = glsl_count_attribute_slots(
2140 instr->variables[0]->var->type,
2141 ctx->stage == MESA_SHADER_VERTEX);
2142 LLVMValueRef tmp_vec = build_gather_values_extended(
2143 ctx, ctx->inputs + idx + chan, count,
2144 4, false);
2145
2146 values[chan] = LLVMBuildExtractElement(ctx->builder,
2147 tmp_vec,
2148 indir_index, "");
2149 } else
2150 values[chan] = ctx->inputs[idx + chan + const_index * 4];
2151 }
2152 return to_integer(ctx, build_gather_values(ctx, values, ve));
2153 break;
2154 case nir_var_local:
2155 radv_get_deref_offset(ctx, &instr->variables[0]->deref, false,
2156 &const_index, &indir_index);
2157 for (unsigned chan = 0; chan < ve; chan++) {
2158 if (indir_index) {
2159 unsigned count = glsl_count_attribute_slots(
2160 instr->variables[0]->var->type, false);
2161 LLVMValueRef tmp_vec = build_gather_values_extended(
2162 ctx, ctx->locals + idx + chan, count,
2163 4, true);
2164
2165 values[chan] = LLVMBuildExtractElement(ctx->builder,
2166 tmp_vec,
2167 indir_index, "");
2168 } else {
2169 values[chan] = LLVMBuildLoad(ctx->builder, ctx->locals[idx + chan + const_index * 4], "");
2170 }
2171 }
2172 return to_integer(ctx, build_gather_values(ctx, values, ve));
2173 case nir_var_shader_out:
2174 radv_get_deref_offset(ctx, &instr->variables[0]->deref, false,
2175 &const_index, &indir_index);
2176 for (unsigned chan = 0; chan < ve; chan++) {
2177 if (indir_index) {
2178 unsigned count = glsl_count_attribute_slots(
2179 instr->variables[0]->var->type, false);
2180 LLVMValueRef tmp_vec = build_gather_values_extended(
2181 ctx, ctx->outputs + idx + chan, count,
2182 4, true);
2183
2184 values[chan] = LLVMBuildExtractElement(ctx->builder,
2185 tmp_vec,
2186 indir_index, "");
2187 } else {
2188 values[chan] = LLVMBuildLoad(ctx->builder,
2189 ctx->outputs[idx + chan + const_index * 4],
2190 "");
2191 }
2192 }
2193 return to_integer(ctx, build_gather_values(ctx, values, ve));
2194 case nir_var_shared: {
2195 radv_get_deref_offset(ctx, &instr->variables[0]->deref, false,
2196 &const_index, &indir_index);
2197 LLVMValueRef ptr = get_shared_memory_ptr(ctx, idx, ctx->i32);
2198 LLVMValueRef derived_ptr;
2199 LLVMValueRef index = ctx->i32zero;
2200 if (indir_index)
2201 index = LLVMBuildAdd(ctx->builder, index, indir_index, "");
2202 derived_ptr = LLVMBuildGEP(ctx->builder, ptr, &index, 1, "");
2203
2204 return to_integer(ctx, LLVMBuildLoad(ctx->builder, derived_ptr, ""));
2205 break;
2206 }
2207 default:
2208 break;
2209 }
2210 return NULL;
2211 }
2212
2213 static void
2214 visit_store_var(struct nir_to_llvm_context *ctx,
2215 nir_intrinsic_instr *instr)
2216 {
2217 LLVMValueRef temp_ptr, value;
2218 int idx = instr->variables[0]->var->data.driver_location;
2219 LLVMValueRef src = to_float(ctx, get_src(ctx, instr->src[0]));
2220 int writemask = instr->const_index[0];
2221 LLVMValueRef indir_index;
2222 unsigned const_index;
2223 switch (instr->variables[0]->var->data.mode) {
2224 case nir_var_shader_out:
2225 radv_get_deref_offset(ctx, &instr->variables[0]->deref, false,
2226 &const_index, &indir_index);
2227 for (unsigned chan = 0; chan < 4; chan++) {
2228 int stride = 4;
2229 if (!(writemask & (1 << chan)))
2230 continue;
2231 if (get_llvm_num_components(src) == 1)
2232 value = src;
2233 else
2234 value = LLVMBuildExtractElement(ctx->builder, src,
2235 LLVMConstInt(ctx->i32,
2236 chan, false),
2237 "");
2238
2239 if (instr->variables[0]->var->data.location == VARYING_SLOT_CLIP_DIST0 ||
2240 instr->variables[0]->var->data.location == VARYING_SLOT_CULL_DIST0)
2241 stride = 1;
2242 if (indir_index) {
2243 unsigned count = glsl_count_attribute_slots(
2244 instr->variables[0]->var->type, false);
2245 LLVMValueRef tmp_vec = build_gather_values_extended(
2246 ctx, ctx->outputs + idx + chan, count,
2247 stride, true);
2248
2249 if (get_llvm_num_components(tmp_vec) > 1) {
2250 tmp_vec = LLVMBuildInsertElement(ctx->builder, tmp_vec,
2251 value, indir_index, "");
2252 } else
2253 tmp_vec = value;
2254 build_store_values_extended(ctx, ctx->outputs + idx + chan,
2255 count, stride, tmp_vec);
2256
2257 } else {
2258 temp_ptr = ctx->outputs[idx + chan + const_index * stride];
2259
2260 LLVMBuildStore(ctx->builder, value, temp_ptr);
2261 }
2262 }
2263 break;
2264 case nir_var_local:
2265 radv_get_deref_offset(ctx, &instr->variables[0]->deref, false,
2266 &const_index, &indir_index);
2267 for (unsigned chan = 0; chan < 4; chan++) {
2268 if (!(writemask & (1 << chan)))
2269 continue;
2270
2271 if (get_llvm_num_components(src) == 1)
2272 value = src;
2273 else
2274 value = LLVMBuildExtractElement(ctx->builder, src,
2275 LLVMConstInt(ctx->i32, chan, false), "");
2276 if (indir_index) {
2277 unsigned count = glsl_count_attribute_slots(
2278 instr->variables[0]->var->type, false);
2279 LLVMValueRef tmp_vec = build_gather_values_extended(
2280 ctx, ctx->locals + idx + chan, count,
2281 4, true);
2282
2283 tmp_vec = LLVMBuildInsertElement(ctx->builder, tmp_vec,
2284 value, indir_index, "");
2285 build_store_values_extended(ctx, ctx->locals + idx + chan,
2286 count, 4, tmp_vec);
2287 } else {
2288 temp_ptr = ctx->locals[idx + chan + const_index * 4];
2289
2290 LLVMBuildStore(ctx->builder, value, temp_ptr);
2291 }
2292 }
2293 break;
2294 case nir_var_shared: {
2295 LLVMValueRef ptr;
2296 radv_get_deref_offset(ctx, &instr->variables[0]->deref, false,
2297 &const_index, &indir_index);
2298
2299 ptr = get_shared_memory_ptr(ctx, idx, ctx->i32);
2300 LLVMValueRef index = ctx->i32zero;
2301 LLVMValueRef derived_ptr;
2302
2303 if (indir_index)
2304 index = LLVMBuildAdd(ctx->builder, index, indir_index, "");
2305 derived_ptr = LLVMBuildGEP(ctx->builder, ptr, &index, 1, "");
2306 LLVMBuildStore(ctx->builder,
2307 to_integer(ctx, src), derived_ptr);
2308 break;
2309 }
2310 default:
2311 break;
2312 }
2313 }
2314
2315 static int image_type_to_components_count(enum glsl_sampler_dim dim, bool array)
2316 {
2317 switch (dim) {
2318 case GLSL_SAMPLER_DIM_BUF:
2319 return 1;
2320 case GLSL_SAMPLER_DIM_1D:
2321 return array ? 2 : 1;
2322 case GLSL_SAMPLER_DIM_2D:
2323 return array ? 3 : 2;
2324 case GLSL_SAMPLER_DIM_3D:
2325 case GLSL_SAMPLER_DIM_CUBE:
2326 return 3;
2327 case GLSL_SAMPLER_DIM_RECT:
2328 case GLSL_SAMPLER_DIM_SUBPASS:
2329 return 2;
2330 default:
2331 break;
2332 }
2333 return 0;
2334 }
2335
2336 static LLVMValueRef get_image_coords(struct nir_to_llvm_context *ctx,
2337 nir_intrinsic_instr *instr, bool add_frag_pos)
2338 {
2339 const struct glsl_type *type = instr->variables[0]->var->type;
2340 if(instr->variables[0]->deref.child)
2341 type = instr->variables[0]->deref.child->type;
2342
2343 LLVMValueRef src0 = get_src(ctx, instr->src[0]);
2344 LLVMValueRef coords[4];
2345 LLVMValueRef masks[] = {
2346 LLVMConstInt(ctx->i32, 0, false), LLVMConstInt(ctx->i32, 1, false),
2347 LLVMConstInt(ctx->i32, 2, false), LLVMConstInt(ctx->i32, 3, false),
2348 };
2349 LLVMValueRef res;
2350 int count;
2351 count = image_type_to_components_count(glsl_get_sampler_dim(type),
2352 glsl_sampler_type_is_array(type));
2353
2354 if (count == 1) {
2355 if (instr->src[0].ssa->num_components)
2356 res = LLVMBuildExtractElement(ctx->builder, src0, masks[0], "");
2357 else
2358 res = src0;
2359 } else {
2360 int chan;
2361 for (chan = 0; chan < count; ++chan) {
2362 coords[chan] = LLVMBuildExtractElement(ctx->builder, src0, masks[chan], "");
2363 }
2364
2365 if (add_frag_pos) {
2366 for (chan = 0; chan < count; ++chan)
2367 coords[chan] = LLVMBuildAdd(ctx->builder, coords[chan], LLVMBuildFPToUI(ctx->builder, ctx->frag_pos[chan], ctx->i32, ""), "");
2368 }
2369 if (count == 3) {
2370 coords[3] = LLVMGetUndef(ctx->i32);
2371 count = 4;
2372 }
2373 res = build_gather_values(ctx, coords, count);
2374 }
2375 return res;
2376 }
2377
2378 static void build_type_name_for_intr(
2379 LLVMTypeRef type,
2380 char *buf, unsigned bufsize)
2381 {
2382 LLVMTypeRef elem_type = type;
2383
2384 assert(bufsize >= 8);
2385
2386 if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
2387 int ret = snprintf(buf, bufsize, "v%u",
2388 LLVMGetVectorSize(type));
2389 if (ret < 0) {
2390 char *type_name = LLVMPrintTypeToString(type);
2391 fprintf(stderr, "Error building type name for: %s\n",
2392 type_name);
2393 return;
2394 }
2395 elem_type = LLVMGetElementType(type);
2396 buf += ret;
2397 bufsize -= ret;
2398 }
2399 switch (LLVMGetTypeKind(elem_type)) {
2400 default: break;
2401 case LLVMIntegerTypeKind:
2402 snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
2403 break;
2404 case LLVMFloatTypeKind:
2405 snprintf(buf, bufsize, "f32");
2406 break;
2407 case LLVMDoubleTypeKind:
2408 snprintf(buf, bufsize, "f64");
2409 break;
2410 }
2411 }
2412
2413 static void get_image_intr_name(const char *base_name,
2414 LLVMTypeRef data_type,
2415 LLVMTypeRef coords_type,
2416 LLVMTypeRef rsrc_type,
2417 char *out_name, unsigned out_len)
2418 {
2419 char coords_type_name[8];
2420
2421 build_type_name_for_intr(coords_type, coords_type_name,
2422 sizeof(coords_type_name));
2423
2424 if (HAVE_LLVM <= 0x0309) {
2425 snprintf(out_name, out_len, "%s.%s", base_name, coords_type_name);
2426 } else {
2427 char data_type_name[8];
2428 char rsrc_type_name[8];
2429
2430 build_type_name_for_intr(data_type, data_type_name,
2431 sizeof(data_type_name));
2432 build_type_name_for_intr(rsrc_type, rsrc_type_name,
2433 sizeof(rsrc_type_name));
2434 snprintf(out_name, out_len, "%s.%s.%s.%s", base_name,
2435 data_type_name, coords_type_name, rsrc_type_name);
2436 }
2437 }
2438
2439 static LLVMValueRef visit_image_load(struct nir_to_llvm_context *ctx,
2440 nir_intrinsic_instr *instr)
2441 {
2442 LLVMValueRef params[7];
2443 LLVMValueRef res;
2444 char intrinsic_name[64];
2445 const nir_variable *var = instr->variables[0]->var;
2446 const struct glsl_type *type = var->type;
2447 if(instr->variables[0]->deref.child)
2448 type = instr->variables[0]->deref.child->type;
2449
2450 type = glsl_without_array(type);
2451 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF) {
2452 params[0] = get_sampler_desc(ctx, instr->variables[0], DESC_BUFFER);
2453 params[1] = LLVMBuildExtractElement(ctx->builder, get_src(ctx, instr->src[0]),
2454 LLVMConstInt(ctx->i32, 0, false), ""); /* vindex */
2455 params[2] = LLVMConstInt(ctx->i32, 0, false); /* voffset */
2456 params[3] = LLVMConstInt(ctx->i1, 0, false); /* glc */
2457 params[4] = LLVMConstInt(ctx->i1, 0, false); /* slc */
2458 res = emit_llvm_intrinsic(ctx, "llvm.amdgcn.buffer.load.format.v4f32", ctx->v4f32,
2459 params, 5, 0);
2460
2461 res = trim_vector(ctx, res, instr->dest.ssa.num_components);
2462 res = to_integer(ctx, res);
2463 } else {
2464 bool is_da = glsl_sampler_type_is_array(type) ||
2465 glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE;
2466 bool add_frag_pos = glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_SUBPASS;
2467 LLVMValueRef da = is_da ? ctx->i32one : ctx->i32zero;
2468 LLVMValueRef glc = LLVMConstInt(ctx->i1, 0, false);
2469 LLVMValueRef slc = LLVMConstInt(ctx->i1, 0, false);
2470
2471 params[0] = get_image_coords(ctx, instr, add_frag_pos);
2472 params[1] = get_sampler_desc(ctx, instr->variables[0], DESC_IMAGE);
2473 params[2] = LLVMConstInt(ctx->i32, 15, false); /* dmask */
2474 if (HAVE_LLVM <= 0x0309) {
2475 params[3] = LLVMConstInt(ctx->i1, 0, false); /* r128 */
2476 params[4] = da;
2477 params[5] = glc;
2478 params[6] = slc;
2479 } else {
2480 LLVMValueRef lwe = LLVMConstInt(ctx->i1, 0, false);
2481 params[3] = glc;
2482 params[4] = slc;
2483 params[5] = lwe;
2484 params[6] = da;
2485 }
2486
2487 get_image_intr_name("llvm.amdgcn.image.load",
2488 ctx->v4f32, /* vdata */
2489 LLVMTypeOf(params[0]), /* coords */
2490 LLVMTypeOf(params[1]), /* rsrc */
2491 intrinsic_name, sizeof(intrinsic_name));
2492
2493 res = emit_llvm_intrinsic(ctx, intrinsic_name, ctx->v4f32,
2494 params, 7, AC_FUNC_ATTR_READONLY);
2495 }
2496 return to_integer(ctx, res);
2497 }
2498
2499 static void visit_image_store(struct nir_to_llvm_context *ctx,
2500 nir_intrinsic_instr *instr)
2501 {
2502 LLVMValueRef params[8];
2503 char intrinsic_name[64];
2504 const nir_variable *var = instr->variables[0]->var;
2505 LLVMValueRef i1false = LLVMConstInt(ctx->i1, 0, 0);
2506 LLVMValueRef i1true = LLVMConstInt(ctx->i1, 1, 0);
2507 const struct glsl_type *type = glsl_without_array(var->type);
2508
2509 if (ctx->stage == MESA_SHADER_FRAGMENT)
2510 ctx->shader_info->fs.writes_memory = true;
2511
2512 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF) {
2513 params[0] = to_float(ctx, get_src(ctx, instr->src[2])); /* data */
2514 params[1] = get_sampler_desc(ctx, instr->variables[0], DESC_BUFFER);
2515 params[2] = LLVMBuildExtractElement(ctx->builder, get_src(ctx, instr->src[0]),
2516 LLVMConstInt(ctx->i32, 0, false), ""); /* vindex */
2517 params[3] = LLVMConstInt(ctx->i32, 0, false); /* voffset */
2518 params[4] = i1false; /* glc */
2519 params[5] = i1false; /* slc */
2520 emit_llvm_intrinsic(ctx, "llvm.amdgcn.buffer.store.format.v4f32", ctx->voidt,
2521 params, 6, 0);
2522 } else {
2523 bool is_da = glsl_sampler_type_is_array(type) ||
2524 glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE;
2525 LLVMValueRef da = is_da ? i1true : i1false;
2526 LLVMValueRef glc = i1false;
2527 LLVMValueRef slc = i1false;
2528
2529 params[0] = to_float(ctx, get_src(ctx, instr->src[2]));
2530 params[1] = get_image_coords(ctx, instr, false); /* coords */
2531 params[2] = get_sampler_desc(ctx, instr->variables[0], DESC_IMAGE);
2532 params[3] = LLVMConstInt(ctx->i32, 15, false); /* dmask */
2533 if (HAVE_LLVM <= 0x0309) {
2534 params[4] = i1false; /* r128 */
2535 params[5] = da;
2536 params[6] = glc;
2537 params[7] = slc;
2538 } else {
2539 LLVMValueRef lwe = i1false;
2540 params[4] = glc;
2541 params[5] = slc;
2542 params[6] = lwe;
2543 params[7] = da;
2544 }
2545
2546 get_image_intr_name("llvm.amdgcn.image.store",
2547 LLVMTypeOf(params[0]), /* vdata */
2548 LLVMTypeOf(params[1]), /* coords */
2549 LLVMTypeOf(params[2]), /* rsrc */
2550 intrinsic_name, sizeof(intrinsic_name));
2551
2552 emit_llvm_intrinsic(ctx, intrinsic_name, ctx->voidt,
2553 params, 8, 0);
2554 }
2555
2556 }
2557
2558 static LLVMValueRef visit_image_atomic(struct nir_to_llvm_context *ctx,
2559 nir_intrinsic_instr *instr)
2560 {
2561 LLVMValueRef params[6];
2562 int param_count = 0;
2563 const nir_variable *var = instr->variables[0]->var;
2564 LLVMValueRef i1false = LLVMConstInt(ctx->i1, 0, 0);
2565 LLVMValueRef i1true = LLVMConstInt(ctx->i1, 1, 0);
2566 const char *base_name = "llvm.amdgcn.image.atomic";
2567 const char *atomic_name;
2568 LLVMValueRef coords;
2569 char intrinsic_name[32], coords_type[8];
2570 const struct glsl_type *type = glsl_without_array(var->type);
2571
2572 if (ctx->stage == MESA_SHADER_FRAGMENT)
2573 ctx->shader_info->fs.writes_memory = true;
2574
2575 params[param_count++] = get_src(ctx, instr->src[2]);
2576 if (instr->intrinsic == nir_intrinsic_image_atomic_comp_swap)
2577 params[param_count++] = get_src(ctx, instr->src[3]);
2578
2579 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF) {
2580 params[param_count++] = get_sampler_desc(ctx, instr->variables[0], DESC_BUFFER);
2581 coords = params[param_count++] = LLVMBuildExtractElement(ctx->builder, get_src(ctx, instr->src[0]),
2582 LLVMConstInt(ctx->i32, 0, false), ""); /* vindex */
2583 params[param_count++] = ctx->i32zero; /* voffset */
2584 params[param_count++] = i1false; /* glc */
2585 params[param_count++] = i1false; /* slc */
2586 } else {
2587 bool da = glsl_sampler_type_is_array(type) ||
2588 glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE;
2589
2590 coords = params[param_count++] = get_image_coords(ctx, instr, false);
2591 params[param_count++] = get_sampler_desc(ctx, instr->variables[0], DESC_IMAGE);
2592 params[param_count++] = i1false; /* r128 */
2593 params[param_count++] = da ? i1true : i1false; /* da */
2594 params[param_count++] = i1false; /* slc */
2595 }
2596
2597 switch (instr->intrinsic) {
2598 case nir_intrinsic_image_atomic_add:
2599 atomic_name = "add";
2600 break;
2601 case nir_intrinsic_image_atomic_min:
2602 atomic_name = "smin";
2603 break;
2604 case nir_intrinsic_image_atomic_max:
2605 atomic_name = "smax";
2606 break;
2607 case nir_intrinsic_image_atomic_and:
2608 atomic_name = "and";
2609 break;
2610 case nir_intrinsic_image_atomic_or:
2611 atomic_name = "or";
2612 break;
2613 case nir_intrinsic_image_atomic_xor:
2614 atomic_name = "xor";
2615 break;
2616 case nir_intrinsic_image_atomic_exchange:
2617 atomic_name = "swap";
2618 break;
2619 case nir_intrinsic_image_atomic_comp_swap:
2620 atomic_name = "cmpswap";
2621 break;
2622 default:
2623 abort();
2624 }
2625 build_int_type_name(LLVMTypeOf(coords),
2626 coords_type, sizeof(coords_type));
2627
2628 snprintf(intrinsic_name, sizeof(intrinsic_name),
2629 "%s.%s.%s", base_name, atomic_name, coords_type);
2630 return emit_llvm_intrinsic(ctx, intrinsic_name, ctx->i32, params, param_count, 0);
2631 }
2632
2633 static LLVMValueRef visit_image_size(struct nir_to_llvm_context *ctx,
2634 nir_intrinsic_instr *instr)
2635 {
2636 LLVMValueRef res;
2637 LLVMValueRef params[10];
2638 const nir_variable *var = instr->variables[0]->var;
2639 const struct glsl_type *type = instr->variables[0]->var->type;
2640 bool da = glsl_sampler_type_is_array(var->type) ||
2641 glsl_get_sampler_dim(var->type) == GLSL_SAMPLER_DIM_CUBE;
2642 if(instr->variables[0]->deref.child)
2643 type = instr->variables[0]->deref.child->type;
2644
2645 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF)
2646 return get_buffer_size(ctx, get_sampler_desc(ctx, instr->variables[0], DESC_BUFFER), true);
2647 params[0] = ctx->i32zero;
2648 params[1] = get_sampler_desc(ctx, instr->variables[0], DESC_IMAGE);
2649 params[2] = LLVMConstInt(ctx->i32, 15, false);
2650 params[3] = ctx->i32zero;
2651 params[4] = ctx->i32zero;
2652 params[5] = da ? ctx->i32one : ctx->i32zero;
2653 params[6] = ctx->i32zero;
2654 params[7] = ctx->i32zero;
2655 params[8] = ctx->i32zero;
2656 params[9] = ctx->i32zero;
2657
2658 res = emit_llvm_intrinsic(ctx, "llvm.SI.getresinfo.i32", ctx->v4i32,
2659 params, 10, AC_FUNC_ATTR_READNONE);
2660
2661 if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE &&
2662 glsl_sampler_type_is_array(type)) {
2663 LLVMValueRef two = LLVMConstInt(ctx->i32, 2, false);
2664 LLVMValueRef six = LLVMConstInt(ctx->i32, 6, false);
2665 LLVMValueRef z = LLVMBuildExtractElement(ctx->builder, res, two, "");
2666 z = LLVMBuildSDiv(ctx->builder, z, six, "");
2667 res = LLVMBuildInsertElement(ctx->builder, res, z, two, "");
2668 }
2669 return res;
2670 }
2671
2672 static void emit_waitcnt(struct nir_to_llvm_context *ctx)
2673 {
2674 LLVMValueRef args[1] = {
2675 LLVMConstInt(ctx->i32, 0xf70, false),
2676 };
2677 emit_llvm_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
2678 ctx->voidt, args, 1, 0);
2679 }
2680
2681 static void emit_barrier(struct nir_to_llvm_context *ctx)
2682 {
2683 // TODO tess
2684 emit_llvm_intrinsic(ctx, "llvm.amdgcn.s.barrier",
2685 ctx->voidt, NULL, 0, 0);
2686 }
2687
2688 static void emit_discard_if(struct nir_to_llvm_context *ctx,
2689 nir_intrinsic_instr *instr)
2690 {
2691 LLVMValueRef cond;
2692 ctx->shader_info->fs.can_discard = true;
2693
2694 cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
2695 get_src(ctx, instr->src[0]),
2696 ctx->i32zero, "");
2697
2698 cond = LLVMBuildSelect(ctx->builder, cond,
2699 LLVMConstReal(ctx->f32, -1.0f),
2700 ctx->f32zero, "");
2701 emit_llvm_intrinsic(ctx, "llvm.AMDGPU.kill",
2702 LLVMVoidTypeInContext(ctx->context),
2703 &cond, 1, 0);
2704 }
2705
2706 static LLVMValueRef
2707 visit_load_local_invocation_index(struct nir_to_llvm_context *ctx)
2708 {
2709 LLVMValueRef result;
2710 LLVMValueRef thread_id = get_thread_id(ctx);
2711 result = LLVMBuildAnd(ctx->builder, ctx->tg_size,
2712 LLVMConstInt(ctx->i32, 0xfc0, false), "");
2713
2714 return LLVMBuildAdd(ctx->builder, result, thread_id, "");
2715 }
2716
2717 static LLVMValueRef visit_var_atomic(struct nir_to_llvm_context *ctx,
2718 nir_intrinsic_instr *instr)
2719 {
2720 LLVMValueRef ptr, result;
2721 int idx = instr->variables[0]->var->data.driver_location;
2722 LLVMValueRef src = get_src(ctx, instr->src[0]);
2723 ptr = get_shared_memory_ptr(ctx, idx, ctx->i32);
2724
2725 if (instr->intrinsic == nir_intrinsic_var_atomic_comp_swap) {
2726 LLVMValueRef src1 = get_src(ctx, instr->src[1]);
2727 result = LLVMBuildAtomicCmpXchg(ctx->builder,
2728 ptr, src, src1,
2729 LLVMAtomicOrderingSequentiallyConsistent,
2730 LLVMAtomicOrderingSequentiallyConsistent,
2731 false);
2732 } else {
2733 LLVMAtomicRMWBinOp op;
2734 switch (instr->intrinsic) {
2735 case nir_intrinsic_var_atomic_add:
2736 op = LLVMAtomicRMWBinOpAdd;
2737 break;
2738 case nir_intrinsic_var_atomic_umin:
2739 op = LLVMAtomicRMWBinOpUMin;
2740 break;
2741 case nir_intrinsic_var_atomic_umax:
2742 op = LLVMAtomicRMWBinOpUMax;
2743 break;
2744 case nir_intrinsic_var_atomic_imin:
2745 op = LLVMAtomicRMWBinOpMin;
2746 break;
2747 case nir_intrinsic_var_atomic_imax:
2748 op = LLVMAtomicRMWBinOpMax;
2749 break;
2750 case nir_intrinsic_var_atomic_and:
2751 op = LLVMAtomicRMWBinOpAnd;
2752 break;
2753 case nir_intrinsic_var_atomic_or:
2754 op = LLVMAtomicRMWBinOpOr;
2755 break;
2756 case nir_intrinsic_var_atomic_xor:
2757 op = LLVMAtomicRMWBinOpXor;
2758 break;
2759 case nir_intrinsic_var_atomic_exchange:
2760 op = LLVMAtomicRMWBinOpXchg;
2761 break;
2762 default:
2763 return NULL;
2764 }
2765
2766 result = LLVMBuildAtomicRMW(ctx->builder, op, ptr, to_integer(ctx, src),
2767 LLVMAtomicOrderingSequentiallyConsistent,
2768 false);
2769 }
2770 return result;
2771 }
2772
2773 #define INTERP_CENTER 0
2774 #define INTERP_CENTROID 1
2775 #define INTERP_SAMPLE 2
2776
2777 static LLVMValueRef lookup_interp_param(struct nir_to_llvm_context *ctx,
2778 enum glsl_interp_mode interp, unsigned location)
2779 {
2780 switch (interp) {
2781 case INTERP_MODE_FLAT:
2782 default:
2783 return NULL;
2784 case INTERP_MODE_SMOOTH:
2785 case INTERP_MODE_NONE:
2786 if (location == INTERP_CENTER)
2787 return ctx->persp_center;
2788 else if (location == INTERP_CENTROID)
2789 return ctx->persp_centroid;
2790 else if (location == INTERP_SAMPLE)
2791 return ctx->persp_sample;
2792 break;
2793 case INTERP_MODE_NOPERSPECTIVE:
2794 if (location == INTERP_CENTER)
2795 return ctx->linear_center;
2796 else if (location == INTERP_CENTROID)
2797 return ctx->linear_centroid;
2798 else if (location == INTERP_SAMPLE)
2799 return ctx->linear_sample;
2800 break;
2801 }
2802 return NULL;
2803 }
2804
2805 static LLVMValueRef load_sample_position(struct nir_to_llvm_context *ctx,
2806 LLVMValueRef sample_id)
2807 {
2808 /* offset = sample_id * 8 (8 = 2 floats containing samplepos.xy) */
2809 LLVMValueRef offset0 = LLVMBuildMul(ctx->builder, sample_id, LLVMConstInt(ctx->i32, 8, false), "");
2810 LLVMValueRef offset1 = LLVMBuildAdd(ctx->builder, offset0, LLVMConstInt(ctx->i32, 4, false), "");
2811 LLVMValueRef result[2];
2812
2813 result[0] = build_indexed_load_const(ctx, ctx->sample_positions, offset0);
2814 result[1] = build_indexed_load_const(ctx, ctx->sample_positions, offset1);
2815
2816 return build_gather_values(ctx, result, 2);
2817 }
2818
2819 static LLVMValueRef visit_interp(struct nir_to_llvm_context *ctx,
2820 nir_intrinsic_instr *instr)
2821 {
2822 LLVMValueRef result[2];
2823 LLVMValueRef interp_param, attr_number;
2824 unsigned location;
2825 unsigned chan;
2826 LLVMValueRef src_c0, src_c1;
2827 const char *intr_name;
2828 LLVMValueRef src0;
2829 int input_index = instr->variables[0]->var->data.location - VARYING_SLOT_VAR0;
2830 switch (instr->intrinsic) {
2831 case nir_intrinsic_interp_var_at_centroid:
2832 location = INTERP_CENTROID;
2833 break;
2834 case nir_intrinsic_interp_var_at_sample:
2835 case nir_intrinsic_interp_var_at_offset:
2836 location = INTERP_SAMPLE;
2837 src0 = get_src(ctx, instr->src[0]);
2838 break;
2839 default:
2840 break;
2841 }
2842
2843 if (instr->intrinsic == nir_intrinsic_interp_var_at_offset) {
2844 src_c0 = to_float(ctx, LLVMBuildExtractElement(ctx->builder, src0, ctx->i32zero, ""));
2845 src_c1 = to_float(ctx, LLVMBuildExtractElement(ctx->builder, src0, ctx->i32one, ""));
2846 } else if (instr->intrinsic == nir_intrinsic_interp_var_at_sample) {
2847 LLVMValueRef sample_position;
2848 LLVMValueRef halfval = LLVMConstReal(ctx->f32, 0.5f);
2849
2850 /* fetch sample ID */
2851 sample_position = load_sample_position(ctx, src0);
2852
2853 src_c0 = LLVMBuildExtractElement(ctx->builder, sample_position, ctx->i32zero, "");
2854 src_c0 = LLVMBuildFSub(ctx->builder, src_c0, halfval, "");
2855 src_c1 = LLVMBuildExtractElement(ctx->builder, sample_position, ctx->i32one, "");
2856 src_c1 = LLVMBuildFSub(ctx->builder, src_c1, halfval, "");
2857 }
2858 interp_param = lookup_interp_param(ctx, instr->variables[0]->var->data.interpolation, location);
2859 attr_number = LLVMConstInt(ctx->i32, input_index, false);
2860
2861 if (location == INTERP_SAMPLE) {
2862 LLVMValueRef ij_out[2];
2863 LLVMValueRef ddxy_out = emit_ddxy_interp(ctx, interp_param);
2864
2865 /*
2866 * take the I then J parameters, and the DDX/Y for it, and
2867 * calculate the IJ inputs for the interpolator.
2868 * temp1 = ddx * offset/sample.x + I;
2869 * interp_param.I = ddy * offset/sample.y + temp1;
2870 * temp1 = ddx * offset/sample.x + J;
2871 * interp_param.J = ddy * offset/sample.y + temp1;
2872 */
2873 for (unsigned i = 0; i < 2; i++) {
2874 LLVMValueRef ix_ll = LLVMConstInt(ctx->i32, i, false);
2875 LLVMValueRef iy_ll = LLVMConstInt(ctx->i32, i + 2, false);
2876 LLVMValueRef ddx_el = LLVMBuildExtractElement(ctx->builder,
2877 ddxy_out, ix_ll, "");
2878 LLVMValueRef ddy_el = LLVMBuildExtractElement(ctx->builder,
2879 ddxy_out, iy_ll, "");
2880 LLVMValueRef interp_el = LLVMBuildExtractElement(ctx->builder,
2881 interp_param, ix_ll, "");
2882 LLVMValueRef temp1, temp2;
2883
2884 interp_el = LLVMBuildBitCast(ctx->builder, interp_el,
2885 ctx->f32, "");
2886
2887 temp1 = LLVMBuildFMul(ctx->builder, ddx_el, src_c0, "");
2888 temp1 = LLVMBuildFAdd(ctx->builder, temp1, interp_el, "");
2889
2890 temp2 = LLVMBuildFMul(ctx->builder, ddy_el, src_c1, "");
2891 temp2 = LLVMBuildFAdd(ctx->builder, temp2, temp1, "");
2892
2893 ij_out[i] = LLVMBuildBitCast(ctx->builder,
2894 temp2, ctx->i32, "");
2895 }
2896 interp_param = build_gather_values(ctx, ij_out, 2);
2897
2898 }
2899 intr_name = interp_param ? "llvm.SI.fs.interp" : "llvm.SI.fs.constant";
2900 for (chan = 0; chan < 2; chan++) {
2901 LLVMValueRef args[4];
2902 LLVMValueRef llvm_chan = LLVMConstInt(ctx->i32, chan, false);
2903
2904 args[0] = llvm_chan;
2905 args[1] = attr_number;
2906 args[2] = ctx->prim_mask;
2907 args[3] = interp_param;
2908 result[chan] = emit_llvm_intrinsic(ctx, intr_name,
2909 ctx->f32, args, args[3] ? 4 : 3,
2910 AC_FUNC_ATTR_READNONE);
2911 }
2912 return build_gather_values(ctx, result, 2);
2913 }
2914
2915 static void visit_intrinsic(struct nir_to_llvm_context *ctx,
2916 nir_intrinsic_instr *instr)
2917 {
2918 LLVMValueRef result = NULL;
2919
2920 switch (instr->intrinsic) {
2921 case nir_intrinsic_load_work_group_id: {
2922 result = ctx->workgroup_ids;
2923 break;
2924 }
2925 case nir_intrinsic_load_base_vertex: {
2926 result = ctx->base_vertex;
2927 break;
2928 }
2929 case nir_intrinsic_load_vertex_id_zero_base: {
2930 result = ctx->vertex_id;
2931 break;
2932 }
2933 case nir_intrinsic_load_local_invocation_id: {
2934 result = ctx->local_invocation_ids;
2935 break;
2936 }
2937 case nir_intrinsic_load_base_instance:
2938 result = ctx->start_instance;
2939 break;
2940 case nir_intrinsic_load_sample_id:
2941 result = ctx->ancillary;
2942 break;
2943 case nir_intrinsic_load_front_face:
2944 result = ctx->front_face;
2945 break;
2946 case nir_intrinsic_load_instance_id:
2947 result = ctx->instance_id;
2948 ctx->shader_info->vs.vgpr_comp_cnt = MAX2(3,
2949 ctx->shader_info->vs.vgpr_comp_cnt);
2950 break;
2951 case nir_intrinsic_load_num_work_groups:
2952 result = ctx->num_work_groups;
2953 break;
2954 case nir_intrinsic_load_local_invocation_index:
2955 result = visit_load_local_invocation_index(ctx);
2956 break;
2957 case nir_intrinsic_load_push_constant:
2958 result = visit_load_push_constant(ctx, instr);
2959 break;
2960 case nir_intrinsic_vulkan_resource_index:
2961 result = visit_vulkan_resource_index(ctx, instr);
2962 break;
2963 case nir_intrinsic_store_ssbo:
2964 visit_store_ssbo(ctx, instr);
2965 break;
2966 case nir_intrinsic_load_ssbo:
2967 result = visit_load_buffer(ctx, instr);
2968 break;
2969 case nir_intrinsic_ssbo_atomic_add:
2970 case nir_intrinsic_ssbo_atomic_imin:
2971 case nir_intrinsic_ssbo_atomic_umin:
2972 case nir_intrinsic_ssbo_atomic_imax:
2973 case nir_intrinsic_ssbo_atomic_umax:
2974 case nir_intrinsic_ssbo_atomic_and:
2975 case nir_intrinsic_ssbo_atomic_or:
2976 case nir_intrinsic_ssbo_atomic_xor:
2977 case nir_intrinsic_ssbo_atomic_exchange:
2978 case nir_intrinsic_ssbo_atomic_comp_swap:
2979 result = visit_atomic_ssbo(ctx, instr);
2980 break;
2981 case nir_intrinsic_load_ubo:
2982 result = visit_load_buffer(ctx, instr);
2983 break;
2984 case nir_intrinsic_get_buffer_size:
2985 result = visit_get_buffer_size(ctx, instr);
2986 break;
2987 case nir_intrinsic_load_var:
2988 result = visit_load_var(ctx, instr);
2989 break;
2990 case nir_intrinsic_store_var:
2991 visit_store_var(ctx, instr);
2992 break;
2993 case nir_intrinsic_image_load:
2994 result = visit_image_load(ctx, instr);
2995 break;
2996 case nir_intrinsic_image_store:
2997 visit_image_store(ctx, instr);
2998 break;
2999 case nir_intrinsic_image_atomic_add:
3000 case nir_intrinsic_image_atomic_min:
3001 case nir_intrinsic_image_atomic_max:
3002 case nir_intrinsic_image_atomic_and:
3003 case nir_intrinsic_image_atomic_or:
3004 case nir_intrinsic_image_atomic_xor:
3005 case nir_intrinsic_image_atomic_exchange:
3006 case nir_intrinsic_image_atomic_comp_swap:
3007 result = visit_image_atomic(ctx, instr);
3008 break;
3009 case nir_intrinsic_image_size:
3010 result = visit_image_size(ctx, instr);
3011 break;
3012 case nir_intrinsic_discard:
3013 ctx->shader_info->fs.can_discard = true;
3014 emit_llvm_intrinsic(ctx, "llvm.AMDGPU.kilp",
3015 LLVMVoidTypeInContext(ctx->context),
3016 NULL, 0, 0);
3017 break;
3018 case nir_intrinsic_discard_if:
3019 emit_discard_if(ctx, instr);
3020 break;
3021 case nir_intrinsic_memory_barrier:
3022 emit_waitcnt(ctx);
3023 break;
3024 case nir_intrinsic_barrier:
3025 emit_barrier(ctx);
3026 break;
3027 case nir_intrinsic_var_atomic_add:
3028 case nir_intrinsic_var_atomic_imin:
3029 case nir_intrinsic_var_atomic_umin:
3030 case nir_intrinsic_var_atomic_imax:
3031 case nir_intrinsic_var_atomic_umax:
3032 case nir_intrinsic_var_atomic_and:
3033 case nir_intrinsic_var_atomic_or:
3034 case nir_intrinsic_var_atomic_xor:
3035 case nir_intrinsic_var_atomic_exchange:
3036 case nir_intrinsic_var_atomic_comp_swap:
3037 result = visit_var_atomic(ctx, instr);
3038 break;
3039 case nir_intrinsic_interp_var_at_centroid:
3040 case nir_intrinsic_interp_var_at_sample:
3041 case nir_intrinsic_interp_var_at_offset:
3042 result = visit_interp(ctx, instr);
3043 break;
3044 default:
3045 fprintf(stderr, "Unknown intrinsic: ");
3046 nir_print_instr(&instr->instr, stderr);
3047 fprintf(stderr, "\n");
3048 break;
3049 }
3050 if (result) {
3051 _mesa_hash_table_insert(ctx->defs, &instr->dest.ssa, result);
3052 }
3053 }
3054
3055 static LLVMValueRef get_sampler_desc(struct nir_to_llvm_context *ctx,
3056 nir_deref_var *deref,
3057 enum desc_type desc_type)
3058 {
3059 unsigned desc_set = deref->var->data.descriptor_set;
3060 LLVMValueRef list = ctx->descriptor_sets[desc_set];
3061 struct radv_descriptor_set_layout *layout = ctx->options->layout->set[desc_set].layout;
3062 struct radv_descriptor_set_binding_layout *binding = layout->binding + deref->var->data.binding;
3063 unsigned offset = binding->offset;
3064 unsigned stride = binding->size;
3065 unsigned type_size;
3066 LLVMBuilderRef builder = ctx->builder;
3067 LLVMTypeRef type;
3068 LLVMValueRef indices[2];
3069 LLVMValueRef index = NULL;
3070
3071 assert(deref->var->data.binding < layout->binding_count);
3072
3073 switch (desc_type) {
3074 case DESC_IMAGE:
3075 type = ctx->v8i32;
3076 type_size = 32;
3077 break;
3078 case DESC_FMASK:
3079 type = ctx->v8i32;
3080 offset += 32;
3081 type_size = 32;
3082 break;
3083 case DESC_SAMPLER:
3084 type = ctx->v4i32;
3085 if (binding->type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
3086 offset += 64;
3087
3088 type_size = 16;
3089 break;
3090 case DESC_BUFFER:
3091 type = ctx->v4i32;
3092 type_size = 16;
3093 break;
3094 }
3095
3096 if (deref->deref.child) {
3097 nir_deref_array *child = (nir_deref_array*)deref->deref.child;
3098
3099 assert(child->deref_array_type != nir_deref_array_type_wildcard);
3100 offset += child->base_offset * stride;
3101 if (child->deref_array_type == nir_deref_array_type_indirect) {
3102 index = get_src(ctx, child->indirect);
3103 }
3104 }
3105
3106 assert(stride % type_size == 0);
3107
3108 if (!index)
3109 index = ctx->i32zero;
3110
3111 index = LLVMBuildMul(builder, index, LLVMConstInt(ctx->i32, stride / type_size, 0), "");
3112 indices[0] = ctx->i32zero;
3113 indices[1] = LLVMConstInt(ctx->i32, offset, 0);
3114 list = LLVMBuildGEP(builder, list, indices, 2, "");
3115 list = LLVMBuildPointerCast(builder, list, const_array(type, 0), "");
3116
3117 return build_indexed_load_const(ctx, list, index);
3118 }
3119
3120 static void set_tex_fetch_args(struct nir_to_llvm_context *ctx,
3121 struct ac_tex_info *tinfo,
3122 nir_tex_instr *instr,
3123 nir_texop op,
3124 LLVMValueRef res_ptr, LLVMValueRef samp_ptr,
3125 LLVMValueRef *param, unsigned count,
3126 unsigned dmask)
3127 {
3128 int num_args;
3129 unsigned is_rect = 0;
3130 bool da = instr->is_array || instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE;
3131
3132 if (op == nir_texop_lod)
3133 da = false;
3134 /* Pad to power of two vector */
3135 while (count < util_next_power_of_two(count))
3136 param[count++] = LLVMGetUndef(ctx->i32);
3137
3138 if (count > 1)
3139 tinfo->args[0] = build_gather_values(ctx, param, count);
3140 else
3141 tinfo->args[0] = param[0];
3142
3143 tinfo->args[1] = res_ptr;
3144 num_args = 2;
3145
3146 if (op == nir_texop_txf ||
3147 op == nir_texop_txf_ms ||
3148 op == nir_texop_query_levels ||
3149 op == nir_texop_texture_samples ||
3150 op == nir_texop_txs)
3151 tinfo->dst_type = ctx->v4i32;
3152 else {
3153 tinfo->dst_type = ctx->v4f32;
3154 tinfo->args[num_args++] = samp_ptr;
3155 }
3156
3157 if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF && op == nir_texop_txf) {
3158 tinfo->args[0] = res_ptr;
3159 tinfo->args[1] = LLVMConstInt(ctx->i32, 0, false);
3160 tinfo->args[2] = param[0];
3161 tinfo->arg_count = 3;
3162 return;
3163 }
3164
3165 tinfo->args[num_args++] = LLVMConstInt(ctx->i32, dmask, 0);
3166 tinfo->args[num_args++] = LLVMConstInt(ctx->i32, is_rect, 0); /* unorm */
3167 tinfo->args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* r128 */
3168 tinfo->args[num_args++] = LLVMConstInt(ctx->i32, da ? 1 : 0, 0);
3169 tinfo->args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* glc */
3170 tinfo->args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* slc */
3171 tinfo->args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* tfe */
3172 tinfo->args[num_args++] = LLVMConstInt(ctx->i32, 0, 0); /* lwe */
3173
3174 tinfo->arg_count = num_args;
3175 }
3176
3177 static void tex_fetch_ptrs(struct nir_to_llvm_context *ctx,
3178 nir_tex_instr *instr,
3179 LLVMValueRef *res_ptr, LLVMValueRef *samp_ptr,
3180 LLVMValueRef *fmask_ptr)
3181 {
3182 if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF)
3183 *res_ptr = get_sampler_desc(ctx, instr->texture, DESC_BUFFER);
3184 else
3185 *res_ptr = get_sampler_desc(ctx, instr->texture, DESC_IMAGE);
3186 if (samp_ptr) {
3187 if (instr->sampler)
3188 *samp_ptr = get_sampler_desc(ctx, instr->sampler, DESC_SAMPLER);
3189 else
3190 *samp_ptr = get_sampler_desc(ctx, instr->texture, DESC_SAMPLER);
3191 }
3192 if (fmask_ptr && !instr->sampler && (instr->op == nir_texop_txf_ms ||
3193 instr->op == nir_texop_samples_identical))
3194 *fmask_ptr = get_sampler_desc(ctx, instr->texture, DESC_FMASK);
3195 }
3196
3197 static LLVMValueRef build_cube_intrinsic(struct nir_to_llvm_context *ctx,
3198 LLVMValueRef *in)
3199 {
3200
3201 LLVMValueRef v, cube_vec;
3202
3203 if (1) {
3204 LLVMTypeRef f32 = LLVMTypeOf(in[0]);
3205 LLVMValueRef out[4];
3206
3207 out[0] = emit_llvm_intrinsic(ctx, "llvm.amdgcn.cubetc",
3208 f32, in, 3, AC_FUNC_ATTR_READNONE);
3209 out[1] = emit_llvm_intrinsic(ctx, "llvm.amdgcn.cubesc",
3210 f32, in, 3, AC_FUNC_ATTR_READNONE);
3211 out[2] = emit_llvm_intrinsic(ctx, "llvm.amdgcn.cubema",
3212 f32, in, 3, AC_FUNC_ATTR_READNONE);
3213 out[3] = emit_llvm_intrinsic(ctx, "llvm.amdgcn.cubeid",
3214 f32, in, 3, AC_FUNC_ATTR_READNONE);
3215
3216 return build_gather_values(ctx, out, 4);
3217 } else {
3218 LLVMValueRef c[4];
3219 c[0] = in[0];
3220 c[1] = in[1];
3221 c[2] = in[2];
3222 c[3] = LLVMGetUndef(LLVMTypeOf(in[0]));
3223 cube_vec = build_gather_values(ctx, c, 4);
3224 v = emit_llvm_intrinsic(ctx, "llvm.AMDGPU.cube", LLVMTypeOf(cube_vec),
3225 &cube_vec, 1, AC_FUNC_ATTR_READNONE);
3226 }
3227 return v;
3228 }
3229
3230 static void cube_to_2d_coords(struct nir_to_llvm_context *ctx,
3231 LLVMValueRef *in, LLVMValueRef *out)
3232 {
3233 LLVMValueRef coords[4];
3234 LLVMValueRef mad_args[3];
3235 LLVMValueRef v;
3236 LLVMValueRef tmp;
3237 int i;
3238
3239 v = build_cube_intrinsic(ctx, in);
3240 for (i = 0; i < 4; i++)
3241 coords[i] = LLVMBuildExtractElement(ctx->builder, v,
3242 LLVMConstInt(ctx->i32, i, false), "");
3243
3244 coords[2] = emit_llvm_intrinsic(ctx, "llvm.fabs.f32", ctx->f32,
3245 &coords[2], 1, AC_FUNC_ATTR_READNONE);
3246 coords[2] = emit_fdiv(ctx, ctx->f32one, coords[2]);
3247
3248 mad_args[1] = coords[2];
3249 mad_args[2] = LLVMConstReal(ctx->f32, 1.5);
3250 mad_args[0] = coords[0];
3251
3252 /* emit MAD */
3253 tmp = LLVMBuildFMul(ctx->builder, mad_args[0], mad_args[1], "");
3254 coords[0] = LLVMBuildFAdd(ctx->builder, tmp, mad_args[2], "");
3255
3256 mad_args[0] = coords[1];
3257
3258 /* emit MAD */
3259 tmp = LLVMBuildFMul(ctx->builder, mad_args[0], mad_args[1], "");
3260 coords[1] = LLVMBuildFAdd(ctx->builder, tmp, mad_args[2], "");
3261
3262 /* apply xyz = yxw swizzle to cooords */
3263 out[0] = coords[1];
3264 out[1] = coords[0];
3265 out[2] = coords[3];
3266 }
3267
3268 static void emit_prepare_cube_coords(struct nir_to_llvm_context *ctx,
3269 LLVMValueRef *coords_arg, int num_coords,
3270 bool is_deriv,
3271 bool is_array, LLVMValueRef *derivs_arg)
3272 {
3273 LLVMValueRef coords[4];
3274 int i;
3275 cube_to_2d_coords(ctx, coords_arg, coords);
3276
3277 if (is_deriv && derivs_arg) {
3278 LLVMValueRef derivs[4];
3279 int axis;
3280
3281 /* Convert cube derivatives to 2D derivatives. */
3282 for (axis = 0; axis < 2; axis++) {
3283 LLVMValueRef shifted_cube_coords[4], shifted_coords[4];
3284
3285 /* Shift the cube coordinates by the derivatives to get
3286 * the cube coordinates of the "neighboring pixel".
3287 */
3288 for (i = 0; i < 3; i++)
3289 shifted_cube_coords[i] =
3290 LLVMBuildFAdd(ctx->builder, coords_arg[i],
3291 derivs_arg[axis*3+i], "");
3292 shifted_cube_coords[3] = LLVMGetUndef(ctx->f32);
3293
3294 /* Project the shifted cube coordinates onto the face. */
3295 cube_to_2d_coords(ctx, shifted_cube_coords,
3296 shifted_coords);
3297
3298 /* Subtract both sets of 2D coordinates to get 2D derivatives.
3299 * This won't work if the shifted coordinates ended up
3300 * in a different face.
3301 */
3302 for (i = 0; i < 2; i++)
3303 derivs[axis * 2 + i] =
3304 LLVMBuildFSub(ctx->builder, shifted_coords[i],
3305 coords[i], "");
3306 }
3307
3308 memcpy(derivs_arg, derivs, sizeof(derivs));
3309 }
3310
3311 if (is_array) {
3312 /* for cube arrays coord.z = coord.w(array_index) * 8 + face */
3313 /* coords_arg.w component - array_index for cube arrays */
3314 LLVMValueRef tmp = LLVMBuildFMul(ctx->builder, coords_arg[3], LLVMConstReal(ctx->f32, 8.0), "");
3315 coords[2] = LLVMBuildFAdd(ctx->builder, tmp, coords[2], "");
3316 }
3317
3318 memcpy(coords_arg, coords, sizeof(coords));
3319 }
3320
3321 static void visit_tex(struct nir_to_llvm_context *ctx, nir_tex_instr *instr)
3322 {
3323 LLVMValueRef result = NULL;
3324 struct ac_tex_info tinfo = { 0 };
3325 unsigned dmask = 0xf;
3326 LLVMValueRef address[16];
3327 LLVMValueRef coords[5];
3328 LLVMValueRef coord = NULL, lod = NULL, comparitor = NULL, bias, offsets = NULL;
3329 LLVMValueRef res_ptr, samp_ptr, fmask_ptr = NULL, sample_index = NULL;
3330 LLVMValueRef ddx = NULL, ddy = NULL;
3331 LLVMValueRef derivs[6];
3332 unsigned chan, count = 0;
3333 unsigned const_src = 0, num_deriv_comp = 0;
3334
3335 tex_fetch_ptrs(ctx, instr, &res_ptr, &samp_ptr, &fmask_ptr);
3336
3337 for (unsigned i = 0; i < instr->num_srcs; i++) {
3338 switch (instr->src[i].src_type) {
3339 case nir_tex_src_coord:
3340 coord = get_src(ctx, instr->src[i].src);
3341 break;
3342 case nir_tex_src_projector:
3343 break;
3344 case nir_tex_src_comparitor:
3345 comparitor = get_src(ctx, instr->src[i].src);
3346 break;
3347 case nir_tex_src_offset:
3348 offsets = get_src(ctx, instr->src[i].src);
3349 const_src = i;
3350 break;
3351 case nir_tex_src_bias:
3352 bias = get_src(ctx, instr->src[i].src);
3353 break;
3354 case nir_tex_src_lod:
3355 lod = get_src(ctx, instr->src[i].src);
3356 break;
3357 case nir_tex_src_ms_index:
3358 sample_index = get_src(ctx, instr->src[i].src);
3359 break;
3360 case nir_tex_src_ms_mcs:
3361 break;
3362 case nir_tex_src_ddx:
3363 ddx = get_src(ctx, instr->src[i].src);
3364 num_deriv_comp = instr->src[i].src.ssa->num_components;
3365 break;
3366 case nir_tex_src_ddy:
3367 ddy = get_src(ctx, instr->src[i].src);
3368 break;
3369 case nir_tex_src_texture_offset:
3370 case nir_tex_src_sampler_offset:
3371 case nir_tex_src_plane:
3372 default:
3373 break;
3374 }
3375 }
3376
3377 if (instr->op == nir_texop_texture_samples) {
3378 LLVMValueRef res, samples, is_msaa;
3379 res = LLVMBuildBitCast(ctx->builder, res_ptr, ctx->v8i32, "");
3380 samples = LLVMBuildExtractElement(ctx->builder, res,
3381 LLVMConstInt(ctx->i32, 3, false), "");
3382 is_msaa = LLVMBuildLShr(ctx->builder, samples,
3383 LLVMConstInt(ctx->i32, 28, false), "");
3384 is_msaa = LLVMBuildAnd(ctx->builder, is_msaa,
3385 LLVMConstInt(ctx->i32, 0xe, false), "");
3386 is_msaa = LLVMBuildICmp(ctx->builder, LLVMIntEQ, is_msaa,
3387 LLVMConstInt(ctx->i32, 0xe, false), "");
3388
3389 samples = LLVMBuildLShr(ctx->builder, samples,
3390 LLVMConstInt(ctx->i32, 16, false), "");
3391 samples = LLVMBuildAnd(ctx->builder, samples,
3392 LLVMConstInt(ctx->i32, 0xf, false), "");
3393 samples = LLVMBuildShl(ctx->builder, ctx->i32one,
3394 samples, "");
3395 samples = LLVMBuildSelect(ctx->builder, is_msaa, samples,
3396 ctx->i32one, "");
3397 result = samples;
3398 goto write_result;
3399 }
3400
3401 if (coord)
3402 for (chan = 0; chan < instr->coord_components; chan++)
3403 coords[chan] = llvm_extract_elem(ctx, coord, chan);
3404
3405 if (offsets && instr->op != nir_texop_txf) {
3406 LLVMValueRef offset[3], pack;
3407 for (chan = 0; chan < 3; ++chan)
3408 offset[chan] = ctx->i32zero;
3409
3410 tinfo.has_offset = true;
3411 for (chan = 0; chan < get_llvm_num_components(offsets); chan++) {
3412 offset[chan] = llvm_extract_elem(ctx, offsets, chan);
3413 offset[chan] = LLVMBuildAnd(ctx->builder, offset[chan],
3414 LLVMConstInt(ctx->i32, 0x3f, false), "");
3415 if (chan)
3416 offset[chan] = LLVMBuildShl(ctx->builder, offset[chan],
3417 LLVMConstInt(ctx->i32, chan * 8, false), "");
3418 }
3419 pack = LLVMBuildOr(ctx->builder, offset[0], offset[1], "");
3420 pack = LLVMBuildOr(ctx->builder, pack, offset[2], "");
3421 address[count++] = pack;
3422
3423 }
3424 /* pack LOD bias value */
3425 if (instr->op == nir_texop_txb && bias) {
3426 address[count++] = bias;
3427 }
3428
3429 /* Pack depth comparison value */
3430 if (instr->is_shadow && comparitor) {
3431 address[count++] = llvm_extract_elem(ctx, comparitor, 0);
3432 }
3433
3434 /* pack derivatives */
3435 if (ddx || ddy) {
3436 switch (instr->sampler_dim) {
3437 case GLSL_SAMPLER_DIM_3D:
3438 case GLSL_SAMPLER_DIM_CUBE:
3439 num_deriv_comp = 3;
3440 break;
3441 case GLSL_SAMPLER_DIM_2D:
3442 default:
3443 num_deriv_comp = 2;
3444 break;
3445 case GLSL_SAMPLER_DIM_1D:
3446 num_deriv_comp = 1;
3447 break;
3448 }
3449
3450 for (unsigned i = 0; i < num_deriv_comp; i++) {
3451 derivs[i * 2] = to_float(ctx, llvm_extract_elem(ctx, ddx, i));
3452 derivs[i * 2 + 1] = to_float(ctx, llvm_extract_elem(ctx, ddy, i));
3453 }
3454 }
3455
3456 if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE && coord) {
3457 for (chan = 0; chan < instr->coord_components; chan++)
3458 coords[chan] = to_float(ctx, coords[chan]);
3459 if (instr->coord_components == 3)
3460 coords[3] = LLVMGetUndef(ctx->f32);
3461 emit_prepare_cube_coords(ctx, coords, instr->coord_components, instr->op == nir_texop_txd, instr->is_array, derivs);
3462 if (num_deriv_comp)
3463 num_deriv_comp--;
3464 }
3465
3466 if (ddx || ddy) {
3467 for (unsigned i = 0; i < num_deriv_comp * 2; i++)
3468 address[count++] = derivs[i];
3469 }
3470
3471 /* Pack texture coordinates */
3472 if (coord) {
3473 address[count++] = coords[0];
3474 if (instr->coord_components > 1)
3475 address[count++] = coords[1];
3476 if (instr->coord_components > 2) {
3477 /* This seems like a bit of a hack - but it passes Vulkan CTS with it */
3478 if (instr->sampler_dim != GLSL_SAMPLER_DIM_3D && instr->op != nir_texop_txf) {
3479 coords[2] = to_float(ctx, coords[2]);
3480 coords[2] = emit_llvm_intrinsic(ctx, "llvm.rint.f32", ctx->f32, &coords[2],
3481 1, 0);
3482 coords[2] = to_integer(ctx, coords[2]);
3483 }
3484 address[count++] = coords[2];
3485 }
3486 }
3487
3488 /* Pack LOD */
3489 if ((instr->op == nir_texop_txl || instr->op == nir_texop_txf) && lod) {
3490 address[count++] = lod;
3491 } else if (instr->op == nir_texop_txf_ms && sample_index) {
3492 address[count++] = sample_index;
3493 } else if(instr->op == nir_texop_txs) {
3494 count = 0;
3495 address[count++] = lod;
3496 }
3497
3498 for (chan = 0; chan < count; chan++) {
3499 address[chan] = LLVMBuildBitCast(ctx->builder,
3500 address[chan], ctx->i32, "");
3501 }
3502
3503 if (instr->op == nir_texop_samples_identical) {
3504 LLVMValueRef txf_address[4];
3505 struct ac_tex_info txf_info = { 0 };
3506 unsigned txf_count = count;
3507 memcpy(txf_address, address, sizeof(txf_address));
3508
3509 if (!instr->is_array)
3510 txf_address[2] = ctx->i32zero;
3511 txf_address[3] = ctx->i32zero;
3512
3513 set_tex_fetch_args(ctx, &txf_info, instr, nir_texop_txf,
3514 fmask_ptr, NULL,
3515 txf_address, txf_count, 0xf);
3516
3517 result = build_tex_intrinsic(ctx, instr, &txf_info);
3518
3519 result = LLVMBuildExtractElement(ctx->builder, result, ctx->i32zero, "");
3520 result = emit_int_cmp(ctx, LLVMIntEQ, result, ctx->i32zero);
3521 goto write_result;
3522 }
3523
3524 /* Adjust the sample index according to FMASK.
3525 *
3526 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
3527 * which is the identity mapping. Each nibble says which physical sample
3528 * should be fetched to get that sample.
3529 *
3530 * For example, 0x11111100 means there are only 2 samples stored and
3531 * the second sample covers 3/4 of the pixel. When reading samples 0
3532 * and 1, return physical sample 0 (determined by the first two 0s
3533 * in FMASK), otherwise return physical sample 1.
3534 *
3535 * The sample index should be adjusted as follows:
3536 * sample_index = (fmask >> (sample_index * 4)) & 0xF;
3537 */
3538 if (instr->sampler_dim == GLSL_SAMPLER_DIM_MS) {
3539 LLVMValueRef txf_address[4];
3540 struct ac_tex_info txf_info = { 0 };
3541 unsigned txf_count = count;
3542 memcpy(txf_address, address, sizeof(txf_address));
3543
3544 if (!instr->is_array)
3545 txf_address[2] = ctx->i32zero;
3546 txf_address[3] = ctx->i32zero;
3547
3548 set_tex_fetch_args(ctx, &txf_info, instr, nir_texop_txf,
3549 fmask_ptr, NULL,
3550 txf_address, txf_count, 0xf);
3551
3552 result = build_tex_intrinsic(ctx, instr, &txf_info);
3553 LLVMValueRef four = LLVMConstInt(ctx->i32, 4, false);
3554 LLVMValueRef F = LLVMConstInt(ctx->i32, 0xf, false);
3555
3556 LLVMValueRef fmask = LLVMBuildExtractElement(ctx->builder,
3557 result,
3558 ctx->i32zero, "");
3559
3560 unsigned sample_chan = instr->is_array ? 3 : 2;
3561
3562 LLVMValueRef sample_index4 =
3563 LLVMBuildMul(ctx->builder, address[sample_chan], four, "");
3564 LLVMValueRef shifted_fmask =
3565 LLVMBuildLShr(ctx->builder, fmask, sample_index4, "");
3566 LLVMValueRef final_sample =
3567 LLVMBuildAnd(ctx->builder, shifted_fmask, F, "");
3568
3569 /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
3570 * resource descriptor is 0 (invalid),
3571 */
3572 LLVMValueRef fmask_desc =
3573 LLVMBuildBitCast(ctx->builder, fmask_ptr,
3574 ctx->v8i32, "");
3575
3576 LLVMValueRef fmask_word1 =
3577 LLVMBuildExtractElement(ctx->builder, fmask_desc,
3578 ctx->i32one, "");
3579
3580 LLVMValueRef word1_is_nonzero =
3581 LLVMBuildICmp(ctx->builder, LLVMIntNE,
3582 fmask_word1, ctx->i32zero, "");
3583
3584 /* Replace the MSAA sample index. */
3585 address[sample_chan] =
3586 LLVMBuildSelect(ctx->builder, word1_is_nonzero,
3587 final_sample, address[sample_chan], "");
3588 }
3589
3590 if (offsets && instr->op == nir_texop_txf) {
3591 nir_const_value *const_offset =
3592 nir_src_as_const_value(instr->src[const_src].src);
3593
3594 assert(const_offset);
3595 if (instr->coord_components > 2)
3596 address[2] = LLVMBuildAdd(ctx->builder,
3597 address[2], LLVMConstInt(ctx->i32, const_offset->i32[2], false), "");
3598 if (instr->coord_components > 1)
3599 address[1] = LLVMBuildAdd(ctx->builder,
3600 address[1], LLVMConstInt(ctx->i32, const_offset->i32[1], false), "");
3601 address[0] = LLVMBuildAdd(ctx->builder,
3602 address[0], LLVMConstInt(ctx->i32, const_offset->i32[0], false), "");
3603
3604 }
3605
3606 /* TODO TG4 support */
3607 if (instr->op == nir_texop_tg4) {
3608 if (instr->is_shadow)
3609 dmask = 1;
3610 else
3611 dmask = 1 << instr->component;
3612 }
3613 set_tex_fetch_args(ctx, &tinfo, instr, instr->op,
3614 res_ptr, samp_ptr, address, count, dmask);
3615
3616 result = build_tex_intrinsic(ctx, instr, &tinfo);
3617
3618 if (instr->op == nir_texop_query_levels)
3619 result = LLVMBuildExtractElement(ctx->builder, result, LLVMConstInt(ctx->i32, 3, false), "");
3620 else if (instr->op == nir_texop_txs &&
3621 instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE &&
3622 instr->is_array) {
3623 LLVMValueRef two = LLVMConstInt(ctx->i32, 2, false);
3624 LLVMValueRef six = LLVMConstInt(ctx->i32, 6, false);
3625 LLVMValueRef z = LLVMBuildExtractElement(ctx->builder, result, two, "");
3626 z = LLVMBuildSDiv(ctx->builder, z, six, "");
3627 result = LLVMBuildInsertElement(ctx->builder, result, z, two, "");
3628 } else if (instr->dest.ssa.num_components != 4)
3629 result = trim_vector(ctx, result, instr->dest.ssa.num_components);
3630
3631 write_result:
3632 if (result) {
3633 assert(instr->dest.is_ssa);
3634 result = to_integer(ctx, result);
3635 _mesa_hash_table_insert(ctx->defs, &instr->dest.ssa, result);
3636 }
3637 }
3638
3639
3640 static void visit_phi(struct nir_to_llvm_context *ctx, nir_phi_instr *instr)
3641 {
3642 LLVMTypeRef type = get_def_type(ctx, &instr->dest.ssa);
3643 LLVMValueRef result = LLVMBuildPhi(ctx->builder, type, "");
3644
3645 _mesa_hash_table_insert(ctx->defs, &instr->dest.ssa, result);
3646 _mesa_hash_table_insert(ctx->phis, instr, result);
3647 }
3648
3649 static void visit_post_phi(struct nir_to_llvm_context *ctx,
3650 nir_phi_instr *instr,
3651 LLVMValueRef llvm_phi)
3652 {
3653 nir_foreach_phi_src(src, instr) {
3654 LLVMBasicBlockRef block = get_block(ctx, src->pred);
3655 LLVMValueRef llvm_src = get_src(ctx, src->src);
3656
3657 LLVMAddIncoming(llvm_phi, &llvm_src, &block, 1);
3658 }
3659 }
3660
3661 static void phi_post_pass(struct nir_to_llvm_context *ctx)
3662 {
3663 struct hash_entry *entry;
3664 hash_table_foreach(ctx->phis, entry) {
3665 visit_post_phi(ctx, (nir_phi_instr*)entry->key,
3666 (LLVMValueRef)entry->data);
3667 }
3668 }
3669
3670
3671 static void visit_ssa_undef(struct nir_to_llvm_context *ctx,
3672 nir_ssa_undef_instr *instr)
3673 {
3674 unsigned num_components = instr->def.num_components;
3675 LLVMValueRef undef;
3676
3677 if (num_components == 1)
3678 undef = LLVMGetUndef(ctx->i32);
3679 else {
3680 undef = LLVMGetUndef(LLVMVectorType(ctx->i32, num_components));
3681 }
3682 _mesa_hash_table_insert(ctx->defs, &instr->def, undef);
3683 }
3684
3685 static void visit_jump(struct nir_to_llvm_context *ctx,
3686 nir_jump_instr *instr)
3687 {
3688 switch (instr->type) {
3689 case nir_jump_break:
3690 LLVMBuildBr(ctx->builder, ctx->break_block);
3691 LLVMClearInsertionPosition(ctx->builder);
3692 break;
3693 case nir_jump_continue:
3694 LLVMBuildBr(ctx->builder, ctx->continue_block);
3695 LLVMClearInsertionPosition(ctx->builder);
3696 break;
3697 default:
3698 fprintf(stderr, "Unknown NIR jump instr: ");
3699 nir_print_instr(&instr->instr, stderr);
3700 fprintf(stderr, "\n");
3701 abort();
3702 }
3703 }
3704
3705 static void visit_cf_list(struct nir_to_llvm_context *ctx,
3706 struct exec_list *list);
3707
3708 static void visit_block(struct nir_to_llvm_context *ctx, nir_block *block)
3709 {
3710 LLVMBasicBlockRef llvm_block = LLVMGetInsertBlock(ctx->builder);
3711 nir_foreach_instr(instr, block)
3712 {
3713 switch (instr->type) {
3714 case nir_instr_type_alu:
3715 visit_alu(ctx, nir_instr_as_alu(instr));
3716 break;
3717 case nir_instr_type_load_const:
3718 visit_load_const(ctx, nir_instr_as_load_const(instr));
3719 break;
3720 case nir_instr_type_intrinsic:
3721 visit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
3722 break;
3723 case nir_instr_type_tex:
3724 visit_tex(ctx, nir_instr_as_tex(instr));
3725 break;
3726 case nir_instr_type_phi:
3727 visit_phi(ctx, nir_instr_as_phi(instr));
3728 break;
3729 case nir_instr_type_ssa_undef:
3730 visit_ssa_undef(ctx, nir_instr_as_ssa_undef(instr));
3731 break;
3732 case nir_instr_type_jump:
3733 visit_jump(ctx, nir_instr_as_jump(instr));
3734 break;
3735 default:
3736 fprintf(stderr, "Unknown NIR instr type: ");
3737 nir_print_instr(instr, stderr);
3738 fprintf(stderr, "\n");
3739 abort();
3740 }
3741 }
3742
3743 _mesa_hash_table_insert(ctx->defs, block, llvm_block);
3744 }
3745
3746 static void visit_if(struct nir_to_llvm_context *ctx, nir_if *if_stmt)
3747 {
3748 LLVMValueRef value = get_src(ctx, if_stmt->condition);
3749
3750 LLVMBasicBlockRef merge_block =
3751 LLVMAppendBasicBlockInContext(ctx->context, ctx->main_function, "");
3752 LLVMBasicBlockRef if_block =
3753 LLVMAppendBasicBlockInContext(ctx->context, ctx->main_function, "");
3754 LLVMBasicBlockRef else_block = merge_block;
3755 if (!exec_list_is_empty(&if_stmt->else_list))
3756 else_block = LLVMAppendBasicBlockInContext(
3757 ctx->context, ctx->main_function, "");
3758
3759 LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE, value,
3760 LLVMConstInt(ctx->i32, 0, false), "");
3761 LLVMBuildCondBr(ctx->builder, cond, if_block, else_block);
3762
3763 LLVMPositionBuilderAtEnd(ctx->builder, if_block);
3764 visit_cf_list(ctx, &if_stmt->then_list);
3765 if (LLVMGetInsertBlock(ctx->builder))
3766 LLVMBuildBr(ctx->builder, merge_block);
3767
3768 if (!exec_list_is_empty(&if_stmt->else_list)) {
3769 LLVMPositionBuilderAtEnd(ctx->builder, else_block);
3770 visit_cf_list(ctx, &if_stmt->else_list);
3771 if (LLVMGetInsertBlock(ctx->builder))
3772 LLVMBuildBr(ctx->builder, merge_block);
3773 }
3774
3775 LLVMPositionBuilderAtEnd(ctx->builder, merge_block);
3776 }
3777
3778 static void visit_loop(struct nir_to_llvm_context *ctx, nir_loop *loop)
3779 {
3780 LLVMBasicBlockRef continue_parent = ctx->continue_block;
3781 LLVMBasicBlockRef break_parent = ctx->break_block;
3782
3783 ctx->continue_block =
3784 LLVMAppendBasicBlockInContext(ctx->context, ctx->main_function, "");
3785 ctx->break_block =
3786 LLVMAppendBasicBlockInContext(ctx->context, ctx->main_function, "");
3787
3788 LLVMBuildBr(ctx->builder, ctx->continue_block);
3789 LLVMPositionBuilderAtEnd(ctx->builder, ctx->continue_block);
3790 visit_cf_list(ctx, &loop->body);
3791
3792 if (LLVMGetInsertBlock(ctx->builder))
3793 LLVMBuildBr(ctx->builder, ctx->continue_block);
3794 LLVMPositionBuilderAtEnd(ctx->builder, ctx->break_block);
3795
3796 ctx->continue_block = continue_parent;
3797 ctx->break_block = break_parent;
3798 }
3799
3800 static void visit_cf_list(struct nir_to_llvm_context *ctx,
3801 struct exec_list *list)
3802 {
3803 foreach_list_typed(nir_cf_node, node, node, list)
3804 {
3805 switch (node->type) {
3806 case nir_cf_node_block:
3807 visit_block(ctx, nir_cf_node_as_block(node));
3808 break;
3809
3810 case nir_cf_node_if:
3811 visit_if(ctx, nir_cf_node_as_if(node));
3812 break;
3813
3814 case nir_cf_node_loop:
3815 visit_loop(ctx, nir_cf_node_as_loop(node));
3816 break;
3817
3818 default:
3819 assert(0);
3820 }
3821 }
3822 }
3823
3824 static void
3825 handle_vs_input_decl(struct nir_to_llvm_context *ctx,
3826 struct nir_variable *variable)
3827 {
3828 LLVMValueRef t_list_ptr = ctx->vertex_buffers;
3829 LLVMValueRef t_offset;
3830 LLVMValueRef t_list;
3831 LLVMValueRef args[3];
3832 LLVMValueRef input;
3833 LLVMValueRef buffer_index;
3834 int index = variable->data.location - VERT_ATTRIB_GENERIC0;
3835 int idx = variable->data.location;
3836 unsigned attrib_count = glsl_count_attribute_slots(variable->type, true);
3837
3838 variable->data.driver_location = idx * 4;
3839
3840 if (ctx->options->key.vs.instance_rate_inputs & (1u << index)) {
3841 buffer_index = LLVMBuildAdd(ctx->builder, ctx->instance_id,
3842 ctx->start_instance, "");
3843 ctx->shader_info->vs.vgpr_comp_cnt = MAX2(3,
3844 ctx->shader_info->vs.vgpr_comp_cnt);
3845 } else
3846 buffer_index = LLVMBuildAdd(ctx->builder, ctx->vertex_id,
3847 ctx->base_vertex, "");
3848
3849 for (unsigned i = 0; i < attrib_count; ++i, ++idx) {
3850 t_offset = LLVMConstInt(ctx->i32, index + i, false);
3851
3852 t_list = build_indexed_load_const(ctx, t_list_ptr, t_offset);
3853 args[0] = t_list;
3854 args[1] = LLVMConstInt(ctx->i32, 0, false);
3855 args[2] = buffer_index;
3856 input = emit_llvm_intrinsic(ctx,
3857 "llvm.SI.vs.load.input", ctx->v4f32, args, 3,
3858 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_NOUNWIND);
3859
3860 for (unsigned chan = 0; chan < 4; chan++) {
3861 LLVMValueRef llvm_chan = LLVMConstInt(ctx->i32, chan, false);
3862 ctx->inputs[radeon_llvm_reg_index_soa(idx, chan)] =
3863 to_integer(ctx, LLVMBuildExtractElement(ctx->builder,
3864 input, llvm_chan, ""));
3865 }
3866 }
3867 }
3868
3869
3870 static void interp_fs_input(struct nir_to_llvm_context *ctx,
3871 unsigned attr,
3872 LLVMValueRef interp_param,
3873 LLVMValueRef prim_mask,
3874 LLVMValueRef result[4])
3875 {
3876 const char *intr_name;
3877 LLVMValueRef attr_number;
3878 unsigned chan;
3879
3880 attr_number = LLVMConstInt(ctx->i32, attr, false);
3881
3882 /* fs.constant returns the param from the middle vertex, so it's not
3883 * really useful for flat shading. It's meant to be used for custom
3884 * interpolation (but the intrinsic can't fetch from the other two
3885 * vertices).
3886 *
3887 * Luckily, it doesn't matter, because we rely on the FLAT_SHADE state
3888 * to do the right thing. The only reason we use fs.constant is that
3889 * fs.interp cannot be used on integers, because they can be equal
3890 * to NaN.
3891 */
3892 intr_name = interp_param ? "llvm.SI.fs.interp" : "llvm.SI.fs.constant";
3893
3894 for (chan = 0; chan < 4; chan++) {
3895 LLVMValueRef args[4];
3896 LLVMValueRef llvm_chan = LLVMConstInt(ctx->i32, chan, false);
3897
3898 args[0] = llvm_chan;
3899 args[1] = attr_number;
3900 args[2] = prim_mask;
3901 args[3] = interp_param;
3902 result[chan] = emit_llvm_intrinsic(ctx, intr_name,
3903 ctx->f32, args, args[3] ? 4 : 3,
3904 AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_NOUNWIND);
3905 }
3906 }
3907
3908 static void
3909 handle_fs_input_decl(struct nir_to_llvm_context *ctx,
3910 struct nir_variable *variable)
3911 {
3912 int idx = variable->data.location;
3913 unsigned attrib_count = glsl_count_attribute_slots(variable->type, false);
3914 LLVMValueRef interp;
3915
3916 variable->data.driver_location = idx * 4;
3917 ctx->input_mask |= ((1ull << attrib_count) - 1) << variable->data.location;
3918
3919 if (glsl_get_base_type(glsl_without_array(variable->type)) == GLSL_TYPE_FLOAT)
3920 interp = lookup_interp_param(ctx, variable->data.interpolation, INTERP_CENTER);
3921 else
3922 interp = NULL;
3923
3924 for (unsigned i = 0; i < attrib_count; ++i)
3925 ctx->inputs[radeon_llvm_reg_index_soa(idx + i, 0)] = interp;
3926
3927 }
3928
3929 static void
3930 handle_shader_input_decl(struct nir_to_llvm_context *ctx,
3931 struct nir_variable *variable)
3932 {
3933 switch (ctx->stage) {
3934 case MESA_SHADER_VERTEX:
3935 handle_vs_input_decl(ctx, variable);
3936 break;
3937 case MESA_SHADER_FRAGMENT:
3938 handle_fs_input_decl(ctx, variable);
3939 break;
3940 default:
3941 break;
3942 }
3943
3944 }
3945
3946 static void
3947 handle_fs_inputs_pre(struct nir_to_llvm_context *ctx,
3948 struct nir_shader *nir)
3949 {
3950 unsigned index = 0;
3951 for (unsigned i = 0; i < RADEON_LLVM_MAX_INPUTS; ++i) {
3952 LLVMValueRef interp_param;
3953 LLVMValueRef *inputs = ctx->inputs +radeon_llvm_reg_index_soa(i, 0);
3954
3955 if (!(ctx->input_mask & (1ull << i)))
3956 continue;
3957
3958 if (i >= VARYING_SLOT_VAR0 || i == VARYING_SLOT_PNTC) {
3959 interp_param = *inputs;
3960 interp_fs_input(ctx, index, interp_param, ctx->prim_mask,
3961 inputs);
3962
3963 if (!interp_param)
3964 ctx->shader_info->fs.flat_shaded_mask |= 1u << index;
3965 ++index;
3966 } else if (i == VARYING_SLOT_POS) {
3967 for(int i = 0; i < 3; ++i)
3968 inputs[i] = ctx->frag_pos[i];
3969
3970 inputs[3] = emit_fdiv(ctx, ctx->f32one, ctx->frag_pos[3]);
3971 }
3972 }
3973 ctx->shader_info->fs.num_interp = index;
3974 if (ctx->input_mask & (1 << VARYING_SLOT_PNTC))
3975 ctx->shader_info->fs.has_pcoord = true;
3976 ctx->shader_info->fs.input_mask = ctx->input_mask >> VARYING_SLOT_VAR0;
3977 }
3978
3979 static LLVMValueRef
3980 ac_build_alloca(struct nir_to_llvm_context *ctx,
3981 LLVMTypeRef type,
3982 const char *name)
3983 {
3984 LLVMBuilderRef builder = ctx->builder;
3985 LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
3986 LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
3987 LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
3988 LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
3989 LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ctx->context);
3990 LLVMValueRef res;
3991
3992 if (first_instr) {
3993 LLVMPositionBuilderBefore(first_builder, first_instr);
3994 } else {
3995 LLVMPositionBuilderAtEnd(first_builder, first_block);
3996 }
3997
3998 res = LLVMBuildAlloca(first_builder, type, name);
3999 LLVMBuildStore(builder, LLVMConstNull(type), res);
4000
4001 LLVMDisposeBuilder(first_builder);
4002
4003 return res;
4004 }
4005
4006 static LLVMValueRef si_build_alloca_undef(struct nir_to_llvm_context *ctx,
4007 LLVMTypeRef type,
4008 const char *name)
4009 {
4010 LLVMValueRef ptr = ac_build_alloca(ctx, type, name);
4011 LLVMBuildStore(ctx->builder, LLVMGetUndef(type), ptr);
4012 return ptr;
4013 }
4014
4015 static void
4016 handle_shader_output_decl(struct nir_to_llvm_context *ctx,
4017 struct nir_variable *variable)
4018 {
4019 int idx = variable->data.location;
4020 unsigned attrib_count = glsl_count_attribute_slots(variable->type, false);
4021
4022 variable->data.driver_location = idx * 4;
4023
4024 if (ctx->stage == MESA_SHADER_VERTEX) {
4025
4026 if (idx == VARYING_SLOT_CLIP_DIST0 ||
4027 idx == VARYING_SLOT_CULL_DIST0) {
4028 int length = glsl_get_length(variable->type);
4029 if (idx == VARYING_SLOT_CLIP_DIST0) {
4030 ctx->shader_info->vs.clip_dist_mask = (1 << length) - 1;
4031 ctx->num_clips = length;
4032 } else if (idx == VARYING_SLOT_CULL_DIST0) {
4033 ctx->shader_info->vs.cull_dist_mask = (1 << length) - 1;
4034 ctx->num_culls = length;
4035 }
4036 if (length > 4)
4037 attrib_count = 2;
4038 else
4039 attrib_count = 1;
4040 }
4041 }
4042
4043 for (unsigned i = 0; i < attrib_count; ++i) {
4044 for (unsigned chan = 0; chan < 4; chan++) {
4045 ctx->outputs[radeon_llvm_reg_index_soa(idx + i, chan)] =
4046 si_build_alloca_undef(ctx, ctx->f32, "");
4047 }
4048 }
4049 ctx->output_mask |= ((1ull << attrib_count) - 1) << variable->data.location;
4050 }
4051
4052 static void
4053 setup_locals(struct nir_to_llvm_context *ctx,
4054 struct nir_function *func)
4055 {
4056 int i, j;
4057 ctx->num_locals = 0;
4058 nir_foreach_variable(variable, &func->impl->locals) {
4059 unsigned attrib_count = glsl_count_attribute_slots(variable->type, false);
4060 variable->data.driver_location = ctx->num_locals * 4;
4061 ctx->num_locals += attrib_count;
4062 }
4063 ctx->locals = malloc(4 * ctx->num_locals * sizeof(LLVMValueRef));
4064 if (!ctx->locals)
4065 return;
4066
4067 for (i = 0; i < ctx->num_locals; i++) {
4068 for (j = 0; j < 4; j++) {
4069 ctx->locals[i * 4 + j] =
4070 si_build_alloca_undef(ctx, ctx->f32, "temp");
4071 }
4072 }
4073 }
4074
4075 static LLVMValueRef
4076 emit_float_saturate(struct nir_to_llvm_context *ctx, LLVMValueRef v, float lo, float hi)
4077 {
4078 v = to_float(ctx, v);
4079 v = emit_intrin_2f_param(ctx, "llvm.maxnum.f32", v, LLVMConstReal(ctx->f32, lo));
4080 return emit_intrin_2f_param(ctx, "llvm.minnum.f32", v, LLVMConstReal(ctx->f32, hi));
4081 }
4082
4083
4084 static LLVMValueRef emit_pack_int16(struct nir_to_llvm_context *ctx,
4085 LLVMValueRef src0, LLVMValueRef src1)
4086 {
4087 LLVMValueRef const16 = LLVMConstInt(ctx->i32, 16, false);
4088 LLVMValueRef comp[2];
4089
4090 comp[0] = LLVMBuildAnd(ctx->builder, src0, LLVMConstInt(ctx-> i32, 65535, 0), "");
4091 comp[1] = LLVMBuildAnd(ctx->builder, src1, LLVMConstInt(ctx-> i32, 65535, 0), "");
4092 comp[1] = LLVMBuildShl(ctx->builder, comp[1], const16, "");
4093 return LLVMBuildOr(ctx->builder, comp[0], comp[1], "");
4094 }
4095
4096 /* Initialize arguments for the shader export intrinsic */
4097 static void
4098 si_llvm_init_export_args(struct nir_to_llvm_context *ctx,
4099 LLVMValueRef *values,
4100 unsigned target,
4101 LLVMValueRef *args)
4102 {
4103 /* Default is 0xf. Adjusted below depending on the format. */
4104 args[0] = LLVMConstInt(ctx->i32, target != V_008DFC_SQ_EXP_NULL ? 0xf : 0, false);
4105 /* Specify whether the EXEC mask represents the valid mask */
4106 args[1] = LLVMConstInt(ctx->i32, 0, false);
4107
4108 /* Specify whether this is the last export */
4109 args[2] = LLVMConstInt(ctx->i32, 0, false);
4110 /* Specify the target we are exporting */
4111 args[3] = LLVMConstInt(ctx->i32, target, false);
4112
4113 args[4] = LLVMConstInt(ctx->i32, 0, false); /* COMPR flag */
4114 args[5] = LLVMGetUndef(ctx->f32);
4115 args[6] = LLVMGetUndef(ctx->f32);
4116 args[7] = LLVMGetUndef(ctx->f32);
4117 args[8] = LLVMGetUndef(ctx->f32);
4118
4119 if (!values)
4120 return;
4121
4122 if (ctx->stage == MESA_SHADER_FRAGMENT && target >= V_008DFC_SQ_EXP_MRT) {
4123 LLVMValueRef val[4];
4124 unsigned index = target - V_008DFC_SQ_EXP_MRT;
4125 unsigned col_format = (ctx->options->key.fs.col_format >> (4 * index)) & 0xf;
4126 bool is_int8 = (ctx->options->key.fs.is_int8 >> index) & 1;
4127
4128 switch(col_format) {
4129 case V_028714_SPI_SHADER_ZERO:
4130 args[0] = LLVMConstInt(ctx->i32, 0x0, 0);
4131 args[3] = LLVMConstInt(ctx->i32, V_008DFC_SQ_EXP_NULL, 0);
4132 break;
4133
4134 case V_028714_SPI_SHADER_32_R:
4135 args[0] = LLVMConstInt(ctx->i32, 0x1, 0);
4136 args[5] = values[0];
4137 break;
4138
4139 case V_028714_SPI_SHADER_32_GR:
4140 args[0] = LLVMConstInt(ctx->i32, 0x3, 0);
4141 args[5] = values[0];
4142 args[6] = values[1];
4143 break;
4144
4145 case V_028714_SPI_SHADER_32_AR:
4146 args[0] = LLVMConstInt(ctx->i32, 0x9, 0);
4147 args[5] = values[0];
4148 args[8] = values[3];
4149 break;
4150
4151 case V_028714_SPI_SHADER_FP16_ABGR:
4152 args[4] = ctx->i32one;
4153
4154 for (unsigned chan = 0; chan < 2; chan++) {
4155 LLVMValueRef pack_args[2] = {
4156 values[2 * chan],
4157 values[2 * chan + 1]
4158 };
4159 LLVMValueRef packed;
4160
4161 packed = emit_llvm_intrinsic(ctx, "llvm.SI.packf16",
4162 ctx->i32, pack_args, 2,
4163 AC_FUNC_ATTR_READNONE);
4164 args[chan + 5] = packed;
4165 }
4166 break;
4167
4168 case V_028714_SPI_SHADER_UNORM16_ABGR:
4169 for (unsigned chan = 0; chan < 4; chan++) {
4170 val[chan] = emit_float_saturate(ctx, values[chan], 0, 1);
4171 val[chan] = LLVMBuildFMul(ctx->builder, val[chan],
4172 LLVMConstReal(ctx->f32, 65535), "");
4173 val[chan] = LLVMBuildFAdd(ctx->builder, val[chan],
4174 LLVMConstReal(ctx->f32, 0.5), "");
4175 val[chan] = LLVMBuildFPToUI(ctx->builder, val[chan],
4176 ctx->i32, "");
4177 }
4178
4179 args[4] = ctx->i32one;
4180 args[5] = emit_pack_int16(ctx, val[0], val[1]);
4181 args[6] = emit_pack_int16(ctx, val[2], val[3]);
4182 break;
4183
4184 case V_028714_SPI_SHADER_SNORM16_ABGR:
4185 for (unsigned chan = 0; chan < 4; chan++) {
4186 val[chan] = emit_float_saturate(ctx, values[chan], -1, 1);
4187 val[chan] = LLVMBuildFMul(ctx->builder, val[chan],
4188 LLVMConstReal(ctx->f32, 32767), "");
4189
4190 /* If positive, add 0.5, else add -0.5. */
4191 val[chan] = LLVMBuildFAdd(ctx->builder, val[chan],
4192 LLVMBuildSelect(ctx->builder,
4193 LLVMBuildFCmp(ctx->builder, LLVMRealOGE,
4194 val[chan], ctx->f32zero, ""),
4195 LLVMConstReal(ctx->f32, 0.5),
4196 LLVMConstReal(ctx->f32, -0.5), ""), "");
4197 val[chan] = LLVMBuildFPToSI(ctx->builder, val[chan], ctx->i32, "");
4198 }
4199
4200 args[4] = ctx->i32one;
4201 args[5] = emit_pack_int16(ctx, val[0], val[1]);
4202 args[6] = emit_pack_int16(ctx, val[2], val[3]);
4203 break;
4204
4205 case V_028714_SPI_SHADER_UINT16_ABGR: {
4206 LLVMValueRef max = LLVMConstInt(ctx->i32, is_int8 ? 255 : 65535, 0);
4207
4208 for (unsigned chan = 0; chan < 4; chan++) {
4209 val[chan] = to_integer(ctx, values[chan]);
4210 val[chan] = emit_minmax_int(ctx, LLVMIntULT, val[chan], max);
4211 }
4212
4213 args[4] = ctx->i32one;
4214 args[5] = emit_pack_int16(ctx, val[0], val[1]);
4215 args[6] = emit_pack_int16(ctx, val[2], val[3]);
4216 break;
4217 }
4218
4219 case V_028714_SPI_SHADER_SINT16_ABGR: {
4220 LLVMValueRef max = LLVMConstInt(ctx->i32, is_int8 ? 127 : 32767, 0);
4221 LLVMValueRef min = LLVMConstInt(ctx->i32, is_int8 ? -128 : -32768, 0);
4222
4223 /* Clamp. */
4224 for (unsigned chan = 0; chan < 4; chan++) {
4225 val[chan] = to_integer(ctx, values[chan]);
4226 val[chan] = emit_minmax_int(ctx, LLVMIntSLT, val[chan], max);
4227 val[chan] = emit_minmax_int(ctx, LLVMIntSGT, val[chan], min);
4228 }
4229
4230 args[4] = ctx->i32one;
4231 args[5] = emit_pack_int16(ctx, val[0], val[1]);
4232 args[6] = emit_pack_int16(ctx, val[2], val[3]);
4233 break;
4234 }
4235
4236 default:
4237 case V_028714_SPI_SHADER_32_ABGR:
4238 memcpy(&args[5], values, sizeof(values[0]) * 4);
4239 break;
4240 }
4241 } else
4242 memcpy(&args[5], values, sizeof(values[0]) * 4);
4243
4244 for (unsigned i = 5; i < 9; ++i)
4245 args[i] = to_float(ctx, args[i]);
4246 }
4247
4248 static void
4249 handle_vs_outputs_post(struct nir_to_llvm_context *ctx,
4250 struct nir_shader *nir)
4251 {
4252 uint32_t param_count = 0;
4253 unsigned target;
4254 unsigned pos_idx, num_pos_exports = 0;
4255 LLVMValueRef args[9];
4256 LLVMValueRef pos_args[4][9] = { { 0 } };
4257 LLVMValueRef psize_value = 0;
4258 int i;
4259 const uint64_t clip_mask = ctx->output_mask & ((1ull << VARYING_SLOT_CLIP_DIST0) |
4260 (1ull << VARYING_SLOT_CLIP_DIST1) |
4261 (1ull << VARYING_SLOT_CULL_DIST0) |
4262 (1ull << VARYING_SLOT_CULL_DIST1));
4263
4264 if (clip_mask) {
4265 LLVMValueRef slots[8];
4266 unsigned j;
4267
4268 if (ctx->shader_info->vs.cull_dist_mask)
4269 ctx->shader_info->vs.cull_dist_mask <<= ctx->num_clips;
4270
4271 i = VARYING_SLOT_CLIP_DIST0;
4272 for (j = 0; j < ctx->num_clips; j++)
4273 slots[j] = to_float(ctx, LLVMBuildLoad(ctx->builder,
4274 ctx->outputs[radeon_llvm_reg_index_soa(i, j)], ""));
4275 i = VARYING_SLOT_CULL_DIST0;
4276 for (j = 0; j < ctx->num_culls; j++)
4277 slots[ctx->num_clips + j] = to_float(ctx, LLVMBuildLoad(ctx->builder,
4278 ctx->outputs[radeon_llvm_reg_index_soa(i, j)], ""));
4279
4280 for (i = ctx->num_clips + ctx->num_culls; i < 8; i++)
4281 slots[i] = LLVMGetUndef(ctx->f32);
4282
4283 if (ctx->num_clips + ctx->num_culls > 4) {
4284 target = V_008DFC_SQ_EXP_POS + 3;
4285 si_llvm_init_export_args(ctx, &slots[4], target, args);
4286 memcpy(pos_args[target - V_008DFC_SQ_EXP_POS],
4287 args, sizeof(args));
4288 }
4289
4290 target = V_008DFC_SQ_EXP_POS + 2;
4291 si_llvm_init_export_args(ctx, &slots[0], target, args);
4292 memcpy(pos_args[target - V_008DFC_SQ_EXP_POS],
4293 args, sizeof(args));
4294
4295 }
4296
4297 for (unsigned i = 0; i < RADEON_LLVM_MAX_OUTPUTS; ++i) {
4298 LLVMValueRef values[4];
4299 if (!(ctx->output_mask & (1ull << i)))
4300 continue;
4301
4302 for (unsigned j = 0; j < 4; j++)
4303 values[j] = to_float(ctx, LLVMBuildLoad(ctx->builder,
4304 ctx->outputs[radeon_llvm_reg_index_soa(i, j)], ""));
4305
4306 if (i == VARYING_SLOT_POS) {
4307 target = V_008DFC_SQ_EXP_POS;
4308 } else if (i == VARYING_SLOT_CLIP_DIST0 ||
4309 i == VARYING_SLOT_CLIP_DIST1 ||
4310 i == VARYING_SLOT_CULL_DIST0 ||
4311 i == VARYING_SLOT_CULL_DIST1) {
4312 continue;
4313 } else if (i == VARYING_SLOT_PSIZ) {
4314 ctx->shader_info->vs.writes_pointsize = true;
4315 psize_value = values[0];
4316 continue;
4317 } else if (i >= VARYING_SLOT_VAR0) {
4318 ctx->shader_info->vs.export_mask |= 1u << (i - VARYING_SLOT_VAR0);
4319 target = V_008DFC_SQ_EXP_PARAM + param_count;
4320 param_count++;
4321 }
4322
4323 si_llvm_init_export_args(ctx, values, target, args);
4324
4325 if (target >= V_008DFC_SQ_EXP_POS &&
4326 target <= (V_008DFC_SQ_EXP_POS + 3)) {
4327 memcpy(pos_args[target - V_008DFC_SQ_EXP_POS],
4328 args, sizeof(args));
4329 } else {
4330 emit_llvm_intrinsic(ctx,
4331 "llvm.SI.export",
4332 LLVMVoidTypeInContext(ctx->context),
4333 args, 9, 0);
4334 }
4335 }
4336
4337 /* We need to add the position output manually if it's missing. */
4338 if (!pos_args[0][0]) {
4339 pos_args[0][0] = LLVMConstInt(ctx->i32, 0xf, false);
4340 pos_args[0][1] = ctx->i32zero; /* EXEC mask */
4341 pos_args[0][2] = ctx->i32zero; /* last export? */
4342 pos_args[0][3] = LLVMConstInt(ctx->i32, V_008DFC_SQ_EXP_POS, false);
4343 pos_args[0][4] = ctx->i32zero; /* COMPR flag */
4344 pos_args[0][5] = ctx->f32zero; /* X */
4345 pos_args[0][6] = ctx->f32zero; /* Y */
4346 pos_args[0][7] = ctx->f32zero; /* Z */
4347 pos_args[0][8] = ctx->f32one; /* W */
4348 }
4349
4350 if (ctx->shader_info->vs.writes_pointsize == true) {
4351 pos_args[1][0] = LLVMConstInt(ctx->i32, (ctx->shader_info->vs.writes_pointsize == true), false); /* writemask */
4352 pos_args[1][1] = ctx->i32zero; /* EXEC mask */
4353 pos_args[1][2] = ctx->i32zero; /* last export? */
4354 pos_args[1][3] = LLVMConstInt(ctx->i32, V_008DFC_SQ_EXP_POS + 1, false);
4355 pos_args[1][4] = ctx->i32zero; /* COMPR flag */
4356 pos_args[1][5] = ctx->f32zero; /* X */
4357 pos_args[1][6] = ctx->f32zero; /* Y */
4358 pos_args[1][7] = ctx->f32zero; /* Z */
4359 pos_args[1][8] = ctx->f32zero; /* W */
4360
4361 if (ctx->shader_info->vs.writes_pointsize == true)
4362 pos_args[1][5] = psize_value;
4363 }
4364 for (i = 0; i < 4; i++) {
4365 if (pos_args[i][0])
4366 num_pos_exports++;
4367 }
4368
4369 pos_idx = 0;
4370 for (i = 0; i < 4; i++) {
4371 if (!pos_args[i][0])
4372 continue;
4373
4374 /* Specify the target we are exporting */
4375 pos_args[i][3] = LLVMConstInt(ctx->i32, V_008DFC_SQ_EXP_POS + pos_idx++, false);
4376 if (pos_idx == num_pos_exports)
4377 pos_args[i][2] = ctx->i32one;
4378 emit_llvm_intrinsic(ctx,
4379 "llvm.SI.export",
4380 LLVMVoidTypeInContext(ctx->context),
4381 pos_args[i], 9, 0);
4382 }
4383
4384 ctx->shader_info->vs.pos_exports = num_pos_exports;
4385 ctx->shader_info->vs.param_exports = param_count;
4386 }
4387
4388 static void
4389 si_export_mrt_color(struct nir_to_llvm_context *ctx,
4390 LLVMValueRef *color, unsigned param, bool is_last)
4391 {
4392 LLVMValueRef args[9];
4393 /* Export */
4394 si_llvm_init_export_args(ctx, color, param,
4395 args);
4396
4397 if (is_last) {
4398 args[1] = ctx->i32one; /* whether the EXEC mask is valid */
4399 args[2] = ctx->i32one; /* DONE bit */
4400 } else if (args[0] == ctx->i32zero)
4401 return; /* unnecessary NULL export */
4402
4403 emit_llvm_intrinsic(ctx, "llvm.SI.export",
4404 ctx->voidt, args, 9, 0);
4405 }
4406
4407 static void
4408 si_export_mrt_z(struct nir_to_llvm_context *ctx,
4409 LLVMValueRef depth, LLVMValueRef stencil,
4410 LLVMValueRef samplemask)
4411 {
4412 LLVMValueRef args[9];
4413 unsigned mask = 0;
4414 args[1] = ctx->i32one; /* whether the EXEC mask is valid */
4415 args[2] = ctx->i32one; /* DONE bit */
4416 /* Specify the target we are exporting */
4417 args[3] = LLVMConstInt(ctx->i32, V_008DFC_SQ_EXP_MRTZ, false);
4418
4419 args[4] = ctx->i32zero; /* COMP flag */
4420 args[5] = LLVMGetUndef(ctx->f32); /* R, depth */
4421 args[6] = LLVMGetUndef(ctx->f32); /* G, stencil test val[0:7], stencil op val[8:15] */
4422 args[7] = LLVMGetUndef(ctx->f32); /* B, sample mask */
4423 args[8] = LLVMGetUndef(ctx->f32); /* A, alpha to mask */
4424
4425 if (depth) {
4426 args[5] = depth;
4427 mask |= 0x1;
4428 }
4429
4430 if (stencil) {
4431 args[6] = stencil;
4432 mask |= 0x2;
4433 }
4434
4435 if (samplemask) {
4436 args[7] = samplemask;
4437 mask |= 0x04;
4438 }
4439
4440 /* SI (except OLAND) has a bug that it only looks
4441 * at the X writemask component. */
4442 if (ctx->options->chip_class == SI &&
4443 ctx->options->family != CHIP_OLAND)
4444 mask |= 0x01;
4445
4446 args[0] = LLVMConstInt(ctx->i32, mask, false);
4447 emit_llvm_intrinsic(ctx, "llvm.SI.export",
4448 ctx->voidt, args, 9, 0);
4449 }
4450
4451 static void
4452 handle_fs_outputs_post(struct nir_to_llvm_context *ctx,
4453 struct nir_shader *nir)
4454 {
4455 unsigned index = 0;
4456 LLVMValueRef depth = NULL, stencil = NULL, samplemask = NULL;
4457
4458 for (unsigned i = 0; i < RADEON_LLVM_MAX_OUTPUTS; ++i) {
4459 LLVMValueRef values[4];
4460
4461 if (!(ctx->output_mask & (1ull << i)))
4462 continue;
4463
4464 if (i == FRAG_RESULT_DEPTH) {
4465 ctx->shader_info->fs.writes_z = true;
4466 depth = to_float(ctx, LLVMBuildLoad(ctx->builder,
4467 ctx->outputs[radeon_llvm_reg_index_soa(i, 0)], ""));
4468 } else if (i == FRAG_RESULT_STENCIL) {
4469 ctx->shader_info->fs.writes_stencil = true;
4470 stencil = to_float(ctx, LLVMBuildLoad(ctx->builder,
4471 ctx->outputs[radeon_llvm_reg_index_soa(i, 0)], ""));
4472 } else {
4473 bool last = false;
4474 for (unsigned j = 0; j < 4; j++)
4475 values[j] = to_float(ctx, LLVMBuildLoad(ctx->builder,
4476 ctx->outputs[radeon_llvm_reg_index_soa(i, j)], ""));
4477
4478 if (!ctx->shader_info->fs.writes_z && !ctx->shader_info->fs.writes_stencil)
4479 last = ctx->output_mask <= ((1ull << (i + 1)) - 1);
4480
4481 si_export_mrt_color(ctx, values, V_008DFC_SQ_EXP_MRT + index, last);
4482 index++;
4483 }
4484 }
4485
4486 if (depth || stencil)
4487 si_export_mrt_z(ctx, depth, stencil, samplemask);
4488 else if (!index)
4489 si_export_mrt_color(ctx, NULL, V_008DFC_SQ_EXP_NULL, true);
4490
4491 ctx->shader_info->fs.output_mask = index ? ((1ull << index) - 1) : 0;
4492 }
4493
4494 static void
4495 handle_shader_outputs_post(struct nir_to_llvm_context *ctx,
4496 struct nir_shader *nir)
4497 {
4498 switch (ctx->stage) {
4499 case MESA_SHADER_VERTEX:
4500 handle_vs_outputs_post(ctx, nir);
4501 break;
4502 case MESA_SHADER_FRAGMENT:
4503 handle_fs_outputs_post(ctx, nir);
4504 break;
4505 default:
4506 break;
4507 }
4508 }
4509
4510 static void
4511 handle_shared_compute_var(struct nir_to_llvm_context *ctx,
4512 struct nir_variable *variable, uint32_t *offset, int idx)
4513 {
4514 unsigned size = glsl_count_attribute_slots(variable->type, false);
4515 variable->data.driver_location = *offset;
4516 *offset += size;
4517 }
4518
4519 static void ac_llvm_finalize_module(struct nir_to_llvm_context * ctx)
4520 {
4521 LLVMPassManagerRef passmgr;
4522 /* Create the pass manager */
4523 passmgr = LLVMCreateFunctionPassManagerForModule(
4524 ctx->module);
4525
4526 /* This pass should eliminate all the load and store instructions */
4527 LLVMAddPromoteMemoryToRegisterPass(passmgr);
4528
4529 /* Add some optimization passes */
4530 LLVMAddScalarReplAggregatesPass(passmgr);
4531 LLVMAddLICMPass(passmgr);
4532 LLVMAddAggressiveDCEPass(passmgr);
4533 LLVMAddCFGSimplificationPass(passmgr);
4534 LLVMAddInstructionCombiningPass(passmgr);
4535
4536 /* Run the pass */
4537 LLVMInitializeFunctionPassManager(passmgr);
4538 LLVMRunFunctionPassManager(passmgr, ctx->main_function);
4539 LLVMFinalizeFunctionPassManager(passmgr);
4540
4541 LLVMDisposeBuilder(ctx->builder);
4542 LLVMDisposePassManager(passmgr);
4543 }
4544
4545 static
4546 LLVMModuleRef ac_translate_nir_to_llvm(LLVMTargetMachineRef tm,
4547 struct nir_shader *nir,
4548 struct ac_shader_variant_info *shader_info,
4549 const struct ac_nir_compiler_options *options)
4550 {
4551 struct nir_to_llvm_context ctx = {0};
4552 struct nir_function *func;
4553 ctx.options = options;
4554 ctx.shader_info = shader_info;
4555 ctx.context = LLVMContextCreate();
4556 ctx.module = LLVMModuleCreateWithNameInContext("shader", ctx.context);
4557
4558 memset(shader_info, 0, sizeof(*shader_info));
4559
4560 LLVMSetTarget(ctx.module, "amdgcn--");
4561 setup_types(&ctx);
4562
4563 ctx.builder = LLVMCreateBuilderInContext(ctx.context);
4564 ctx.stage = nir->stage;
4565
4566 create_function(&ctx, nir);
4567
4568 if (nir->stage == MESA_SHADER_COMPUTE) {
4569 int num_shared = 0;
4570 nir_foreach_variable(variable, &nir->shared)
4571 num_shared++;
4572 if (num_shared) {
4573 int idx = 0;
4574 uint32_t shared_size = 0;
4575 LLVMValueRef var;
4576 LLVMTypeRef i8p = LLVMPointerType(ctx.i8, LOCAL_ADDR_SPACE);
4577 nir_foreach_variable(variable, &nir->shared) {
4578 handle_shared_compute_var(&ctx, variable, &shared_size, idx);
4579 idx++;
4580 }
4581
4582 shared_size *= 4;
4583 var = LLVMAddGlobalInAddressSpace(ctx.module,
4584 LLVMArrayType(ctx.i8, shared_size),
4585 "compute_lds",
4586 LOCAL_ADDR_SPACE);
4587 LLVMSetAlignment(var, 4);
4588 ctx.shared_memory = LLVMBuildBitCast(ctx.builder, var, i8p, "");
4589 }
4590 }
4591
4592 nir_foreach_variable(variable, &nir->inputs)
4593 handle_shader_input_decl(&ctx, variable);
4594
4595 if (nir->stage == MESA_SHADER_FRAGMENT)
4596 handle_fs_inputs_pre(&ctx, nir);
4597
4598 nir_foreach_variable(variable, &nir->outputs)
4599 handle_shader_output_decl(&ctx, variable);
4600
4601 ctx.defs = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
4602 _mesa_key_pointer_equal);
4603 ctx.phis = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
4604 _mesa_key_pointer_equal);
4605
4606 func = (struct nir_function *)exec_list_get_head(&nir->functions);
4607
4608 setup_locals(&ctx, func);
4609
4610 visit_cf_list(&ctx, &func->impl->body);
4611 phi_post_pass(&ctx);
4612
4613 handle_shader_outputs_post(&ctx, nir);
4614 LLVMBuildRetVoid(ctx.builder);
4615
4616 ac_llvm_finalize_module(&ctx);
4617 free(ctx.locals);
4618 ralloc_free(ctx.defs);
4619 ralloc_free(ctx.phis);
4620
4621 return ctx.module;
4622 }
4623
4624 static void ac_diagnostic_handler(LLVMDiagnosticInfoRef di, void *context)
4625 {
4626 unsigned *retval = (unsigned *)context;
4627 LLVMDiagnosticSeverity severity = LLVMGetDiagInfoSeverity(di);
4628 char *description = LLVMGetDiagInfoDescription(di);
4629
4630 if (severity == LLVMDSError) {
4631 *retval = 1;
4632 fprintf(stderr, "LLVM triggered Diagnostic Handler: %s\n",
4633 description);
4634 }
4635
4636 LLVMDisposeMessage(description);
4637 }
4638
4639 static unsigned ac_llvm_compile(LLVMModuleRef M,
4640 struct ac_shader_binary *binary,
4641 LLVMTargetMachineRef tm)
4642 {
4643 unsigned retval = 0;
4644 char *err;
4645 LLVMContextRef llvm_ctx;
4646 LLVMMemoryBufferRef out_buffer;
4647 unsigned buffer_size;
4648 const char *buffer_data;
4649 LLVMBool mem_err;
4650
4651 /* Setup Diagnostic Handler*/
4652 llvm_ctx = LLVMGetModuleContext(M);
4653
4654 LLVMContextSetDiagnosticHandler(llvm_ctx, ac_diagnostic_handler,
4655 &retval);
4656
4657 /* Compile IR*/
4658 mem_err = LLVMTargetMachineEmitToMemoryBuffer(tm, M, LLVMObjectFile,
4659 &err, &out_buffer);
4660
4661 /* Process Errors/Warnings */
4662 if (mem_err) {
4663 fprintf(stderr, "%s: %s", __FUNCTION__, err);
4664 free(err);
4665 retval = 1;
4666 goto out;
4667 }
4668
4669 /* Extract Shader Code*/
4670 buffer_size = LLVMGetBufferSize(out_buffer);
4671 buffer_data = LLVMGetBufferStart(out_buffer);
4672
4673 ac_elf_read(buffer_data, buffer_size, binary);
4674
4675 /* Clean up */
4676 LLVMDisposeMemoryBuffer(out_buffer);
4677
4678 out:
4679 return retval;
4680 }
4681
4682 void ac_compile_nir_shader(LLVMTargetMachineRef tm,
4683 struct ac_shader_binary *binary,
4684 struct ac_shader_config *config,
4685 struct ac_shader_variant_info *shader_info,
4686 struct nir_shader *nir,
4687 const struct ac_nir_compiler_options *options,
4688 bool dump_shader)
4689 {
4690
4691 LLVMModuleRef llvm_module = ac_translate_nir_to_llvm(tm, nir, shader_info,
4692 options);
4693 if (dump_shader)
4694 LLVMDumpModule(llvm_module);
4695
4696 memset(binary, 0, sizeof(*binary));
4697 int v = ac_llvm_compile(llvm_module, binary, tm);
4698 if (v) {
4699 fprintf(stderr, "compile failed\n");
4700 }
4701
4702 if (dump_shader)
4703 fprintf(stderr, "disasm:\n%s\n", binary->disasm_string);
4704
4705 ac_shader_binary_read_config(binary, config, 0);
4706
4707 LLVMContextRef ctx = LLVMGetModuleContext(llvm_module);
4708 LLVMDisposeModule(llvm_module);
4709 LLVMContextDispose(ctx);
4710
4711 if (nir->stage == MESA_SHADER_FRAGMENT) {
4712 shader_info->num_input_vgprs = 0;
4713 if (G_0286CC_PERSP_SAMPLE_ENA(config->spi_ps_input_addr))
4714 shader_info->num_input_vgprs += 2;
4715 if (G_0286CC_PERSP_CENTER_ENA(config->spi_ps_input_addr))
4716 shader_info->num_input_vgprs += 2;
4717 if (G_0286CC_PERSP_CENTROID_ENA(config->spi_ps_input_addr))
4718 shader_info->num_input_vgprs += 2;
4719 if (G_0286CC_PERSP_PULL_MODEL_ENA(config->spi_ps_input_addr))
4720 shader_info->num_input_vgprs += 3;
4721 if (G_0286CC_LINEAR_SAMPLE_ENA(config->spi_ps_input_addr))
4722 shader_info->num_input_vgprs += 2;
4723 if (G_0286CC_LINEAR_CENTER_ENA(config->spi_ps_input_addr))
4724 shader_info->num_input_vgprs += 2;
4725 if (G_0286CC_LINEAR_CENTROID_ENA(config->spi_ps_input_addr))
4726 shader_info->num_input_vgprs += 2;
4727 if (G_0286CC_LINE_STIPPLE_TEX_ENA(config->spi_ps_input_addr))
4728 shader_info->num_input_vgprs += 1;
4729 if (G_0286CC_POS_X_FLOAT_ENA(config->spi_ps_input_addr))
4730 shader_info->num_input_vgprs += 1;
4731 if (G_0286CC_POS_Y_FLOAT_ENA(config->spi_ps_input_addr))
4732 shader_info->num_input_vgprs += 1;
4733 if (G_0286CC_POS_Z_FLOAT_ENA(config->spi_ps_input_addr))
4734 shader_info->num_input_vgprs += 1;
4735 if (G_0286CC_POS_W_FLOAT_ENA(config->spi_ps_input_addr))
4736 shader_info->num_input_vgprs += 1;
4737 if (G_0286CC_FRONT_FACE_ENA(config->spi_ps_input_addr))
4738 shader_info->num_input_vgprs += 1;
4739 if (G_0286CC_ANCILLARY_ENA(config->spi_ps_input_addr))
4740 shader_info->num_input_vgprs += 1;
4741 if (G_0286CC_SAMPLE_COVERAGE_ENA(config->spi_ps_input_addr))
4742 shader_info->num_input_vgprs += 1;
4743 if (G_0286CC_POS_FIXED_PT_ENA(config->spi_ps_input_addr))
4744 shader_info->num_input_vgprs += 1;
4745 }
4746 config->num_vgprs = MAX2(config->num_vgprs, shader_info->num_input_vgprs);
4747
4748 /* +3 for scratch wave offset and VCC */
4749 config->num_sgprs = MAX2(config->num_sgprs,
4750 shader_info->num_input_sgprs + 3);
4751 if (nir->stage == MESA_SHADER_COMPUTE) {
4752 for (int i = 0; i < 3; ++i)
4753 shader_info->cs.block_size[i] = nir->info->cs.local_size[i];
4754 }
4755
4756 if (nir->stage == MESA_SHADER_FRAGMENT)
4757 shader_info->fs.early_fragment_test = nir->info->fs.early_fragment_tests;
4758 }