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