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