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