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