• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2018 Valve Corporation
3  * Copyright © 2018 Google
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  *
24  */
25 
26 #include <algorithm>
27 #include <numeric>
28 #include <array>
29 #include <stack>
30 #include <map>
31 
32 #include "ac_shader_util.h"
33 #include "aco_ir.h"
34 #include "aco_builder.h"
35 #include "aco_interface.h"
36 #include "aco_instruction_selection.h"
37 #include "util/fast_idiv_by_const.h"
38 #include "util/memstream.h"
39 
40 #include "ac_exp_param.h"
41 #include "sid.h"
42 #include "vulkan/radv_descriptor_set.h"
43 #include "vulkan/radv_shader.h"
44 
45 namespace aco {
46 namespace {
47 
48 #define isel_err(...) _isel_err(ctx, __FILE__, __LINE__, __VA_ARGS__)
49 
_isel_err(isel_context * ctx,const char * file,unsigned line,const nir_instr * instr,const char * msg)50 static void _isel_err(isel_context *ctx, const char *file, unsigned line,
51                       const nir_instr *instr, const char *msg)
52 {
53    char *out;
54    size_t outsize;
55    struct u_memstream mem;
56    u_memstream_open(&mem, &out, &outsize);
57    FILE *const memf = u_memstream_get(&mem);
58 
59    fprintf(memf, "%s: ", msg);
60    nir_print_instr(instr, memf);
61    u_memstream_close(&mem);
62 
63    _aco_err(ctx->program, file, line, out);
64    free(out);
65 }
66 
67 struct if_context {
68    Temp cond;
69 
70    bool divergent_old;
71    bool exec_potentially_empty_discard_old;
72    bool exec_potentially_empty_break_old;
73    uint16_t exec_potentially_empty_break_depth_old;
74 
75    unsigned BB_if_idx;
76    unsigned invert_idx;
77    bool uniform_has_then_branch;
78    bool then_branch_divergent;
79    Block BB_invert;
80    Block BB_endif;
81 };
82 
83 struct loop_context {
84    Block loop_exit;
85 
86    unsigned header_idx_old;
87    Block* exit_old;
88    bool divergent_cont_old;
89    bool divergent_branch_old;
90    bool divergent_if_old;
91 };
92 
93 static bool visit_cf_list(struct isel_context *ctx,
94                           struct exec_list *list);
95 
add_logical_edge(unsigned pred_idx,Block * succ)96 static void add_logical_edge(unsigned pred_idx, Block *succ)
97 {
98    succ->logical_preds.emplace_back(pred_idx);
99 }
100 
101 
add_linear_edge(unsigned pred_idx,Block * succ)102 static void add_linear_edge(unsigned pred_idx, Block *succ)
103 {
104    succ->linear_preds.emplace_back(pred_idx);
105 }
106 
add_edge(unsigned pred_idx,Block * succ)107 static void add_edge(unsigned pred_idx, Block *succ)
108 {
109    add_logical_edge(pred_idx, succ);
110    add_linear_edge(pred_idx, succ);
111 }
112 
append_logical_start(Block * b)113 static void append_logical_start(Block *b)
114 {
115    Builder(NULL, b).pseudo(aco_opcode::p_logical_start);
116 }
117 
append_logical_end(Block * b)118 static void append_logical_end(Block *b)
119 {
120    Builder(NULL, b).pseudo(aco_opcode::p_logical_end);
121 }
122 
get_ssa_temp(struct isel_context * ctx,nir_ssa_def * def)123 Temp get_ssa_temp(struct isel_context *ctx, nir_ssa_def *def)
124 {
125    uint32_t id = ctx->first_temp_id + def->index;
126    return Temp(id, ctx->program->temp_rc[id]);
127 }
128 
emit_mbcnt(isel_context * ctx,Temp dst,Operand mask=Operand (),Operand base=Operand (0u))129 Temp emit_mbcnt(isel_context *ctx, Temp dst, Operand mask = Operand(), Operand base = Operand(0u))
130 {
131    Builder bld(ctx->program, ctx->block);
132    assert(mask.isUndefined() || mask.isTemp() || (mask.isFixed() && mask.physReg() == exec));
133    assert(mask.isUndefined() || mask.regClass() == bld.lm);
134 
135    if (ctx->program->wave_size == 32) {
136       Operand mask_lo = mask.isUndefined() ? Operand(-1u) : mask;
137       return bld.vop3(aco_opcode::v_mbcnt_lo_u32_b32, Definition(dst), mask_lo, base);
138    }
139 
140    Operand mask_lo(-1u);
141    Operand mask_hi(-1u);
142 
143    if (mask.isTemp()) {
144       Builder::Result mask_split = bld.pseudo(aco_opcode::p_split_vector, bld.def(s1), bld.def(s1), mask);
145       mask_lo = Operand(mask_split.def(0).getTemp());
146       mask_hi = Operand(mask_split.def(1).getTemp());
147    } else if (mask.physReg() == exec) {
148       mask_lo = Operand(exec_lo, s1);
149       mask_hi = Operand(exec_hi, s1);
150    }
151 
152    Temp mbcnt_lo = bld.vop3(aco_opcode::v_mbcnt_lo_u32_b32, bld.def(v1), mask_lo, base);
153 
154    if (ctx->program->chip_class <= GFX7)
155       return bld.vop2(aco_opcode::v_mbcnt_hi_u32_b32, Definition(dst), mask_hi, mbcnt_lo);
156    else
157       return bld.vop3(aco_opcode::v_mbcnt_hi_u32_b32_e64, Definition(dst), mask_hi, mbcnt_lo);
158 }
159 
emit_wqm(isel_context * ctx,Temp src,Temp dst=Temp (0,s1),bool program_needs_wqm=false)160 Temp emit_wqm(isel_context *ctx, Temp src, Temp dst=Temp(0, s1), bool program_needs_wqm = false)
161 {
162    Builder bld(ctx->program, ctx->block);
163 
164    if (!dst.id())
165       dst = bld.tmp(src.regClass());
166 
167    assert(src.size() == dst.size());
168 
169    if (ctx->stage != fragment_fs) {
170       if (!dst.id())
171          return src;
172 
173       bld.copy(Definition(dst), src);
174       return dst;
175    }
176 
177    bld.pseudo(aco_opcode::p_wqm, Definition(dst), src);
178    ctx->program->needs_wqm |= program_needs_wqm;
179    return dst;
180 }
181 
emit_bpermute(isel_context * ctx,Builder & bld,Temp index,Temp data)182 static Temp emit_bpermute(isel_context *ctx, Builder &bld, Temp index, Temp data)
183 {
184    if (index.regClass() == s1)
185       return bld.readlane(bld.def(s1), data, index);
186 
187    if (ctx->options->chip_class <= GFX7) {
188       /* GFX6-7: there is no bpermute instruction */
189       Operand index_op(index);
190       Operand input_data(data);
191       index_op.setLateKill(true);
192       input_data.setLateKill(true);
193 
194       return bld.pseudo(aco_opcode::p_bpermute, bld.def(v1), bld.def(bld.lm), bld.def(bld.lm, vcc), index_op, input_data);
195    } else if (ctx->options->chip_class >= GFX10 && ctx->program->wave_size == 64) {
196       /* GFX10 wave64 mode: emulate full-wave bpermute */
197       if (!ctx->has_gfx10_wave64_bpermute) {
198          ctx->has_gfx10_wave64_bpermute = true;
199          ctx->program->config->num_shared_vgprs = 8; /* Shared VGPRs are allocated in groups of 8 */
200          ctx->program->vgpr_limit -= 4; /* We allocate 8 shared VGPRs, so we'll have 4 fewer normal VGPRs */
201       }
202 
203       Temp index_is_lo = bld.vopc(aco_opcode::v_cmp_ge_u32, bld.def(bld.lm), Operand(31u), index);
204       Builder::Result index_is_lo_split = bld.pseudo(aco_opcode::p_split_vector, bld.def(s1), bld.def(s1), index_is_lo);
205       Temp index_is_lo_n1 = bld.sop1(aco_opcode::s_not_b32, bld.def(s1), bld.def(s1, scc), index_is_lo_split.def(1).getTemp());
206       Operand same_half = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), index_is_lo_split.def(0).getTemp(), index_is_lo_n1);
207       Operand index_x4 = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(2u), index);
208       Operand input_data(data);
209 
210       index_x4.setLateKill(true);
211       input_data.setLateKill(true);
212       same_half.setLateKill(true);
213 
214       return bld.pseudo(aco_opcode::p_bpermute, bld.def(v1), bld.def(s2), bld.def(s1, scc), index_x4, input_data, same_half);
215    } else {
216       /* GFX8-9 or GFX10 wave32: bpermute works normally */
217       Temp index_x4 = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(2u), index);
218       return bld.ds(aco_opcode::ds_bpermute_b32, bld.def(v1), index_x4, data);
219    }
220 }
221 
emit_masked_swizzle(isel_context * ctx,Builder & bld,Temp src,unsigned mask)222 static Temp emit_masked_swizzle(isel_context *ctx, Builder &bld, Temp src, unsigned mask)
223 {
224    if (ctx->options->chip_class >= GFX8) {
225       unsigned and_mask = mask & 0x1f;
226       unsigned or_mask = (mask >> 5) & 0x1f;
227       unsigned xor_mask = (mask >> 10) & 0x1f;
228 
229       uint16_t dpp_ctrl = 0xffff;
230 
231       // TODO: we could use DPP8 for some swizzles
232       if (and_mask == 0x1f && or_mask < 4 && xor_mask < 4) {
233          unsigned res[4] = {0, 1, 2, 3};
234          for (unsigned i = 0; i < 4; i++)
235             res[i] = ((res[i] | or_mask) ^ xor_mask) & 0x3;
236          dpp_ctrl = dpp_quad_perm(res[0], res[1], res[2], res[3]);
237       } else if (and_mask == 0x1f && !or_mask && xor_mask == 8) {
238          dpp_ctrl = dpp_row_rr(8);
239       } else if (and_mask == 0x1f && !or_mask && xor_mask == 0xf) {
240          dpp_ctrl = dpp_row_mirror;
241       } else if (and_mask == 0x1f && !or_mask && xor_mask == 0x7) {
242          dpp_ctrl = dpp_row_half_mirror;
243       }
244 
245       if (dpp_ctrl != 0xffff)
246          return bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl);
247    }
248 
249    return bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, mask, 0, false);
250 }
251 
as_vgpr(isel_context * ctx,Temp val)252 Temp as_vgpr(isel_context *ctx, Temp val)
253 {
254    if (val.type() == RegType::sgpr) {
255       Builder bld(ctx->program, ctx->block);
256       return bld.copy(bld.def(RegType::vgpr, val.size()), val);
257    }
258    assert(val.type() == RegType::vgpr);
259    return val;
260 }
261 
262 //assumes a != 0xffffffff
emit_v_div_u32(isel_context * ctx,Temp dst,Temp a,uint32_t b)263 void emit_v_div_u32(isel_context *ctx, Temp dst, Temp a, uint32_t b)
264 {
265    assert(b != 0);
266    Builder bld(ctx->program, ctx->block);
267 
268    if (util_is_power_of_two_or_zero(b)) {
269       bld.vop2(aco_opcode::v_lshrrev_b32, Definition(dst), Operand((uint32_t)util_logbase2(b)), a);
270       return;
271    }
272 
273    util_fast_udiv_info info = util_compute_fast_udiv_info(b, 32, 32);
274 
275    assert(info.multiplier <= 0xffffffff);
276 
277    bool pre_shift = info.pre_shift != 0;
278    bool increment = info.increment != 0;
279    bool multiply = true;
280    bool post_shift = info.post_shift != 0;
281 
282    if (!pre_shift && !increment && !multiply && !post_shift) {
283       bld.copy(Definition(dst), a);
284       return;
285    }
286 
287    Temp pre_shift_dst = a;
288    if (pre_shift) {
289       pre_shift_dst = (increment || multiply || post_shift) ? bld.tmp(v1) : dst;
290       bld.vop2(aco_opcode::v_lshrrev_b32, Definition(pre_shift_dst), Operand((uint32_t)info.pre_shift), a);
291    }
292 
293    Temp increment_dst = pre_shift_dst;
294    if (increment) {
295       increment_dst = (post_shift || multiply) ? bld.tmp(v1) : dst;
296       bld.vadd32(Definition(increment_dst), Operand((uint32_t) info.increment), pre_shift_dst);
297    }
298 
299    Temp multiply_dst = increment_dst;
300    if (multiply) {
301       multiply_dst = post_shift ? bld.tmp(v1) : dst;
302       bld.vop3(aco_opcode::v_mul_hi_u32, Definition(multiply_dst), increment_dst,
303                bld.copy(bld.def(v1), Operand((uint32_t)info.multiplier)));
304    }
305 
306    if (post_shift) {
307       bld.vop2(aco_opcode::v_lshrrev_b32, Definition(dst), Operand((uint32_t)info.post_shift), multiply_dst);
308    }
309 }
310 
emit_extract_vector(isel_context * ctx,Temp src,uint32_t idx,Temp dst)311 void emit_extract_vector(isel_context* ctx, Temp src, uint32_t idx, Temp dst)
312 {
313    Builder bld(ctx->program, ctx->block);
314    bld.pseudo(aco_opcode::p_extract_vector, Definition(dst), src, Operand(idx));
315 }
316 
317 
emit_extract_vector(isel_context * ctx,Temp src,uint32_t idx,RegClass dst_rc)318 Temp emit_extract_vector(isel_context* ctx, Temp src, uint32_t idx, RegClass dst_rc)
319 {
320    /* no need to extract the whole vector */
321    if (src.regClass() == dst_rc) {
322       assert(idx == 0);
323       return src;
324    }
325 
326    assert(src.bytes() > (idx * dst_rc.bytes()));
327    Builder bld(ctx->program, ctx->block);
328    auto it = ctx->allocated_vec.find(src.id());
329    if (it != ctx->allocated_vec.end() && dst_rc.bytes() == it->second[idx].regClass().bytes()) {
330       if (it->second[idx].regClass() == dst_rc) {
331          return it->second[idx];
332       } else {
333          assert(!dst_rc.is_subdword());
334          assert(dst_rc.type() == RegType::vgpr && it->second[idx].type() == RegType::sgpr);
335          return bld.copy(bld.def(dst_rc), it->second[idx]);
336       }
337    }
338 
339    if (dst_rc.is_subdword())
340       src = as_vgpr(ctx, src);
341 
342    if (src.bytes() == dst_rc.bytes()) {
343       assert(idx == 0);
344       return bld.copy(bld.def(dst_rc), src);
345    } else {
346       Temp dst = bld.tmp(dst_rc);
347       emit_extract_vector(ctx, src, idx, dst);
348       return dst;
349    }
350 }
351 
emit_split_vector(isel_context * ctx,Temp vec_src,unsigned num_components)352 void emit_split_vector(isel_context* ctx, Temp vec_src, unsigned num_components)
353 {
354    if (num_components == 1)
355       return;
356    if (ctx->allocated_vec.find(vec_src.id()) != ctx->allocated_vec.end())
357       return;
358    RegClass rc;
359    if (num_components > vec_src.size()) {
360       if (vec_src.type() == RegType::sgpr) {
361          /* should still help get_alu_src() */
362          emit_split_vector(ctx, vec_src, vec_src.size());
363          return;
364       }
365       /* sub-dword split */
366       rc = RegClass(RegType::vgpr, vec_src.bytes() / num_components).as_subdword();
367    } else {
368       rc = RegClass(vec_src.type(), vec_src.size() / num_components);
369    }
370    aco_ptr<Pseudo_instruction> split{create_instruction<Pseudo_instruction>(aco_opcode::p_split_vector, Format::PSEUDO, 1, num_components)};
371    split->operands[0] = Operand(vec_src);
372    std::array<Temp,NIR_MAX_VEC_COMPONENTS> elems;
373    for (unsigned i = 0; i < num_components; i++) {
374       elems[i] = ctx->program->allocateTmp(rc);
375       split->definitions[i] = Definition(elems[i]);
376    }
377    ctx->block->instructions.emplace_back(std::move(split));
378    ctx->allocated_vec.emplace(vec_src.id(), elems);
379 }
380 
381 /* This vector expansion uses a mask to determine which elements in the new vector
382  * come from the original vector. The other elements are undefined. */
expand_vector(isel_context * ctx,Temp vec_src,Temp dst,unsigned num_components,unsigned mask)383 void expand_vector(isel_context* ctx, Temp vec_src, Temp dst, unsigned num_components, unsigned mask)
384 {
385    emit_split_vector(ctx, vec_src, util_bitcount(mask));
386 
387    if (vec_src == dst)
388       return;
389 
390    Builder bld(ctx->program, ctx->block);
391    if (num_components == 1) {
392       if (dst.type() == RegType::sgpr)
393          bld.pseudo(aco_opcode::p_as_uniform, Definition(dst), vec_src);
394       else
395          bld.copy(Definition(dst), vec_src);
396       return;
397    }
398 
399    unsigned component_size = dst.size() / num_components;
400    std::array<Temp,NIR_MAX_VEC_COMPONENTS> elems;
401 
402    aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, num_components, 1)};
403    vec->definitions[0] = Definition(dst);
404    unsigned k = 0;
405    for (unsigned i = 0; i < num_components; i++) {
406       if (mask & (1 << i)) {
407          Temp src = emit_extract_vector(ctx, vec_src, k++, RegClass(vec_src.type(), component_size));
408          if (dst.type() == RegType::sgpr)
409             src = bld.as_uniform(src);
410          vec->operands[i] = Operand(src);
411       } else {
412          vec->operands[i] = Operand(0u, component_size == 2);
413       }
414       elems[i] = vec->operands[i].getTemp();
415    }
416    ctx->block->instructions.emplace_back(std::move(vec));
417    ctx->allocated_vec.emplace(dst.id(), elems);
418 }
419 
420 /* adjust misaligned small bit size loads */
byte_align_scalar(isel_context * ctx,Temp vec,Operand offset,Temp dst)421 void byte_align_scalar(isel_context *ctx, Temp vec, Operand offset, Temp dst)
422 {
423    Builder bld(ctx->program, ctx->block);
424    Operand shift;
425    Temp select = Temp();
426    if (offset.isConstant()) {
427       assert(offset.constantValue() && offset.constantValue() < 4);
428       shift = Operand(offset.constantValue() * 8);
429    } else {
430       /* bit_offset = 8 * (offset & 0x3) */
431       Temp tmp = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), offset, Operand(3u));
432       select = bld.tmp(s1);
433       shift = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.scc(Definition(select)), tmp, Operand(3u));
434    }
435 
436    if (vec.size() == 1) {
437       bld.sop2(aco_opcode::s_lshr_b32, Definition(dst), bld.def(s1, scc), vec, shift);
438    } else if (vec.size() == 2) {
439       Temp tmp = dst.size() == 2 ? dst : bld.tmp(s2);
440       bld.sop2(aco_opcode::s_lshr_b64, Definition(tmp), bld.def(s1, scc), vec, shift);
441       if (tmp == dst)
442          emit_split_vector(ctx, dst, 2);
443       else
444          emit_extract_vector(ctx, tmp, 0, dst);
445    } else if (vec.size() == 3 || vec.size() == 4) {
446       Temp lo = bld.tmp(s2), hi;
447       if (vec.size() == 3) {
448          /* this can happen if we use VMEM for a uniform load */
449          hi = bld.tmp(s1);
450          bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), vec);
451       } else {
452          hi = bld.tmp(s2);
453          bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), vec);
454          hi = bld.pseudo(aco_opcode::p_extract_vector, bld.def(s1), hi, Operand(0u));
455       }
456       if (select != Temp())
457          hi = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1), hi, Operand(0u), bld.scc(select));
458       lo = bld.sop2(aco_opcode::s_lshr_b64, bld.def(s2), bld.def(s1, scc), lo, shift);
459       Temp mid = bld.tmp(s1);
460       lo = bld.pseudo(aco_opcode::p_split_vector, bld.def(s1), Definition(mid), lo);
461       hi = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), hi, shift);
462       mid = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), hi, mid);
463       bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, mid);
464       emit_split_vector(ctx, dst, 2);
465    }
466 }
467 
byte_align_vector(isel_context * ctx,Temp vec,Operand offset,Temp dst,unsigned component_size)468 void byte_align_vector(isel_context *ctx, Temp vec, Operand offset, Temp dst, unsigned component_size)
469 {
470    Builder bld(ctx->program, ctx->block);
471    if (offset.isTemp()) {
472       Temp tmp[4] = {vec, vec, vec, vec};
473 
474       if (vec.size() == 4) {
475          tmp[0] = bld.tmp(v1), tmp[1] = bld.tmp(v1), tmp[2] = bld.tmp(v1), tmp[3] = bld.tmp(v1);
476          bld.pseudo(aco_opcode::p_split_vector, Definition(tmp[0]), Definition(tmp[1]), Definition(tmp[2]), Definition(tmp[3]), vec);
477       } else if (vec.size() == 3) {
478          tmp[0] = bld.tmp(v1), tmp[1] = bld.tmp(v1), tmp[2] = bld.tmp(v1);
479          bld.pseudo(aco_opcode::p_split_vector, Definition(tmp[0]), Definition(tmp[1]), Definition(tmp[2]), vec);
480       } else if (vec.size() == 2) {
481          tmp[0] = bld.tmp(v1), tmp[1] = bld.tmp(v1), tmp[2] = tmp[1];
482          bld.pseudo(aco_opcode::p_split_vector, Definition(tmp[0]), Definition(tmp[1]), vec);
483       }
484       for (unsigned i = 0; i < dst.size(); i++)
485          tmp[i] = bld.vop3(aco_opcode::v_alignbyte_b32, bld.def(v1), tmp[i + 1], tmp[i], offset);
486 
487       vec = tmp[0];
488       if (dst.size() == 2)
489          vec = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), tmp[0], tmp[1]);
490 
491       offset = Operand(0u);
492    }
493 
494    unsigned num_components = vec.bytes() / component_size;
495    if (vec.regClass() == dst.regClass()) {
496       assert(offset.constantValue() == 0);
497       bld.copy(Definition(dst), vec);
498       emit_split_vector(ctx, dst, num_components);
499       return;
500    }
501 
502    emit_split_vector(ctx, vec, num_components);
503    std::array<Temp, NIR_MAX_VEC_COMPONENTS> elems;
504    RegClass rc = RegClass(RegType::vgpr, component_size).as_subdword();
505 
506    assert(offset.constantValue() % component_size == 0);
507    unsigned skip = offset.constantValue() / component_size;
508    for (unsigned i = skip; i < num_components; i++)
509       elems[i - skip] = emit_extract_vector(ctx, vec, i, rc);
510 
511    /* if dst is vgpr - split the src and create a shrunk version according to the mask. */
512    if (dst.type() == RegType::vgpr) {
513       num_components = dst.bytes() / component_size;
514       aco_ptr<Pseudo_instruction> create_vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, num_components, 1)};
515       for (unsigned i = 0; i < num_components; i++)
516          create_vec->operands[i] = Operand(elems[i]);
517       create_vec->definitions[0] = Definition(dst);
518       bld.insert(std::move(create_vec));
519 
520    /* if dst is sgpr - split the src, but move the original to sgpr. */
521    } else if (skip) {
522       vec = bld.pseudo(aco_opcode::p_as_uniform, bld.def(RegClass(RegType::sgpr, vec.size())), vec);
523       byte_align_scalar(ctx, vec, offset, dst);
524    } else {
525       assert(dst.size() == vec.size());
526       bld.pseudo(aco_opcode::p_as_uniform, Definition(dst), vec);
527    }
528 
529    ctx->allocated_vec.emplace(dst.id(), elems);
530 }
531 
bool_to_vector_condition(isel_context * ctx,Temp val,Temp dst=Temp (0,s2))532 Temp bool_to_vector_condition(isel_context *ctx, Temp val, Temp dst = Temp(0, s2))
533 {
534    Builder bld(ctx->program, ctx->block);
535    if (!dst.id())
536       dst = bld.tmp(bld.lm);
537 
538    assert(val.regClass() == s1);
539    assert(dst.regClass() == bld.lm);
540 
541    return bld.sop2(Builder::s_cselect, Definition(dst), Operand((uint32_t) -1), Operand(0u), bld.scc(val));
542 }
543 
bool_to_scalar_condition(isel_context * ctx,Temp val,Temp dst=Temp (0,s1))544 Temp bool_to_scalar_condition(isel_context *ctx, Temp val, Temp dst = Temp(0, s1))
545 {
546    Builder bld(ctx->program, ctx->block);
547    if (!dst.id())
548       dst = bld.tmp(s1);
549 
550    assert(val.regClass() == bld.lm);
551    assert(dst.regClass() == s1);
552 
553    /* if we're currently in WQM mode, ensure that the source is also computed in WQM */
554    Temp tmp = bld.tmp(s1);
555    bld.sop2(Builder::s_and, bld.def(bld.lm), bld.scc(Definition(tmp)), val, Operand(exec, bld.lm));
556    return emit_wqm(ctx, tmp, dst);
557 }
558 
convert_int(isel_context * ctx,Builder & bld,Temp src,unsigned src_bits,unsigned dst_bits,bool is_signed,Temp dst=Temp ())559 Temp convert_int(isel_context *ctx, Builder& bld, Temp src, unsigned src_bits, unsigned dst_bits, bool is_signed, Temp dst=Temp())
560 {
561    if (!dst.id()) {
562       if (dst_bits % 32 == 0 || src.type() == RegType::sgpr)
563          dst = bld.tmp(src.type(), DIV_ROUND_UP(dst_bits, 32u));
564       else
565          dst = bld.tmp(RegClass(RegType::vgpr, dst_bits / 8u).as_subdword());
566    }
567 
568    if (dst.bytes() == src.bytes() && dst_bits < src_bits)
569       return bld.copy(Definition(dst), src);
570    else if (dst.bytes() < src.bytes())
571       return bld.pseudo(aco_opcode::p_extract_vector, Definition(dst), src, Operand(0u));
572 
573    Temp tmp = dst;
574    if (dst_bits == 64)
575       tmp = src_bits == 32 ? src : bld.tmp(src.type(), 1);
576 
577    if (tmp == src) {
578    } else if (src.regClass() == s1) {
579       if (is_signed)
580          bld.sop1(src_bits == 8 ? aco_opcode::s_sext_i32_i8 : aco_opcode::s_sext_i32_i16, Definition(tmp), src);
581       else
582          bld.sop2(aco_opcode::s_and_b32, Definition(tmp), bld.def(s1, scc), Operand(src_bits == 8 ? 0xFFu : 0xFFFFu), src);
583    } else if (ctx->options->chip_class >= GFX8) {
584       assert(src_bits != 8 || src.regClass() == v1b);
585       assert(src_bits != 16 || src.regClass() == v2b);
586       aco_ptr<SDWA_instruction> sdwa{create_instruction<SDWA_instruction>(aco_opcode::v_mov_b32, asSDWA(Format::VOP1), 1, 1)};
587       sdwa->operands[0] = Operand(src);
588       sdwa->definitions[0] = Definition(tmp);
589       if (is_signed)
590          sdwa->sel[0] = src_bits == 8 ? sdwa_sbyte : sdwa_sword;
591       else
592          sdwa->sel[0] = src_bits == 8 ? sdwa_ubyte : sdwa_uword;
593       sdwa->dst_sel = tmp.bytes() == 2 ? sdwa_uword : sdwa_udword;
594       bld.insert(std::move(sdwa));
595    } else {
596       assert(ctx->options->chip_class == GFX6 || ctx->options->chip_class == GFX7);
597       aco_opcode opcode = is_signed ? aco_opcode::v_bfe_i32 : aco_opcode::v_bfe_u32;
598       bld.vop3(opcode, Definition(tmp), src, Operand(0u), Operand(src_bits == 8 ? 8u : 16u));
599    }
600 
601    if (dst_bits == 64) {
602       if (is_signed && dst.regClass() == s2) {
603          Temp high = bld.sop2(aco_opcode::s_ashr_i32, bld.def(s1), bld.def(s1, scc), tmp, Operand(31u));
604          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), tmp, high);
605       } else if (is_signed && dst.regClass() == v2) {
606          Temp high = bld.vop2(aco_opcode::v_ashrrev_i32, bld.def(v1), Operand(31u), tmp);
607          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), tmp, high);
608       } else {
609          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), tmp, Operand(0u));
610       }
611    }
612 
613    return dst;
614 }
615 
616 enum sgpr_extract_mode {
617    sgpr_extract_sext,
618    sgpr_extract_zext,
619    sgpr_extract_undef,
620 };
621 
extract_8_16_bit_sgpr_element(isel_context * ctx,Temp dst,nir_alu_src * src,sgpr_extract_mode mode)622 Temp extract_8_16_bit_sgpr_element(isel_context *ctx, Temp dst, nir_alu_src *src, sgpr_extract_mode mode)
623 {
624    Temp vec = get_ssa_temp(ctx, src->src.ssa);
625    unsigned src_size = src->src.ssa->bit_size;
626    unsigned swizzle = src->swizzle[0];
627 
628    if (vec.size() > 1) {
629       assert(src_size == 16);
630       vec = emit_extract_vector(ctx, vec, swizzle / 2, s1);
631       swizzle = swizzle & 1;
632    }
633 
634    Builder bld(ctx->program, ctx->block);
635    unsigned offset = src_size * swizzle;
636    Temp tmp = dst.regClass() == s2 ? bld.tmp(s1) : dst;
637 
638    if (mode == sgpr_extract_undef && swizzle == 0) {
639       bld.copy(Definition(tmp), vec);
640    } else if (mode == sgpr_extract_undef || (offset == 24 && mode == sgpr_extract_zext)) {
641       bld.sop2(aco_opcode::s_lshr_b32, Definition(tmp), bld.def(s1, scc), vec, Operand(offset));
642    } else if (src_size == 8 && swizzle == 0 && mode == sgpr_extract_sext) {
643       bld.sop1(aco_opcode::s_sext_i32_i8, Definition(tmp), vec);
644    } else if (src_size == 16 && swizzle == 0 && mode == sgpr_extract_sext) {
645       bld.sop1(aco_opcode::s_sext_i32_i16, Definition(tmp), vec);
646    } else {
647       aco_opcode op = mode == sgpr_extract_zext ? aco_opcode::s_bfe_u32 : aco_opcode::s_bfe_i32;
648       bld.sop2(op, Definition(tmp), bld.def(s1, scc), vec, Operand((src_size << 16) | offset));
649    }
650 
651    if (dst.regClass() == s2)
652       convert_int(ctx, bld, tmp, 32, 64, mode == sgpr_extract_sext, dst);
653 
654    return dst;
655 }
656 
get_alu_src(struct isel_context * ctx,nir_alu_src src,unsigned size=1)657 Temp get_alu_src(struct isel_context *ctx, nir_alu_src src, unsigned size=1)
658 {
659    if (src.src.ssa->num_components == 1 && src.swizzle[0] == 0 && size == 1)
660       return get_ssa_temp(ctx, src.src.ssa);
661 
662    if (src.src.ssa->num_components == size) {
663       bool identity_swizzle = true;
664       for (unsigned i = 0; identity_swizzle && i < size; i++) {
665          if (src.swizzle[i] != i)
666             identity_swizzle = false;
667       }
668       if (identity_swizzle)
669          return get_ssa_temp(ctx, src.src.ssa);
670    }
671 
672    Temp vec = get_ssa_temp(ctx, src.src.ssa);
673    unsigned elem_size = vec.bytes() / src.src.ssa->num_components;
674    assert(elem_size > 0);
675    assert(vec.bytes() % elem_size == 0);
676 
677    if (elem_size < 4 && vec.type() == RegType::sgpr) {
678       assert(src.src.ssa->bit_size == 8 || src.src.ssa->bit_size == 16);
679       assert(size == 1);
680       return extract_8_16_bit_sgpr_element(
681          ctx, ctx->program->allocateTmp(s1), &src, sgpr_extract_undef);
682    }
683 
684    RegClass elem_rc = elem_size < 4 ? RegClass(vec.type(), elem_size).as_subdword() : RegClass(vec.type(), elem_size / 4);
685    if (size == 1) {
686       return emit_extract_vector(ctx, vec, src.swizzle[0], elem_rc);
687    } else {
688       assert(size <= 4);
689       std::array<Temp,NIR_MAX_VEC_COMPONENTS> elems;
690       aco_ptr<Pseudo_instruction> vec_instr{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, size, 1)};
691       for (unsigned i = 0; i < size; ++i) {
692          elems[i] = emit_extract_vector(ctx, vec, src.swizzle[i], elem_rc);
693          vec_instr->operands[i] = Operand{elems[i]};
694       }
695       Temp dst = ctx->program->allocateTmp(RegClass(vec.type(), elem_size * size / 4));
696       vec_instr->definitions[0] = Definition(dst);
697       ctx->block->instructions.emplace_back(std::move(vec_instr));
698       ctx->allocated_vec.emplace(dst.id(), elems);
699       return dst;
700    }
701 }
702 
get_alu_src_ub(isel_context * ctx,nir_alu_instr * instr,int src_idx)703 uint32_t get_alu_src_ub(isel_context *ctx, nir_alu_instr *instr, int src_idx)
704 {
705    nir_ssa_scalar scalar = (nir_ssa_scalar){instr->src[src_idx].src.ssa,
706                                             instr->src[src_idx].swizzle[0]};
707    return nir_unsigned_upper_bound(ctx->shader, ctx->range_ht, scalar, &ctx->ub_config);
708 }
709 
convert_pointer_to_64_bit(isel_context * ctx,Temp ptr)710 Temp convert_pointer_to_64_bit(isel_context *ctx, Temp ptr)
711 {
712    if (ptr.size() == 2)
713       return ptr;
714    Builder bld(ctx->program, ctx->block);
715    if (ptr.type() == RegType::vgpr)
716       ptr = bld.vop1(aco_opcode::v_readfirstlane_b32, bld.def(s1), ptr);
717    return bld.pseudo(aco_opcode::p_create_vector, bld.def(s2),
718                      ptr, Operand((unsigned)ctx->options->address32_hi));
719 }
720 
emit_sop2_instruction(isel_context * ctx,nir_alu_instr * instr,aco_opcode op,Temp dst,bool writes_scc)721 void emit_sop2_instruction(isel_context *ctx, nir_alu_instr *instr, aco_opcode op, Temp dst, bool writes_scc)
722 {
723    aco_ptr<SOP2_instruction> sop2{create_instruction<SOP2_instruction>(op, Format::SOP2, 2, writes_scc ? 2 : 1)};
724    sop2->operands[0] = Operand(get_alu_src(ctx, instr->src[0]));
725    sop2->operands[1] = Operand(get_alu_src(ctx, instr->src[1]));
726    sop2->definitions[0] = Definition(dst);
727    if (instr->no_unsigned_wrap)
728       sop2->definitions[0].setNUW(true);
729    if (writes_scc)
730       sop2->definitions[1] = Definition(ctx->program->allocateId(s1), scc, s1);
731    ctx->block->instructions.emplace_back(std::move(sop2));
732 }
733 
emit_vop2_instruction(isel_context * ctx,nir_alu_instr * instr,aco_opcode op,Temp dst,bool commutative,bool swap_srcs=false,bool flush_denorms=false)734 void emit_vop2_instruction(isel_context *ctx, nir_alu_instr *instr, aco_opcode op, Temp dst,
735                            bool commutative, bool swap_srcs=false, bool flush_denorms = false)
736 {
737    Builder bld(ctx->program, ctx->block);
738    bld.is_precise = instr->exact;
739 
740    Temp src0 = get_alu_src(ctx, instr->src[swap_srcs ? 1 : 0]);
741    Temp src1 = get_alu_src(ctx, instr->src[swap_srcs ? 0 : 1]);
742    if (src1.type() == RegType::sgpr) {
743       if (commutative && src0.type() == RegType::vgpr) {
744          Temp t = src0;
745          src0 = src1;
746          src1 = t;
747       } else {
748          src1 = as_vgpr(ctx, src1);
749       }
750    }
751 
752    if (flush_denorms && ctx->program->chip_class < GFX9) {
753       assert(dst.size() == 1);
754       Temp tmp = bld.vop2(op, bld.def(v1), src0, src1);
755       bld.vop2(aco_opcode::v_mul_f32, Definition(dst), Operand(0x3f800000u), tmp);
756    } else {
757       bld.vop2(op, Definition(dst), src0, src1);
758    }
759 }
760 
emit_vop2_instruction_logic64(isel_context * ctx,nir_alu_instr * instr,aco_opcode op,Temp dst)761 void emit_vop2_instruction_logic64(isel_context *ctx, nir_alu_instr *instr,
762                                    aco_opcode op, Temp dst)
763 {
764    Builder bld(ctx->program, ctx->block);
765    bld.is_precise = instr->exact;
766 
767    Temp src0 = get_alu_src(ctx, instr->src[0]);
768    Temp src1 = get_alu_src(ctx, instr->src[1]);
769 
770    if (src1.type() == RegType::sgpr) {
771       assert(src0.type() == RegType::vgpr);
772       std::swap(src0, src1);
773    }
774 
775    Temp src00 = bld.tmp(src0.type(), 1);
776    Temp src01 = bld.tmp(src0.type(), 1);
777    bld.pseudo(aco_opcode::p_split_vector, Definition(src00), Definition(src01), src0);
778    Temp src10 = bld.tmp(v1);
779    Temp src11 = bld.tmp(v1);
780    bld.pseudo(aco_opcode::p_split_vector, Definition(src10), Definition(src11), src1);
781    Temp lo = bld.vop2(op, bld.def(v1), src00, src10);
782    Temp hi = bld.vop2(op, bld.def(v1), src01, src11);
783    bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, hi);
784 }
785 
emit_vop3a_instruction(isel_context * ctx,nir_alu_instr * instr,aco_opcode op,Temp dst,bool flush_denorms=false,unsigned num_sources=2,bool swap_srcs=false)786 void emit_vop3a_instruction(isel_context *ctx, nir_alu_instr *instr, aco_opcode op, Temp dst,
787                             bool flush_denorms = false, unsigned num_sources = 2, bool swap_srcs = false)
788 {
789    assert(num_sources == 2 || num_sources == 3);
790    Temp src[3] = { Temp(0, v1), Temp(0, v1), Temp(0, v1) };
791    bool has_sgpr = false;
792    for (unsigned i = 0; i < num_sources; i++) {
793       src[i] = get_alu_src(ctx, instr->src[swap_srcs ? 1 - i : i]);
794       if (has_sgpr)
795          src[i] = as_vgpr(ctx, src[i]);
796       else
797          has_sgpr = src[i].type() == RegType::sgpr;
798    }
799 
800    Builder bld(ctx->program, ctx->block);
801    bld.is_precise = instr->exact;
802    if (flush_denorms && ctx->program->chip_class < GFX9) {
803       Temp tmp;
804       if (num_sources == 3)
805          tmp = bld.vop3(op, bld.def(dst.regClass()), src[0], src[1], src[2]);
806       else
807          tmp = bld.vop3(op, bld.def(dst.regClass()), src[0], src[1]);
808       if (dst.size() == 1)
809          bld.vop2(aco_opcode::v_mul_f32, Definition(dst), Operand(0x3f800000u), tmp);
810       else
811          bld.vop3(aco_opcode::v_mul_f64, Definition(dst), Operand(UINT64_C(0x3FF0000000000000)), tmp);
812    } else if (num_sources == 3) {
813       bld.vop3(op, Definition(dst), src[0], src[1], src[2]);
814    } else {
815       bld.vop3(op, Definition(dst), src[0], src[1]);
816    }
817 }
818 
emit_vop1_instruction(isel_context * ctx,nir_alu_instr * instr,aco_opcode op,Temp dst)819 void emit_vop1_instruction(isel_context *ctx, nir_alu_instr *instr, aco_opcode op, Temp dst)
820 {
821    Builder bld(ctx->program, ctx->block);
822    bld.is_precise = instr->exact;
823    if (dst.type() == RegType::sgpr)
824       bld.pseudo(aco_opcode::p_as_uniform, Definition(dst),
825                  bld.vop1(op, bld.def(RegType::vgpr, dst.size()), get_alu_src(ctx, instr->src[0])));
826    else
827       bld.vop1(op, Definition(dst), get_alu_src(ctx, instr->src[0]));
828 }
829 
emit_vopc_instruction(isel_context * ctx,nir_alu_instr * instr,aco_opcode op,Temp dst)830 void emit_vopc_instruction(isel_context *ctx, nir_alu_instr *instr, aco_opcode op, Temp dst)
831 {
832    Temp src0 = get_alu_src(ctx, instr->src[0]);
833    Temp src1 = get_alu_src(ctx, instr->src[1]);
834    assert(src0.size() == src1.size());
835 
836    aco_ptr<Instruction> vopc;
837    if (src1.type() == RegType::sgpr) {
838       if (src0.type() == RegType::vgpr) {
839          /* to swap the operands, we might also have to change the opcode */
840          switch (op) {
841             case aco_opcode::v_cmp_lt_f16:
842                op = aco_opcode::v_cmp_gt_f16;
843                break;
844             case aco_opcode::v_cmp_ge_f16:
845                op = aco_opcode::v_cmp_le_f16;
846                break;
847             case aco_opcode::v_cmp_lt_i16:
848                op = aco_opcode::v_cmp_gt_i16;
849                break;
850             case aco_opcode::v_cmp_ge_i16:
851                op = aco_opcode::v_cmp_le_i16;
852                break;
853             case aco_opcode::v_cmp_lt_u16:
854                op = aco_opcode::v_cmp_gt_u16;
855                break;
856             case aco_opcode::v_cmp_ge_u16:
857                op = aco_opcode::v_cmp_le_u16;
858                break;
859             case aco_opcode::v_cmp_lt_f32:
860                op = aco_opcode::v_cmp_gt_f32;
861                break;
862             case aco_opcode::v_cmp_ge_f32:
863                op = aco_opcode::v_cmp_le_f32;
864                break;
865             case aco_opcode::v_cmp_lt_i32:
866                op = aco_opcode::v_cmp_gt_i32;
867                break;
868             case aco_opcode::v_cmp_ge_i32:
869                op = aco_opcode::v_cmp_le_i32;
870                break;
871             case aco_opcode::v_cmp_lt_u32:
872                op = aco_opcode::v_cmp_gt_u32;
873                break;
874             case aco_opcode::v_cmp_ge_u32:
875                op = aco_opcode::v_cmp_le_u32;
876                break;
877             case aco_opcode::v_cmp_lt_f64:
878                op = aco_opcode::v_cmp_gt_f64;
879                break;
880             case aco_opcode::v_cmp_ge_f64:
881                op = aco_opcode::v_cmp_le_f64;
882                break;
883             case aco_opcode::v_cmp_lt_i64:
884                op = aco_opcode::v_cmp_gt_i64;
885                break;
886             case aco_opcode::v_cmp_ge_i64:
887                op = aco_opcode::v_cmp_le_i64;
888                break;
889             case aco_opcode::v_cmp_lt_u64:
890                op = aco_opcode::v_cmp_gt_u64;
891                break;
892             case aco_opcode::v_cmp_ge_u64:
893                op = aco_opcode::v_cmp_le_u64;
894                break;
895             default: /* eq and ne are commutative */
896                break;
897          }
898          Temp t = src0;
899          src0 = src1;
900          src1 = t;
901       } else {
902          src1 = as_vgpr(ctx, src1);
903       }
904    }
905 
906    Builder bld(ctx->program, ctx->block);
907    bld.vopc(op, bld.hint_vcc(Definition(dst)), src0, src1);
908 }
909 
emit_sopc_instruction(isel_context * ctx,nir_alu_instr * instr,aco_opcode op,Temp dst)910 void emit_sopc_instruction(isel_context *ctx, nir_alu_instr *instr, aco_opcode op, Temp dst)
911 {
912    Temp src0 = get_alu_src(ctx, instr->src[0]);
913    Temp src1 = get_alu_src(ctx, instr->src[1]);
914    Builder bld(ctx->program, ctx->block);
915 
916    assert(dst.regClass() == bld.lm);
917    assert(src0.type() == RegType::sgpr);
918    assert(src1.type() == RegType::sgpr);
919    assert(src0.regClass() == src1.regClass());
920 
921    /* Emit the SALU comparison instruction */
922    Temp cmp = bld.sopc(op, bld.scc(bld.def(s1)), src0, src1);
923    /* Turn the result into a per-lane bool */
924    bool_to_vector_condition(ctx, cmp, dst);
925 }
926 
emit_comparison(isel_context * ctx,nir_alu_instr * instr,Temp dst,aco_opcode v16_op,aco_opcode v32_op,aco_opcode v64_op,aco_opcode s32_op=aco_opcode::num_opcodes,aco_opcode s64_op=aco_opcode::num_opcodes)927 void emit_comparison(isel_context *ctx, nir_alu_instr *instr, Temp dst,
928                      aco_opcode v16_op, aco_opcode v32_op, aco_opcode v64_op, aco_opcode s32_op = aco_opcode::num_opcodes, aco_opcode s64_op = aco_opcode::num_opcodes)
929 {
930    aco_opcode s_op = instr->src[0].src.ssa->bit_size == 64 ? s64_op : instr->src[0].src.ssa->bit_size == 32 ? s32_op : aco_opcode::num_opcodes;
931    aco_opcode v_op = instr->src[0].src.ssa->bit_size == 64 ? v64_op : instr->src[0].src.ssa->bit_size == 32 ? v32_op : v16_op;
932    bool use_valu = s_op == aco_opcode::num_opcodes ||
933                    nir_dest_is_divergent(instr->dest.dest) ||
934                    get_ssa_temp(ctx, instr->src[0].src.ssa).type() == RegType::vgpr ||
935                    get_ssa_temp(ctx, instr->src[1].src.ssa).type() == RegType::vgpr;
936    aco_opcode op = use_valu ? v_op : s_op;
937    assert(op != aco_opcode::num_opcodes);
938    assert(dst.regClass() == ctx->program->lane_mask);
939 
940    if (use_valu)
941       emit_vopc_instruction(ctx, instr, op, dst);
942    else
943       emit_sopc_instruction(ctx, instr, op, dst);
944 }
945 
emit_boolean_logic(isel_context * ctx,nir_alu_instr * instr,Builder::WaveSpecificOpcode op,Temp dst)946 void emit_boolean_logic(isel_context *ctx, nir_alu_instr *instr, Builder::WaveSpecificOpcode op, Temp dst)
947 {
948    Builder bld(ctx->program, ctx->block);
949    Temp src0 = get_alu_src(ctx, instr->src[0]);
950    Temp src1 = get_alu_src(ctx, instr->src[1]);
951 
952    assert(dst.regClass() == bld.lm);
953    assert(src0.regClass() == bld.lm);
954    assert(src1.regClass() == bld.lm);
955 
956    bld.sop2(op, Definition(dst), bld.def(s1, scc), src0, src1);
957 }
958 
emit_bcsel(isel_context * ctx,nir_alu_instr * instr,Temp dst)959 void emit_bcsel(isel_context *ctx, nir_alu_instr *instr, Temp dst)
960 {
961    Builder bld(ctx->program, ctx->block);
962    Temp cond = get_alu_src(ctx, instr->src[0]);
963    Temp then = get_alu_src(ctx, instr->src[1]);
964    Temp els = get_alu_src(ctx, instr->src[2]);
965 
966    assert(cond.regClass() == bld.lm);
967 
968    if (dst.type() == RegType::vgpr) {
969       aco_ptr<Instruction> bcsel;
970       if (dst.size() == 1) {
971          then = as_vgpr(ctx, then);
972          els = as_vgpr(ctx, els);
973 
974          bld.vop2(aco_opcode::v_cndmask_b32, Definition(dst), els, then, cond);
975       } else if (dst.size() == 2) {
976          Temp then_lo = bld.tmp(v1), then_hi = bld.tmp(v1);
977          bld.pseudo(aco_opcode::p_split_vector, Definition(then_lo), Definition(then_hi), then);
978          Temp else_lo = bld.tmp(v1), else_hi = bld.tmp(v1);
979          bld.pseudo(aco_opcode::p_split_vector, Definition(else_lo), Definition(else_hi), els);
980 
981          Temp dst0 = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), else_lo, then_lo, cond);
982          Temp dst1 = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), else_hi, then_hi, cond);
983 
984          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), dst0, dst1);
985       } else {
986          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
987       }
988       return;
989    }
990 
991    if (instr->dest.dest.ssa.bit_size == 1) {
992       assert(dst.regClass() == bld.lm);
993       assert(then.regClass() == bld.lm);
994       assert(els.regClass() == bld.lm);
995    }
996 
997    if (!nir_src_is_divergent(instr->src[0].src)) { /* uniform condition and values in sgpr */
998       if (dst.regClass() == s1 || dst.regClass() == s2) {
999          assert((then.regClass() == s1 || then.regClass() == s2) && els.regClass() == then.regClass());
1000          assert(dst.size() == then.size());
1001          aco_opcode op = dst.regClass() == s1 ? aco_opcode::s_cselect_b32 : aco_opcode::s_cselect_b64;
1002          bld.sop2(op, Definition(dst), then, els, bld.scc(bool_to_scalar_condition(ctx, cond)));
1003       } else {
1004          isel_err(&instr->instr, "Unimplemented uniform bcsel bit size");
1005       }
1006       return;
1007    }
1008 
1009    /* divergent boolean bcsel
1010     * this implements bcsel on bools: dst = s0 ? s1 : s2
1011     * are going to be: dst = (s0 & s1) | (~s0 & s2) */
1012    assert(instr->dest.dest.ssa.bit_size == 1);
1013 
1014    if (cond.id() != then.id())
1015       then = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), cond, then);
1016 
1017    if (cond.id() == els.id())
1018       bld.copy(Definition(dst), then);
1019    else
1020       bld.sop2(Builder::s_or, Definition(dst), bld.def(s1, scc), then,
1021                bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc), els, cond));
1022 }
1023 
emit_scaled_op(isel_context * ctx,Builder & bld,Definition dst,Temp val,aco_opcode op,uint32_t undo)1024 void emit_scaled_op(isel_context *ctx, Builder& bld, Definition dst, Temp val,
1025                     aco_opcode op, uint32_t undo)
1026 {
1027    /* multiply by 16777216 to handle denormals */
1028    Temp is_denormal = bld.vopc(aco_opcode::v_cmp_class_f32, bld.hint_vcc(bld.def(bld.lm)),
1029                                as_vgpr(ctx, val), bld.copy(bld.def(v1), Operand((1u << 7) | (1u << 4))));
1030    Temp scaled = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), Operand(0x4b800000u), val);
1031    scaled = bld.vop1(op, bld.def(v1), scaled);
1032    scaled = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), Operand(undo), scaled);
1033 
1034    Temp not_scaled = bld.vop1(op, bld.def(v1), val);
1035 
1036    bld.vop2(aco_opcode::v_cndmask_b32, dst, not_scaled, scaled, is_denormal);
1037 }
1038 
emit_rcp(isel_context * ctx,Builder & bld,Definition dst,Temp val)1039 void emit_rcp(isel_context *ctx, Builder& bld, Definition dst, Temp val)
1040 {
1041    if (ctx->block->fp_mode.denorm32 == 0) {
1042       bld.vop1(aco_opcode::v_rcp_f32, dst, val);
1043       return;
1044    }
1045 
1046    emit_scaled_op(ctx, bld, dst, val, aco_opcode::v_rcp_f32, 0x4b800000u);
1047 }
1048 
emit_rsq(isel_context * ctx,Builder & bld,Definition dst,Temp val)1049 void emit_rsq(isel_context *ctx, Builder& bld, Definition dst, Temp val)
1050 {
1051    if (ctx->block->fp_mode.denorm32 == 0) {
1052       bld.vop1(aco_opcode::v_rsq_f32, dst, val);
1053       return;
1054    }
1055 
1056    emit_scaled_op(ctx, bld, dst, val, aco_opcode::v_rsq_f32, 0x45800000u);
1057 }
1058 
emit_sqrt(isel_context * ctx,Builder & bld,Definition dst,Temp val)1059 void emit_sqrt(isel_context *ctx, Builder& bld, Definition dst, Temp val)
1060 {
1061    if (ctx->block->fp_mode.denorm32 == 0) {
1062       bld.vop1(aco_opcode::v_sqrt_f32, dst, val);
1063       return;
1064    }
1065 
1066    emit_scaled_op(ctx, bld, dst, val, aco_opcode::v_sqrt_f32, 0x39800000u);
1067 }
1068 
emit_log2(isel_context * ctx,Builder & bld,Definition dst,Temp val)1069 void emit_log2(isel_context *ctx, Builder& bld, Definition dst, Temp val)
1070 {
1071    if (ctx->block->fp_mode.denorm32 == 0) {
1072       bld.vop1(aco_opcode::v_log_f32, dst, val);
1073       return;
1074    }
1075 
1076    emit_scaled_op(ctx, bld, dst, val, aco_opcode::v_log_f32, 0xc1c00000u);
1077 }
1078 
emit_trunc_f64(isel_context * ctx,Builder & bld,Definition dst,Temp val)1079 Temp emit_trunc_f64(isel_context *ctx, Builder& bld, Definition dst, Temp val)
1080 {
1081    if (ctx->options->chip_class >= GFX7)
1082       return bld.vop1(aco_opcode::v_trunc_f64, Definition(dst), val);
1083 
1084    /* GFX6 doesn't support V_TRUNC_F64, lower it. */
1085    /* TODO: create more efficient code! */
1086    if (val.type() == RegType::sgpr)
1087       val = as_vgpr(ctx, val);
1088 
1089    /* Split the input value. */
1090    Temp val_lo = bld.tmp(v1), val_hi = bld.tmp(v1);
1091    bld.pseudo(aco_opcode::p_split_vector, Definition(val_lo), Definition(val_hi), val);
1092 
1093    /* Extract the exponent and compute the unbiased value. */
1094    Temp exponent = bld.vop3(aco_opcode::v_bfe_u32, bld.def(v1), val_hi, Operand(20u), Operand(11u));
1095    exponent = bld.vsub32(bld.def(v1), exponent, Operand(1023u));
1096 
1097    /* Extract the fractional part. */
1098    Temp fract_mask = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), Operand(-1u), Operand(0x000fffffu));
1099    fract_mask = bld.vop3(aco_opcode::v_lshr_b64, bld.def(v2), fract_mask, exponent);
1100 
1101    Temp fract_mask_lo = bld.tmp(v1), fract_mask_hi = bld.tmp(v1);
1102    bld.pseudo(aco_opcode::p_split_vector, Definition(fract_mask_lo), Definition(fract_mask_hi), fract_mask);
1103 
1104    Temp fract_lo = bld.tmp(v1), fract_hi = bld.tmp(v1);
1105    Temp tmp = bld.vop1(aco_opcode::v_not_b32, bld.def(v1), fract_mask_lo);
1106    fract_lo = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), val_lo, tmp);
1107    tmp = bld.vop1(aco_opcode::v_not_b32, bld.def(v1), fract_mask_hi);
1108    fract_hi = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), val_hi, tmp);
1109 
1110    /* Get the sign bit. */
1111    Temp sign = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0x80000000u), val_hi);
1112 
1113    /* Decide the operation to apply depending on the unbiased exponent. */
1114    Temp exp_lt0 = bld.vopc_e64(aco_opcode::v_cmp_lt_i32, bld.hint_vcc(bld.def(bld.lm)), exponent, Operand(0u));
1115    Temp dst_lo = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), fract_lo, bld.copy(bld.def(v1), Operand(0u)), exp_lt0);
1116    Temp dst_hi = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), fract_hi, sign, exp_lt0);
1117    Temp exp_gt51 = bld.vopc_e64(aco_opcode::v_cmp_gt_i32, bld.def(s2), exponent, Operand(51u));
1118    dst_lo = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), dst_lo, val_lo, exp_gt51);
1119    dst_hi = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), dst_hi, val_hi, exp_gt51);
1120 
1121    return bld.pseudo(aco_opcode::p_create_vector, Definition(dst), dst_lo, dst_hi);
1122 }
1123 
emit_floor_f64(isel_context * ctx,Builder & bld,Definition dst,Temp val)1124 Temp emit_floor_f64(isel_context *ctx, Builder& bld, Definition dst, Temp val)
1125 {
1126    if (ctx->options->chip_class >= GFX7)
1127       return bld.vop1(aco_opcode::v_floor_f64, Definition(dst), val);
1128 
1129    /* GFX6 doesn't support V_FLOOR_F64, lower it (note that it's actually
1130     * lowered at NIR level for precision reasons). */
1131    Temp src0 = as_vgpr(ctx, val);
1132 
1133    Temp mask = bld.copy(bld.def(s1), Operand(3u)); /* isnan */
1134    Temp min_val = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), Operand(-1u), Operand(0x3fefffffu));
1135 
1136    Temp isnan = bld.vopc_e64(aco_opcode::v_cmp_class_f64, bld.hint_vcc(bld.def(bld.lm)), src0, mask);
1137    Temp fract = bld.vop1(aco_opcode::v_fract_f64, bld.def(v2), src0);
1138    Temp min = bld.vop3(aco_opcode::v_min_f64, bld.def(v2), fract, min_val);
1139 
1140    Temp then_lo = bld.tmp(v1), then_hi = bld.tmp(v1);
1141    bld.pseudo(aco_opcode::p_split_vector, Definition(then_lo), Definition(then_hi), src0);
1142    Temp else_lo = bld.tmp(v1), else_hi = bld.tmp(v1);
1143    bld.pseudo(aco_opcode::p_split_vector, Definition(else_lo), Definition(else_hi), min);
1144 
1145    Temp dst0 = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), else_lo, then_lo, isnan);
1146    Temp dst1 = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), else_hi, then_hi, isnan);
1147 
1148    Temp v = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), dst0, dst1);
1149 
1150    Instruction* add = bld.vop3(aco_opcode::v_add_f64, Definition(dst), src0, v);
1151    static_cast<VOP3A_instruction*>(add)->neg[1] = true;
1152 
1153    return add->definitions[0].getTemp();
1154 }
1155 
visit_alu_instr(isel_context * ctx,nir_alu_instr * instr)1156 void visit_alu_instr(isel_context *ctx, nir_alu_instr *instr)
1157 {
1158    if (!instr->dest.dest.is_ssa) {
1159       isel_err(&instr->instr, "nir alu dst not in ssa");
1160       abort();
1161    }
1162    Builder bld(ctx->program, ctx->block);
1163    bld.is_precise = instr->exact;
1164    Temp dst = get_ssa_temp(ctx, &instr->dest.dest.ssa);
1165    switch(instr->op) {
1166    case nir_op_vec2:
1167    case nir_op_vec3:
1168    case nir_op_vec4: {
1169       std::array<Temp,NIR_MAX_VEC_COMPONENTS> elems;
1170       unsigned num = instr->dest.dest.ssa.num_components;
1171       for (unsigned i = 0; i < num; ++i)
1172          elems[i] = get_alu_src(ctx, instr->src[i]);
1173 
1174       if (instr->dest.dest.ssa.bit_size >= 32 || dst.type() == RegType::vgpr) {
1175          aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, instr->dest.dest.ssa.num_components, 1)};
1176          RegClass elem_rc = RegClass::get(RegType::vgpr, instr->dest.dest.ssa.bit_size / 8u);
1177          for (unsigned i = 0; i < num; ++i) {
1178             if (elems[i].type() == RegType::sgpr && elem_rc.is_subdword())
1179                vec->operands[i] = Operand(emit_extract_vector(ctx, elems[i], 0, elem_rc));
1180             else
1181                vec->operands[i] = Operand{elems[i]};
1182          }
1183          vec->definitions[0] = Definition(dst);
1184          ctx->block->instructions.emplace_back(std::move(vec));
1185          ctx->allocated_vec.emplace(dst.id(), elems);
1186       } else {
1187          // TODO: that is a bit suboptimal..
1188          Temp mask = bld.copy(bld.def(s1), Operand((1u << instr->dest.dest.ssa.bit_size) - 1));
1189          for (unsigned i = 0; i < num - 1; ++i)
1190             if (((i+1) * instr->dest.dest.ssa.bit_size) % 32)
1191                elems[i] = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), elems[i], mask);
1192          for (unsigned i = 0; i < num; ++i) {
1193             unsigned bit = i * instr->dest.dest.ssa.bit_size;
1194             if (bit % 32 == 0) {
1195                elems[bit / 32] = elems[i];
1196             } else {
1197                elems[i] = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc),
1198                                    elems[i], Operand((i * instr->dest.dest.ssa.bit_size) % 32));
1199                elems[bit / 32] = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), elems[bit / 32], elems[i]);
1200             }
1201          }
1202          if (dst.size() == 1)
1203             bld.copy(Definition(dst), elems[0]);
1204          else
1205             bld.pseudo(aco_opcode::p_create_vector, Definition(dst), elems[0], elems[1]);
1206       }
1207       break;
1208    }
1209    case nir_op_mov: {
1210       Temp src = get_alu_src(ctx, instr->src[0]);
1211       if (src.type() == RegType::vgpr && dst.type() == RegType::sgpr) {
1212          /* use size() instead of bytes() for 8/16-bit */
1213          assert(src.size() == dst.size() && "wrong src or dst register class for nir_op_mov");
1214          bld.pseudo(aco_opcode::p_as_uniform, Definition(dst), src);
1215       } else {
1216          assert(src.bytes() == dst.bytes() && "wrong src or dst register class for nir_op_mov");
1217          bld.copy(Definition(dst), src);
1218       }
1219       break;
1220    }
1221    case nir_op_inot: {
1222       Temp src = get_alu_src(ctx, instr->src[0]);
1223       if (instr->dest.dest.ssa.bit_size == 1) {
1224          assert(src.regClass() == bld.lm);
1225          assert(dst.regClass() == bld.lm);
1226          /* Don't use s_andn2 here, this allows the optimizer to make a better decision */
1227          Temp tmp = bld.sop1(Builder::s_not, bld.def(bld.lm), bld.def(s1, scc), src);
1228          bld.sop2(Builder::s_and, Definition(dst), bld.def(s1, scc), tmp, Operand(exec, bld.lm));
1229       } else if (dst.regClass() == v1 || dst.regClass() == v2b || dst.regClass() == v1b) {
1230          emit_vop1_instruction(ctx, instr, aco_opcode::v_not_b32, dst);
1231       } else if (dst.regClass() == v2) {
1232          Temp lo = bld.tmp(v1), hi = bld.tmp(v1);
1233          bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), src);
1234          lo = bld.vop1(aco_opcode::v_not_b32, bld.def(v1), lo);
1235          hi = bld.vop1(aco_opcode::v_not_b32, bld.def(v1), hi);
1236          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, hi);
1237       } else if (dst.type() == RegType::sgpr) {
1238          aco_opcode opcode = dst.size() == 1 ? aco_opcode::s_not_b32 : aco_opcode::s_not_b64;
1239          bld.sop1(opcode, Definition(dst), bld.def(s1, scc), src);
1240       } else {
1241          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1242       }
1243       break;
1244    }
1245    case nir_op_ineg: {
1246       Temp src = get_alu_src(ctx, instr->src[0]);
1247       if (dst.regClass() == v1) {
1248          bld.vsub32(Definition(dst), Operand(0u), Operand(src));
1249       } else if (dst.regClass() == s1) {
1250          bld.sop2(aco_opcode::s_mul_i32, Definition(dst), Operand((uint32_t) -1), src);
1251       } else if (dst.size() == 2) {
1252          Temp src0 = bld.tmp(dst.type(), 1);
1253          Temp src1 = bld.tmp(dst.type(), 1);
1254          bld.pseudo(aco_opcode::p_split_vector, Definition(src0), Definition(src1), src);
1255 
1256          if (dst.regClass() == s2) {
1257             Temp carry = bld.tmp(s1);
1258             Temp dst0 = bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.scc(Definition(carry)), Operand(0u), src0);
1259             Temp dst1 = bld.sop2(aco_opcode::s_subb_u32, bld.def(s1), bld.def(s1, scc), Operand(0u), src1, carry);
1260             bld.pseudo(aco_opcode::p_create_vector, Definition(dst), dst0, dst1);
1261          } else {
1262             Temp lower = bld.tmp(v1);
1263             Temp borrow = bld.vsub32(Definition(lower), Operand(0u), src0, true).def(1).getTemp();
1264             Temp upper = bld.vsub32(bld.def(v1), Operand(0u), src1, false, borrow);
1265             bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
1266          }
1267       } else {
1268          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1269       }
1270       break;
1271    }
1272    case nir_op_iabs: {
1273       Temp src = get_alu_src(ctx, instr->src[0]);
1274       if (dst.regClass() == s1) {
1275          bld.sop1(aco_opcode::s_abs_i32, Definition(dst), bld.def(s1, scc), src);
1276       } else if (dst.regClass() == v1) {
1277          bld.vop2(aco_opcode::v_max_i32, Definition(dst), src, bld.vsub32(bld.def(v1), Operand(0u), src));
1278       } else {
1279          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1280       }
1281       break;
1282    }
1283    case nir_op_isign: {
1284       Temp src = get_alu_src(ctx, instr->src[0]);
1285       if (dst.regClass() == s1) {
1286          Temp tmp = bld.sop2(aco_opcode::s_max_i32, bld.def(s1), bld.def(s1, scc), src, Operand((uint32_t)-1));
1287          bld.sop2(aco_opcode::s_min_i32, Definition(dst), bld.def(s1, scc), tmp, Operand(1u));
1288       } else if (dst.regClass() == s2) {
1289          Temp neg = bld.sop2(aco_opcode::s_ashr_i64, bld.def(s2), bld.def(s1, scc), src, Operand(63u));
1290          Temp neqz;
1291          if (ctx->program->chip_class >= GFX8)
1292             neqz = bld.sopc(aco_opcode::s_cmp_lg_u64, bld.def(s1, scc), src, Operand(0u));
1293          else
1294             neqz = bld.sop2(aco_opcode::s_or_b64, bld.def(s2), bld.def(s1, scc), src, Operand(0u)).def(1).getTemp();
1295          /* SCC gets zero-extended to 64 bit */
1296          bld.sop2(aco_opcode::s_or_b64, Definition(dst), bld.def(s1, scc), neg, bld.scc(neqz));
1297       } else if (dst.regClass() == v1) {
1298          bld.vop3(aco_opcode::v_med3_i32, Definition(dst), Operand((uint32_t)-1), src, Operand(1u));
1299       } else if (dst.regClass() == v2) {
1300          Temp upper = emit_extract_vector(ctx, src, 1, v1);
1301          Temp neg = bld.vop2(aco_opcode::v_ashrrev_i32, bld.def(v1), Operand(31u), upper);
1302          Temp gtz = bld.vopc(aco_opcode::v_cmp_ge_i64, bld.hint_vcc(bld.def(bld.lm)), Operand(0u), src);
1303          Temp lower = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(1u), neg, gtz);
1304          upper = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0u), neg, gtz);
1305          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
1306       } else {
1307          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1308       }
1309       break;
1310    }
1311    case nir_op_imax: {
1312       if (dst.regClass() == v2b && ctx->program->chip_class >= GFX10) {
1313          emit_vop3a_instruction(ctx, instr, aco_opcode::v_max_i16_e64, dst);
1314       } else if (dst.regClass() == v2b) {
1315          emit_vop2_instruction(ctx, instr, aco_opcode::v_max_i16, dst, true);
1316       } else if (dst.regClass() == v1) {
1317          emit_vop2_instruction(ctx, instr, aco_opcode::v_max_i32, dst, true);
1318       } else if (dst.regClass() == s1) {
1319          emit_sop2_instruction(ctx, instr, aco_opcode::s_max_i32, dst, true);
1320       } else {
1321          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1322       }
1323       break;
1324    }
1325    case nir_op_umax: {
1326       if (dst.regClass() == v2b && ctx->program->chip_class >= GFX10) {
1327          emit_vop3a_instruction(ctx, instr, aco_opcode::v_max_u16_e64, dst);
1328       } else if (dst.regClass() == v2b) {
1329          emit_vop2_instruction(ctx, instr, aco_opcode::v_max_u16, dst, true);
1330       } else if (dst.regClass() == v1) {
1331          emit_vop2_instruction(ctx, instr, aco_opcode::v_max_u32, dst, true);
1332       } else if (dst.regClass() == s1) {
1333          emit_sop2_instruction(ctx, instr, aco_opcode::s_max_u32, dst, true);
1334       } else {
1335          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1336       }
1337       break;
1338    }
1339    case nir_op_imin: {
1340       if (dst.regClass() == v2b && ctx->program->chip_class >= GFX10) {
1341          emit_vop3a_instruction(ctx, instr, aco_opcode::v_min_i16_e64, dst);
1342       } else if (dst.regClass() == v2b) {
1343          emit_vop2_instruction(ctx, instr, aco_opcode::v_min_i16, dst, true);
1344       } else if (dst.regClass() == v1) {
1345          emit_vop2_instruction(ctx, instr, aco_opcode::v_min_i32, dst, true);
1346       } else if (dst.regClass() == s1) {
1347          emit_sop2_instruction(ctx, instr, aco_opcode::s_min_i32, dst, true);
1348       } else {
1349          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1350       }
1351       break;
1352    }
1353    case nir_op_umin: {
1354       if (dst.regClass() == v2b && ctx->program->chip_class >= GFX10) {
1355          emit_vop3a_instruction(ctx, instr, aco_opcode::v_min_u16_e64, dst);
1356       } else if (dst.regClass() == v2b) {
1357          emit_vop2_instruction(ctx, instr, aco_opcode::v_min_u16, dst, true);
1358       } else if (dst.regClass() == v1) {
1359          emit_vop2_instruction(ctx, instr, aco_opcode::v_min_u32, dst, true);
1360       } else if (dst.regClass() == s1) {
1361          emit_sop2_instruction(ctx, instr, aco_opcode::s_min_u32, dst, true);
1362       } else {
1363          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1364       }
1365       break;
1366    }
1367    case nir_op_ior: {
1368       if (instr->dest.dest.ssa.bit_size == 1) {
1369          emit_boolean_logic(ctx, instr, Builder::s_or, dst);
1370       } else if (dst.regClass() == v1 || dst.regClass() == v2b || dst.regClass() == v1b) {
1371          emit_vop2_instruction(ctx, instr, aco_opcode::v_or_b32, dst, true);
1372       } else if (dst.regClass() == v2) {
1373          emit_vop2_instruction_logic64(ctx, instr, aco_opcode::v_or_b32, dst);
1374       } else if (dst.regClass() == s1) {
1375          emit_sop2_instruction(ctx, instr, aco_opcode::s_or_b32, dst, true);
1376       } else if (dst.regClass() == s2) {
1377          emit_sop2_instruction(ctx, instr, aco_opcode::s_or_b64, dst, true);
1378       } else {
1379          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1380       }
1381       break;
1382    }
1383    case nir_op_iand: {
1384       if (instr->dest.dest.ssa.bit_size == 1) {
1385          emit_boolean_logic(ctx, instr, Builder::s_and, dst);
1386       } else if (dst.regClass() == v1 || dst.regClass() == v2b || dst.regClass() == v1b) {
1387          emit_vop2_instruction(ctx, instr, aco_opcode::v_and_b32, dst, true);
1388       } else if (dst.regClass() == v2) {
1389          emit_vop2_instruction_logic64(ctx, instr, aco_opcode::v_and_b32, dst);
1390       } else if (dst.regClass() == s1) {
1391          emit_sop2_instruction(ctx, instr, aco_opcode::s_and_b32, dst, true);
1392       } else if (dst.regClass() == s2) {
1393          emit_sop2_instruction(ctx, instr, aco_opcode::s_and_b64, dst, true);
1394       } else {
1395          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1396       }
1397       break;
1398    }
1399    case nir_op_ixor: {
1400       if (instr->dest.dest.ssa.bit_size == 1) {
1401          emit_boolean_logic(ctx, instr, Builder::s_xor, dst);
1402       } else if (dst.regClass() == v1 || dst.regClass() == v2b || dst.regClass() == v1b) {
1403          emit_vop2_instruction(ctx, instr, aco_opcode::v_xor_b32, dst, true);
1404       } else if (dst.regClass() == v2) {
1405          emit_vop2_instruction_logic64(ctx, instr, aco_opcode::v_xor_b32, dst);
1406       } else if (dst.regClass() == s1) {
1407          emit_sop2_instruction(ctx, instr, aco_opcode::s_xor_b32, dst, true);
1408       } else if (dst.regClass() == s2) {
1409          emit_sop2_instruction(ctx, instr, aco_opcode::s_xor_b64, dst, true);
1410       } else {
1411          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1412       }
1413       break;
1414    }
1415    case nir_op_ushr: {
1416       if (dst.regClass() == v2b && ctx->program->chip_class >= GFX10) {
1417          emit_vop3a_instruction(ctx, instr, aco_opcode::v_lshrrev_b16_e64, dst, false, 2, true);
1418       } else if (dst.regClass() == v2b) {
1419          emit_vop2_instruction(ctx, instr, aco_opcode::v_lshrrev_b16, dst, false, true);
1420       } else if (dst.regClass() == v1) {
1421          emit_vop2_instruction(ctx, instr, aco_opcode::v_lshrrev_b32, dst, false, true);
1422       } else if (dst.regClass() == v2 && ctx->program->chip_class >= GFX8) {
1423          bld.vop3(aco_opcode::v_lshrrev_b64, Definition(dst),
1424                   get_alu_src(ctx, instr->src[1]), get_alu_src(ctx, instr->src[0]));
1425       } else if (dst.regClass() == v2) {
1426          emit_vop3a_instruction(ctx, instr, aco_opcode::v_lshr_b64, dst);
1427       } else if (dst.regClass() == s2) {
1428          emit_sop2_instruction(ctx, instr, aco_opcode::s_lshr_b64, dst, true);
1429       } else if (dst.regClass() == s1) {
1430          emit_sop2_instruction(ctx, instr, aco_opcode::s_lshr_b32, dst, true);
1431       } else {
1432          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1433       }
1434       break;
1435    }
1436    case nir_op_ishl: {
1437       if (dst.regClass() == v2b && ctx->program->chip_class >= GFX10) {
1438          emit_vop3a_instruction(ctx, instr, aco_opcode::v_lshlrev_b16_e64, dst, false, 2, true);
1439       } else if (dst.regClass() == v2b) {
1440          emit_vop2_instruction(ctx, instr, aco_opcode::v_lshlrev_b16, dst, false, true);
1441       } else if (dst.regClass() == v1) {
1442          emit_vop2_instruction(ctx, instr, aco_opcode::v_lshlrev_b32, dst, false, true);
1443       } else if (dst.regClass() == v2 && ctx->program->chip_class >= GFX8) {
1444          bld.vop3(aco_opcode::v_lshlrev_b64, Definition(dst),
1445                   get_alu_src(ctx, instr->src[1]), get_alu_src(ctx, instr->src[0]));
1446       } else if (dst.regClass() == v2) {
1447          emit_vop3a_instruction(ctx, instr, aco_opcode::v_lshl_b64, dst);
1448       } else if (dst.regClass() == s1) {
1449          emit_sop2_instruction(ctx, instr, aco_opcode::s_lshl_b32, dst, true);
1450       } else if (dst.regClass() == s2) {
1451          emit_sop2_instruction(ctx, instr, aco_opcode::s_lshl_b64, dst, true);
1452       } else {
1453          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1454       }
1455       break;
1456    }
1457    case nir_op_ishr: {
1458       if (dst.regClass() == v2b && ctx->program->chip_class >= GFX10) {
1459          emit_vop3a_instruction(ctx, instr, aco_opcode::v_ashrrev_i16_e64, dst, false, 2, true);
1460       } else if (dst.regClass() == v2b) {
1461          emit_vop2_instruction(ctx, instr, aco_opcode::v_ashrrev_i16, dst, false, true);
1462       } else if (dst.regClass() == v1) {
1463          emit_vop2_instruction(ctx, instr, aco_opcode::v_ashrrev_i32, dst, false, true);
1464       } else if (dst.regClass() == v2 && ctx->program->chip_class >= GFX8) {
1465          bld.vop3(aco_opcode::v_ashrrev_i64, Definition(dst),
1466                   get_alu_src(ctx, instr->src[1]), get_alu_src(ctx, instr->src[0]));
1467       } else if (dst.regClass() == v2) {
1468          emit_vop3a_instruction(ctx, instr, aco_opcode::v_ashr_i64, dst);
1469       } else if (dst.regClass() == s1) {
1470          emit_sop2_instruction(ctx, instr, aco_opcode::s_ashr_i32, dst, true);
1471       } else if (dst.regClass() == s2) {
1472          emit_sop2_instruction(ctx, instr, aco_opcode::s_ashr_i64, dst, true);
1473       } else {
1474          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1475       }
1476       break;
1477    }
1478    case nir_op_find_lsb: {
1479       Temp src = get_alu_src(ctx, instr->src[0]);
1480       if (src.regClass() == s1) {
1481          bld.sop1(aco_opcode::s_ff1_i32_b32, Definition(dst), src);
1482       } else if (src.regClass() == v1) {
1483          emit_vop1_instruction(ctx, instr, aco_opcode::v_ffbl_b32, dst);
1484       } else if (src.regClass() == s2) {
1485          bld.sop1(aco_opcode::s_ff1_i32_b64, Definition(dst), src);
1486       } else {
1487          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1488       }
1489       break;
1490    }
1491    case nir_op_ufind_msb:
1492    case nir_op_ifind_msb: {
1493       Temp src = get_alu_src(ctx, instr->src[0]);
1494       if (src.regClass() == s1 || src.regClass() == s2) {
1495          aco_opcode op = src.regClass() == s2 ?
1496                          (instr->op == nir_op_ufind_msb ? aco_opcode::s_flbit_i32_b64 : aco_opcode::s_flbit_i32_i64) :
1497                          (instr->op == nir_op_ufind_msb ? aco_opcode::s_flbit_i32_b32 : aco_opcode::s_flbit_i32);
1498          Temp msb_rev = bld.sop1(op, bld.def(s1), src);
1499 
1500          Builder::Result sub = bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.def(s1, scc),
1501                                         Operand(src.size() * 32u - 1u), msb_rev);
1502          Temp msb = sub.def(0).getTemp();
1503          Temp carry = sub.def(1).getTemp();
1504 
1505          bld.sop2(aco_opcode::s_cselect_b32, Definition(dst), Operand((uint32_t)-1), msb, bld.scc(carry));
1506       } else if (src.regClass() == v1) {
1507          aco_opcode op = instr->op == nir_op_ufind_msb ? aco_opcode::v_ffbh_u32 : aco_opcode::v_ffbh_i32;
1508          Temp msb_rev = bld.tmp(v1);
1509          emit_vop1_instruction(ctx, instr, op, msb_rev);
1510          Temp msb = bld.tmp(v1);
1511          Temp carry = bld.vsub32(Definition(msb), Operand(31u), Operand(msb_rev), true).def(1).getTemp();
1512          bld.vop2_e64(aco_opcode::v_cndmask_b32, Definition(dst), msb, Operand((uint32_t)-1), carry);
1513       } else {
1514          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1515       }
1516       break;
1517    }
1518    case nir_op_bitfield_reverse: {
1519       if (dst.regClass() == s1) {
1520          bld.sop1(aco_opcode::s_brev_b32, Definition(dst), get_alu_src(ctx, instr->src[0]));
1521       } else if (dst.regClass() == v1) {
1522          bld.vop1(aco_opcode::v_bfrev_b32, Definition(dst), get_alu_src(ctx, instr->src[0]));
1523       } else {
1524          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1525       }
1526       break;
1527    }
1528    case nir_op_iadd: {
1529       if (dst.regClass() == s1) {
1530          emit_sop2_instruction(ctx, instr, aco_opcode::s_add_u32, dst, true);
1531          break;
1532       } else if (dst.bytes() <= 2 && ctx->program->chip_class >= GFX10) {
1533          emit_vop3a_instruction(ctx, instr, aco_opcode::v_add_u16_e64, dst);
1534          break;
1535       } else if (dst.bytes() <= 2 && ctx->program->chip_class >= GFX8) {
1536          emit_vop2_instruction(ctx, instr, aco_opcode::v_add_u16, dst, true);
1537          break;
1538       }
1539 
1540       Temp src0 = get_alu_src(ctx, instr->src[0]);
1541       Temp src1 = get_alu_src(ctx, instr->src[1]);
1542       if (dst.type() == RegType::vgpr && dst.bytes() <= 4) {
1543          bld.vadd32(Definition(dst), Operand(src0), Operand(src1));
1544          break;
1545       }
1546 
1547       assert(src0.size() == 2 && src1.size() == 2);
1548       Temp src00 = bld.tmp(src0.type(), 1);
1549       Temp src01 = bld.tmp(dst.type(), 1);
1550       bld.pseudo(aco_opcode::p_split_vector, Definition(src00), Definition(src01), src0);
1551       Temp src10 = bld.tmp(src1.type(), 1);
1552       Temp src11 = bld.tmp(dst.type(), 1);
1553       bld.pseudo(aco_opcode::p_split_vector, Definition(src10), Definition(src11), src1);
1554 
1555       if (dst.regClass() == s2) {
1556          Temp carry = bld.tmp(s1);
1557          Temp dst0 = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.scc(Definition(carry)), src00, src10);
1558          Temp dst1 = bld.sop2(aco_opcode::s_addc_u32, bld.def(s1), bld.def(s1, scc), src01, src11, bld.scc(carry));
1559          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), dst0, dst1);
1560       } else if (dst.regClass() == v2) {
1561          Temp dst0 = bld.tmp(v1);
1562          Temp carry = bld.vadd32(Definition(dst0), src00, src10, true).def(1).getTemp();
1563          Temp dst1 = bld.vadd32(bld.def(v1), src01, src11, false, carry);
1564          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), dst0, dst1);
1565       } else {
1566          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1567       }
1568       break;
1569    }
1570    case nir_op_uadd_sat: {
1571       Temp src0 = get_alu_src(ctx, instr->src[0]);
1572       Temp src1 = get_alu_src(ctx, instr->src[1]);
1573       if (dst.regClass() == s1) {
1574          Temp tmp = bld.tmp(s1), carry = bld.tmp(s1);
1575          bld.sop2(aco_opcode::s_add_u32, Definition(tmp), bld.scc(Definition(carry)),
1576                   src0, src1);
1577          bld.sop2(aco_opcode::s_cselect_b32, Definition(dst), Operand((uint32_t) -1), tmp, bld.scc(carry));
1578       } else if (dst.regClass() == v2b) {
1579          Instruction *instr;
1580          if (ctx->program->chip_class >= GFX10) {
1581             instr = bld.vop3(aco_opcode::v_add_u16_e64, Definition(dst), src0, src1).instr;
1582          } else {
1583             if (src1.type() == RegType::sgpr)
1584                std::swap(src0, src1);
1585             instr = bld.vop2_e64(aco_opcode::v_add_u16, Definition(dst), src0, as_vgpr(ctx, src1)).instr;
1586          }
1587          static_cast<VOP3A_instruction*>(instr)->clamp = 1;
1588       } else if (dst.regClass() == v1) {
1589          if (ctx->options->chip_class >= GFX9) {
1590             aco_ptr<VOP3A_instruction> add{create_instruction<VOP3A_instruction>(aco_opcode::v_add_u32, asVOP3(Format::VOP2), 2, 1)};
1591             add->operands[0] = Operand(src0);
1592             add->operands[1] = Operand(src1);
1593             add->definitions[0] = Definition(dst);
1594             add->clamp = 1;
1595             ctx->block->instructions.emplace_back(std::move(add));
1596          } else {
1597             if (src1.regClass() != v1)
1598                std::swap(src0, src1);
1599             assert(src1.regClass() == v1);
1600             Temp tmp = bld.tmp(v1);
1601             Temp carry = bld.vadd32(Definition(tmp), src0, src1, true).def(1).getTemp();
1602             bld.vop2_e64(aco_opcode::v_cndmask_b32, Definition(dst), tmp, Operand((uint32_t) -1), carry);
1603          }
1604       } else {
1605          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1606       }
1607       break;
1608    }
1609    case nir_op_uadd_carry: {
1610       Temp src0 = get_alu_src(ctx, instr->src[0]);
1611       Temp src1 = get_alu_src(ctx, instr->src[1]);
1612       if (dst.regClass() == s1) {
1613          bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.scc(Definition(dst)), src0, src1);
1614          break;
1615       }
1616       if (dst.regClass() == v1) {
1617          Temp carry = bld.vadd32(bld.def(v1), src0, src1, true).def(1).getTemp();
1618          bld.vop2_e64(aco_opcode::v_cndmask_b32, Definition(dst), Operand(0u), Operand(1u), carry);
1619          break;
1620       }
1621 
1622       Temp src00 = bld.tmp(src0.type(), 1);
1623       Temp src01 = bld.tmp(dst.type(), 1);
1624       bld.pseudo(aco_opcode::p_split_vector, Definition(src00), Definition(src01), src0);
1625       Temp src10 = bld.tmp(src1.type(), 1);
1626       Temp src11 = bld.tmp(dst.type(), 1);
1627       bld.pseudo(aco_opcode::p_split_vector, Definition(src10), Definition(src11), src1);
1628       if (dst.regClass() == s2) {
1629          Temp carry = bld.tmp(s1);
1630          bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.scc(Definition(carry)), src00, src10);
1631          carry = bld.sop2(aco_opcode::s_addc_u32, bld.def(s1), bld.scc(bld.def(s1)), src01, src11, bld.scc(carry)).def(1).getTemp();
1632          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), carry, Operand(0u));
1633       } else if (dst.regClass() == v2) {
1634          Temp carry = bld.vadd32(bld.def(v1), src00, src10, true).def(1).getTemp();
1635          carry = bld.vadd32(bld.def(v1), src01, src11, true, carry).def(1).getTemp();
1636          carry = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0u), Operand(1u), carry);
1637          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), carry, Operand(0u));
1638       } else {
1639          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1640       }
1641       break;
1642    }
1643    case nir_op_isub: {
1644       if (dst.regClass() == s1) {
1645          emit_sop2_instruction(ctx, instr, aco_opcode::s_sub_i32, dst, true);
1646          break;
1647       }
1648 
1649       Temp src0 = get_alu_src(ctx, instr->src[0]);
1650       Temp src1 = get_alu_src(ctx, instr->src[1]);
1651       if (dst.regClass() == v1) {
1652          bld.vsub32(Definition(dst), src0, src1);
1653          break;
1654       } else if (dst.bytes() <= 2) {
1655          if (ctx->program->chip_class >= GFX10)
1656             bld.vop3(aco_opcode::v_sub_u16_e64, Definition(dst), src0, src1);
1657          else if (src1.type() == RegType::sgpr)
1658             bld.vop2(aco_opcode::v_subrev_u16, Definition(dst), src1, as_vgpr(ctx, src0));
1659          else if (ctx->program->chip_class >= GFX8)
1660             bld.vop2(aco_opcode::v_sub_u16, Definition(dst), src0, as_vgpr(ctx, src1));
1661          else
1662             bld.vsub32(Definition(dst), src0, src1);
1663          break;
1664       }
1665 
1666       Temp src00 = bld.tmp(src0.type(), 1);
1667       Temp src01 = bld.tmp(dst.type(), 1);
1668       bld.pseudo(aco_opcode::p_split_vector, Definition(src00), Definition(src01), src0);
1669       Temp src10 = bld.tmp(src1.type(), 1);
1670       Temp src11 = bld.tmp(dst.type(), 1);
1671       bld.pseudo(aco_opcode::p_split_vector, Definition(src10), Definition(src11), src1);
1672       if (dst.regClass() == s2) {
1673          Temp carry = bld.tmp(s1);
1674          Temp dst0 = bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.scc(Definition(carry)), src00, src10);
1675          Temp dst1 = bld.sop2(aco_opcode::s_subb_u32, bld.def(s1), bld.def(s1, scc), src01, src11, carry);
1676          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), dst0, dst1);
1677       } else if (dst.regClass() == v2) {
1678          Temp lower = bld.tmp(v1);
1679          Temp borrow = bld.vsub32(Definition(lower), src00, src10, true).def(1).getTemp();
1680          Temp upper = bld.vsub32(bld.def(v1), src01, src11, false, borrow);
1681          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
1682       } else {
1683          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1684       }
1685       break;
1686    }
1687    case nir_op_usub_borrow: {
1688       Temp src0 = get_alu_src(ctx, instr->src[0]);
1689       Temp src1 = get_alu_src(ctx, instr->src[1]);
1690       if (dst.regClass() == s1) {
1691          bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.scc(Definition(dst)), src0, src1);
1692          break;
1693       } else if (dst.regClass() == v1) {
1694          Temp borrow = bld.vsub32(bld.def(v1), src0, src1, true).def(1).getTemp();
1695          bld.vop2_e64(aco_opcode::v_cndmask_b32, Definition(dst), Operand(0u), Operand(1u), borrow);
1696          break;
1697       }
1698 
1699       Temp src00 = bld.tmp(src0.type(), 1);
1700       Temp src01 = bld.tmp(dst.type(), 1);
1701       bld.pseudo(aco_opcode::p_split_vector, Definition(src00), Definition(src01), src0);
1702       Temp src10 = bld.tmp(src1.type(), 1);
1703       Temp src11 = bld.tmp(dst.type(), 1);
1704       bld.pseudo(aco_opcode::p_split_vector, Definition(src10), Definition(src11), src1);
1705       if (dst.regClass() == s2) {
1706          Temp borrow = bld.tmp(s1);
1707          bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.scc(Definition(borrow)), src00, src10);
1708          borrow = bld.sop2(aco_opcode::s_subb_u32, bld.def(s1), bld.scc(bld.def(s1)), src01, src11, bld.scc(borrow)).def(1).getTemp();
1709          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), borrow, Operand(0u));
1710       } else if (dst.regClass() == v2) {
1711          Temp borrow = bld.vsub32(bld.def(v1), src00, src10, true).def(1).getTemp();
1712          borrow = bld.vsub32(bld.def(v1), src01, src11, true, Operand(borrow)).def(1).getTemp();
1713          borrow = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0u), Operand(1u), borrow);
1714          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), borrow, Operand(0u));
1715       } else {
1716          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1717       }
1718       break;
1719    }
1720    case nir_op_imul: {
1721       if (dst.bytes() <= 2 && ctx->program->chip_class >= GFX10) {
1722          emit_vop3a_instruction(ctx, instr, aco_opcode::v_mul_lo_u16_e64, dst);
1723       } else if (dst.bytes() <= 2 && ctx->program->chip_class >= GFX8) {
1724          emit_vop2_instruction(ctx, instr, aco_opcode::v_mul_lo_u16, dst, true);
1725       } else if (dst.type() == RegType::vgpr) {
1726          uint32_t src0_ub = get_alu_src_ub(ctx, instr, 0);
1727          uint32_t src1_ub = get_alu_src_ub(ctx, instr, 1);
1728 
1729          if (src0_ub <= 0xffffff && src1_ub <= 0xffffff) {
1730             emit_vop2_instruction(ctx, instr, aco_opcode::v_mul_u32_u24, dst, true);
1731          } else {
1732             emit_vop3a_instruction(ctx, instr, aco_opcode::v_mul_lo_u32, dst);
1733          }
1734       } else if (dst.regClass() == s1) {
1735          emit_sop2_instruction(ctx, instr, aco_opcode::s_mul_i32, dst, false);
1736       } else {
1737          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1738       }
1739       break;
1740    }
1741    case nir_op_umul_high: {
1742       if (dst.regClass() == s1 && ctx->options->chip_class >= GFX9) {
1743          emit_sop2_instruction(ctx, instr, aco_opcode::s_mul_hi_u32, dst, false);
1744       } else if (dst.bytes() == 4) {
1745          uint32_t src0_ub = get_alu_src_ub(ctx, instr, 0);
1746          uint32_t src1_ub = get_alu_src_ub(ctx, instr, 1);
1747 
1748          Temp tmp = dst.regClass() == s1 ? bld.tmp(v1) : dst;
1749          if (src0_ub <= 0xffffff && src1_ub <= 0xffffff) {
1750             emit_vop2_instruction(ctx, instr, aco_opcode::v_mul_hi_u32_u24, tmp, true);
1751          } else {
1752             emit_vop3a_instruction(ctx, instr, aco_opcode::v_mul_hi_u32, tmp);
1753          }
1754 
1755          if (dst.regClass() == s1)
1756             bld.pseudo(aco_opcode::p_as_uniform, Definition(dst), tmp);
1757       } else {
1758          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1759       }
1760       break;
1761    }
1762    case nir_op_imul_high: {
1763       if (dst.regClass() == v1) {
1764          emit_vop3a_instruction(ctx, instr, aco_opcode::v_mul_hi_i32, dst);
1765       } else if (dst.regClass() == s1 && ctx->options->chip_class >= GFX9) {
1766          emit_sop2_instruction(ctx, instr, aco_opcode::s_mul_hi_i32, dst, false);
1767       } else if (dst.regClass() == s1) {
1768          Temp tmp = bld.vop3(aco_opcode::v_mul_hi_i32, bld.def(v1), get_alu_src(ctx, instr->src[0]),
1769                              as_vgpr(ctx, get_alu_src(ctx, instr->src[1])));
1770          bld.pseudo(aco_opcode::p_as_uniform, Definition(dst), tmp);
1771       } else {
1772          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1773       }
1774       break;
1775    }
1776    case nir_op_fmul: {
1777       if (dst.regClass() == v2b) {
1778          emit_vop2_instruction(ctx, instr, aco_opcode::v_mul_f16, dst, true);
1779       } else if (dst.regClass() == v1) {
1780          emit_vop2_instruction(ctx, instr, aco_opcode::v_mul_f32, dst, true);
1781       } else if (dst.regClass() == v2) {
1782          emit_vop3a_instruction(ctx, instr, aco_opcode::v_mul_f64, dst);
1783       } else {
1784          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1785       }
1786       break;
1787    }
1788    case nir_op_fadd: {
1789       if (dst.regClass() == v2b) {
1790          emit_vop2_instruction(ctx, instr, aco_opcode::v_add_f16, dst, true);
1791       } else if (dst.regClass() == v1) {
1792          emit_vop2_instruction(ctx, instr, aco_opcode::v_add_f32, dst, true);
1793       } else if (dst.regClass() == v2) {
1794          emit_vop3a_instruction(ctx, instr, aco_opcode::v_add_f64, dst);
1795       } else {
1796          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1797       }
1798       break;
1799    }
1800    case nir_op_fsub: {
1801       Temp src0 = get_alu_src(ctx, instr->src[0]);
1802       Temp src1 = get_alu_src(ctx, instr->src[1]);
1803       if (dst.regClass() == v2b) {
1804          if (src1.type() == RegType::vgpr || src0.type() != RegType::vgpr)
1805             emit_vop2_instruction(ctx, instr, aco_opcode::v_sub_f16, dst, false);
1806          else
1807             emit_vop2_instruction(ctx, instr, aco_opcode::v_subrev_f16, dst, true);
1808       } else if (dst.regClass() == v1) {
1809          if (src1.type() == RegType::vgpr || src0.type() != RegType::vgpr)
1810             emit_vop2_instruction(ctx, instr, aco_opcode::v_sub_f32, dst, false);
1811          else
1812             emit_vop2_instruction(ctx, instr, aco_opcode::v_subrev_f32, dst, true);
1813       } else if (dst.regClass() == v2) {
1814          Instruction* add = bld.vop3(aco_opcode::v_add_f64, Definition(dst),
1815                                      as_vgpr(ctx, src0), as_vgpr(ctx, src1));
1816          VOP3A_instruction* sub = static_cast<VOP3A_instruction*>(add);
1817          sub->neg[1] = true;
1818       } else {
1819          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1820       }
1821       break;
1822    }
1823    case nir_op_fmax: {
1824       if (dst.regClass() == v2b) {
1825          // TODO: check fp_mode.must_flush_denorms16_64
1826          emit_vop2_instruction(ctx, instr, aco_opcode::v_max_f16, dst, true);
1827       } else if (dst.regClass() == v1) {
1828          emit_vop2_instruction(ctx, instr, aco_opcode::v_max_f32, dst, true, false, ctx->block->fp_mode.must_flush_denorms32);
1829       } else if (dst.regClass() == v2) {
1830          emit_vop3a_instruction(ctx, instr, aco_opcode::v_max_f64, dst, ctx->block->fp_mode.must_flush_denorms16_64);
1831       } else {
1832          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1833       }
1834       break;
1835    }
1836    case nir_op_fmin: {
1837       if (dst.regClass() == v2b) {
1838          // TODO: check fp_mode.must_flush_denorms16_64
1839          emit_vop2_instruction(ctx, instr, aco_opcode::v_min_f16, dst, true);
1840       } else if (dst.regClass() == v1) {
1841          emit_vop2_instruction(ctx, instr, aco_opcode::v_min_f32, dst, true, false, ctx->block->fp_mode.must_flush_denorms32);
1842       } else if (dst.regClass() == v2) {
1843          emit_vop3a_instruction(ctx, instr, aco_opcode::v_min_f64, dst, ctx->block->fp_mode.must_flush_denorms16_64);
1844       } else {
1845          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1846       }
1847       break;
1848    }
1849    case nir_op_cube_face_coord: {
1850       Temp in = get_alu_src(ctx, instr->src[0], 3);
1851       Temp src[3] = { emit_extract_vector(ctx, in, 0, v1),
1852                       emit_extract_vector(ctx, in, 1, v1),
1853                       emit_extract_vector(ctx, in, 2, v1) };
1854       Temp ma = bld.vop3(aco_opcode::v_cubema_f32, bld.def(v1), src[0], src[1], src[2]);
1855       ma = bld.vop1(aco_opcode::v_rcp_f32, bld.def(v1), ma);
1856       Temp sc = bld.vop3(aco_opcode::v_cubesc_f32, bld.def(v1), src[0], src[1], src[2]);
1857       Temp tc = bld.vop3(aco_opcode::v_cubetc_f32, bld.def(v1), src[0], src[1], src[2]);
1858       sc = bld.vop2(aco_opcode::v_add_f32, bld.def(v1),
1859                     Operand(0x3f000000u/*0.5*/),
1860                     bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), sc, ma));
1861       tc = bld.vop2(aco_opcode::v_add_f32, bld.def(v1),
1862                     Operand(0x3f000000u/*0.5*/),
1863                     bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), tc, ma));
1864       bld.pseudo(aco_opcode::p_create_vector, Definition(dst), sc, tc);
1865       break;
1866    }
1867    case nir_op_cube_face_index: {
1868       Temp in = get_alu_src(ctx, instr->src[0], 3);
1869       Temp src[3] = { emit_extract_vector(ctx, in, 0, v1),
1870                       emit_extract_vector(ctx, in, 1, v1),
1871                       emit_extract_vector(ctx, in, 2, v1) };
1872       bld.vop3(aco_opcode::v_cubeid_f32, Definition(dst), src[0], src[1], src[2]);
1873       break;
1874    }
1875    case nir_op_bcsel: {
1876       emit_bcsel(ctx, instr, dst);
1877       break;
1878    }
1879    case nir_op_frsq: {
1880       if (dst.regClass() == v2b) {
1881          emit_vop1_instruction(ctx, instr, aco_opcode::v_rsq_f16, dst);
1882       } else if (dst.regClass() == v1) {
1883          Temp src = get_alu_src(ctx, instr->src[0]);
1884          emit_rsq(ctx, bld, Definition(dst), src);
1885       } else if (dst.regClass() == v2) {
1886          /* Lowered at NIR level for precision reasons. */
1887          emit_vop1_instruction(ctx, instr, aco_opcode::v_rsq_f64, dst);
1888       } else {
1889          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1890       }
1891       break;
1892    }
1893    case nir_op_fneg: {
1894       Temp src = get_alu_src(ctx, instr->src[0]);
1895       if (dst.regClass() == v2b) {
1896          if (ctx->block->fp_mode.must_flush_denorms16_64)
1897             src = bld.vop2(aco_opcode::v_mul_f16, bld.def(v2b), Operand((uint16_t)0x3C00), as_vgpr(ctx, src));
1898          bld.vop2(aco_opcode::v_xor_b32, Definition(dst), Operand(0x8000u), as_vgpr(ctx, src));
1899       } else if (dst.regClass() == v1) {
1900          if (ctx->block->fp_mode.must_flush_denorms32)
1901             src = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), Operand(0x3f800000u), as_vgpr(ctx, src));
1902          bld.vop2(aco_opcode::v_xor_b32, Definition(dst), Operand(0x80000000u), as_vgpr(ctx, src));
1903       } else if (dst.regClass() == v2) {
1904          if (ctx->block->fp_mode.must_flush_denorms16_64)
1905             src = bld.vop3(aco_opcode::v_mul_f64, bld.def(v2), Operand(UINT64_C(0x3FF0000000000000)), as_vgpr(ctx, src));
1906          Temp upper = bld.tmp(v1), lower = bld.tmp(v1);
1907          bld.pseudo(aco_opcode::p_split_vector, Definition(lower), Definition(upper), src);
1908          upper = bld.vop2(aco_opcode::v_xor_b32, bld.def(v1), Operand(0x80000000u), upper);
1909          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
1910       } else {
1911          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1912       }
1913       break;
1914    }
1915    case nir_op_fabs: {
1916       Temp src = get_alu_src(ctx, instr->src[0]);
1917       if (dst.regClass() == v2b) {
1918          if (ctx->block->fp_mode.must_flush_denorms16_64)
1919             src = bld.vop2(aco_opcode::v_mul_f16, bld.def(v2b), Operand((uint16_t)0x3C00), as_vgpr(ctx, src));
1920          bld.vop2(aco_opcode::v_and_b32, Definition(dst), Operand(0x7FFFu), as_vgpr(ctx, src));
1921       } else if (dst.regClass() == v1) {
1922          if (ctx->block->fp_mode.must_flush_denorms32)
1923             src = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), Operand(0x3f800000u), as_vgpr(ctx, src));
1924          bld.vop2(aco_opcode::v_and_b32, Definition(dst), Operand(0x7FFFFFFFu), as_vgpr(ctx, src));
1925       } else if (dst.regClass() == v2) {
1926          if (ctx->block->fp_mode.must_flush_denorms16_64)
1927             src = bld.vop3(aco_opcode::v_mul_f64, bld.def(v2), Operand(UINT64_C(0x3FF0000000000000)), as_vgpr(ctx, src));
1928          Temp upper = bld.tmp(v1), lower = bld.tmp(v1);
1929          bld.pseudo(aco_opcode::p_split_vector, Definition(lower), Definition(upper), src);
1930          upper = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0x7FFFFFFFu), upper);
1931          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
1932       } else {
1933          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1934       }
1935       break;
1936    }
1937    case nir_op_fsat: {
1938       Temp src = get_alu_src(ctx, instr->src[0]);
1939       if (dst.regClass() == v2b) {
1940          bld.vop3(aco_opcode::v_med3_f16, Definition(dst), Operand((uint16_t)0u), Operand((uint16_t)0x3c00), src);
1941       } else if (dst.regClass() == v1) {
1942          bld.vop3(aco_opcode::v_med3_f32, Definition(dst), Operand(0u), Operand(0x3f800000u), src);
1943          /* apparently, it is not necessary to flush denorms if this instruction is used with these operands */
1944          // TODO: confirm that this holds under any circumstances
1945       } else if (dst.regClass() == v2) {
1946          Instruction* add = bld.vop3(aco_opcode::v_add_f64, Definition(dst), src, Operand(0u));
1947          VOP3A_instruction* vop3 = static_cast<VOP3A_instruction*>(add);
1948          vop3->clamp = true;
1949       } else {
1950          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1951       }
1952       break;
1953    }
1954    case nir_op_flog2: {
1955       if (dst.regClass() == v2b) {
1956          emit_vop1_instruction(ctx, instr, aco_opcode::v_log_f16, dst);
1957       } else if (dst.regClass() == v1) {
1958          Temp src = get_alu_src(ctx, instr->src[0]);
1959          emit_log2(ctx, bld, Definition(dst), src);
1960       } else {
1961          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1962       }
1963       break;
1964    }
1965    case nir_op_frcp: {
1966       if (dst.regClass() == v2b) {
1967          emit_vop1_instruction(ctx, instr, aco_opcode::v_rcp_f16, dst);
1968       } else if (dst.regClass() == v1) {
1969          Temp src = get_alu_src(ctx, instr->src[0]);
1970          emit_rcp(ctx, bld, Definition(dst), src);
1971       } else if (dst.regClass() == v2) {
1972          /* Lowered at NIR level for precision reasons. */
1973          emit_vop1_instruction(ctx, instr, aco_opcode::v_rcp_f64, dst);
1974       } else {
1975          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1976       }
1977       break;
1978    }
1979    case nir_op_fexp2: {
1980       if (dst.regClass() == v2b) {
1981          emit_vop1_instruction(ctx, instr, aco_opcode::v_exp_f16, dst);
1982       } else if (dst.regClass() == v1) {
1983          emit_vop1_instruction(ctx, instr, aco_opcode::v_exp_f32, dst);
1984       } else {
1985          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
1986       }
1987       break;
1988    }
1989    case nir_op_fsqrt: {
1990       if (dst.regClass() == v2b) {
1991          emit_vop1_instruction(ctx, instr, aco_opcode::v_sqrt_f16, dst);
1992       } else if (dst.regClass() == v1) {
1993          Temp src = get_alu_src(ctx, instr->src[0]);
1994          emit_sqrt(ctx, bld, Definition(dst), src);
1995       } else if (dst.regClass() == v2) {
1996          /* Lowered at NIR level for precision reasons. */
1997          emit_vop1_instruction(ctx, instr, aco_opcode::v_sqrt_f64, dst);
1998       } else {
1999          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2000       }
2001       break;
2002    }
2003    case nir_op_ffract: {
2004       if (dst.regClass() == v2b) {
2005          emit_vop1_instruction(ctx, instr, aco_opcode::v_fract_f16, dst);
2006       } else if (dst.regClass() == v1) {
2007          emit_vop1_instruction(ctx, instr, aco_opcode::v_fract_f32, dst);
2008       } else if (dst.regClass() == v2) {
2009          emit_vop1_instruction(ctx, instr, aco_opcode::v_fract_f64, dst);
2010       } else {
2011          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2012       }
2013       break;
2014    }
2015    case nir_op_ffloor: {
2016       if (dst.regClass() == v2b) {
2017          emit_vop1_instruction(ctx, instr, aco_opcode::v_floor_f16, dst);
2018       } else if (dst.regClass() == v1) {
2019          emit_vop1_instruction(ctx, instr, aco_opcode::v_floor_f32, dst);
2020       } else if (dst.regClass() == v2) {
2021          Temp src = get_alu_src(ctx, instr->src[0]);
2022          emit_floor_f64(ctx, bld, Definition(dst), src);
2023       } else {
2024          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2025       }
2026       break;
2027    }
2028    case nir_op_fceil: {
2029       if (dst.regClass() == v2b) {
2030          emit_vop1_instruction(ctx, instr, aco_opcode::v_ceil_f16, dst);
2031       } else if (dst.regClass() == v1) {
2032          emit_vop1_instruction(ctx, instr, aco_opcode::v_ceil_f32, dst);
2033       } else if (dst.regClass() == v2) {
2034          if (ctx->options->chip_class >= GFX7) {
2035             emit_vop1_instruction(ctx, instr, aco_opcode::v_ceil_f64, dst);
2036          } else {
2037             /* GFX6 doesn't support V_CEIL_F64, lower it. */
2038             /* trunc = trunc(src0)
2039              * if (src0 > 0.0 && src0 != trunc)
2040              *    trunc += 1.0
2041              */
2042             Temp src0 = get_alu_src(ctx, instr->src[0]);
2043             Temp trunc = emit_trunc_f64(ctx, bld, bld.def(v2), src0);
2044             Temp tmp0 = bld.vopc_e64(aco_opcode::v_cmp_gt_f64, bld.def(bld.lm), src0, Operand(0u));
2045             Temp tmp1 = bld.vopc(aco_opcode::v_cmp_lg_f64, bld.hint_vcc(bld.def(bld.lm)), src0, trunc);
2046             Temp cond = bld.sop2(aco_opcode::s_and_b64, bld.hint_vcc(bld.def(s2)), bld.def(s1, scc), tmp0, tmp1);
2047             Temp add = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), bld.copy(bld.def(v1), Operand(0u)), bld.copy(bld.def(v1), Operand(0x3ff00000u)), cond);
2048             add = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), bld.copy(bld.def(v1), Operand(0u)), add);
2049             bld.vop3(aco_opcode::v_add_f64, Definition(dst), trunc, add);
2050          }
2051       } else {
2052          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2053       }
2054       break;
2055    }
2056    case nir_op_ftrunc: {
2057       if (dst.regClass() == v2b) {
2058          emit_vop1_instruction(ctx, instr, aco_opcode::v_trunc_f16, dst);
2059       } else if (dst.regClass() == v1) {
2060          emit_vop1_instruction(ctx, instr, aco_opcode::v_trunc_f32, dst);
2061       } else if (dst.regClass() == v2) {
2062          Temp src = get_alu_src(ctx, instr->src[0]);
2063          emit_trunc_f64(ctx, bld, Definition(dst), src);
2064       } else {
2065          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2066       }
2067       break;
2068    }
2069    case nir_op_fround_even: {
2070       if (dst.regClass() == v2b) {
2071          emit_vop1_instruction(ctx, instr, aco_opcode::v_rndne_f16, dst);
2072       } else if (dst.regClass() == v1) {
2073          emit_vop1_instruction(ctx, instr, aco_opcode::v_rndne_f32, dst);
2074       } else if (dst.regClass() == v2) {
2075          if (ctx->options->chip_class >= GFX7) {
2076             emit_vop1_instruction(ctx, instr, aco_opcode::v_rndne_f64, dst);
2077          } else {
2078             /* GFX6 doesn't support V_RNDNE_F64, lower it. */
2079             Temp src0_lo = bld.tmp(v1), src0_hi = bld.tmp(v1);
2080             Temp src0 = get_alu_src(ctx, instr->src[0]);
2081             bld.pseudo(aco_opcode::p_split_vector, Definition(src0_lo), Definition(src0_hi), src0);
2082 
2083             Temp bitmask = bld.sop1(aco_opcode::s_brev_b32, bld.def(s1), bld.copy(bld.def(s1), Operand(-2u)));
2084             Temp bfi = bld.vop3(aco_opcode::v_bfi_b32, bld.def(v1), bitmask, bld.copy(bld.def(v1), Operand(0x43300000u)), as_vgpr(ctx, src0_hi));
2085             Temp tmp = bld.vop3(aco_opcode::v_add_f64, bld.def(v2), src0, bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), Operand(0u), bfi));
2086             Instruction *sub = bld.vop3(aco_opcode::v_add_f64, bld.def(v2), tmp, bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), Operand(0u), bfi));
2087             static_cast<VOP3A_instruction*>(sub)->neg[1] = true;
2088             tmp = sub->definitions[0].getTemp();
2089 
2090             Temp v = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), Operand(-1u), Operand(0x432fffffu));
2091             Instruction* vop3 = bld.vopc_e64(aco_opcode::v_cmp_gt_f64, bld.hint_vcc(bld.def(bld.lm)), src0, v);
2092             static_cast<VOP3A_instruction*>(vop3)->abs[0] = true;
2093             Temp cond = vop3->definitions[0].getTemp();
2094 
2095             Temp tmp_lo = bld.tmp(v1), tmp_hi = bld.tmp(v1);
2096             bld.pseudo(aco_opcode::p_split_vector, Definition(tmp_lo), Definition(tmp_hi), tmp);
2097             Temp dst0 = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), tmp_lo, as_vgpr(ctx, src0_lo), cond);
2098             Temp dst1 = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), tmp_hi, as_vgpr(ctx, src0_hi), cond);
2099 
2100             bld.pseudo(aco_opcode::p_create_vector, Definition(dst), dst0, dst1);
2101          }
2102       } else {
2103          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2104       }
2105       break;
2106    }
2107    case nir_op_fsin:
2108    case nir_op_fcos: {
2109       Temp src = as_vgpr(ctx, get_alu_src(ctx, instr->src[0]));
2110       aco_ptr<Instruction> norm;
2111       if (dst.regClass() == v2b) {
2112          Temp half_pi = bld.copy(bld.def(s1), Operand(0x3118u));
2113          Temp tmp = bld.vop2(aco_opcode::v_mul_f16, bld.def(v1), half_pi, src);
2114          aco_opcode opcode = instr->op == nir_op_fsin ? aco_opcode::v_sin_f16 : aco_opcode::v_cos_f16;
2115          bld.vop1(opcode, Definition(dst), tmp);
2116       } else if (dst.regClass() == v1) {
2117          Temp half_pi = bld.copy(bld.def(s1), Operand(0x3e22f983u));
2118          Temp tmp = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), half_pi, src);
2119 
2120          /* before GFX9, v_sin_f32 and v_cos_f32 had a valid input domain of [-256, +256] */
2121          if (ctx->options->chip_class < GFX9)
2122             tmp = bld.vop1(aco_opcode::v_fract_f32, bld.def(v1), tmp);
2123 
2124          aco_opcode opcode = instr->op == nir_op_fsin ? aco_opcode::v_sin_f32 : aco_opcode::v_cos_f32;
2125          bld.vop1(opcode, Definition(dst), tmp);
2126       } else {
2127          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2128       }
2129       break;
2130    }
2131    case nir_op_ldexp: {
2132       if (dst.regClass() == v2b) {
2133          emit_vop2_instruction(ctx, instr, aco_opcode::v_ldexp_f16, dst, false);
2134       } else if (dst.regClass() == v1) {
2135          emit_vop3a_instruction(ctx, instr, aco_opcode::v_ldexp_f32, dst);
2136       } else if (dst.regClass() == v2) {
2137          emit_vop3a_instruction(ctx, instr, aco_opcode::v_ldexp_f64, dst);
2138       } else {
2139          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2140       }
2141       break;
2142    }
2143    case nir_op_frexp_sig: {
2144       if (dst.regClass() == v2b) {
2145          emit_vop1_instruction(ctx, instr, aco_opcode::v_frexp_mant_f16, dst);
2146       } else if (dst.regClass() == v1) {
2147          emit_vop1_instruction(ctx, instr, aco_opcode::v_frexp_mant_f32, dst);
2148       } else if (dst.regClass() == v2) {
2149          emit_vop1_instruction(ctx, instr, aco_opcode::v_frexp_mant_f64, dst);
2150       } else {
2151          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2152       }
2153       break;
2154    }
2155    case nir_op_frexp_exp: {
2156       if (instr->src[0].src.ssa->bit_size == 16) {
2157          Temp src = get_alu_src(ctx, instr->src[0]);
2158          Temp tmp = bld.vop1(aco_opcode::v_frexp_exp_i16_f16, bld.def(v1), src);
2159          tmp = bld.pseudo(aco_opcode::p_extract_vector, bld.def(v1b), tmp, Operand(0u));
2160          convert_int(ctx, bld, tmp, 8, 32, true, dst);
2161       } else if (instr->src[0].src.ssa->bit_size == 32) {
2162          emit_vop1_instruction(ctx, instr, aco_opcode::v_frexp_exp_i32_f32, dst);
2163       } else if (instr->src[0].src.ssa->bit_size == 64) {
2164          emit_vop1_instruction(ctx, instr, aco_opcode::v_frexp_exp_i32_f64, dst);
2165       } else {
2166          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2167       }
2168       break;
2169    }
2170    case nir_op_fsign: {
2171       Temp src = as_vgpr(ctx, get_alu_src(ctx, instr->src[0]));
2172       if (dst.regClass() == v2b) {
2173          assert(ctx->program->chip_class >= GFX9);
2174          /* replace negative zero with positive zero */
2175          src = bld.vop2(aco_opcode::v_add_f16, bld.def(v2b), Operand(0u), src);
2176          src = bld.vop3(aco_opcode::v_med3_i16, bld.def(v2b), Operand((uint16_t)-1), src, Operand((uint16_t)1u));
2177          bld.vop1(aco_opcode::v_cvt_f16_i16, Definition(dst), src);
2178       } else if (dst.regClass() == v1) {
2179          src = bld.vop2(aco_opcode::v_add_f32, bld.def(v1), Operand(0u), src);
2180          src = bld.vop3(aco_opcode::v_med3_i32, bld.def(v1), Operand((uint32_t)-1), src, Operand(1u));
2181          bld.vop1(aco_opcode::v_cvt_f32_i32, Definition(dst), src);
2182       } else if (dst.regClass() == v2) {
2183          Temp cond = bld.vopc(aco_opcode::v_cmp_nlt_f64, bld.hint_vcc(bld.def(bld.lm)), Operand(0u), src);
2184          Temp tmp = bld.copy(bld.def(v1), Operand(0x3FF00000u));
2185          Temp upper = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), tmp, emit_extract_vector(ctx, src, 1, v1), cond);
2186 
2187          cond = bld.vopc(aco_opcode::v_cmp_le_f64, bld.hint_vcc(bld.def(bld.lm)), Operand(0u), src);
2188          tmp = bld.copy(bld.def(v1), Operand(0xBFF00000u));
2189          upper = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), tmp, upper, cond);
2190 
2191          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), Operand(0u), upper);
2192       } else {
2193          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2194       }
2195       break;
2196    }
2197    case nir_op_f2f16:
2198    case nir_op_f2f16_rtne: {
2199       Temp src = get_alu_src(ctx, instr->src[0]);
2200       if (instr->src[0].src.ssa->bit_size == 64)
2201          src = bld.vop1(aco_opcode::v_cvt_f32_f64, bld.def(v1), src);
2202       if (instr->op == nir_op_f2f16_rtne && ctx->block->fp_mode.round16_64 != fp_round_ne)
2203          /* We emit s_round_mode/s_setreg_imm32 in lower_to_hw_instr to
2204           * keep value numbering and the scheduler simpler.
2205           */
2206          bld.vop1(aco_opcode::p_cvt_f16_f32_rtne, Definition(dst), src);
2207       else
2208          bld.vop1(aco_opcode::v_cvt_f16_f32, Definition(dst), src);
2209       break;
2210    }
2211    case nir_op_f2f16_rtz: {
2212       Temp src = get_alu_src(ctx, instr->src[0]);
2213       if (instr->src[0].src.ssa->bit_size == 64)
2214          src = bld.vop1(aco_opcode::v_cvt_f32_f64, bld.def(v1), src);
2215       if (ctx->block->fp_mode.round16_64 == fp_round_tz)
2216          bld.vop1(aco_opcode::v_cvt_f16_f32, Definition(dst), src);
2217       else if (ctx->program->chip_class == GFX8 || ctx->program->chip_class == GFX9)
2218          bld.vop3(aco_opcode::v_cvt_pkrtz_f16_f32_e64, Definition(dst), src, Operand(0u));
2219       else
2220          bld.vop2(aco_opcode::v_cvt_pkrtz_f16_f32, Definition(dst), src, as_vgpr(ctx, src));
2221       break;
2222    }
2223    case nir_op_f2f32: {
2224       if (instr->src[0].src.ssa->bit_size == 16) {
2225          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_f32_f16, dst);
2226       } else if (instr->src[0].src.ssa->bit_size == 64) {
2227          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_f32_f64, dst);
2228       } else {
2229          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2230       }
2231       break;
2232    }
2233    case nir_op_f2f64: {
2234       Temp src = get_alu_src(ctx, instr->src[0]);
2235       if (instr->src[0].src.ssa->bit_size == 16)
2236          src = bld.vop1(aco_opcode::v_cvt_f32_f16, bld.def(v1), src);
2237       bld.vop1(aco_opcode::v_cvt_f64_f32, Definition(dst), src);
2238       break;
2239    }
2240    case nir_op_i2f16: {
2241       assert(dst.regClass() == v2b);
2242       Temp src = get_alu_src(ctx, instr->src[0]);
2243       if (instr->src[0].src.ssa->bit_size == 8)
2244          src = convert_int(ctx, bld, src, 8, 16, true);
2245       else if (instr->src[0].src.ssa->bit_size == 64)
2246          src = convert_int(ctx, bld, src, 64, 32, false);
2247       bld.vop1(aco_opcode::v_cvt_f16_i16, Definition(dst), src);
2248       break;
2249    }
2250    case nir_op_i2f32: {
2251       assert(dst.size() == 1);
2252       Temp src = get_alu_src(ctx, instr->src[0]);
2253       if (instr->src[0].src.ssa->bit_size <= 16)
2254          src = convert_int(ctx, bld, src, instr->src[0].src.ssa->bit_size, 32, true);
2255       bld.vop1(aco_opcode::v_cvt_f32_i32, Definition(dst), src);
2256       break;
2257    }
2258    case nir_op_i2f64: {
2259       if (instr->src[0].src.ssa->bit_size <= 32) {
2260          Temp src = get_alu_src(ctx, instr->src[0]);
2261          if (instr->src[0].src.ssa->bit_size <= 16)
2262             src = convert_int(ctx, bld, src, instr->src[0].src.ssa->bit_size, 32, true);
2263          bld.vop1(aco_opcode::v_cvt_f64_i32, Definition(dst), src);
2264       } else if (instr->src[0].src.ssa->bit_size == 64) {
2265          Temp src = get_alu_src(ctx, instr->src[0]);
2266          RegClass rc = RegClass(src.type(), 1);
2267          Temp lower = bld.tmp(rc), upper = bld.tmp(rc);
2268          bld.pseudo(aco_opcode::p_split_vector, Definition(lower), Definition(upper), src);
2269          lower = bld.vop1(aco_opcode::v_cvt_f64_u32, bld.def(v2), lower);
2270          upper = bld.vop1(aco_opcode::v_cvt_f64_i32, bld.def(v2), upper);
2271          upper = bld.vop3(aco_opcode::v_ldexp_f64, bld.def(v2), upper, Operand(32u));
2272          bld.vop3(aco_opcode::v_add_f64, Definition(dst), lower, upper);
2273 
2274       } else {
2275          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2276       }
2277       break;
2278    }
2279    case nir_op_u2f16: {
2280       assert(dst.regClass() == v2b);
2281       Temp src = get_alu_src(ctx, instr->src[0]);
2282       if (instr->src[0].src.ssa->bit_size == 8)
2283          src = convert_int(ctx, bld, src, 8, 16, false);
2284       else if (instr->src[0].src.ssa->bit_size == 64)
2285          src = convert_int(ctx, bld, src, 64, 32, false);
2286       bld.vop1(aco_opcode::v_cvt_f16_u16, Definition(dst), src);
2287       break;
2288    }
2289    case nir_op_u2f32: {
2290       assert(dst.size() == 1);
2291       Temp src = get_alu_src(ctx, instr->src[0]);
2292       if (instr->src[0].src.ssa->bit_size == 8) {
2293          bld.vop1(aco_opcode::v_cvt_f32_ubyte0, Definition(dst), src);
2294       } else {
2295          if (instr->src[0].src.ssa->bit_size == 16)
2296             src = convert_int(ctx, bld, src, instr->src[0].src.ssa->bit_size, 32, true);
2297          bld.vop1(aco_opcode::v_cvt_f32_u32, Definition(dst), src);
2298       }
2299       break;
2300    }
2301    case nir_op_u2f64: {
2302       if (instr->src[0].src.ssa->bit_size <= 32) {
2303          Temp src = get_alu_src(ctx, instr->src[0]);
2304          if (instr->src[0].src.ssa->bit_size <= 16)
2305             src = convert_int(ctx, bld, src, instr->src[0].src.ssa->bit_size, 32, false);
2306          bld.vop1(aco_opcode::v_cvt_f64_u32, Definition(dst), src);
2307       } else if (instr->src[0].src.ssa->bit_size == 64) {
2308          Temp src = get_alu_src(ctx, instr->src[0]);
2309          RegClass rc = RegClass(src.type(), 1);
2310          Temp lower = bld.tmp(rc), upper = bld.tmp(rc);
2311          bld.pseudo(aco_opcode::p_split_vector, Definition(lower), Definition(upper), src);
2312          lower = bld.vop1(aco_opcode::v_cvt_f64_u32, bld.def(v2), lower);
2313          upper = bld.vop1(aco_opcode::v_cvt_f64_u32, bld.def(v2), upper);
2314          upper = bld.vop3(aco_opcode::v_ldexp_f64, bld.def(v2), upper, Operand(32u));
2315          bld.vop3(aco_opcode::v_add_f64, Definition(dst), lower, upper);
2316       } else {
2317          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2318       }
2319       break;
2320    }
2321    case nir_op_f2i8:
2322    case nir_op_f2i16: {
2323       if (instr->src[0].src.ssa->bit_size == 16)
2324          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_i16_f16, dst);
2325       else if (instr->src[0].src.ssa->bit_size == 32)
2326          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_i32_f32, dst);
2327       else
2328          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_i32_f64, dst);
2329       break;
2330    }
2331    case nir_op_f2u8:
2332    case nir_op_f2u16: {
2333       if (instr->src[0].src.ssa->bit_size == 16)
2334          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_u16_f16, dst);
2335       else if (instr->src[0].src.ssa->bit_size == 32)
2336          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_u32_f32, dst);
2337       else
2338          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_u32_f64, dst);
2339       break;
2340    }
2341    case nir_op_f2i32: {
2342       Temp src = get_alu_src(ctx, instr->src[0]);
2343       if (instr->src[0].src.ssa->bit_size == 16) {
2344          Temp tmp = bld.vop1(aco_opcode::v_cvt_f32_f16, bld.def(v1), src);
2345          if (dst.type() == RegType::vgpr) {
2346             bld.vop1(aco_opcode::v_cvt_i32_f32, Definition(dst), tmp);
2347          } else {
2348             bld.pseudo(aco_opcode::p_as_uniform, Definition(dst),
2349                        bld.vop1(aco_opcode::v_cvt_i32_f32, bld.def(v1), tmp));
2350          }
2351       } else if (instr->src[0].src.ssa->bit_size == 32) {
2352          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_i32_f32, dst);
2353       } else if (instr->src[0].src.ssa->bit_size == 64) {
2354          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_i32_f64, dst);
2355       } else {
2356          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2357       }
2358       break;
2359    }
2360    case nir_op_f2u32: {
2361       Temp src = get_alu_src(ctx, instr->src[0]);
2362       if (instr->src[0].src.ssa->bit_size == 16) {
2363          Temp tmp = bld.vop1(aco_opcode::v_cvt_f32_f16, bld.def(v1), src);
2364          if (dst.type() == RegType::vgpr) {
2365             bld.vop1(aco_opcode::v_cvt_u32_f32, Definition(dst), tmp);
2366          } else {
2367             bld.pseudo(aco_opcode::p_as_uniform, Definition(dst),
2368                        bld.vop1(aco_opcode::v_cvt_u32_f32, bld.def(v1), tmp));
2369          }
2370       } else if (instr->src[0].src.ssa->bit_size == 32) {
2371          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_u32_f32, dst);
2372       } else if (instr->src[0].src.ssa->bit_size == 64) {
2373          emit_vop1_instruction(ctx, instr, aco_opcode::v_cvt_u32_f64, dst);
2374       } else {
2375          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2376       }
2377       break;
2378    }
2379    case nir_op_f2i64: {
2380       Temp src = get_alu_src(ctx, instr->src[0]);
2381       if (instr->src[0].src.ssa->bit_size == 16)
2382          src = bld.vop1(aco_opcode::v_cvt_f32_f16, bld.def(v1), src);
2383 
2384       if (instr->src[0].src.ssa->bit_size <= 32 && dst.type() == RegType::vgpr) {
2385          Temp exponent = bld.vop1(aco_opcode::v_frexp_exp_i32_f32, bld.def(v1), src);
2386          exponent = bld.vop3(aco_opcode::v_med3_i32, bld.def(v1), Operand(0x0u), exponent, Operand(64u));
2387          Temp mantissa = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0x7fffffu), src);
2388          Temp sign = bld.vop2(aco_opcode::v_ashrrev_i32, bld.def(v1), Operand(31u), src);
2389          mantissa = bld.vop2(aco_opcode::v_or_b32, bld.def(v1), Operand(0x800000u), mantissa);
2390          mantissa = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(7u), mantissa);
2391          mantissa = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), Operand(0u), mantissa);
2392          Temp new_exponent = bld.tmp(v1);
2393          Temp borrow = bld.vsub32(Definition(new_exponent), Operand(63u), exponent, true).def(1).getTemp();
2394          if (ctx->program->chip_class >= GFX8)
2395             mantissa = bld.vop3(aco_opcode::v_lshrrev_b64, bld.def(v2), new_exponent, mantissa);
2396          else
2397             mantissa = bld.vop3(aco_opcode::v_lshr_b64, bld.def(v2), mantissa, new_exponent);
2398          Temp saturate = bld.vop1(aco_opcode::v_bfrev_b32, bld.def(v1), Operand(0xfffffffeu));
2399          Temp lower = bld.tmp(v1), upper = bld.tmp(v1);
2400          bld.pseudo(aco_opcode::p_split_vector, Definition(lower), Definition(upper), mantissa);
2401          lower = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), lower, Operand(0xffffffffu), borrow);
2402          upper = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), upper, saturate, borrow);
2403          lower = bld.vop2(aco_opcode::v_xor_b32, bld.def(v1), sign, lower);
2404          upper = bld.vop2(aco_opcode::v_xor_b32, bld.def(v1), sign, upper);
2405          Temp new_lower = bld.tmp(v1);
2406          borrow = bld.vsub32(Definition(new_lower), lower, sign, true).def(1).getTemp();
2407          Temp new_upper = bld.vsub32(bld.def(v1), upper, sign, false, borrow);
2408          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), new_lower, new_upper);
2409 
2410       } else if (instr->src[0].src.ssa->bit_size <= 32 && dst.type() == RegType::sgpr) {
2411          if (src.type() == RegType::vgpr)
2412             src = bld.as_uniform(src);
2413          Temp exponent = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc), src, Operand(0x80017u));
2414          exponent = bld.sop2(aco_opcode::s_sub_i32, bld.def(s1), bld.def(s1, scc), exponent, Operand(126u));
2415          exponent = bld.sop2(aco_opcode::s_max_i32, bld.def(s1), bld.def(s1, scc), Operand(0u), exponent);
2416          exponent = bld.sop2(aco_opcode::s_min_i32, bld.def(s1), bld.def(s1, scc), Operand(64u), exponent);
2417          Temp mantissa = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), Operand(0x7fffffu), src);
2418          Temp sign = bld.sop2(aco_opcode::s_ashr_i32, bld.def(s1), bld.def(s1, scc), src, Operand(31u));
2419          mantissa = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), Operand(0x800000u), mantissa);
2420          mantissa = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), mantissa, Operand(7u));
2421          mantissa = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), Operand(0u), mantissa);
2422          exponent = bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.def(s1, scc), Operand(63u), exponent);
2423          mantissa = bld.sop2(aco_opcode::s_lshr_b64, bld.def(s2), bld.def(s1, scc), mantissa, exponent);
2424          Temp cond = bld.sopc(aco_opcode::s_cmp_eq_u32, bld.def(s1, scc), exponent, Operand(0xffffffffu)); // exp >= 64
2425          Temp saturate = bld.sop1(aco_opcode::s_brev_b64, bld.def(s2), Operand(0xfffffffeu));
2426          mantissa = bld.sop2(aco_opcode::s_cselect_b64, bld.def(s2), saturate, mantissa, cond);
2427          Temp lower = bld.tmp(s1), upper = bld.tmp(s1);
2428          bld.pseudo(aco_opcode::p_split_vector, Definition(lower), Definition(upper), mantissa);
2429          lower = bld.sop2(aco_opcode::s_xor_b32, bld.def(s1), bld.def(s1, scc), sign, lower);
2430          upper = bld.sop2(aco_opcode::s_xor_b32, bld.def(s1), bld.def(s1, scc), sign, upper);
2431          Temp borrow = bld.tmp(s1);
2432          lower = bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.scc(Definition(borrow)), lower, sign);
2433          upper = bld.sop2(aco_opcode::s_subb_u32, bld.def(s1), bld.def(s1, scc), upper, sign, borrow);
2434          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
2435 
2436       } else if (instr->src[0].src.ssa->bit_size == 64) {
2437          Temp vec = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), Operand(0u), Operand(0x3df00000u));
2438          Temp trunc = emit_trunc_f64(ctx, bld, bld.def(v2), src);
2439          Temp mul = bld.vop3(aco_opcode::v_mul_f64, bld.def(v2), trunc, vec);
2440          vec = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), Operand(0u), Operand(0xc1f00000u));
2441          Temp floor = emit_floor_f64(ctx, bld, bld.def(v2), mul);
2442          Temp fma = bld.vop3(aco_opcode::v_fma_f64, bld.def(v2), floor, vec, trunc);
2443          Temp lower = bld.vop1(aco_opcode::v_cvt_u32_f64, bld.def(v1), fma);
2444          Temp upper = bld.vop1(aco_opcode::v_cvt_i32_f64, bld.def(v1), floor);
2445          if (dst.type() == RegType::sgpr) {
2446             lower = bld.as_uniform(lower);
2447             upper = bld.as_uniform(upper);
2448          }
2449          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
2450 
2451       } else {
2452          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2453       }
2454       break;
2455    }
2456    case nir_op_f2u64: {
2457       Temp src = get_alu_src(ctx, instr->src[0]);
2458       if (instr->src[0].src.ssa->bit_size == 16)
2459          src = bld.vop1(aco_opcode::v_cvt_f32_f16, bld.def(v1), src);
2460 
2461       if (instr->src[0].src.ssa->bit_size <= 32 && dst.type() == RegType::vgpr) {
2462          Temp exponent = bld.vop1(aco_opcode::v_frexp_exp_i32_f32, bld.def(v1), src);
2463          Temp exponent_in_range = bld.vopc(aco_opcode::v_cmp_ge_i32, bld.hint_vcc(bld.def(bld.lm)), Operand(64u), exponent);
2464          exponent = bld.vop2(aco_opcode::v_max_i32, bld.def(v1), Operand(0x0u), exponent);
2465          Temp mantissa = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0x7fffffu), src);
2466          mantissa = bld.vop2(aco_opcode::v_or_b32, bld.def(v1), Operand(0x800000u), mantissa);
2467          Temp exponent_small = bld.vsub32(bld.def(v1), Operand(24u), exponent);
2468          Temp small = bld.vop2(aco_opcode::v_lshrrev_b32, bld.def(v1), exponent_small, mantissa);
2469          mantissa = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), Operand(0u), mantissa);
2470          Temp new_exponent = bld.tmp(v1);
2471          Temp cond_small = bld.vsub32(Definition(new_exponent), exponent, Operand(24u), true).def(1).getTemp();
2472          if (ctx->program->chip_class >= GFX8)
2473             mantissa = bld.vop3(aco_opcode::v_lshlrev_b64, bld.def(v2), new_exponent, mantissa);
2474          else
2475             mantissa = bld.vop3(aco_opcode::v_lshl_b64, bld.def(v2), mantissa, new_exponent);
2476          Temp lower = bld.tmp(v1), upper = bld.tmp(v1);
2477          bld.pseudo(aco_opcode::p_split_vector, Definition(lower), Definition(upper), mantissa);
2478          lower = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), lower, small, cond_small);
2479          upper = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), upper, Operand(0u), cond_small);
2480          lower = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0xffffffffu), lower, exponent_in_range);
2481          upper = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0xffffffffu), upper, exponent_in_range);
2482          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
2483 
2484       } else if (instr->src[0].src.ssa->bit_size <= 32 && dst.type() == RegType::sgpr) {
2485          if (src.type() == RegType::vgpr)
2486             src = bld.as_uniform(src);
2487          Temp exponent = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc), src, Operand(0x80017u));
2488          exponent = bld.sop2(aco_opcode::s_sub_i32, bld.def(s1), bld.def(s1, scc), exponent, Operand(126u));
2489          exponent = bld.sop2(aco_opcode::s_max_i32, bld.def(s1), bld.def(s1, scc), Operand(0u), exponent);
2490          Temp mantissa = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), Operand(0x7fffffu), src);
2491          mantissa = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), Operand(0x800000u), mantissa);
2492          Temp exponent_small = bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.def(s1, scc), Operand(24u), exponent);
2493          Temp small = bld.sop2(aco_opcode::s_lshr_b32, bld.def(s1), bld.def(s1, scc), mantissa, exponent_small);
2494          mantissa = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), Operand(0u), mantissa);
2495          Temp exponent_large = bld.sop2(aco_opcode::s_sub_u32, bld.def(s1), bld.def(s1, scc), exponent, Operand(24u));
2496          mantissa = bld.sop2(aco_opcode::s_lshl_b64, bld.def(s2), bld.def(s1, scc), mantissa, exponent_large);
2497          Temp cond = bld.sopc(aco_opcode::s_cmp_ge_i32, bld.def(s1, scc), Operand(64u), exponent);
2498          mantissa = bld.sop2(aco_opcode::s_cselect_b64, bld.def(s2), mantissa, Operand(0xffffffffu), cond);
2499          Temp lower = bld.tmp(s1), upper = bld.tmp(s1);
2500          bld.pseudo(aco_opcode::p_split_vector, Definition(lower), Definition(upper), mantissa);
2501          Temp cond_small = bld.sopc(aco_opcode::s_cmp_le_i32, bld.def(s1, scc), exponent, Operand(24u));
2502          lower = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1), small, lower, cond_small);
2503          upper = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1), Operand(0u), upper, cond_small);
2504          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
2505 
2506       } else if (instr->src[0].src.ssa->bit_size == 64) {
2507          Temp vec = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), Operand(0u), Operand(0x3df00000u));
2508          Temp trunc = emit_trunc_f64(ctx, bld, bld.def(v2), src);
2509          Temp mul = bld.vop3(aco_opcode::v_mul_f64, bld.def(v2), trunc, vec);
2510          vec = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), Operand(0u), Operand(0xc1f00000u));
2511          Temp floor = emit_floor_f64(ctx, bld, bld.def(v2), mul);
2512          Temp fma = bld.vop3(aco_opcode::v_fma_f64, bld.def(v2), floor, vec, trunc);
2513          Temp lower = bld.vop1(aco_opcode::v_cvt_u32_f64, bld.def(v1), fma);
2514          Temp upper = bld.vop1(aco_opcode::v_cvt_u32_f64, bld.def(v1), floor);
2515          if (dst.type() == RegType::sgpr) {
2516             lower = bld.as_uniform(lower);
2517             upper = bld.as_uniform(upper);
2518          }
2519          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lower, upper);
2520 
2521       } else {
2522          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2523       }
2524       break;
2525    }
2526    case nir_op_b2f16: {
2527       Temp src = get_alu_src(ctx, instr->src[0]);
2528       assert(src.regClass() == bld.lm);
2529 
2530       if (dst.regClass() == s1) {
2531          src = bool_to_scalar_condition(ctx, src);
2532          bld.sop2(aco_opcode::s_mul_i32, Definition(dst), Operand(0x3c00u), src);
2533       } else if (dst.regClass() == v2b) {
2534          Temp one = bld.copy(bld.def(v1), Operand(0x3c00u));
2535          bld.vop2(aco_opcode::v_cndmask_b32, Definition(dst), Operand(0u), one, src);
2536       } else {
2537          unreachable("Wrong destination register class for nir_op_b2f16.");
2538       }
2539       break;
2540    }
2541    case nir_op_b2f32: {
2542       Temp src = get_alu_src(ctx, instr->src[0]);
2543       assert(src.regClass() == bld.lm);
2544 
2545       if (dst.regClass() == s1) {
2546          src = bool_to_scalar_condition(ctx, src);
2547          bld.sop2(aco_opcode::s_mul_i32, Definition(dst), Operand(0x3f800000u), src);
2548       } else if (dst.regClass() == v1) {
2549          bld.vop2_e64(aco_opcode::v_cndmask_b32, Definition(dst), Operand(0u), Operand(0x3f800000u), src);
2550       } else {
2551          unreachable("Wrong destination register class for nir_op_b2f32.");
2552       }
2553       break;
2554    }
2555    case nir_op_b2f64: {
2556       Temp src = get_alu_src(ctx, instr->src[0]);
2557       assert(src.regClass() == bld.lm);
2558 
2559       if (dst.regClass() == s2) {
2560          src = bool_to_scalar_condition(ctx, src);
2561          bld.sop2(aco_opcode::s_cselect_b64, Definition(dst), Operand(0x3f800000u), Operand(0u), bld.scc(src));
2562       } else if (dst.regClass() == v2) {
2563          Temp one = bld.copy(bld.def(v2), Operand(0x3FF00000u));
2564          Temp upper = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0u), one, src);
2565          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), Operand(0u), upper);
2566       } else {
2567          unreachable("Wrong destination register class for nir_op_b2f64.");
2568       }
2569       break;
2570    }
2571    case nir_op_i2i8:
2572    case nir_op_i2i16:
2573    case nir_op_i2i32:
2574    case nir_op_i2i64: {
2575       if (dst.type() == RegType::sgpr && instr->src[0].src.ssa->bit_size < 32) {
2576          /* no need to do the extract in get_alu_src() */
2577          sgpr_extract_mode mode = instr->dest.dest.ssa.bit_size > instr->src[0].src.ssa->bit_size ?
2578                                   sgpr_extract_sext : sgpr_extract_undef;
2579          extract_8_16_bit_sgpr_element(ctx, dst, &instr->src[0], mode);
2580       } else {
2581          convert_int(ctx, bld, get_alu_src(ctx, instr->src[0]),
2582                      instr->src[0].src.ssa->bit_size, instr->dest.dest.ssa.bit_size, true, dst);
2583       }
2584       break;
2585    }
2586    case nir_op_u2u8:
2587    case nir_op_u2u16:
2588    case nir_op_u2u32:
2589    case nir_op_u2u64: {
2590       if (dst.type() == RegType::sgpr && instr->src[0].src.ssa->bit_size < 32) {
2591          /* no need to do the extract in get_alu_src() */
2592          sgpr_extract_mode mode = instr->dest.dest.ssa.bit_size > instr->src[0].src.ssa->bit_size ?
2593                                   sgpr_extract_zext : sgpr_extract_undef;
2594          extract_8_16_bit_sgpr_element(ctx, dst, &instr->src[0], mode);
2595       } else {
2596          convert_int(ctx, bld, get_alu_src(ctx, instr->src[0]),
2597                      instr->src[0].src.ssa->bit_size, instr->dest.dest.ssa.bit_size, false, dst);
2598       }
2599       break;
2600    }
2601    case nir_op_b2b32:
2602    case nir_op_b2i8:
2603    case nir_op_b2i16:
2604    case nir_op_b2i32:
2605    case nir_op_b2i64: {
2606       Temp src = get_alu_src(ctx, instr->src[0]);
2607       assert(src.regClass() == bld.lm);
2608 
2609       Temp tmp = dst.bytes() == 8 ? bld.tmp(RegClass::get(dst.type(), 4)) : dst;
2610       if (tmp.regClass() == s1) {
2611          // TODO: in a post-RA optimization, we can check if src is in VCC, and directly use VCCNZ
2612          bool_to_scalar_condition(ctx, src, tmp);
2613       } else if (tmp.type() == RegType::vgpr) {
2614          bld.vop2_e64(aco_opcode::v_cndmask_b32, Definition(tmp), Operand(0u), Operand(1u), src);
2615       } else {
2616          unreachable("Invalid register class for b2i32");
2617       }
2618 
2619       if (tmp != dst)
2620          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), tmp, Operand(0u));
2621       break;
2622    }
2623    case nir_op_b2b1:
2624    case nir_op_i2b1: {
2625       Temp src = get_alu_src(ctx, instr->src[0]);
2626       assert(dst.regClass() == bld.lm);
2627 
2628       if (src.type() == RegType::vgpr) {
2629          assert(src.regClass() == v1 || src.regClass() == v2);
2630          assert(dst.regClass() == bld.lm);
2631          bld.vopc(src.size() == 2 ? aco_opcode::v_cmp_lg_u64 : aco_opcode::v_cmp_lg_u32,
2632                   Definition(dst), Operand(0u), src).def(0).setHint(vcc);
2633       } else {
2634          assert(src.regClass() == s1 || src.regClass() == s2);
2635          Temp tmp;
2636          if (src.regClass() == s2 && ctx->program->chip_class <= GFX7) {
2637             tmp = bld.sop2(aco_opcode::s_or_b64, bld.def(s2), bld.def(s1, scc), Operand(0u), src).def(1).getTemp();
2638          } else {
2639             tmp = bld.sopc(src.size() == 2 ? aco_opcode::s_cmp_lg_u64 : aco_opcode::s_cmp_lg_u32,
2640                            bld.scc(bld.def(s1)), Operand(0u), src);
2641          }
2642          bool_to_vector_condition(ctx, tmp, dst);
2643       }
2644       break;
2645    }
2646    case nir_op_unpack_64_2x32:
2647    case nir_op_unpack_32_2x16:
2648    case nir_op_unpack_64_4x16:
2649       bld.copy(Definition(dst), get_alu_src(ctx, instr->src[0]));
2650       emit_split_vector(ctx, dst, instr->op == nir_op_unpack_64_4x16 ? 4 : 2);
2651       break;
2652    case nir_op_pack_64_2x32_split: {
2653       Temp src0 = get_alu_src(ctx, instr->src[0]);
2654       Temp src1 = get_alu_src(ctx, instr->src[1]);
2655 
2656       bld.pseudo(aco_opcode::p_create_vector, Definition(dst), src0, src1);
2657       break;
2658    }
2659    case nir_op_unpack_64_2x32_split_x:
2660       bld.pseudo(aco_opcode::p_split_vector, Definition(dst), bld.def(dst.regClass()), get_alu_src(ctx, instr->src[0]));
2661       break;
2662    case nir_op_unpack_64_2x32_split_y:
2663       bld.pseudo(aco_opcode::p_split_vector, bld.def(dst.regClass()), Definition(dst), get_alu_src(ctx, instr->src[0]));
2664       break;
2665    case nir_op_unpack_32_2x16_split_x:
2666       if (dst.type() == RegType::vgpr) {
2667          bld.pseudo(aco_opcode::p_split_vector, Definition(dst), bld.def(dst.regClass()), get_alu_src(ctx, instr->src[0]));
2668       } else {
2669          bld.copy(Definition(dst), get_alu_src(ctx, instr->src[0]));
2670       }
2671       break;
2672    case nir_op_unpack_32_2x16_split_y:
2673       if (dst.type() == RegType::vgpr) {
2674          bld.pseudo(aco_opcode::p_split_vector, bld.def(dst.regClass()), Definition(dst), get_alu_src(ctx, instr->src[0]));
2675       } else {
2676          bld.sop2(aco_opcode::s_bfe_u32, Definition(dst), bld.def(s1, scc), get_alu_src(ctx, instr->src[0]), Operand(uint32_t(16 << 16 | 16)));
2677       }
2678       break;
2679    case nir_op_pack_32_2x16_split: {
2680       Temp src0 = get_alu_src(ctx, instr->src[0]);
2681       Temp src1 = get_alu_src(ctx, instr->src[1]);
2682       if (dst.regClass() == v1) {
2683          src0 = emit_extract_vector(ctx, src0, 0, v2b);
2684          src1 = emit_extract_vector(ctx, src1, 0, v2b);
2685          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), src0, src1);
2686       } else {
2687          src0 = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), src0, Operand(0xFFFFu));
2688          src1 = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), src1, Operand(16u));
2689          bld.sop2(aco_opcode::s_or_b32, Definition(dst), bld.def(s1, scc), src0, src1);
2690       }
2691       break;
2692    }
2693    case nir_op_pack_half_2x16_split: {
2694       if (dst.regClass() == v1) {
2695          nir_const_value* val = nir_src_as_const_value(instr->src[1].src);
2696          if (val && val->u32 == 0 && ctx->program->chip_class <= GFX9) {
2697             /* upper bits zero on GFX6-GFX9 */
2698             bld.vop1(aco_opcode::v_cvt_f16_f32, Definition(dst), get_alu_src(ctx, instr->src[0]));
2699          } else if (!ctx->block->fp_mode.care_about_round16_64 || ctx->block->fp_mode.round16_64 == fp_round_tz) {
2700             if (ctx->program->chip_class == GFX8 || ctx->program->chip_class == GFX9)
2701                emit_vop3a_instruction(ctx, instr, aco_opcode::v_cvt_pkrtz_f16_f32_e64, dst);
2702             else
2703                emit_vop2_instruction(ctx, instr, aco_opcode::v_cvt_pkrtz_f16_f32, dst, false);
2704          } else {
2705             Temp src0 = bld.vop1(aco_opcode::v_cvt_f16_f32, bld.def(v2b), get_alu_src(ctx, instr->src[0]));
2706             Temp src1 = bld.vop1(aco_opcode::v_cvt_f16_f32, bld.def(v2b), get_alu_src(ctx, instr->src[1]));
2707             bld.pseudo(aco_opcode::p_create_vector, Definition(dst), src0, src1);
2708          }
2709       } else {
2710          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2711       }
2712       break;
2713    }
2714    case nir_op_unpack_half_2x16_split_x_flush_to_zero:
2715    case nir_op_unpack_half_2x16_split_x: {
2716       Temp src = get_alu_src(ctx, instr->src[0]);
2717       if (src.regClass() == v1)
2718          src = bld.pseudo(aco_opcode::p_split_vector, bld.def(v2b), bld.def(v2b), src);
2719       if (dst.regClass() == v1) {
2720          assert(ctx->block->fp_mode.must_flush_denorms16_64 == (instr->op == nir_op_unpack_half_2x16_split_x_flush_to_zero));
2721          bld.vop1(aco_opcode::v_cvt_f32_f16, Definition(dst), src);
2722       } else {
2723          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2724       }
2725       break;
2726    }
2727    case nir_op_unpack_half_2x16_split_y_flush_to_zero:
2728    case nir_op_unpack_half_2x16_split_y: {
2729       Temp src = get_alu_src(ctx, instr->src[0]);
2730       if (src.regClass() == s1)
2731          src = bld.sop2(aco_opcode::s_lshr_b32, bld.def(s1), bld.def(s1, scc), src, Operand(16u));
2732       else
2733          src = bld.pseudo(aco_opcode::p_split_vector, bld.def(v2b), bld.def(v2b), src).def(1).getTemp();
2734       if (dst.regClass() == v1) {
2735          assert(ctx->block->fp_mode.must_flush_denorms16_64 == (instr->op == nir_op_unpack_half_2x16_split_y_flush_to_zero));
2736          bld.vop1(aco_opcode::v_cvt_f32_f16, Definition(dst), src);
2737       } else {
2738          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2739       }
2740       break;
2741    }
2742    case nir_op_fquantize2f16: {
2743       Temp src = get_alu_src(ctx, instr->src[0]);
2744       Temp f16 = bld.vop1(aco_opcode::v_cvt_f16_f32, bld.def(v1), src);
2745       Temp f32, cmp_res;
2746 
2747       if (ctx->program->chip_class >= GFX8) {
2748          Temp mask = bld.copy(bld.def(s1), Operand(0x36Fu)); /* value is NOT negative/positive denormal value */
2749          cmp_res = bld.vopc_e64(aco_opcode::v_cmp_class_f16, bld.hint_vcc(bld.def(bld.lm)), f16, mask);
2750          f32 = bld.vop1(aco_opcode::v_cvt_f32_f16, bld.def(v1), f16);
2751       } else {
2752          /* 0x38800000 is smallest half float value (2^-14) in 32-bit float,
2753           * so compare the result and flush to 0 if it's smaller.
2754           */
2755          f32 = bld.vop1(aco_opcode::v_cvt_f32_f16, bld.def(v1), f16);
2756          Temp smallest = bld.copy(bld.def(s1), Operand(0x38800000u));
2757          Instruction* vop3 = bld.vopc_e64(aco_opcode::v_cmp_nlt_f32, bld.hint_vcc(bld.def(bld.lm)), f32, smallest);
2758          static_cast<VOP3A_instruction*>(vop3)->abs[0] = true;
2759          cmp_res = vop3->definitions[0].getTemp();
2760       }
2761 
2762       if (ctx->block->fp_mode.preserve_signed_zero_inf_nan32 || ctx->program->chip_class < GFX8) {
2763          Temp copysign_0 = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), Operand(0u), as_vgpr(ctx, src));
2764          bld.vop2(aco_opcode::v_cndmask_b32, Definition(dst), copysign_0, f32, cmp_res);
2765       } else {
2766          bld.vop2(aco_opcode::v_cndmask_b32, Definition(dst), Operand(0u), f32, cmp_res);
2767       }
2768       break;
2769    }
2770    case nir_op_bfm: {
2771       Temp bits = get_alu_src(ctx, instr->src[0]);
2772       Temp offset = get_alu_src(ctx, instr->src[1]);
2773 
2774       if (dst.regClass() == s1) {
2775          bld.sop2(aco_opcode::s_bfm_b32, Definition(dst), bits, offset);
2776       } else if (dst.regClass() == v1) {
2777          bld.vop3(aco_opcode::v_bfm_b32, Definition(dst), bits, offset);
2778       } else {
2779          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2780       }
2781       break;
2782    }
2783    case nir_op_bitfield_select: {
2784 
2785       /* dst = (insert & bitmask) | (base & ~bitmask) */
2786       if (dst.regClass() == s1) {
2787          Temp bitmask = get_alu_src(ctx, instr->src[0]);
2788          Temp insert = get_alu_src(ctx, instr->src[1]);
2789          Temp base = get_alu_src(ctx, instr->src[2]);
2790          aco_ptr<Instruction> sop2;
2791          nir_const_value* const_bitmask = nir_src_as_const_value(instr->src[0].src);
2792          nir_const_value* const_insert = nir_src_as_const_value(instr->src[1].src);
2793          Operand lhs;
2794          if (const_insert && const_bitmask) {
2795             lhs = Operand(const_insert->u32 & const_bitmask->u32);
2796          } else {
2797             insert = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), insert, bitmask);
2798             lhs = Operand(insert);
2799          }
2800 
2801          Operand rhs;
2802          nir_const_value* const_base = nir_src_as_const_value(instr->src[2].src);
2803          if (const_base && const_bitmask) {
2804             rhs = Operand(const_base->u32 & ~const_bitmask->u32);
2805          } else {
2806             base = bld.sop2(aco_opcode::s_andn2_b32, bld.def(s1), bld.def(s1, scc), base, bitmask);
2807             rhs = Operand(base);
2808          }
2809 
2810          bld.sop2(aco_opcode::s_or_b32, Definition(dst), bld.def(s1, scc), rhs, lhs);
2811 
2812       } else if (dst.regClass() == v1) {
2813          emit_vop3a_instruction(ctx, instr, aco_opcode::v_bfi_b32, dst, false, 3);
2814       } else {
2815          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2816       }
2817       break;
2818    }
2819    case nir_op_ubfe:
2820    case nir_op_ibfe: {
2821       if (dst.bytes() != 4)
2822          unreachable("Unsupported BFE bit size");
2823 
2824       if (dst.type() == RegType::sgpr) {
2825          Temp base = get_alu_src(ctx, instr->src[0]);
2826 
2827          nir_const_value* const_offset = nir_src_as_const_value(instr->src[1].src);
2828          nir_const_value* const_bits = nir_src_as_const_value(instr->src[2].src);
2829          if (const_offset && const_bits) {
2830             uint32_t extract = (const_bits->u32 << 16) | (const_offset->u32 & 0x1f);
2831             aco_opcode opcode = instr->op == nir_op_ubfe ? aco_opcode::s_bfe_u32 : aco_opcode::s_bfe_i32;
2832             bld.sop2(opcode, Definition(dst), bld.def(s1, scc), base, Operand(extract));
2833             break;
2834          }
2835 
2836          Temp offset = get_alu_src(ctx, instr->src[1]);
2837          Temp bits = get_alu_src(ctx, instr->src[2]);
2838          if (instr->op == nir_op_ubfe) {
2839             Temp mask = bld.sop2(aco_opcode::s_bfm_b32, bld.def(s1), bits, offset);
2840             Temp masked = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), base, mask);
2841             bld.sop2(aco_opcode::s_lshr_b32, Definition(dst), bld.def(s1, scc), masked, offset);
2842          } else {
2843             Operand bits_op = const_bits ? Operand(const_bits->u32 << 16) :
2844                               bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), bits, Operand(16u));
2845             Operand offset_op = const_offset ? Operand(const_offset->u32 & 0x1fu) :
2846                                 bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), offset, Operand(0x1fu));
2847 
2848             Temp extract = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), bits_op, offset_op);
2849             bld.sop2(aco_opcode::s_bfe_i32, Definition(dst), bld.def(s1, scc), base, extract);
2850          }
2851 
2852       } else {
2853          aco_opcode opcode = instr->op == nir_op_ubfe ? aco_opcode::v_bfe_u32 : aco_opcode::v_bfe_i32;
2854          emit_vop3a_instruction(ctx, instr, opcode, dst, false, 3);
2855       }
2856       break;
2857    }
2858    case nir_op_bit_count: {
2859       Temp src = get_alu_src(ctx, instr->src[0]);
2860       if (src.regClass() == s1) {
2861          bld.sop1(aco_opcode::s_bcnt1_i32_b32, Definition(dst), bld.def(s1, scc), src);
2862       } else if (src.regClass() == v1) {
2863          bld.vop3(aco_opcode::v_bcnt_u32_b32, Definition(dst), src, Operand(0u));
2864       } else if (src.regClass() == v2) {
2865          bld.vop3(aco_opcode::v_bcnt_u32_b32, Definition(dst),
2866                   emit_extract_vector(ctx, src, 1, v1),
2867                   bld.vop3(aco_opcode::v_bcnt_u32_b32, bld.def(v1),
2868                            emit_extract_vector(ctx, src, 0, v1), Operand(0u)));
2869       } else if (src.regClass() == s2) {
2870          bld.sop1(aco_opcode::s_bcnt1_i32_b64, Definition(dst), bld.def(s1, scc), src);
2871       } else {
2872          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
2873       }
2874       break;
2875    }
2876    case nir_op_flt: {
2877       emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_lt_f16, aco_opcode::v_cmp_lt_f32, aco_opcode::v_cmp_lt_f64);
2878       break;
2879    }
2880    case nir_op_fge: {
2881       emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_ge_f16, aco_opcode::v_cmp_ge_f32, aco_opcode::v_cmp_ge_f64);
2882       break;
2883    }
2884    case nir_op_feq: {
2885       emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_eq_f16, aco_opcode::v_cmp_eq_f32, aco_opcode::v_cmp_eq_f64);
2886       break;
2887    }
2888    case nir_op_fneu: {
2889       emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_neq_f16, aco_opcode::v_cmp_neq_f32, aco_opcode::v_cmp_neq_f64);
2890       break;
2891    }
2892    case nir_op_ilt: {
2893       emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_lt_i16, aco_opcode::v_cmp_lt_i32, aco_opcode::v_cmp_lt_i64, aco_opcode::s_cmp_lt_i32);
2894       break;
2895    }
2896    case nir_op_ige: {
2897       emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_ge_i16, aco_opcode::v_cmp_ge_i32, aco_opcode::v_cmp_ge_i64, aco_opcode::s_cmp_ge_i32);
2898       break;
2899    }
2900    case nir_op_ieq: {
2901       if (instr->src[0].src.ssa->bit_size == 1)
2902          emit_boolean_logic(ctx, instr, Builder::s_xnor, dst);
2903       else
2904          emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_eq_i16, aco_opcode::v_cmp_eq_i32, aco_opcode::v_cmp_eq_i64, aco_opcode::s_cmp_eq_i32,
2905                          ctx->program->chip_class >= GFX8 ? aco_opcode::s_cmp_eq_u64 : aco_opcode::num_opcodes);
2906       break;
2907    }
2908    case nir_op_ine: {
2909       if (instr->src[0].src.ssa->bit_size == 1)
2910          emit_boolean_logic(ctx, instr, Builder::s_xor, dst);
2911       else
2912          emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_lg_i16, aco_opcode::v_cmp_lg_i32, aco_opcode::v_cmp_lg_i64, aco_opcode::s_cmp_lg_i32,
2913                          ctx->program->chip_class >= GFX8 ? aco_opcode::s_cmp_lg_u64 : aco_opcode::num_opcodes);
2914       break;
2915    }
2916    case nir_op_ult: {
2917       emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_lt_u16, aco_opcode::v_cmp_lt_u32, aco_opcode::v_cmp_lt_u64, aco_opcode::s_cmp_lt_u32);
2918       break;
2919    }
2920    case nir_op_uge: {
2921       emit_comparison(ctx, instr, dst, aco_opcode::v_cmp_ge_u16, aco_opcode::v_cmp_ge_u32, aco_opcode::v_cmp_ge_u64, aco_opcode::s_cmp_ge_u32);
2922       break;
2923    }
2924    case nir_op_fddx:
2925    case nir_op_fddy:
2926    case nir_op_fddx_fine:
2927    case nir_op_fddy_fine:
2928    case nir_op_fddx_coarse:
2929    case nir_op_fddy_coarse: {
2930       Temp src = get_alu_src(ctx, instr->src[0]);
2931       uint16_t dpp_ctrl1, dpp_ctrl2;
2932       if (instr->op == nir_op_fddx_fine) {
2933          dpp_ctrl1 = dpp_quad_perm(0, 0, 2, 2);
2934          dpp_ctrl2 = dpp_quad_perm(1, 1, 3, 3);
2935       } else if (instr->op == nir_op_fddy_fine) {
2936          dpp_ctrl1 = dpp_quad_perm(0, 1, 0, 1);
2937          dpp_ctrl2 = dpp_quad_perm(2, 3, 2, 3);
2938       } else {
2939          dpp_ctrl1 = dpp_quad_perm(0, 0, 0, 0);
2940          if (instr->op == nir_op_fddx || instr->op == nir_op_fddx_coarse)
2941             dpp_ctrl2 = dpp_quad_perm(1, 1, 1, 1);
2942          else
2943             dpp_ctrl2 = dpp_quad_perm(2, 2, 2, 2);
2944       }
2945 
2946       Temp tmp;
2947       if (ctx->program->chip_class >= GFX8) {
2948          Temp tl = bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl1);
2949          tmp = bld.vop2_dpp(aco_opcode::v_sub_f32, bld.def(v1), src, tl, dpp_ctrl2);
2950       } else {
2951          Temp tl = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, (1 << 15) | dpp_ctrl1);
2952          Temp tr = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, (1 << 15) | dpp_ctrl2);
2953          tmp = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1), tr, tl);
2954       }
2955       emit_wqm(ctx, tmp, dst, true);
2956       break;
2957    }
2958    default:
2959       isel_err(&instr->instr, "Unknown NIR ALU instr");
2960    }
2961 }
2962 
visit_load_const(isel_context * ctx,nir_load_const_instr * instr)2963 void visit_load_const(isel_context *ctx, nir_load_const_instr *instr)
2964 {
2965    Temp dst = get_ssa_temp(ctx, &instr->def);
2966 
2967    // TODO: we really want to have the resulting type as this would allow for 64bit literals
2968    // which get truncated the lsb if double and msb if int
2969    // for now, we only use s_mov_b64 with 64bit inline constants
2970    assert(instr->def.num_components == 1 && "Vector load_const should be lowered to scalar.");
2971    assert(dst.type() == RegType::sgpr);
2972 
2973    Builder bld(ctx->program, ctx->block);
2974 
2975    if (instr->def.bit_size == 1) {
2976       assert(dst.regClass() == bld.lm);
2977       int val = instr->value[0].b ? -1 : 0;
2978       Operand op = bld.lm.size() == 1 ? Operand((uint32_t) val) : Operand((uint64_t) val);
2979       bld.copy(Definition(dst), op);
2980    } else if (instr->def.bit_size == 8) {
2981       bld.copy(Definition(dst), Operand((uint32_t)instr->value[0].u8));
2982    } else if (instr->def.bit_size == 16) {
2983       /* sign-extend to use s_movk_i32 instead of a literal */
2984       bld.copy(Definition(dst), Operand((uint32_t)instr->value[0].i16));
2985    } else if (dst.size() == 1) {
2986       bld.copy(Definition(dst), Operand(instr->value[0].u32));
2987    } else {
2988       assert(dst.size() != 1);
2989       aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, dst.size(), 1)};
2990       if (instr->def.bit_size == 64)
2991          for (unsigned i = 0; i < dst.size(); i++)
2992             vec->operands[i] = Operand{(uint32_t)(instr->value[0].u64 >> i * 32)};
2993       else {
2994          for (unsigned i = 0; i < dst.size(); i++)
2995             vec->operands[i] = Operand{instr->value[i].u32};
2996       }
2997       vec->definitions[0] = Definition(dst);
2998       ctx->block->instructions.emplace_back(std::move(vec));
2999    }
3000 }
3001 
widen_mask(uint32_t mask,unsigned multiplier)3002 uint32_t widen_mask(uint32_t mask, unsigned multiplier)
3003 {
3004    uint32_t new_mask = 0;
3005    for(unsigned i = 0; i < 32 && (1u << i) <= mask; ++i)
3006       if (mask & (1u << i))
3007          new_mask |= ((1u << multiplier) - 1u) << (i * multiplier);
3008    return new_mask;
3009 }
3010 
3011 struct LoadEmitInfo {
3012    Operand offset;
3013    Temp dst;
3014    unsigned num_components;
3015    unsigned component_size;
3016    Temp resource = Temp(0, s1);
3017    unsigned component_stride = 0;
3018    unsigned const_offset = 0;
3019    unsigned align_mul = 0;
3020    unsigned align_offset = 0;
3021 
3022    bool glc = false;
3023    bool slc = false;
3024    unsigned swizzle_component_size = 0;
3025    memory_sync_info sync;
3026    Temp soffset = Temp(0, s1);
3027 };
3028 
3029 struct EmitLoadParameters {
3030    using Callback = Temp (*)(Builder &bld, const LoadEmitInfo &info,
3031                              Temp offset, unsigned bytes_needed,
3032                              unsigned align, unsigned const_offset,
3033                              Temp dst_hint);
3034 
3035    Callback callback;
3036    bool byte_align_loads;
3037    bool supports_8bit_16bit_loads;
3038    unsigned max_const_offset_plus_one;
3039 };
3040 
emit_load(isel_context * ctx,Builder & bld,const LoadEmitInfo & info,const EmitLoadParameters & params)3041 void emit_load(isel_context *ctx, Builder &bld, const LoadEmitInfo &info,
3042                const EmitLoadParameters &params)
3043 {
3044    unsigned load_size = info.num_components * info.component_size;
3045    unsigned component_size = info.component_size;
3046 
3047    unsigned num_vals = 0;
3048    Temp *const vals = (Temp *)alloca(info.dst.bytes() * sizeof(Temp));
3049 
3050    unsigned const_offset = info.const_offset;
3051 
3052    const unsigned align_mul = info.align_mul ? info.align_mul : component_size;
3053    unsigned align_offset = (info.align_offset + const_offset) % align_mul;
3054 
3055    unsigned bytes_read = 0;
3056    while (bytes_read < load_size) {
3057       unsigned bytes_needed = load_size - bytes_read;
3058 
3059       /* add buffer for unaligned loads */
3060       int byte_align = 0;
3061       if (params.byte_align_loads) {
3062          byte_align = align_mul % 4 == 0 ? align_offset % 4 : -1;
3063       }
3064 
3065       if (byte_align) {
3066          if (bytes_needed > 2 ||
3067              (bytes_needed == 2 && (align_mul % 2 || align_offset % 2)) ||
3068              !params.supports_8bit_16bit_loads) {
3069             if (info.component_stride) {
3070                assert(params.supports_8bit_16bit_loads && "unimplemented");
3071                bytes_needed = 2;
3072                byte_align = 0;
3073             } else {
3074                bytes_needed += byte_align == -1 ? 4 - info.align_mul : byte_align;
3075                bytes_needed = align(bytes_needed, 4);
3076             }
3077          } else {
3078             byte_align = 0;
3079          }
3080       }
3081 
3082       if (info.swizzle_component_size)
3083          bytes_needed = MIN2(bytes_needed, info.swizzle_component_size);
3084       if (info.component_stride)
3085          bytes_needed = MIN2(bytes_needed, info.component_size);
3086 
3087       bool need_to_align_offset = byte_align && (align_mul % 4 || align_offset % 4);
3088 
3089       /* reduce constant offset */
3090       Operand offset = info.offset;
3091       unsigned reduced_const_offset = const_offset;
3092       bool remove_const_offset_completely = need_to_align_offset;
3093       if (const_offset &&
3094           (remove_const_offset_completely ||
3095            const_offset >= params.max_const_offset_plus_one)) {
3096          unsigned to_add = const_offset;
3097          if (remove_const_offset_completely) {
3098             reduced_const_offset = 0;
3099          } else {
3100             to_add = const_offset / params.max_const_offset_plus_one *
3101                      params.max_const_offset_plus_one;
3102             reduced_const_offset %= params.max_const_offset_plus_one;
3103          }
3104          Temp offset_tmp = offset.isTemp() ? offset.getTemp() : Temp();
3105          if (offset.isConstant()) {
3106             offset = Operand(offset.constantValue() + to_add);
3107          } else if (offset_tmp.regClass() == s1) {
3108             offset = bld.sop2(aco_opcode::s_add_i32, bld.def(s1), bld.def(s1, scc),
3109                               offset_tmp, Operand(to_add));
3110          } else if (offset_tmp.regClass() == v1) {
3111             offset = bld.vadd32(bld.def(v1), offset_tmp, Operand(to_add));
3112          } else {
3113             Temp lo = bld.tmp(offset_tmp.type(), 1);
3114             Temp hi = bld.tmp(offset_tmp.type(), 1);
3115             bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), offset_tmp);
3116 
3117             if (offset_tmp.regClass() == s2) {
3118                Temp carry = bld.tmp(s1);
3119                lo = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.scc(Definition(carry)), lo, Operand(to_add));
3120                hi = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.def(s1, scc), hi, carry);
3121                offset = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), lo, hi);
3122             } else {
3123                Temp new_lo = bld.tmp(v1);
3124                Temp carry = bld.vadd32(Definition(new_lo), lo, Operand(to_add), true).def(1).getTemp();
3125                hi = bld.vadd32(bld.def(v1), hi, Operand(0u), false, carry);
3126                offset = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), new_lo, hi);
3127             }
3128          }
3129       }
3130 
3131       /* align offset down if needed */
3132       Operand aligned_offset = offset;
3133       unsigned align = align_offset ? 1 << (ffs(align_offset) - 1) : align_mul;
3134       if (need_to_align_offset) {
3135          align = 4;
3136          Temp offset_tmp = offset.isTemp() ? offset.getTemp() : Temp();
3137          if (offset.isConstant()) {
3138             aligned_offset = Operand(offset.constantValue() & 0xfffffffcu);
3139          } else if (offset_tmp.regClass() == s1) {
3140             aligned_offset = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), Operand(0xfffffffcu), offset_tmp);
3141          } else if (offset_tmp.regClass() == s2) {
3142             aligned_offset = bld.sop2(aco_opcode::s_and_b64, bld.def(s2), bld.def(s1, scc), Operand((uint64_t)0xfffffffffffffffcllu), offset_tmp);
3143          } else if (offset_tmp.regClass() == v1) {
3144             aligned_offset = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0xfffffffcu), offset_tmp);
3145          } else if (offset_tmp.regClass() == v2) {
3146             Temp hi = bld.tmp(v1), lo = bld.tmp(v1);
3147             bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), offset_tmp);
3148             lo = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0xfffffffcu), lo);
3149             aligned_offset = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), lo, hi);
3150          }
3151       }
3152       Temp aligned_offset_tmp = aligned_offset.isTemp() ?
3153                                    aligned_offset.getTemp() :
3154                                    bld.copy(bld.def(s1), aligned_offset);
3155 
3156       Temp val = params.callback(bld, info, aligned_offset_tmp, bytes_needed,
3157                                  align, reduced_const_offset,
3158                                  byte_align ? Temp() : info.dst);
3159 
3160       /* the callback wrote directly to dst */
3161       if (val == info.dst) {
3162          assert(num_vals == 0);
3163          emit_split_vector(ctx, info.dst, info.num_components);
3164          return;
3165       }
3166 
3167       /* shift result right if needed */
3168       if (params.byte_align_loads && info.component_size < 4) {
3169          Operand align((uint32_t)byte_align);
3170          if (byte_align == -1) {
3171             if (offset.isConstant())
3172                align = Operand(offset.constantValue() % 4u);
3173             else if (offset.size() == 2)
3174                align = Operand(emit_extract_vector(ctx, offset.getTemp(), 0, RegClass(offset.getTemp().type(), 1)));
3175             else
3176                align = offset;
3177          }
3178 
3179          assert(val.bytes() >= load_size && "unimplemented");
3180          if (val.type() == RegType::sgpr)
3181             byte_align_scalar(ctx, val, align, info.dst);
3182          else
3183             byte_align_vector(ctx, val, align, info.dst, component_size);
3184          return;
3185       }
3186 
3187       /* add result to list and advance */
3188       if (info.component_stride) {
3189          assert(val.bytes() == info.component_size && "unimplemented");
3190          const_offset += info.component_stride;
3191          align_offset = (align_offset + info.component_stride) % align_mul;
3192       } else {
3193          const_offset += val.bytes();
3194          align_offset = (align_offset + val.bytes()) % align_mul;
3195       }
3196       bytes_read += val.bytes();
3197       vals[num_vals++] = val;
3198    }
3199 
3200    /* create array of components */
3201    unsigned components_split = 0;
3202    std::array<Temp, NIR_MAX_VEC_COMPONENTS> allocated_vec;
3203    bool has_vgprs = false;
3204    for (unsigned i = 0; i < num_vals;) {
3205       Temp *const tmp = (Temp *)alloca(num_vals * sizeof(Temp));
3206       unsigned num_tmps = 0;
3207       unsigned tmp_size = 0;
3208       RegType reg_type = RegType::sgpr;
3209       while ((!tmp_size || (tmp_size % component_size)) && i < num_vals) {
3210          if (vals[i].type() == RegType::vgpr)
3211             reg_type = RegType::vgpr;
3212          tmp_size += vals[i].bytes();
3213          tmp[num_tmps++] = vals[i++];
3214       }
3215       if (num_tmps > 1) {
3216          aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(
3217             aco_opcode::p_create_vector, Format::PSEUDO, num_tmps, 1)};
3218          for (unsigned i = 0; i < num_tmps; i++)
3219             vec->operands[i] = Operand(tmp[i]);
3220          tmp[0] = bld.tmp(RegClass::get(reg_type, tmp_size));
3221          vec->definitions[0] = Definition(tmp[0]);
3222          bld.insert(std::move(vec));
3223       }
3224 
3225       if (tmp[0].bytes() % component_size) {
3226          /* trim tmp[0] */
3227          assert(i == num_vals);
3228          RegClass new_rc = RegClass::get(reg_type, tmp[0].bytes() / component_size * component_size);
3229          tmp[0] = bld.pseudo(aco_opcode::p_extract_vector, bld.def(new_rc), tmp[0], Operand(0u));
3230       }
3231 
3232       RegClass elem_rc = RegClass::get(reg_type, component_size);
3233 
3234       unsigned start = components_split;
3235 
3236       if (tmp_size == elem_rc.bytes()) {
3237          allocated_vec[components_split++] = tmp[0];
3238       } else {
3239          assert(tmp_size % elem_rc.bytes() == 0);
3240          aco_ptr<Pseudo_instruction> split{create_instruction<Pseudo_instruction>(
3241             aco_opcode::p_split_vector, Format::PSEUDO, 1, tmp_size / elem_rc.bytes())};
3242          for (unsigned i = 0; i < split->definitions.size(); i++) {
3243             Temp component = bld.tmp(elem_rc);
3244             allocated_vec[components_split++] = component;
3245             split->definitions[i] = Definition(component);
3246          }
3247          split->operands[0] = Operand(tmp[0]);
3248          bld.insert(std::move(split));
3249       }
3250 
3251       /* try to p_as_uniform early so we can create more optimizable code and
3252        * also update allocated_vec */
3253       for (unsigned j = start; j < components_split; j++) {
3254          if (allocated_vec[j].bytes() % 4 == 0 && info.dst.type() == RegType::sgpr)
3255             allocated_vec[j] = bld.as_uniform(allocated_vec[j]);
3256          has_vgprs |= allocated_vec[j].type() == RegType::vgpr;
3257       }
3258    }
3259 
3260    /* concatenate components and p_as_uniform() result if needed */
3261    if (info.dst.type() == RegType::vgpr || !has_vgprs)
3262       ctx->allocated_vec.emplace(info.dst.id(), allocated_vec);
3263 
3264    int padding_bytes = MAX2((int)info.dst.bytes() - int(allocated_vec[0].bytes() * info.num_components), 0);
3265 
3266    aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(
3267       aco_opcode::p_create_vector, Format::PSEUDO, info.num_components + !!padding_bytes, 1)};
3268    for (unsigned i = 0; i < info.num_components; i++)
3269       vec->operands[i] = Operand(allocated_vec[i]);
3270    if (padding_bytes)
3271       vec->operands[info.num_components] = Operand(RegClass::get(RegType::vgpr, padding_bytes));
3272    if (info.dst.type() == RegType::sgpr && has_vgprs) {
3273       Temp tmp = bld.tmp(RegType::vgpr, info.dst.size());
3274       vec->definitions[0] = Definition(tmp);
3275       bld.insert(std::move(vec));
3276       bld.pseudo(aco_opcode::p_as_uniform, Definition(info.dst), tmp);
3277    } else {
3278       vec->definitions[0] = Definition(info.dst);
3279       bld.insert(std::move(vec));
3280    }
3281 }
3282 
load_lds_size_m0(Builder & bld)3283 Operand load_lds_size_m0(Builder& bld)
3284 {
3285    /* TODO: m0 does not need to be initialized on GFX9+ */
3286    return bld.m0((Temp)bld.copy(bld.def(s1, m0), Operand(0xffffffffu)));
3287 }
3288 
lds_load_callback(Builder & bld,const LoadEmitInfo & info,Temp offset,unsigned bytes_needed,unsigned align,unsigned const_offset,Temp dst_hint)3289 Temp lds_load_callback(Builder& bld, const LoadEmitInfo &info,
3290                        Temp offset, unsigned bytes_needed,
3291                        unsigned align, unsigned const_offset,
3292                        Temp dst_hint)
3293 {
3294    offset = offset.regClass() == s1 ? bld.copy(bld.def(v1), offset) : offset;
3295 
3296    Operand m = load_lds_size_m0(bld);
3297 
3298    bool large_ds_read = bld.program->chip_class >= GFX7;
3299    bool usable_read2 = bld.program->chip_class >= GFX7;
3300 
3301    bool read2 = false;
3302    unsigned size = 0;
3303    aco_opcode op;
3304    //TODO: use ds_read_u8_d16_hi/ds_read_u16_d16_hi if beneficial
3305    if (bytes_needed >= 16 && align % 16 == 0 && large_ds_read) {
3306       size = 16;
3307       op = aco_opcode::ds_read_b128;
3308    } else if (bytes_needed >= 16 && align % 8 == 0 && const_offset % 8 == 0 && usable_read2) {
3309       size = 16;
3310       read2 = true;
3311       op = aco_opcode::ds_read2_b64;
3312    } else if (bytes_needed >= 12 && align % 16 == 0 && large_ds_read) {
3313       size = 12;
3314       op = aco_opcode::ds_read_b96;
3315    } else if (bytes_needed >= 8 && align % 8 == 0) {
3316       size = 8;
3317       op = aco_opcode::ds_read_b64;
3318    } else if (bytes_needed >= 8 && align % 4 == 0 && const_offset % 4 == 0) {
3319       size = 8;
3320       read2 = true;
3321       op = aco_opcode::ds_read2_b32;
3322    } else if (bytes_needed >= 4 && align % 4 == 0) {
3323       size = 4;
3324       op = aco_opcode::ds_read_b32;
3325    } else if (bytes_needed >= 2 && align % 2 == 0) {
3326       size = 2;
3327       op = aco_opcode::ds_read_u16;
3328    } else {
3329       size = 1;
3330       op = aco_opcode::ds_read_u8;
3331    }
3332 
3333    unsigned max_offset_plus_one = read2 ? 254 * (size / 2u) + 1 : 65536;
3334    if (const_offset >= max_offset_plus_one) {
3335       offset = bld.vadd32(bld.def(v1), offset, Operand(const_offset / max_offset_plus_one));
3336       const_offset %= max_offset_plus_one;
3337    }
3338 
3339    if (read2)
3340       const_offset /= (size / 2u);
3341 
3342    RegClass rc = RegClass(RegType::vgpr, DIV_ROUND_UP(size, 4));
3343    Temp val = rc == info.dst.regClass() && dst_hint.id() ? dst_hint : bld.tmp(rc);
3344    Instruction *instr;
3345    if (read2)
3346       instr = bld.ds(op, Definition(val), offset, m, const_offset, const_offset + 1);
3347    else
3348       instr = bld.ds(op, Definition(val), offset, m, const_offset);
3349    static_cast<DS_instruction *>(instr)->sync = info.sync;
3350 
3351    if (size < 4)
3352       val = bld.pseudo(aco_opcode::p_extract_vector, bld.def(RegClass::get(RegType::vgpr, size)), val, Operand(0u));
3353 
3354    return val;
3355 }
3356 
3357 const EmitLoadParameters lds_load_params { lds_load_callback, false, true, UINT32_MAX };
3358 
smem_load_callback(Builder & bld,const LoadEmitInfo & info,Temp offset,unsigned bytes_needed,unsigned align,unsigned const_offset,Temp dst_hint)3359 Temp smem_load_callback(Builder& bld, const LoadEmitInfo &info,
3360                         Temp offset, unsigned bytes_needed,
3361                         unsigned align, unsigned const_offset,
3362                         Temp dst_hint)
3363 {
3364    unsigned size = 0;
3365    aco_opcode op;
3366    if (bytes_needed <= 4) {
3367       size = 1;
3368       op = info.resource.id() ? aco_opcode::s_buffer_load_dword : aco_opcode::s_load_dword;
3369    } else if (bytes_needed <= 8) {
3370       size = 2;
3371       op = info.resource.id() ? aco_opcode::s_buffer_load_dwordx2 : aco_opcode::s_load_dwordx2;
3372    } else if (bytes_needed <= 16) {
3373       size = 4;
3374       op = info.resource.id() ? aco_opcode::s_buffer_load_dwordx4 : aco_opcode::s_load_dwordx4;
3375    } else if (bytes_needed <= 32) {
3376       size = 8;
3377       op = info.resource.id() ? aco_opcode::s_buffer_load_dwordx8 : aco_opcode::s_load_dwordx8;
3378    } else {
3379       size = 16;
3380       op = info.resource.id() ? aco_opcode::s_buffer_load_dwordx16 : aco_opcode::s_load_dwordx16;
3381    }
3382    aco_ptr<SMEM_instruction> load{create_instruction<SMEM_instruction>(op, Format::SMEM, 2, 1)};
3383    if (info.resource.id()) {
3384       load->operands[0] = Operand(info.resource);
3385       load->operands[1] = Operand(offset);
3386    } else {
3387       load->operands[0] = Operand(offset);
3388       load->operands[1] = Operand(0u);
3389    }
3390    RegClass rc(RegType::sgpr, size);
3391    Temp val = dst_hint.id() && dst_hint.regClass() == rc ? dst_hint : bld.tmp(rc);
3392    load->definitions[0] = Definition(val);
3393    load->glc = info.glc;
3394    load->dlc = info.glc && bld.program->chip_class >= GFX10;
3395    load->sync = info.sync;
3396    bld.insert(std::move(load));
3397    return val;
3398 }
3399 
3400 const EmitLoadParameters smem_load_params { smem_load_callback, true, false, 1024 };
3401 
mubuf_load_callback(Builder & bld,const LoadEmitInfo & info,Temp offset,unsigned bytes_needed,unsigned align_,unsigned const_offset,Temp dst_hint)3402 Temp mubuf_load_callback(Builder& bld, const LoadEmitInfo &info,
3403                          Temp offset, unsigned bytes_needed,
3404                          unsigned align_, unsigned const_offset,
3405                          Temp dst_hint)
3406 {
3407    Operand vaddr = offset.type() == RegType::vgpr ? Operand(offset) : Operand(v1);
3408    Operand soffset = offset.type() == RegType::sgpr ? Operand(offset) : Operand((uint32_t) 0);
3409 
3410    if (info.soffset.id()) {
3411       if (soffset.isTemp())
3412          vaddr = bld.copy(bld.def(v1), soffset);
3413       soffset = Operand(info.soffset);
3414    }
3415 
3416    unsigned bytes_size = 0;
3417    aco_opcode op;
3418    if (bytes_needed == 1 || align_ % 2) {
3419       bytes_size = 1;
3420       op = aco_opcode::buffer_load_ubyte;
3421    } else if (bytes_needed == 2 || align_ % 4) {
3422       bytes_size = 2;
3423       op = aco_opcode::buffer_load_ushort;
3424    } else if (bytes_needed <= 4) {
3425       bytes_size = 4;
3426       op = aco_opcode::buffer_load_dword;
3427    } else if (bytes_needed <= 8) {
3428       bytes_size = 8;
3429       op = aco_opcode::buffer_load_dwordx2;
3430    } else if (bytes_needed <= 12 && bld.program->chip_class > GFX6) {
3431       bytes_size = 12;
3432       op = aco_opcode::buffer_load_dwordx3;
3433    } else {
3434       bytes_size = 16;
3435       op = aco_opcode::buffer_load_dwordx4;
3436    }
3437    aco_ptr<MUBUF_instruction> mubuf{create_instruction<MUBUF_instruction>(op, Format::MUBUF, 3, 1)};
3438    mubuf->operands[0] = Operand(info.resource);
3439    mubuf->operands[1] = vaddr;
3440    mubuf->operands[2] = soffset;
3441    mubuf->offen = (offset.type() == RegType::vgpr);
3442    mubuf->glc = info.glc;
3443    mubuf->dlc = info.glc && bld.program->chip_class >= GFX10;
3444    mubuf->slc = info.slc;
3445    mubuf->sync = info.sync;
3446    mubuf->offset = const_offset;
3447    mubuf->swizzled = info.swizzle_component_size != 0;
3448    RegClass rc = RegClass::get(RegType::vgpr, bytes_size);
3449    Temp val = dst_hint.id() && rc == dst_hint.regClass() ? dst_hint : bld.tmp(rc);
3450    mubuf->definitions[0] = Definition(val);
3451    bld.insert(std::move(mubuf));
3452 
3453    return val;
3454 }
3455 
3456 const EmitLoadParameters mubuf_load_params { mubuf_load_callback, true, true, 4096 };
3457 const EmitLoadParameters scratch_load_params { mubuf_load_callback, false, true, 4096 };
3458 
get_gfx6_global_rsrc(Builder & bld,Temp addr)3459 Temp get_gfx6_global_rsrc(Builder& bld, Temp addr)
3460 {
3461    uint32_t rsrc_conf = S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3462                         S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3463 
3464    if (addr.type() == RegType::vgpr)
3465       return bld.pseudo(aco_opcode::p_create_vector, bld.def(s4), Operand(0u), Operand(0u), Operand(-1u), Operand(rsrc_conf));
3466    return bld.pseudo(aco_opcode::p_create_vector, bld.def(s4), addr, Operand(-1u), Operand(rsrc_conf));
3467 }
3468 
global_load_callback(Builder & bld,const LoadEmitInfo & info,Temp offset,unsigned bytes_needed,unsigned align_,unsigned const_offset,Temp dst_hint)3469 Temp global_load_callback(Builder& bld, const LoadEmitInfo &info,
3470                           Temp offset, unsigned bytes_needed,
3471                           unsigned align_, unsigned const_offset,
3472                           Temp dst_hint)
3473 {
3474    unsigned bytes_size = 0;
3475    bool mubuf = bld.program->chip_class == GFX6;
3476    bool global = bld.program->chip_class >= GFX9;
3477    aco_opcode op;
3478    if (bytes_needed == 1) {
3479       bytes_size = 1;
3480       op = mubuf ? aco_opcode::buffer_load_ubyte : global ? aco_opcode::global_load_ubyte : aco_opcode::flat_load_ubyte;
3481    } else if (bytes_needed == 2) {
3482       bytes_size = 2;
3483       op = mubuf ? aco_opcode::buffer_load_ushort : global ? aco_opcode::global_load_ushort : aco_opcode::flat_load_ushort;
3484    } else if (bytes_needed <= 4) {
3485       bytes_size = 4;
3486       op = mubuf ? aco_opcode::buffer_load_dword : global ? aco_opcode::global_load_dword : aco_opcode::flat_load_dword;
3487    } else if (bytes_needed <= 8) {
3488       bytes_size = 8;
3489       op = mubuf ? aco_opcode::buffer_load_dwordx2 : global ? aco_opcode::global_load_dwordx2 : aco_opcode::flat_load_dwordx2;
3490    } else if (bytes_needed <= 12 && !mubuf) {
3491       bytes_size = 12;
3492       op = global ? aco_opcode::global_load_dwordx3 : aco_opcode::flat_load_dwordx3;
3493    } else {
3494       bytes_size = 16;
3495       op = mubuf ? aco_opcode::buffer_load_dwordx4 : global ? aco_opcode::global_load_dwordx4 : aco_opcode::flat_load_dwordx4;
3496    }
3497    RegClass rc = RegClass::get(RegType::vgpr, align(bytes_size, 4));
3498    Temp val = dst_hint.id() && rc == dst_hint.regClass() ? dst_hint : bld.tmp(rc);
3499    if (mubuf) {
3500       aco_ptr<MUBUF_instruction> mubuf{create_instruction<MUBUF_instruction>(op, Format::MUBUF, 3, 1)};
3501       mubuf->operands[0] = Operand(get_gfx6_global_rsrc(bld, offset));
3502       mubuf->operands[1] = offset.type() == RegType::vgpr ? Operand(offset) : Operand(v1);
3503       mubuf->operands[2] = Operand(0u);
3504       mubuf->glc = info.glc;
3505       mubuf->dlc = false;
3506       mubuf->offset = 0;
3507       mubuf->addr64 = offset.type() == RegType::vgpr;
3508       mubuf->disable_wqm = false;
3509       mubuf->sync = info.sync;
3510       mubuf->definitions[0] = Definition(val);
3511       bld.insert(std::move(mubuf));
3512    } else {
3513       offset = offset.regClass() == s2 ? bld.copy(bld.def(v2), offset) : offset;
3514 
3515       aco_ptr<FLAT_instruction> flat{create_instruction<FLAT_instruction>(op, global ? Format::GLOBAL : Format::FLAT, 2, 1)};
3516       flat->operands[0] = Operand(offset);
3517       flat->operands[1] = Operand(s1);
3518       flat->glc = info.glc;
3519       flat->dlc = info.glc && bld.program->chip_class >= GFX10;
3520       flat->sync = info.sync;
3521       flat->offset = 0u;
3522       flat->definitions[0] = Definition(val);
3523       bld.insert(std::move(flat));
3524    }
3525 
3526    return val;
3527 }
3528 
3529 const EmitLoadParameters global_load_params { global_load_callback, true, true, 1 };
3530 
load_lds(isel_context * ctx,unsigned elem_size_bytes,Temp dst,Temp address,unsigned base_offset,unsigned align)3531 Temp load_lds(isel_context *ctx, unsigned elem_size_bytes, Temp dst,
3532               Temp address, unsigned base_offset, unsigned align)
3533 {
3534    assert(util_is_power_of_two_nonzero(align));
3535 
3536    Builder bld(ctx->program, ctx->block);
3537 
3538    unsigned num_components = dst.bytes() / elem_size_bytes;
3539    LoadEmitInfo info = {Operand(as_vgpr(ctx, address)), dst, num_components, elem_size_bytes};
3540    info.align_mul = align;
3541    info.align_offset = 0;
3542    info.sync = memory_sync_info(storage_shared);
3543    info.const_offset = base_offset;
3544    emit_load(ctx, bld, info, lds_load_params);
3545 
3546    return dst;
3547 }
3548 
split_store_data(isel_context * ctx,RegType dst_type,unsigned count,Temp * dst,unsigned * bytes,Temp src)3549 void split_store_data(isel_context *ctx, RegType dst_type, unsigned count, Temp *dst, unsigned *bytes, Temp src)
3550 {
3551    if (!count)
3552       return;
3553 
3554    Builder bld(ctx->program, ctx->block);
3555 
3556    /* count == 1 fast path */
3557    if (count == 1) {
3558       if (dst_type == RegType::sgpr)
3559          dst[0] = bld.as_uniform(src);
3560       else
3561          dst[0] = as_vgpr(ctx, src);
3562       return;
3563    }
3564 
3565    /* elem_size_bytes is the greatest common divisor which is a power of 2 */
3566    unsigned elem_size_bytes = 1u << (ffs(std::accumulate(bytes, bytes + count, 8, std::bit_or<>{})) - 1);
3567 
3568    ASSERTED bool is_subdword = elem_size_bytes < 4;
3569    assert(!is_subdword || dst_type == RegType::vgpr);
3570 
3571    for (unsigned i = 0; i < count; i++)
3572       dst[i] = bld.tmp(RegClass::get(dst_type, bytes[i]));
3573 
3574    std::vector<Temp> temps;
3575    /* use allocated_vec if possible */
3576    auto it = ctx->allocated_vec.find(src.id());
3577    if (it != ctx->allocated_vec.end()) {
3578       if (!it->second[0].id())
3579          goto split;
3580       unsigned elem_size = it->second[0].bytes();
3581       assert(src.bytes() % elem_size == 0);
3582 
3583       for (unsigned i = 0; i < src.bytes() / elem_size; i++) {
3584          if (!it->second[i].id())
3585             goto split;
3586       }
3587       if (elem_size_bytes % elem_size)
3588          goto split;
3589 
3590       temps.insert(temps.end(), it->second.begin(),
3591                    it->second.begin() + src.bytes() / elem_size);
3592       elem_size_bytes = elem_size;
3593    }
3594 
3595    split:
3596    /* split src if necessary */
3597    if (temps.empty()) {
3598       if (is_subdword && src.type() == RegType::sgpr)
3599          src = as_vgpr(ctx, src);
3600       if (dst_type == RegType::sgpr)
3601          src = bld.as_uniform(src);
3602 
3603       unsigned num_elems = src.bytes() / elem_size_bytes;
3604       aco_ptr<Instruction> split{create_instruction<Pseudo_instruction>(aco_opcode::p_split_vector, Format::PSEUDO, 1, num_elems)};
3605       split->operands[0] = Operand(src);
3606       for (unsigned i = 0; i < num_elems; i++) {
3607          temps.emplace_back(bld.tmp(RegClass::get(dst_type, elem_size_bytes)));
3608          split->definitions[i] = Definition(temps.back());
3609       }
3610       bld.insert(std::move(split));
3611    }
3612 
3613    unsigned idx = 0;
3614    for (unsigned i = 0; i < count; i++) {
3615       unsigned op_count = dst[i].bytes() / elem_size_bytes;
3616       if (op_count == 1) {
3617          if (dst_type == RegType::sgpr)
3618             dst[i] = bld.as_uniform(temps[idx++]);
3619          else
3620             dst[i] = as_vgpr(ctx, temps[idx++]);
3621          continue;
3622       }
3623 
3624       aco_ptr<Instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, op_count, 1)};
3625       for (unsigned j = 0; j < op_count; j++) {
3626          Temp tmp = temps[idx++];
3627          if (dst_type == RegType::sgpr)
3628             tmp = bld.as_uniform(tmp);
3629          vec->operands[j] = Operand(tmp);
3630       }
3631       vec->definitions[0] = Definition(dst[i]);
3632       bld.insert(std::move(vec));
3633    }
3634    return;
3635 }
3636 
scan_write_mask(uint32_t mask,uint32_t todo_mask,int * start,int * count)3637 bool scan_write_mask(uint32_t mask, uint32_t todo_mask,
3638                      int *start, int *count)
3639 {
3640    unsigned start_elem = ffs(todo_mask) - 1;
3641    bool skip = !(mask & (1 << start_elem));
3642    if (skip)
3643       mask = ~mask & todo_mask;
3644 
3645    mask &= todo_mask;
3646 
3647    u_bit_scan_consecutive_range(&mask, start, count);
3648 
3649    return !skip;
3650 }
3651 
advance_write_mask(uint32_t * todo_mask,int start,int count)3652 void advance_write_mask(uint32_t *todo_mask, int start, int count)
3653 {
3654    *todo_mask &= ~u_bit_consecutive(0, count) << start;
3655 }
3656 
store_lds(isel_context * ctx,unsigned elem_size_bytes,Temp data,uint32_t wrmask,Temp address,unsigned base_offset,unsigned align)3657 void store_lds(isel_context *ctx, unsigned elem_size_bytes, Temp data, uint32_t wrmask,
3658                Temp address, unsigned base_offset, unsigned align)
3659 {
3660    assert(util_is_power_of_two_nonzero(align));
3661    assert(util_is_power_of_two_nonzero(elem_size_bytes) && elem_size_bytes <= 8);
3662 
3663    Builder bld(ctx->program, ctx->block);
3664    bool large_ds_write = ctx->options->chip_class >= GFX7;
3665    bool usable_write2 = ctx->options->chip_class >= GFX7;
3666 
3667    unsigned write_count = 0;
3668    Temp write_datas[32];
3669    unsigned offsets[32];
3670    unsigned bytes[32];
3671    aco_opcode opcodes[32];
3672 
3673    wrmask = widen_mask(wrmask, elem_size_bytes);
3674 
3675    uint32_t todo = u_bit_consecutive(0, data.bytes());
3676    while (todo) {
3677       int offset, byte;
3678       if (!scan_write_mask(wrmask, todo, &offset, &byte)) {
3679          offsets[write_count] = offset;
3680          bytes[write_count] = byte;
3681          opcodes[write_count] = aco_opcode::num_opcodes;
3682          write_count++;
3683          advance_write_mask(&todo, offset, byte);
3684          continue;
3685       }
3686 
3687       bool aligned2 = offset % 2 == 0 && align % 2 == 0;
3688       bool aligned4 = offset % 4 == 0 && align % 4 == 0;
3689       bool aligned8 = offset % 8 == 0 && align % 8 == 0;
3690       bool aligned16 = offset % 16 == 0 && align % 16 == 0;
3691 
3692       //TODO: use ds_write_b8_d16_hi/ds_write_b16_d16_hi if beneficial
3693       aco_opcode op = aco_opcode::num_opcodes;
3694       if (byte >= 16 && aligned16 && large_ds_write) {
3695          op = aco_opcode::ds_write_b128;
3696          byte = 16;
3697       } else if (byte >= 12 && aligned16 && large_ds_write) {
3698          op = aco_opcode::ds_write_b96;
3699          byte = 12;
3700       } else if (byte >= 8 && aligned8) {
3701          op = aco_opcode::ds_write_b64;
3702          byte = 8;
3703       } else if (byte >= 4 && aligned4) {
3704          op = aco_opcode::ds_write_b32;
3705          byte = 4;
3706       } else if (byte >= 2 && aligned2) {
3707          op = aco_opcode::ds_write_b16;
3708          byte = 2;
3709       } else if (byte >= 1) {
3710          op = aco_opcode::ds_write_b8;
3711          byte = 1;
3712       } else {
3713          assert(false);
3714       }
3715 
3716       offsets[write_count] = offset;
3717       bytes[write_count] = byte;
3718       opcodes[write_count] = op;
3719       write_count++;
3720       advance_write_mask(&todo, offset, byte);
3721    }
3722 
3723    Operand m = load_lds_size_m0(bld);
3724 
3725    split_store_data(ctx, RegType::vgpr, write_count, write_datas, bytes, data);
3726 
3727    for (unsigned i = 0; i < write_count; i++) {
3728       aco_opcode op = opcodes[i];
3729       if (op == aco_opcode::num_opcodes)
3730          continue;
3731 
3732       Temp data = write_datas[i];
3733 
3734       unsigned second = write_count;
3735       if (usable_write2 && (op == aco_opcode::ds_write_b32 || op == aco_opcode::ds_write_b64)) {
3736          for (second = i + 1; second < write_count; second++) {
3737             if (opcodes[second] == op && (offsets[second] - offsets[i]) % data.bytes() == 0) {
3738                op = data.bytes() == 4 ? aco_opcode::ds_write2_b32 : aco_opcode::ds_write2_b64;
3739                opcodes[second] = aco_opcode::num_opcodes;
3740                break;
3741             }
3742          }
3743       }
3744 
3745       bool write2 = op == aco_opcode::ds_write2_b32 || op == aco_opcode::ds_write2_b64;
3746       unsigned write2_off = (offsets[second] - offsets[i]) / data.bytes();
3747 
3748       unsigned inline_offset = base_offset + offsets[i];
3749       unsigned max_offset = write2 ? (255 - write2_off) * data.bytes() : 65535;
3750       Temp address_offset = address;
3751       if (inline_offset > max_offset) {
3752          address_offset = bld.vadd32(bld.def(v1), Operand(base_offset), address_offset);
3753          inline_offset = offsets[i];
3754       }
3755       assert(inline_offset <= max_offset); /* offsets[i] shouldn't be large enough for this to happen */
3756 
3757       Instruction *instr;
3758       if (write2) {
3759          Temp second_data = write_datas[second];
3760          inline_offset /= data.bytes();
3761          instr = bld.ds(op, address_offset, data, second_data, m, inline_offset, inline_offset + write2_off);
3762       } else {
3763          instr = bld.ds(op, address_offset, data, m, inline_offset);
3764       }
3765       static_cast<DS_instruction *>(instr)->sync =
3766          memory_sync_info(storage_shared);
3767    }
3768 }
3769 
calculate_lds_alignment(isel_context * ctx,unsigned const_offset)3770 unsigned calculate_lds_alignment(isel_context *ctx, unsigned const_offset)
3771 {
3772    unsigned align = 16;
3773    if (const_offset)
3774       align = std::min(align, 1u << (ffs(const_offset) - 1));
3775 
3776    return align;
3777 }
3778 
3779 
get_buffer_store_op(bool smem,unsigned bytes)3780 aco_opcode get_buffer_store_op(bool smem, unsigned bytes)
3781 {
3782    switch (bytes) {
3783    case 1:
3784       assert(!smem);
3785       return aco_opcode::buffer_store_byte;
3786    case 2:
3787       assert(!smem);
3788       return aco_opcode::buffer_store_short;
3789    case 4:
3790       return smem ? aco_opcode::s_buffer_store_dword : aco_opcode::buffer_store_dword;
3791    case 8:
3792       return smem ? aco_opcode::s_buffer_store_dwordx2 : aco_opcode::buffer_store_dwordx2;
3793    case 12:
3794       assert(!smem);
3795       return aco_opcode::buffer_store_dwordx3;
3796    case 16:
3797       return smem ? aco_opcode::s_buffer_store_dwordx4 : aco_opcode::buffer_store_dwordx4;
3798    }
3799    unreachable("Unexpected store size");
3800    return aco_opcode::num_opcodes;
3801 }
3802 
split_buffer_store(isel_context * ctx,nir_intrinsic_instr * instr,bool smem,RegType dst_type,Temp data,unsigned writemask,int swizzle_element_size,unsigned * write_count,Temp * write_datas,unsigned * offsets)3803 void split_buffer_store(isel_context *ctx, nir_intrinsic_instr *instr, bool smem, RegType dst_type,
3804                         Temp data, unsigned writemask, int swizzle_element_size,
3805                         unsigned *write_count, Temp *write_datas, unsigned *offsets)
3806 {
3807    unsigned write_count_with_skips = 0;
3808    bool skips[16];
3809    unsigned bytes[16];
3810 
3811    /* determine how to split the data */
3812    unsigned todo = u_bit_consecutive(0, data.bytes());
3813    while (todo) {
3814       int offset, byte;
3815       skips[write_count_with_skips] = !scan_write_mask(writemask, todo, &offset, &byte);
3816       offsets[write_count_with_skips] = offset;
3817       if (skips[write_count_with_skips]) {
3818          bytes[write_count_with_skips] = byte;
3819          advance_write_mask(&todo, offset, byte);
3820          write_count_with_skips++;
3821          continue;
3822       }
3823 
3824       /* only supported sizes are 1, 2, 4, 8, 12 and 16 bytes and can't be
3825        * larger than swizzle_element_size */
3826       byte = MIN2(byte, swizzle_element_size);
3827       if (byte % 4)
3828          byte = byte > 4 ? byte & ~0x3 : MIN2(byte, 2);
3829 
3830       /* SMEM and GFX6 VMEM can't emit 12-byte stores */
3831       if ((ctx->program->chip_class == GFX6 || smem) && byte == 12)
3832          byte = 8;
3833 
3834       /* dword or larger stores have to be dword-aligned */
3835       unsigned align_mul = instr ? nir_intrinsic_align_mul(instr) : 4;
3836       unsigned align_offset = (instr ? nir_intrinsic_align_offset(instr) : 0) + offset;
3837       bool dword_aligned = align_offset % 4 == 0 && align_mul % 4 == 0;
3838       if (!dword_aligned)
3839          byte = MIN2(byte, (align_offset % 2 == 0 && align_mul % 2 == 0) ? 2 : 1);
3840 
3841       bytes[write_count_with_skips] = byte;
3842       advance_write_mask(&todo, offset, byte);
3843       write_count_with_skips++;
3844    }
3845 
3846    /* actually split data */
3847    split_store_data(ctx, dst_type, write_count_with_skips, write_datas, bytes, data);
3848 
3849    /* remove skips */
3850    for (unsigned i = 0; i < write_count_with_skips; i++) {
3851       if (skips[i])
3852          continue;
3853       write_datas[*write_count] = write_datas[i];
3854       offsets[*write_count] = offsets[i];
3855       (*write_count)++;
3856    }
3857 }
3858 
create_vec_from_array(isel_context * ctx,Temp arr[],unsigned cnt,RegType reg_type,unsigned elem_size_bytes,unsigned split_cnt=0u,Temp dst=Temp ())3859 Temp create_vec_from_array(isel_context *ctx, Temp arr[], unsigned cnt, RegType reg_type, unsigned elem_size_bytes,
3860                            unsigned split_cnt = 0u, Temp dst = Temp())
3861 {
3862    Builder bld(ctx->program, ctx->block);
3863    unsigned dword_size = elem_size_bytes / 4;
3864 
3865    if (!dst.id())
3866       dst = bld.tmp(RegClass(reg_type, cnt * dword_size));
3867 
3868    std::array<Temp, NIR_MAX_VEC_COMPONENTS> allocated_vec;
3869    aco_ptr<Pseudo_instruction> instr {create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, cnt, 1)};
3870    instr->definitions[0] = Definition(dst);
3871 
3872    for (unsigned i = 0; i < cnt; ++i) {
3873       if (arr[i].id()) {
3874          assert(arr[i].size() == dword_size);
3875          allocated_vec[i] = arr[i];
3876          instr->operands[i] = Operand(arr[i]);
3877       } else {
3878          Temp zero = bld.copy(bld.def(RegClass(reg_type, dword_size)), Operand(0u, dword_size == 2));
3879          allocated_vec[i] = zero;
3880          instr->operands[i] = Operand(zero);
3881       }
3882    }
3883 
3884    bld.insert(std::move(instr));
3885 
3886    if (split_cnt)
3887       emit_split_vector(ctx, dst, split_cnt);
3888    else
3889       ctx->allocated_vec.emplace(dst.id(), allocated_vec); /* emit_split_vector already does this */
3890 
3891    return dst;
3892 }
3893 
resolve_excess_vmem_const_offset(Builder & bld,Temp & voffset,unsigned const_offset)3894 inline unsigned resolve_excess_vmem_const_offset(Builder &bld, Temp &voffset, unsigned const_offset)
3895 {
3896    if (const_offset >= 4096) {
3897       unsigned excess_const_offset = const_offset / 4096u * 4096u;
3898       const_offset %= 4096u;
3899 
3900       if (!voffset.id())
3901          voffset = bld.copy(bld.def(v1), Operand(excess_const_offset));
3902       else if (unlikely(voffset.regClass() == s1))
3903          voffset = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.def(s1, scc), Operand(excess_const_offset), Operand(voffset));
3904       else if (likely(voffset.regClass() == v1))
3905          voffset = bld.vadd32(bld.def(v1), Operand(voffset), Operand(excess_const_offset));
3906       else
3907          unreachable("Unsupported register class of voffset");
3908    }
3909 
3910    return const_offset;
3911 }
3912 
emit_single_mubuf_store(isel_context * ctx,Temp descriptor,Temp voffset,Temp soffset,Temp vdata,unsigned const_offset=0u,memory_sync_info sync=memory_sync_info (),bool slc=false,bool swizzled=false)3913 void emit_single_mubuf_store(isel_context *ctx, Temp descriptor, Temp voffset, Temp soffset, Temp vdata,
3914                              unsigned const_offset = 0u, memory_sync_info sync=memory_sync_info(),
3915                              bool slc = false, bool swizzled = false)
3916 {
3917    assert(vdata.id());
3918    assert(vdata.size() != 3 || ctx->program->chip_class != GFX6);
3919    assert(vdata.size() >= 1 && vdata.size() <= 4);
3920 
3921    Builder bld(ctx->program, ctx->block);
3922    aco_opcode op = get_buffer_store_op(false, vdata.bytes());
3923    const_offset = resolve_excess_vmem_const_offset(bld, voffset, const_offset);
3924 
3925    Operand voffset_op = voffset.id() ? Operand(as_vgpr(ctx, voffset)) : Operand(v1);
3926    Operand soffset_op = soffset.id() ? Operand(soffset) : Operand(0u);
3927    Builder::Result r = bld.mubuf(op, Operand(descriptor), voffset_op, soffset_op, Operand(vdata), const_offset,
3928                                  /* offen */ !voffset_op.isUndefined(), /* swizzled */ swizzled,
3929                                  /* idxen*/ false, /* addr64 */ false, /* disable_wqm */ false, /* glc */ true,
3930                                  /* dlc*/ false, /* slc */ slc);
3931 
3932    static_cast<MUBUF_instruction *>(r.instr)->sync = sync;
3933 }
3934 
store_vmem_mubuf(isel_context * ctx,Temp src,Temp descriptor,Temp voffset,Temp soffset,unsigned base_const_offset,unsigned elem_size_bytes,unsigned write_mask,bool allow_combining=true,memory_sync_info sync=memory_sync_info (),bool slc=false)3935 void store_vmem_mubuf(isel_context *ctx, Temp src, Temp descriptor, Temp voffset, Temp soffset,
3936                                    unsigned base_const_offset, unsigned elem_size_bytes, unsigned write_mask,
3937                                    bool allow_combining = true, memory_sync_info sync=memory_sync_info(), bool slc = false)
3938 {
3939    Builder bld(ctx->program, ctx->block);
3940    assert(elem_size_bytes == 2 || elem_size_bytes == 4 || elem_size_bytes == 8);
3941    assert(write_mask);
3942    write_mask = widen_mask(write_mask, elem_size_bytes);
3943 
3944    unsigned write_count = 0;
3945    Temp write_datas[32];
3946    unsigned offsets[32];
3947    split_buffer_store(ctx, NULL, false, RegType::vgpr, src, write_mask,
3948                       allow_combining ? 16 : 4, &write_count, write_datas, offsets);
3949 
3950    for (unsigned i = 0; i < write_count; i++) {
3951       unsigned const_offset = offsets[i] + base_const_offset;
3952       emit_single_mubuf_store(ctx, descriptor, voffset, soffset, write_datas[i], const_offset, sync, slc, !allow_combining);
3953    }
3954 }
3955 
load_vmem_mubuf(isel_context * ctx,Temp dst,Temp descriptor,Temp voffset,Temp soffset,unsigned base_const_offset,unsigned elem_size_bytes,unsigned num_components,unsigned stride=0u,bool allow_combining=true,bool allow_reorder=true,bool slc=false)3956 void load_vmem_mubuf(isel_context *ctx, Temp dst, Temp descriptor, Temp voffset, Temp soffset,
3957                      unsigned base_const_offset, unsigned elem_size_bytes, unsigned num_components,
3958                      unsigned stride = 0u, bool allow_combining = true, bool allow_reorder = true,
3959                      bool slc = false)
3960 {
3961    assert(elem_size_bytes == 2 || elem_size_bytes == 4 || elem_size_bytes == 8);
3962    assert((num_components * elem_size_bytes) == dst.bytes());
3963    assert(!!stride != allow_combining);
3964 
3965    Builder bld(ctx->program, ctx->block);
3966 
3967    LoadEmitInfo info = {Operand(voffset), dst, num_components, elem_size_bytes, descriptor};
3968    info.component_stride = allow_combining ? 0 : stride;
3969    info.glc = true;
3970    info.slc = slc;
3971    info.swizzle_component_size = allow_combining ? 0 : 4;
3972    info.align_mul = MIN2(elem_size_bytes, 4);
3973    info.align_offset = 0;
3974    info.soffset = soffset;
3975    info.const_offset = base_const_offset;
3976    emit_load(ctx, bld, info, mubuf_load_params);
3977 }
3978 
wave_id_in_threadgroup(isel_context * ctx)3979 Temp wave_id_in_threadgroup(isel_context *ctx)
3980 {
3981    Builder bld(ctx->program, ctx->block);
3982    return bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
3983                    get_arg(ctx, ctx->args->merged_wave_info), Operand(24u | (4u << 16)));
3984 }
3985 
thread_id_in_threadgroup(isel_context * ctx)3986 Temp thread_id_in_threadgroup(isel_context *ctx)
3987 {
3988    /* tid_in_tg = wave_id * wave_size + tid_in_wave */
3989 
3990    Builder bld(ctx->program, ctx->block);
3991    Temp tid_in_wave = emit_mbcnt(ctx, bld.tmp(v1));
3992 
3993    if (ctx->program->workgroup_size <= ctx->program->wave_size)
3994       return tid_in_wave;
3995 
3996    Temp wave_id_in_tg = wave_id_in_threadgroup(ctx);
3997    Temp num_pre_threads = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), wave_id_in_tg,
3998                                    Operand(ctx->program->wave_size == 64 ? 6u : 5u));
3999    return bld.vadd32(bld.def(v1), Operand(num_pre_threads), Operand(tid_in_wave));
4000 }
4001 
wave_count_in_threadgroup(isel_context * ctx)4002 Temp wave_count_in_threadgroup(isel_context *ctx)
4003 {
4004    Builder bld(ctx->program, ctx->block);
4005    return bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
4006                    get_arg(ctx, ctx->args->merged_wave_info), Operand(28u | (4u << 16)));
4007 }
4008 
ngg_gs_vertex_lds_addr(isel_context * ctx,Temp vertex_idx)4009 Temp ngg_gs_vertex_lds_addr(isel_context *ctx, Temp vertex_idx)
4010 {
4011    Builder bld(ctx->program, ctx->block);
4012    unsigned write_stride_2exp = ffs(ctx->shader->info.gs.vertices_out) - 1;
4013 
4014    /* gs_max_out_vertices = 2^(write_stride_2exp) * some odd number */
4015    if (write_stride_2exp) {
4016       Temp row = bld.vop2(aco_opcode::v_lshrrev_b32, bld.def(v1), Operand(5u), vertex_idx);
4017       Temp swizzle = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand((1u << write_stride_2exp) - 1), row);
4018       vertex_idx = bld.vop2(aco_opcode::v_xor_b32, bld.def(v1), vertex_idx, swizzle);
4019    }
4020 
4021    Temp vertex_idx_bytes = bld.v_mul24_imm(bld.def(v1), vertex_idx, ctx->ngg_gs_emit_vtx_bytes);
4022    return bld.vadd32(bld.def(v1), vertex_idx_bytes, Operand(ctx->ngg_gs_emit_addr));
4023 }
4024 
ngg_gs_emit_vertex_lds_addr(isel_context * ctx,Temp emit_vertex_idx)4025 Temp ngg_gs_emit_vertex_lds_addr(isel_context *ctx, Temp emit_vertex_idx)
4026 {
4027    /* Should be used by GS threads only (not by the NGG GS epilogue).
4028     * Returns the LDS address of the given vertex index as emitted by the current GS thread.
4029     */
4030 
4031    Builder bld(ctx->program, ctx->block);
4032 
4033    Temp thread_id_in_tg = thread_id_in_threadgroup(ctx);
4034    Temp thread_vertices_addr = bld.v_mul24_imm(bld.def(v1), thread_id_in_tg, ctx->shader->info.gs.vertices_out);
4035    Temp vertex_idx = bld.vadd32(bld.def(v1), thread_vertices_addr, emit_vertex_idx);
4036 
4037    return ngg_gs_vertex_lds_addr(ctx, vertex_idx);
4038 }
4039 
offset_add_from_nir(isel_context * ctx,const std::pair<Temp,unsigned> & base_offset,nir_src * off_src,unsigned stride=1u)4040 std::pair<Temp, unsigned> offset_add_from_nir(isel_context *ctx, const std::pair<Temp, unsigned> &base_offset, nir_src *off_src, unsigned stride = 1u)
4041 {
4042    Builder bld(ctx->program, ctx->block);
4043    Temp offset = base_offset.first;
4044    unsigned const_offset = base_offset.second;
4045 
4046    if (!nir_src_is_const(*off_src)) {
4047       Temp indirect_offset_arg = get_ssa_temp(ctx, off_src->ssa);
4048       Temp with_stride;
4049 
4050       /* Calculate indirect offset with stride */
4051       if (likely(indirect_offset_arg.regClass() == v1))
4052          with_stride = bld.v_mul24_imm(bld.def(v1), indirect_offset_arg, stride);
4053       else if (indirect_offset_arg.regClass() == s1)
4054          with_stride = bld.sop2(aco_opcode::s_mul_i32, bld.def(s1), Operand(stride), indirect_offset_arg);
4055       else
4056          unreachable("Unsupported register class of indirect offset");
4057 
4058       /* Add to the supplied base offset */
4059       if (offset.id() == 0)
4060          offset = with_stride;
4061       else if (unlikely(offset.regClass() == s1 && with_stride.regClass() == s1))
4062          offset = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.def(s1, scc), with_stride, offset);
4063       else if (offset.size() == 1 && with_stride.size() == 1)
4064          offset = bld.vadd32(bld.def(v1), with_stride, offset);
4065       else
4066          unreachable("Unsupported register class of indirect offset");
4067    } else {
4068       unsigned const_offset_arg = nir_src_as_uint(*off_src);
4069       const_offset += const_offset_arg * stride;
4070    }
4071 
4072    return std::make_pair(offset, const_offset);
4073 }
4074 
offset_add(isel_context * ctx,const std::pair<Temp,unsigned> & off1,const std::pair<Temp,unsigned> & off2)4075 std::pair<Temp, unsigned> offset_add(isel_context *ctx, const std::pair<Temp, unsigned> &off1, const std::pair<Temp, unsigned> &off2)
4076 {
4077    Builder bld(ctx->program, ctx->block);
4078    Temp offset;
4079 
4080    if (off1.first.id() && off2.first.id()) {
4081       if (unlikely(off1.first.regClass() == s1 && off2.first.regClass() == s1))
4082          offset = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.def(s1, scc), off1.first, off2.first);
4083       else if (off1.first.size() == 1 && off2.first.size() == 1)
4084          offset = bld.vadd32(bld.def(v1), off1.first, off2.first);
4085       else
4086          unreachable("Unsupported register class of indirect offset");
4087    } else {
4088       offset = off1.first.id() ? off1.first : off2.first;
4089    }
4090 
4091    return std::make_pair(offset, off1.second + off2.second);
4092 }
4093 
offset_mul(isel_context * ctx,const std::pair<Temp,unsigned> & offs,unsigned multiplier)4094 std::pair<Temp, unsigned> offset_mul(isel_context *ctx, const std::pair<Temp, unsigned> &offs, unsigned multiplier)
4095 {
4096    Builder bld(ctx->program, ctx->block);
4097    unsigned const_offset = offs.second * multiplier;
4098 
4099    if (!offs.first.id())
4100       return std::make_pair(offs.first, const_offset);
4101 
4102    Temp offset = unlikely(offs.first.regClass() == s1)
4103                  ? bld.sop2(aco_opcode::s_mul_i32, bld.def(s1), Operand(multiplier), offs.first)
4104                  : bld.v_mul24_imm(bld.def(v1), offs.first, multiplier);
4105 
4106    return std::make_pair(offset, const_offset);
4107 }
4108 
get_intrinsic_io_basic_offset(isel_context * ctx,nir_intrinsic_instr * instr,unsigned base_stride,unsigned component_stride)4109 std::pair<Temp, unsigned> get_intrinsic_io_basic_offset(isel_context *ctx, nir_intrinsic_instr *instr, unsigned base_stride, unsigned component_stride)
4110 {
4111    Builder bld(ctx->program, ctx->block);
4112 
4113    /* base is the driver_location, which is in slots */
4114    unsigned const_offset = nir_intrinsic_base(instr) * 4u * base_stride;
4115    /* component is in bytes */
4116    const_offset += nir_intrinsic_component(instr) * component_stride;
4117 
4118    /* offset should be interpreted in relation to the base, so the instruction effectively reads/writes another input/output when it has an offset */
4119    nir_src *off_src = nir_get_io_offset_src(instr);
4120    return offset_add_from_nir(ctx, std::make_pair(Temp(), const_offset), off_src, 4u * base_stride);
4121 }
4122 
get_intrinsic_io_basic_offset(isel_context * ctx,nir_intrinsic_instr * instr,unsigned stride=1u)4123 std::pair<Temp, unsigned> get_intrinsic_io_basic_offset(isel_context *ctx, nir_intrinsic_instr *instr, unsigned stride = 1u)
4124 {
4125    return get_intrinsic_io_basic_offset(ctx, instr, stride, stride);
4126 }
4127 
get_tess_rel_patch_id(isel_context * ctx)4128 Temp get_tess_rel_patch_id(isel_context *ctx)
4129 {
4130    Builder bld(ctx->program, ctx->block);
4131 
4132    switch (ctx->shader->info.stage) {
4133    case MESA_SHADER_TESS_CTRL:
4134       return bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0xffu),
4135                       get_arg(ctx, ctx->args->ac.tcs_rel_ids));
4136    case MESA_SHADER_TESS_EVAL:
4137       return get_arg(ctx, ctx->args->tes_rel_patch_id);
4138    default:
4139       unreachable("Unsupported stage in get_tess_rel_patch_id");
4140    }
4141 }
4142 
get_tcs_per_vertex_input_lds_offset(isel_context * ctx,nir_intrinsic_instr * instr)4143 std::pair<Temp, unsigned> get_tcs_per_vertex_input_lds_offset(isel_context *ctx, nir_intrinsic_instr *instr)
4144 {
4145    assert(ctx->shader->info.stage == MESA_SHADER_TESS_CTRL);
4146    Builder bld(ctx->program, ctx->block);
4147 
4148    uint32_t tcs_in_patch_stride = ctx->args->options->key.tcs.input_vertices * ctx->tcs_num_inputs * 4;
4149    uint32_t tcs_in_vertex_stride = ctx->tcs_num_inputs * 4;
4150 
4151    std::pair<Temp, unsigned> offs = get_intrinsic_io_basic_offset(ctx, instr);
4152 
4153    nir_src *vertex_index_src = nir_get_io_vertex_index_src(instr);
4154    offs = offset_add_from_nir(ctx, offs, vertex_index_src, tcs_in_vertex_stride);
4155 
4156    Temp rel_patch_id = get_tess_rel_patch_id(ctx);
4157    Temp tcs_in_current_patch_offset = bld.v_mul24_imm(bld.def(v1), rel_patch_id, tcs_in_patch_stride);
4158    offs = offset_add(ctx, offs, std::make_pair(tcs_in_current_patch_offset, 0));
4159 
4160    return offset_mul(ctx, offs, 4u);
4161 }
4162 
get_tcs_output_lds_offset(isel_context * ctx,nir_intrinsic_instr * instr=nullptr,bool per_vertex=false)4163 std::pair<Temp, unsigned> get_tcs_output_lds_offset(isel_context *ctx, nir_intrinsic_instr *instr = nullptr, bool per_vertex = false)
4164 {
4165    assert(ctx->shader->info.stage == MESA_SHADER_TESS_CTRL);
4166    Builder bld(ctx->program, ctx->block);
4167 
4168    uint32_t input_patch_size = ctx->args->options->key.tcs.input_vertices * ctx->tcs_num_inputs * 16;
4169    uint32_t output_vertex_size = ctx->tcs_num_outputs * 16;
4170    uint32_t pervertex_output_patch_size = ctx->shader->info.tess.tcs_vertices_out * output_vertex_size;
4171    uint32_t output_patch_stride = pervertex_output_patch_size + ctx->tcs_num_patch_outputs * 16;
4172 
4173    std::pair<Temp, unsigned> offs = instr
4174                                     ? get_intrinsic_io_basic_offset(ctx, instr, 4u)
4175                                     : std::make_pair(Temp(), 0u);
4176 
4177    Temp rel_patch_id = get_tess_rel_patch_id(ctx);
4178    Temp patch_off = bld.v_mul24_imm(bld.def(v1), rel_patch_id, output_patch_stride);
4179 
4180    if (per_vertex) {
4181       assert(instr);
4182 
4183       nir_src *vertex_index_src = nir_get_io_vertex_index_src(instr);
4184       offs = offset_add_from_nir(ctx, offs, vertex_index_src, output_vertex_size);
4185 
4186       uint32_t output_patch0_offset = (input_patch_size * ctx->tcs_num_patches);
4187       offs = offset_add(ctx, offs, std::make_pair(patch_off, output_patch0_offset));
4188    } else {
4189       uint32_t output_patch0_patch_data_offset = (input_patch_size * ctx->tcs_num_patches + pervertex_output_patch_size);
4190       offs = offset_add(ctx, offs, std::make_pair(patch_off, output_patch0_patch_data_offset));
4191    }
4192 
4193    return offs;
4194 }
4195 
get_tcs_per_vertex_output_vmem_offset(isel_context * ctx,nir_intrinsic_instr * instr)4196 std::pair<Temp, unsigned> get_tcs_per_vertex_output_vmem_offset(isel_context *ctx, nir_intrinsic_instr *instr)
4197 {
4198    Builder bld(ctx->program, ctx->block);
4199 
4200    unsigned vertices_per_patch = ctx->shader->info.tess.tcs_vertices_out;
4201    unsigned attr_stride = vertices_per_patch * ctx->tcs_num_patches;
4202 
4203    std::pair<Temp, unsigned> offs = get_intrinsic_io_basic_offset(ctx, instr, attr_stride * 4u, 4u);
4204 
4205    Temp rel_patch_id = get_tess_rel_patch_id(ctx);
4206    Temp patch_off = bld.v_mul24_imm(bld.def(v1), rel_patch_id, vertices_per_patch * 16u);
4207    offs = offset_add(ctx, offs, std::make_pair(patch_off, 0u));
4208 
4209    nir_src *vertex_index_src = nir_get_io_vertex_index_src(instr);
4210    offs = offset_add_from_nir(ctx, offs, vertex_index_src, 16u);
4211 
4212    return offs;
4213 }
4214 
get_tcs_per_patch_output_vmem_offset(isel_context * ctx,nir_intrinsic_instr * instr=nullptr,unsigned const_base_offset=0u)4215 std::pair<Temp, unsigned> get_tcs_per_patch_output_vmem_offset(isel_context *ctx, nir_intrinsic_instr *instr = nullptr, unsigned const_base_offset = 0u)
4216 {
4217    Builder bld(ctx->program, ctx->block);
4218 
4219    unsigned output_vertex_size = ctx->tcs_num_outputs * 16;
4220    unsigned per_vertex_output_patch_size = ctx->shader->info.tess.tcs_vertices_out * output_vertex_size;
4221    unsigned per_patch_data_offset = per_vertex_output_patch_size * ctx->tcs_num_patches;
4222    unsigned attr_stride = ctx->tcs_num_patches;
4223 
4224    std::pair<Temp, unsigned> offs = instr
4225                                     ? get_intrinsic_io_basic_offset(ctx, instr, attr_stride * 4u, 4u)
4226                                     : std::make_pair(Temp(), 0u);
4227 
4228    if (const_base_offset)
4229       offs.second += const_base_offset * attr_stride;
4230 
4231    Temp rel_patch_id = get_tess_rel_patch_id(ctx);
4232    Temp patch_off = bld.v_mul24_imm(bld.def(v1), rel_patch_id, 16u);
4233    offs = offset_add(ctx, offs, std::make_pair(patch_off, per_patch_data_offset));
4234 
4235    return offs;
4236 }
4237 
tcs_compare_intrin_with_mask(isel_context * ctx,nir_intrinsic_instr * instr,bool per_vertex,uint64_t mask,bool * indirect)4238 bool tcs_compare_intrin_with_mask(isel_context *ctx, nir_intrinsic_instr *instr, bool per_vertex, uint64_t mask, bool *indirect)
4239 {
4240    assert(per_vertex || ctx->shader->info.stage == MESA_SHADER_TESS_CTRL);
4241 
4242    if (mask == 0)
4243       return false;
4244 
4245    nir_src *off_src = nir_get_io_offset_src(instr);
4246 
4247    if (!nir_src_is_const(*off_src)) {
4248       *indirect = true;
4249       return false;
4250    }
4251 
4252    *indirect = false;
4253    uint64_t slot = nir_intrinsic_io_semantics(instr).location;
4254    if (!per_vertex)
4255       slot -= VARYING_SLOT_PATCH0;
4256 
4257    return (((uint64_t) 1) << slot) & mask;
4258 }
4259 
store_output_to_temps(isel_context * ctx,nir_intrinsic_instr * instr)4260 bool store_output_to_temps(isel_context *ctx, nir_intrinsic_instr *instr)
4261 {
4262    unsigned write_mask = nir_intrinsic_write_mask(instr);
4263    unsigned component = nir_intrinsic_component(instr);
4264    unsigned idx = nir_intrinsic_base(instr) * 4u + component;
4265    nir_src offset = *nir_get_io_offset_src(instr);
4266 
4267    if (!nir_src_is_const(offset) || nir_src_as_uint(offset))
4268       return false;
4269 
4270    Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
4271 
4272    if (instr->src[0].ssa->bit_size == 64)
4273       write_mask = widen_mask(write_mask, 2);
4274 
4275    RegClass rc = instr->src[0].ssa->bit_size == 16 ? v2b : v1;
4276 
4277    for (unsigned i = 0; i < 8; ++i) {
4278       if (write_mask & (1 << i)) {
4279          ctx->outputs.mask[idx / 4u] |= 1 << (idx % 4u);
4280          ctx->outputs.temps[idx] = emit_extract_vector(ctx, src, i, rc);
4281       }
4282       idx++;
4283    }
4284 
4285    return true;
4286 }
4287 
load_input_from_temps(isel_context * ctx,nir_intrinsic_instr * instr,Temp dst)4288 bool load_input_from_temps(isel_context *ctx, nir_intrinsic_instr *instr, Temp dst)
4289 {
4290    /* Only TCS per-vertex inputs are supported by this function.
4291     * Per-vertex inputs only match between the VS/TCS invocation id when the number of invocations is the same.
4292     */
4293    if (ctx->shader->info.stage != MESA_SHADER_TESS_CTRL || !ctx->tcs_in_out_eq)
4294       return false;
4295 
4296    nir_src *off_src = nir_get_io_offset_src(instr);
4297    nir_src *vertex_index_src = nir_get_io_vertex_index_src(instr);
4298    nir_instr *vertex_index_instr = vertex_index_src->ssa->parent_instr;
4299    bool can_use_temps = nir_src_is_const(*off_src) &&
4300                         vertex_index_instr->type == nir_instr_type_intrinsic &&
4301                         nir_instr_as_intrinsic(vertex_index_instr)->intrinsic == nir_intrinsic_load_invocation_id;
4302 
4303    if (!can_use_temps)
4304       return false;
4305 
4306    unsigned idx = nir_intrinsic_base(instr) * 4u + nir_intrinsic_component(instr) + 4 * nir_src_as_uint(*off_src);
4307    Temp *src = &ctx->inputs.temps[idx];
4308    create_vec_from_array(ctx, src, dst.size(), dst.regClass().type(), 4u, 0, dst);
4309 
4310    return true;
4311 }
4312 
visit_store_ls_or_es_output(isel_context * ctx,nir_intrinsic_instr * instr)4313 void visit_store_ls_or_es_output(isel_context *ctx, nir_intrinsic_instr *instr)
4314 {
4315    Builder bld(ctx->program, ctx->block);
4316 
4317    if (ctx->tcs_in_out_eq && store_output_to_temps(ctx, instr)) {
4318       /* When the TCS only reads this output directly and for the same vertices as its invocation id, it is unnecessary to store the VS output to LDS. */
4319       bool indirect_write;
4320       bool temp_only_input = tcs_compare_intrin_with_mask(ctx, instr, true, ctx->tcs_temp_only_inputs, &indirect_write);
4321       if (temp_only_input && !indirect_write)
4322          return;
4323    }
4324 
4325    std::pair<Temp, unsigned> offs = get_intrinsic_io_basic_offset(ctx, instr, 4u);
4326    Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
4327    unsigned write_mask = nir_intrinsic_write_mask(instr);
4328    unsigned elem_size_bytes = instr->src[0].ssa->bit_size / 8u;
4329 
4330    if (ctx->stage.hw == HWStage::ES) {
4331       /* GFX6-8: ES stage is not merged into GS, data is passed from ES to GS in VMEM. */
4332       Temp esgs_ring = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), ctx->program->private_segment_buffer, Operand(RING_ESGS_VS * 16u));
4333       Temp es2gs_offset = get_arg(ctx, ctx->args->es2gs_offset);
4334       store_vmem_mubuf(ctx, src, esgs_ring, offs.first, es2gs_offset, offs.second, elem_size_bytes, write_mask, false, memory_sync_info(), true);
4335    } else {
4336       Temp lds_base;
4337 
4338       if (ctx->stage == vertex_geometry_gs || ctx->stage == tess_eval_geometry_gs ||
4339           ctx->stage == vertex_geometry_ngg || ctx->stage == tess_eval_geometry_ngg) {
4340          /* GFX9+: ES stage is merged into GS, data is passed between them using LDS. */
4341          unsigned itemsize = ctx->stage.has(SWStage::VS)
4342                              ? ctx->program->info->vs.es_info.esgs_itemsize
4343                              : ctx->program->info->tes.es_info.esgs_itemsize;
4344          Temp vertex_idx = thread_id_in_threadgroup(ctx);
4345          lds_base = bld.v_mul24_imm(bld.def(v1), vertex_idx, itemsize);
4346       } else if (ctx->stage == vertex_ls || ctx->stage == vertex_tess_control_hs) {
4347          /* GFX6-8: VS runs on LS stage when tessellation is used, but LS shares LDS space with HS.
4348           * GFX9+: LS is merged into HS, but still uses the same LDS layout.
4349           */
4350          Temp vertex_idx = get_arg(ctx, ctx->args->rel_auto_id);
4351          lds_base = bld.v_mul24_imm(bld.def(v1), vertex_idx, ctx->tcs_num_inputs * 16u);
4352       } else {
4353          unreachable("Invalid LS or ES stage");
4354       }
4355 
4356       offs = offset_add(ctx, offs, std::make_pair(lds_base, 0u));
4357       unsigned lds_align = calculate_lds_alignment(ctx, offs.second);
4358       store_lds(ctx, elem_size_bytes, src, write_mask, offs.first, offs.second, lds_align);
4359    }
4360 }
4361 
tcs_output_is_read_by_tes(isel_context * ctx,nir_intrinsic_instr * instr,bool per_vertex)4362 bool tcs_output_is_read_by_tes(isel_context *ctx, nir_intrinsic_instr *instr, bool per_vertex)
4363 {
4364    uint64_t mask = per_vertex
4365                    ? ctx->program->info->tcs.tes_inputs_read
4366                    : ctx->program->info->tcs.tes_patch_inputs_read;
4367 
4368    bool indirect_write = false;
4369    bool output_read_by_tes = tcs_compare_intrin_with_mask(ctx, instr, per_vertex, mask, &indirect_write);
4370    return indirect_write || output_read_by_tes;
4371 }
4372 
tcs_output_is_read_by_tcs(isel_context * ctx,nir_intrinsic_instr * instr,bool per_vertex)4373 bool tcs_output_is_read_by_tcs(isel_context *ctx, nir_intrinsic_instr *instr, bool per_vertex)
4374 {
4375    uint64_t mask = per_vertex
4376                    ? ctx->shader->info.outputs_read
4377                    : ctx->shader->info.patch_outputs_read;
4378 
4379    bool indirect_write = false;
4380    bool output_read = tcs_compare_intrin_with_mask(ctx, instr, per_vertex, mask, &indirect_write);
4381    return indirect_write || output_read;
4382 }
4383 
visit_store_tcs_output(isel_context * ctx,nir_intrinsic_instr * instr,bool per_vertex)4384 void visit_store_tcs_output(isel_context *ctx, nir_intrinsic_instr *instr, bool per_vertex)
4385 {
4386    assert(ctx->stage == tess_control_hs || ctx->stage == vertex_tess_control_hs);
4387    assert(ctx->shader->info.stage == MESA_SHADER_TESS_CTRL);
4388 
4389    Builder bld(ctx->program, ctx->block);
4390 
4391    Temp store_val = get_ssa_temp(ctx, instr->src[0].ssa);
4392    unsigned elem_size_bytes = instr->src[0].ssa->bit_size / 8;
4393    unsigned write_mask = nir_intrinsic_write_mask(instr);
4394    nir_io_semantics semantics = nir_intrinsic_io_semantics(instr);
4395 
4396    bool is_tess_factor = semantics.location == VARYING_SLOT_TESS_LEVEL_INNER ||
4397                          semantics.location == VARYING_SLOT_TESS_LEVEL_OUTER;
4398    bool write_to_vmem = !is_tess_factor && tcs_output_is_read_by_tes(ctx, instr, per_vertex);
4399    bool write_to_lds = is_tess_factor || tcs_output_is_read_by_tcs(ctx, instr, per_vertex);
4400 
4401    if (write_to_vmem) {
4402       std::pair<Temp, unsigned> vmem_offs = per_vertex
4403                                             ? get_tcs_per_vertex_output_vmem_offset(ctx, instr)
4404                                             : get_tcs_per_patch_output_vmem_offset(ctx, instr);
4405 
4406       Temp hs_ring_tess_offchip = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), ctx->program->private_segment_buffer, Operand(RING_HS_TESS_OFFCHIP * 16u));
4407       Temp oc_lds = get_arg(ctx, ctx->args->oc_lds);
4408       store_vmem_mubuf(ctx, store_val, hs_ring_tess_offchip, vmem_offs.first, oc_lds, vmem_offs.second, elem_size_bytes, write_mask, true, memory_sync_info(storage_vmem_output));
4409    }
4410 
4411    if (write_to_lds) {
4412       /* Remember driver location of tess factors, so we can read them later, in write_tcs_tess_factors */
4413       if (semantics.location == VARYING_SLOT_TESS_LEVEL_INNER)
4414          ctx->tcs_tess_lvl_in_loc = nir_intrinsic_base(instr) * 16u;
4415       else if (semantics.location == VARYING_SLOT_TESS_LEVEL_OUTER)
4416          ctx->tcs_tess_lvl_out_loc = nir_intrinsic_base(instr) * 16u;
4417 
4418       std::pair<Temp, unsigned> lds_offs = get_tcs_output_lds_offset(ctx, instr, per_vertex);
4419       unsigned lds_align = calculate_lds_alignment(ctx, lds_offs.second);
4420       store_lds(ctx, elem_size_bytes, store_val, write_mask, lds_offs.first, lds_offs.second, lds_align);
4421    }
4422 }
4423 
visit_load_tcs_output(isel_context * ctx,nir_intrinsic_instr * instr,bool per_vertex)4424 void visit_load_tcs_output(isel_context *ctx, nir_intrinsic_instr *instr, bool per_vertex)
4425 {
4426    assert(ctx->stage == tess_control_hs || ctx->stage == vertex_tess_control_hs);
4427    assert(ctx->shader->info.stage == MESA_SHADER_TESS_CTRL);
4428 
4429    Builder bld(ctx->program, ctx->block);
4430 
4431    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
4432    std::pair<Temp, unsigned> lds_offs = get_tcs_output_lds_offset(ctx, instr, per_vertex);
4433    unsigned lds_align = calculate_lds_alignment(ctx, lds_offs.second);
4434    unsigned elem_size_bytes = instr->src[0].ssa->bit_size / 8;
4435 
4436    load_lds(ctx, elem_size_bytes, dst, lds_offs.first, lds_offs.second, lds_align);
4437 }
4438 
visit_store_output(isel_context * ctx,nir_intrinsic_instr * instr)4439 void visit_store_output(isel_context *ctx, nir_intrinsic_instr *instr)
4440 {
4441    if (ctx->stage == vertex_vs ||
4442        ctx->stage == tess_eval_vs ||
4443        ctx->stage == fragment_fs ||
4444        ctx->stage == vertex_ngg ||
4445        ctx->stage == tess_eval_ngg ||
4446        ctx->shader->info.stage == MESA_SHADER_GEOMETRY) {
4447       bool stored_to_temps = store_output_to_temps(ctx, instr);
4448       if (!stored_to_temps) {
4449          isel_err(instr->src[1].ssa->parent_instr, "Unimplemented output offset instruction");
4450          abort();
4451       }
4452    } else if ((ctx->stage.hw == HWStage::LS || ctx->stage.hw == HWStage::ES) ||
4453               (ctx->stage == vertex_tess_control_hs && ctx->shader->info.stage == MESA_SHADER_VERTEX) ||
4454               (ctx->stage.has(SWStage::GS) && ctx->shader->info.stage != MESA_SHADER_GEOMETRY)) {
4455       visit_store_ls_or_es_output(ctx, instr);
4456    } else if (ctx->shader->info.stage == MESA_SHADER_TESS_CTRL) {
4457       visit_store_tcs_output(ctx, instr, false);
4458    } else {
4459       unreachable("Shader stage not implemented");
4460    }
4461 }
4462 
visit_load_output(isel_context * ctx,nir_intrinsic_instr * instr)4463 void visit_load_output(isel_context *ctx, nir_intrinsic_instr *instr)
4464 {
4465    visit_load_tcs_output(ctx, instr, false);
4466 }
4467 
emit_interp_instr(isel_context * ctx,unsigned idx,unsigned component,Temp src,Temp dst,Temp prim_mask)4468 void emit_interp_instr(isel_context *ctx, unsigned idx, unsigned component, Temp src, Temp dst, Temp prim_mask)
4469 {
4470    Temp coord1 = emit_extract_vector(ctx, src, 0, v1);
4471    Temp coord2 = emit_extract_vector(ctx, src, 1, v1);
4472 
4473    Builder bld(ctx->program, ctx->block);
4474 
4475    if (dst.regClass() == v2b) {
4476       if (ctx->program->has_16bank_lds) {
4477          assert(ctx->options->chip_class <= GFX8);
4478          Builder::Result interp_p1 =
4479             bld.vintrp(aco_opcode::v_interp_mov_f32, bld.def(v1),
4480                        Operand(2u) /* P0 */, bld.m0(prim_mask), idx, component);
4481          interp_p1 = bld.vintrp(aco_opcode::v_interp_p1lv_f16, bld.def(v2b),
4482                                 coord1, bld.m0(prim_mask), interp_p1, idx, component);
4483          bld.vintrp(aco_opcode::v_interp_p2_legacy_f16, Definition(dst), coord2,
4484                  bld.m0(prim_mask), interp_p1, idx, component);
4485       } else {
4486          aco_opcode interp_p2_op = aco_opcode::v_interp_p2_f16;
4487 
4488          if (ctx->options->chip_class == GFX8)
4489             interp_p2_op = aco_opcode::v_interp_p2_legacy_f16;
4490 
4491          Builder::Result interp_p1 =
4492             bld.vintrp(aco_opcode::v_interp_p1ll_f16, bld.def(v1),
4493                        coord1, bld.m0(prim_mask), idx, component);
4494          bld.vintrp(interp_p2_op, Definition(dst), coord2, bld.m0(prim_mask),
4495                     interp_p1, idx, component);
4496       }
4497    } else {
4498       Builder::Result interp_p1 =
4499          bld.vintrp(aco_opcode::v_interp_p1_f32, bld.def(v1), coord1,
4500                     bld.m0(prim_mask), idx, component);
4501 
4502       if (ctx->program->has_16bank_lds)
4503          interp_p1.instr->operands[0].setLateKill(true);
4504 
4505       bld.vintrp(aco_opcode::v_interp_p2_f32, Definition(dst), coord2,
4506                  bld.m0(prim_mask), interp_p1, idx, component);
4507    }
4508 }
4509 
emit_load_frag_coord(isel_context * ctx,Temp dst,unsigned num_components)4510 void emit_load_frag_coord(isel_context *ctx, Temp dst, unsigned num_components)
4511 {
4512    aco_ptr<Pseudo_instruction> vec(create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, num_components, 1));
4513    for (unsigned i = 0; i < num_components; i++)
4514       vec->operands[i] = Operand(get_arg(ctx, ctx->args->ac.frag_pos[i]));
4515    if (G_0286CC_POS_W_FLOAT_ENA(ctx->program->config->spi_ps_input_ena)) {
4516       assert(num_components == 4);
4517       Builder bld(ctx->program, ctx->block);
4518       vec->operands[3] = bld.vop1(aco_opcode::v_rcp_f32, bld.def(v1), get_arg(ctx, ctx->args->ac.frag_pos[3]));
4519    }
4520 
4521    for (Operand& op : vec->operands)
4522       op = op.isUndefined() ? Operand(0u) : op;
4523 
4524    vec->definitions[0] = Definition(dst);
4525    ctx->block->instructions.emplace_back(std::move(vec));
4526    emit_split_vector(ctx, dst, num_components);
4527    return;
4528 }
4529 
visit_load_interpolated_input(isel_context * ctx,nir_intrinsic_instr * instr)4530 void visit_load_interpolated_input(isel_context *ctx, nir_intrinsic_instr *instr)
4531 {
4532    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
4533    Temp coords = get_ssa_temp(ctx, instr->src[0].ssa);
4534    unsigned idx = nir_intrinsic_base(instr);
4535    unsigned component = nir_intrinsic_component(instr);
4536    Temp prim_mask = get_arg(ctx, ctx->args->ac.prim_mask);
4537 
4538    assert(nir_src_is_const(instr->src[1]) && !nir_src_as_uint(instr->src[1]));
4539 
4540    if (instr->dest.ssa.num_components == 1) {
4541       emit_interp_instr(ctx, idx, component, coords, dst, prim_mask);
4542    } else {
4543       aco_ptr<Pseudo_instruction> vec(create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, instr->dest.ssa.num_components, 1));
4544       for (unsigned i = 0; i < instr->dest.ssa.num_components; i++)
4545       {
4546          Temp tmp = ctx->program->allocateTmp(v1);
4547          emit_interp_instr(ctx, idx, component+i, coords, tmp, prim_mask);
4548          vec->operands[i] = Operand(tmp);
4549       }
4550       vec->definitions[0] = Definition(dst);
4551       ctx->block->instructions.emplace_back(std::move(vec));
4552    }
4553 }
4554 
check_vertex_fetch_size(isel_context * ctx,const ac_data_format_info * vtx_info,unsigned offset,unsigned stride,unsigned channels)4555 bool check_vertex_fetch_size(isel_context *ctx, const ac_data_format_info *vtx_info,
4556                              unsigned offset, unsigned stride, unsigned channels)
4557 {
4558    if (vtx_info->chan_byte_size != 4 && channels == 3)
4559       return false;
4560 
4561    /* Always split typed vertex buffer loads on GFX6 and GFX10+ to avoid any
4562     * alignment issues that triggers memory violations and eventually a GPU
4563     * hang. This can happen if the stride (static or dynamic) is unaligned and
4564     * also if the VBO offset is aligned to a scalar (eg. stride is 8 and VBO
4565     * offset is 2 for R16G16B16A16_SNORM).
4566     */
4567    return (ctx->options->chip_class >= GFX7 && ctx->options->chip_class <= GFX9) ||
4568           (channels == 1);
4569 }
4570 
get_fetch_data_format(isel_context * ctx,const ac_data_format_info * vtx_info,unsigned offset,unsigned stride,unsigned * channels)4571 uint8_t get_fetch_data_format(isel_context *ctx, const ac_data_format_info *vtx_info,
4572                               unsigned offset, unsigned stride, unsigned *channels)
4573 {
4574    if (!vtx_info->chan_byte_size) {
4575       *channels = vtx_info->num_channels;
4576       return vtx_info->chan_format;
4577    }
4578 
4579    unsigned num_channels = *channels;
4580    if (!check_vertex_fetch_size(ctx, vtx_info, offset, stride, *channels)) {
4581       unsigned new_channels = num_channels + 1;
4582       /* first, assume more loads is worse and try using a larger data format */
4583       while (new_channels <= 4 && !check_vertex_fetch_size(ctx, vtx_info, offset, stride, new_channels)) {
4584          new_channels++;
4585          /* don't make the attribute potentially out-of-bounds */
4586          if (offset + new_channels * vtx_info->chan_byte_size > stride)
4587             new_channels = 5;
4588       }
4589 
4590       if (new_channels == 5) {
4591          /* then try decreasing load size (at the cost of more loads) */
4592          new_channels = *channels;
4593          while (new_channels > 1 && !check_vertex_fetch_size(ctx, vtx_info, offset, stride, new_channels))
4594             new_channels--;
4595       }
4596 
4597       if (new_channels < *channels)
4598          *channels = new_channels;
4599       num_channels = new_channels;
4600    }
4601 
4602    switch (vtx_info->chan_format) {
4603    case V_008F0C_BUF_DATA_FORMAT_8:
4604       return (uint8_t[]){V_008F0C_BUF_DATA_FORMAT_8, V_008F0C_BUF_DATA_FORMAT_8_8,
4605                          V_008F0C_BUF_DATA_FORMAT_INVALID, V_008F0C_BUF_DATA_FORMAT_8_8_8_8}[num_channels - 1];
4606    case V_008F0C_BUF_DATA_FORMAT_16:
4607       return (uint8_t[]){V_008F0C_BUF_DATA_FORMAT_16, V_008F0C_BUF_DATA_FORMAT_16_16,
4608                          V_008F0C_BUF_DATA_FORMAT_INVALID, V_008F0C_BUF_DATA_FORMAT_16_16_16_16}[num_channels - 1];
4609    case V_008F0C_BUF_DATA_FORMAT_32:
4610       return (uint8_t[]){V_008F0C_BUF_DATA_FORMAT_32, V_008F0C_BUF_DATA_FORMAT_32_32,
4611                          V_008F0C_BUF_DATA_FORMAT_32_32_32, V_008F0C_BUF_DATA_FORMAT_32_32_32_32}[num_channels - 1];
4612    }
4613    unreachable("shouldn't reach here");
4614    return V_008F0C_BUF_DATA_FORMAT_INVALID;
4615 }
4616 
4617 /* For 2_10_10_10 formats the alpha is handled as unsigned by pre-vega HW.
4618  * so we may need to fix it up. */
adjust_vertex_fetch_alpha(isel_context * ctx,unsigned adjustment,Temp alpha)4619 Temp adjust_vertex_fetch_alpha(isel_context *ctx, unsigned adjustment, Temp alpha)
4620 {
4621    Builder bld(ctx->program, ctx->block);
4622 
4623    if (adjustment == AC_FETCH_FORMAT_SSCALED)
4624       alpha = bld.vop1(aco_opcode::v_cvt_u32_f32, bld.def(v1), alpha);
4625 
4626    /* For the integer-like cases, do a natural sign extension.
4627     *
4628     * For the SNORM case, the values are 0.0, 0.333, 0.666, 1.0
4629     * and happen to contain 0, 1, 2, 3 as the two LSBs of the
4630     * exponent.
4631     */
4632    alpha = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(adjustment == AC_FETCH_FORMAT_SNORM ? 7u : 30u), alpha);
4633    alpha = bld.vop2(aco_opcode::v_ashrrev_i32, bld.def(v1), Operand(30u), alpha);
4634 
4635    /* Convert back to the right type. */
4636    if (adjustment == AC_FETCH_FORMAT_SNORM) {
4637       alpha = bld.vop1(aco_opcode::v_cvt_f32_i32, bld.def(v1), alpha);
4638       Temp clamp = bld.vopc(aco_opcode::v_cmp_le_f32, bld.hint_vcc(bld.def(bld.lm)), Operand(0xbf800000u), alpha);
4639       alpha = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0xbf800000u), alpha, clamp);
4640    } else if (adjustment == AC_FETCH_FORMAT_SSCALED) {
4641       alpha = bld.vop1(aco_opcode::v_cvt_f32_i32, bld.def(v1), alpha);
4642    }
4643 
4644    return alpha;
4645 }
4646 
visit_load_input(isel_context * ctx,nir_intrinsic_instr * instr)4647 void visit_load_input(isel_context *ctx, nir_intrinsic_instr *instr)
4648 {
4649    Builder bld(ctx->program, ctx->block);
4650    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
4651    nir_src offset = *nir_get_io_offset_src(instr);
4652 
4653    if (ctx->shader->info.stage == MESA_SHADER_VERTEX) {
4654 
4655       if (!nir_src_is_const(offset) || nir_src_as_uint(offset))
4656          isel_err(offset.ssa->parent_instr, "Unimplemented non-zero nir_intrinsic_load_input offset");
4657 
4658       Temp vertex_buffers = convert_pointer_to_64_bit(ctx, get_arg(ctx, ctx->args->vertex_buffers));
4659 
4660       unsigned location = nir_intrinsic_base(instr) - VERT_ATTRIB_GENERIC0;
4661       unsigned component = nir_intrinsic_component(instr);
4662       unsigned bitsize = instr->dest.ssa.bit_size;
4663       unsigned attrib_binding = ctx->options->key.vs.vertex_attribute_bindings[location];
4664       uint32_t attrib_offset = ctx->options->key.vs.vertex_attribute_offsets[location];
4665       uint32_t attrib_stride = ctx->options->key.vs.vertex_attribute_strides[location];
4666       unsigned attrib_format = ctx->options->key.vs.vertex_attribute_formats[location];
4667       enum ac_fetch_format alpha_adjust = ctx->options->key.vs.alpha_adjust[location];
4668 
4669       unsigned dfmt = attrib_format & 0xf;
4670       unsigned nfmt = (attrib_format >> 4) & 0x7;
4671       const struct ac_data_format_info *vtx_info = ac_get_data_format_info(dfmt);
4672 
4673       unsigned mask = nir_ssa_def_components_read(&instr->dest.ssa) << component;
4674       unsigned num_channels = MIN2(util_last_bit(mask), vtx_info->num_channels);
4675       bool post_shuffle = ctx->options->key.vs.post_shuffle & (1 << location);
4676       if (post_shuffle)
4677          num_channels = MAX2(num_channels, 3);
4678 
4679       Operand off = bld.copy(bld.def(s1), Operand(attrib_binding * 16u));
4680       Temp list = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), vertex_buffers, off);
4681 
4682       Temp index;
4683       if (ctx->options->key.vs.instance_rate_inputs & (1u << location)) {
4684          uint32_t divisor = ctx->options->key.vs.instance_rate_divisors[location];
4685          Temp start_instance = get_arg(ctx, ctx->args->ac.start_instance);
4686          if (divisor) {
4687             Temp instance_id = get_arg(ctx, ctx->args->ac.instance_id);
4688             if (divisor != 1) {
4689                Temp divided = bld.tmp(v1);
4690                emit_v_div_u32(ctx, divided, as_vgpr(ctx, instance_id), divisor);
4691                index = bld.vadd32(bld.def(v1), start_instance, divided);
4692             } else {
4693                index = bld.vadd32(bld.def(v1), start_instance, instance_id);
4694             }
4695          } else {
4696             index = bld.copy(bld.def(v1), start_instance);
4697          }
4698       } else {
4699          index = bld.vadd32(bld.def(v1),
4700                             get_arg(ctx, ctx->args->ac.base_vertex),
4701                             get_arg(ctx, ctx->args->ac.vertex_id));
4702       }
4703 
4704       Temp *const channels = (Temp *)alloca(num_channels * sizeof(Temp));
4705       unsigned channel_start = 0;
4706       bool direct_fetch = false;
4707 
4708       /* skip unused channels at the start */
4709       if (vtx_info->chan_byte_size && !post_shuffle) {
4710          channel_start = ffs(mask) - 1;
4711          for (unsigned i = 0; i < MIN2(channel_start, num_channels); i++)
4712             channels[i] = Temp(0, s1);
4713       } else if (vtx_info->chan_byte_size && post_shuffle && !(mask & 0x8)) {
4714          num_channels = 3 - (ffs(mask) - 1);
4715       }
4716 
4717       /* load channels */
4718       while (channel_start < num_channels) {
4719          unsigned fetch_component = num_channels - channel_start;
4720          unsigned fetch_offset = attrib_offset + channel_start * vtx_info->chan_byte_size;
4721          bool expanded = false;
4722 
4723          /* use MUBUF when possible to avoid possible alignment issues */
4724          /* TODO: we could use SDWA to unpack 8/16-bit attributes without extra instructions */
4725          bool use_mubuf = (nfmt == V_008F0C_BUF_NUM_FORMAT_FLOAT ||
4726                            nfmt == V_008F0C_BUF_NUM_FORMAT_UINT ||
4727                            nfmt == V_008F0C_BUF_NUM_FORMAT_SINT) &&
4728                           vtx_info->chan_byte_size == 4;
4729          unsigned fetch_dfmt = V_008F0C_BUF_DATA_FORMAT_INVALID;
4730          if (!use_mubuf) {
4731             fetch_dfmt = get_fetch_data_format(ctx, vtx_info, fetch_offset, attrib_stride, &fetch_component);
4732          } else {
4733             if (fetch_component == 3 && ctx->options->chip_class == GFX6) {
4734                /* GFX6 only supports loading vec3 with MTBUF, expand to vec4. */
4735                fetch_component = 4;
4736                expanded = true;
4737             }
4738          }
4739 
4740          unsigned fetch_bytes = fetch_component * bitsize / 8;
4741 
4742          Temp fetch_index = index;
4743          if (attrib_stride != 0 && fetch_offset > attrib_stride) {
4744             fetch_index = bld.vadd32(bld.def(v1), Operand(fetch_offset / attrib_stride), fetch_index);
4745             fetch_offset = fetch_offset % attrib_stride;
4746          }
4747 
4748          Operand soffset(0u);
4749          if (fetch_offset >= 4096) {
4750             soffset = bld.copy(bld.def(s1), Operand(fetch_offset / 4096 * 4096));
4751             fetch_offset %= 4096;
4752          }
4753 
4754          aco_opcode opcode;
4755          switch (fetch_bytes) {
4756          case 2:
4757             assert(!use_mubuf && bitsize == 16);
4758             opcode = aco_opcode::tbuffer_load_format_d16_x;
4759             break;
4760          case 4:
4761             if (bitsize == 16) {
4762                assert(!use_mubuf);
4763                opcode = aco_opcode::tbuffer_load_format_d16_xy;
4764             } else {
4765                opcode = use_mubuf ? aco_opcode::buffer_load_dword : aco_opcode::tbuffer_load_format_x;
4766             }
4767             break;
4768          case 6:
4769             assert(!use_mubuf && bitsize == 16);
4770             opcode = aco_opcode::tbuffer_load_format_d16_xyz;
4771             break;
4772          case 8:
4773             if (bitsize == 16) {
4774                assert(!use_mubuf);
4775                opcode = aco_opcode::tbuffer_load_format_d16_xyzw;
4776             } else {
4777                opcode = use_mubuf ? aco_opcode::buffer_load_dwordx2 : aco_opcode::tbuffer_load_format_xy;
4778             }
4779             break;
4780          case 12:
4781             assert(ctx->options->chip_class >= GFX7 ||
4782                    (!use_mubuf && ctx->options->chip_class == GFX6));
4783             opcode = use_mubuf ? aco_opcode::buffer_load_dwordx3 : aco_opcode::tbuffer_load_format_xyz;
4784             break;
4785          case 16:
4786             opcode = use_mubuf ? aco_opcode::buffer_load_dwordx4 : aco_opcode::tbuffer_load_format_xyzw;
4787             break;
4788          default:
4789             unreachable("Unimplemented load_input vector size");
4790          }
4791 
4792          Temp fetch_dst;
4793          if (channel_start == 0 && fetch_bytes == dst.bytes() && !post_shuffle &&
4794              !expanded && (alpha_adjust == AC_FETCH_FORMAT_NONE ||
4795                            num_channels <= 3)) {
4796             direct_fetch = true;
4797             fetch_dst = dst;
4798          } else {
4799             fetch_dst = bld.tmp(RegClass::get(RegType::vgpr, fetch_bytes));
4800          }
4801 
4802          if (use_mubuf) {
4803             bld.mubuf(opcode,
4804                       Definition(fetch_dst), list, fetch_index, soffset,
4805                       fetch_offset, false, false, true).instr;
4806          } else {
4807             bld.mtbuf(opcode,
4808                       Definition(fetch_dst), list, fetch_index, soffset,
4809                       fetch_dfmt, nfmt, fetch_offset, false, true).instr;
4810          }
4811 
4812          emit_split_vector(ctx, fetch_dst, fetch_dst.size());
4813 
4814          if (fetch_component == 1) {
4815             channels[channel_start] = fetch_dst;
4816          } else {
4817             for (unsigned i = 0; i < MIN2(fetch_component, num_channels - channel_start); i++)
4818                channels[channel_start + i] = emit_extract_vector(ctx, fetch_dst, i,
4819                                                                  bitsize == 16 ? v2b : v1);
4820          }
4821 
4822          channel_start += fetch_component;
4823       }
4824 
4825       if (!direct_fetch) {
4826          bool is_float = nfmt != V_008F0C_BUF_NUM_FORMAT_UINT &&
4827                          nfmt != V_008F0C_BUF_NUM_FORMAT_SINT;
4828 
4829          static const unsigned swizzle_normal[4] = {0, 1, 2, 3};
4830          static const unsigned swizzle_post_shuffle[4] = {2, 1, 0, 3};
4831          const unsigned *swizzle = post_shuffle ? swizzle_post_shuffle : swizzle_normal;
4832          unsigned num_components = instr->dest.ssa.num_components;
4833 
4834          aco_ptr<Instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, num_components, 1)};
4835          std::array<Temp,NIR_MAX_VEC_COMPONENTS> elems;
4836          unsigned num_temp = 0;
4837          for (unsigned i = 0; i < num_components; i++) {
4838             unsigned idx = i + component;
4839             if (swizzle[idx] < num_channels && channels[swizzle[idx]].id()) {
4840                Temp channel = channels[swizzle[idx]];
4841                if (idx == 3 && alpha_adjust != AC_FETCH_FORMAT_NONE)
4842                   channel = adjust_vertex_fetch_alpha(ctx, alpha_adjust, channel);
4843                vec->operands[i] = Operand(channel);
4844 
4845                num_temp++;
4846                elems[i] = channel;
4847             } else if (is_float && idx == 3) {
4848                vec->operands[i] = Operand(0x3f800000u);
4849             } else if (!is_float && idx == 3) {
4850                vec->operands[i] = Operand(1u);
4851             } else {
4852                vec->operands[i] = Operand(0u);
4853             }
4854          }
4855          vec->definitions[0] = Definition(dst);
4856          ctx->block->instructions.emplace_back(std::move(vec));
4857          emit_split_vector(ctx, dst, num_components);
4858 
4859          if (num_temp == num_components)
4860             ctx->allocated_vec.emplace(dst.id(), elems);
4861       }
4862    } else if (ctx->shader->info.stage == MESA_SHADER_FRAGMENT) {
4863       if (!nir_src_is_const(offset) || nir_src_as_uint(offset))
4864          isel_err(offset.ssa->parent_instr, "Unimplemented non-zero nir_intrinsic_load_input offset");
4865 
4866       Temp prim_mask = get_arg(ctx, ctx->args->ac.prim_mask);
4867 
4868       unsigned idx = nir_intrinsic_base(instr);
4869       unsigned component = nir_intrinsic_component(instr);
4870       unsigned vertex_id = 2; /* P0 */
4871 
4872       if (instr->intrinsic == nir_intrinsic_load_input_vertex) {
4873          nir_const_value* src0 = nir_src_as_const_value(instr->src[0]);
4874          switch (src0->u32) {
4875          case 0:
4876             vertex_id = 2; /* P0 */
4877             break;
4878          case 1:
4879             vertex_id = 0; /* P10 */
4880             break;
4881          case 2:
4882             vertex_id = 1; /* P20 */
4883             break;
4884          default:
4885             unreachable("invalid vertex index");
4886          }
4887       }
4888 
4889       if (dst.size() == 1) {
4890          bld.vintrp(aco_opcode::v_interp_mov_f32, Definition(dst), Operand(vertex_id), bld.m0(prim_mask), idx, component);
4891       } else {
4892          aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, dst.size(), 1)};
4893          for (unsigned i = 0; i < dst.size(); i++)
4894             vec->operands[i] = bld.vintrp(aco_opcode::v_interp_mov_f32, bld.def(v1), Operand(vertex_id), bld.m0(prim_mask), idx, component + i);
4895          vec->definitions[0] = Definition(dst);
4896          bld.insert(std::move(vec));
4897       }
4898 
4899    } else if (ctx->shader->info.stage == MESA_SHADER_TESS_EVAL) {
4900       Temp ring = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), ctx->program->private_segment_buffer, Operand(RING_HS_TESS_OFFCHIP * 16u));
4901       Temp soffset = get_arg(ctx, ctx->args->oc_lds);
4902       std::pair<Temp, unsigned> offs = get_tcs_per_patch_output_vmem_offset(ctx, instr);
4903       unsigned elem_size_bytes = instr->dest.ssa.bit_size / 8u;
4904 
4905       load_vmem_mubuf(ctx, dst, ring, offs.first, soffset, offs.second, elem_size_bytes, instr->dest.ssa.num_components);
4906    } else {
4907       unreachable("Shader stage not implemented");
4908    }
4909 }
4910 
get_gs_per_vertex_input_offset(isel_context * ctx,nir_intrinsic_instr * instr,unsigned base_stride=1u)4911 std::pair<Temp, unsigned> get_gs_per_vertex_input_offset(isel_context *ctx, nir_intrinsic_instr *instr, unsigned base_stride = 1u)
4912 {
4913    assert(ctx->shader->info.stage == MESA_SHADER_GEOMETRY);
4914 
4915    bool merged_esgs = ctx->stage != geometry_gs;
4916    Builder bld(ctx->program, ctx->block);
4917    nir_src *vertex_src = nir_get_io_vertex_index_src(instr);
4918    Temp vertex_offset;
4919 
4920    if (!nir_src_is_const(*vertex_src)) {
4921       /* better code could be created, but this case probably doesn't happen
4922        * much in practice */
4923       Temp indirect_vertex = as_vgpr(ctx, get_ssa_temp(ctx, vertex_src->ssa));
4924       for (unsigned i = 0; i < ctx->shader->info.gs.vertices_in; i++) {
4925          Temp elem;
4926 
4927          if (merged_esgs) {
4928             elem = get_arg(ctx, ctx->args->gs_vtx_offset[i / 2u * 2u]);
4929             if (i % 2u)
4930                elem = bld.vop2(aco_opcode::v_lshrrev_b32, bld.def(v1), Operand(16u), elem);
4931          } else {
4932             elem = get_arg(ctx, ctx->args->gs_vtx_offset[i]);
4933          }
4934 
4935          if (vertex_offset.id()) {
4936             Temp cond = bld.vopc(aco_opcode::v_cmp_eq_u32, bld.hint_vcc(bld.def(bld.lm)),
4937                                  Operand(i), indirect_vertex);
4938             vertex_offset = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), vertex_offset, elem, cond);
4939          } else {
4940             vertex_offset = elem;
4941          }
4942       }
4943 
4944       if (merged_esgs)
4945          vertex_offset = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0xffffu), vertex_offset);
4946    } else {
4947       unsigned vertex = nir_src_as_uint(*vertex_src);
4948       if (merged_esgs)
4949          vertex_offset = bld.vop3(aco_opcode::v_bfe_u32, bld.def(v1),
4950                                   get_arg(ctx, ctx->args->gs_vtx_offset[vertex / 2u * 2u]),
4951                                   Operand((vertex % 2u) * 16u), Operand(16u));
4952       else
4953          vertex_offset = get_arg(ctx, ctx->args->gs_vtx_offset[vertex]);
4954    }
4955 
4956    std::pair<Temp, unsigned> offs = get_intrinsic_io_basic_offset(ctx, instr, base_stride);
4957    offs = offset_add(ctx, offs, std::make_pair(vertex_offset, 0u));
4958    return offset_mul(ctx, offs, 4u);
4959 }
4960 
visit_load_gs_per_vertex_input(isel_context * ctx,nir_intrinsic_instr * instr)4961 void visit_load_gs_per_vertex_input(isel_context *ctx, nir_intrinsic_instr *instr)
4962 {
4963    assert(ctx->shader->info.stage == MESA_SHADER_GEOMETRY);
4964 
4965    Builder bld(ctx->program, ctx->block);
4966    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
4967    unsigned elem_size_bytes = instr->dest.ssa.bit_size / 8;
4968 
4969    if (ctx->stage == geometry_gs) {
4970       std::pair<Temp, unsigned> offs = get_gs_per_vertex_input_offset(ctx, instr, ctx->program->wave_size);
4971       Temp ring = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), ctx->program->private_segment_buffer, Operand(RING_ESGS_GS * 16u));
4972       load_vmem_mubuf(ctx, dst, ring, offs.first, Temp(), offs.second, elem_size_bytes, instr->dest.ssa.num_components, 4u * ctx->program->wave_size, false, true);
4973    } else {
4974       std::pair<Temp, unsigned> offs = get_gs_per_vertex_input_offset(ctx, instr);
4975       unsigned lds_align = calculate_lds_alignment(ctx, offs.second);
4976       load_lds(ctx, elem_size_bytes, dst, offs.first, offs.second, lds_align);
4977    }
4978 }
4979 
visit_load_tcs_per_vertex_input(isel_context * ctx,nir_intrinsic_instr * instr)4980 void visit_load_tcs_per_vertex_input(isel_context *ctx, nir_intrinsic_instr *instr)
4981 {
4982    assert(ctx->shader->info.stage == MESA_SHADER_TESS_CTRL);
4983 
4984    Builder bld(ctx->program, ctx->block);
4985    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
4986 
4987    if (load_input_from_temps(ctx, instr, dst))
4988       return;
4989 
4990    std::pair<Temp, unsigned> offs = get_tcs_per_vertex_input_lds_offset(ctx, instr);
4991    unsigned elem_size_bytes = instr->dest.ssa.bit_size / 8;
4992    unsigned lds_align = calculate_lds_alignment(ctx, offs.second);
4993 
4994    load_lds(ctx, elem_size_bytes, dst, offs.first, offs.second, lds_align);
4995 }
4996 
visit_load_tes_per_vertex_input(isel_context * ctx,nir_intrinsic_instr * instr)4997 void visit_load_tes_per_vertex_input(isel_context *ctx, nir_intrinsic_instr *instr)
4998 {
4999    assert(ctx->shader->info.stage == MESA_SHADER_TESS_EVAL);
5000 
5001    Builder bld(ctx->program, ctx->block);
5002 
5003    Temp ring = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), ctx->program->private_segment_buffer, Operand(RING_HS_TESS_OFFCHIP * 16u));
5004    Temp oc_lds = get_arg(ctx, ctx->args->oc_lds);
5005    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
5006 
5007    unsigned elem_size_bytes = instr->dest.ssa.bit_size / 8;
5008    std::pair<Temp, unsigned> offs = get_tcs_per_vertex_output_vmem_offset(ctx, instr);
5009 
5010    load_vmem_mubuf(ctx, dst, ring, offs.first, oc_lds, offs.second, elem_size_bytes, instr->dest.ssa.num_components, 0u, true, true);
5011 }
5012 
visit_load_per_vertex_input(isel_context * ctx,nir_intrinsic_instr * instr)5013 void visit_load_per_vertex_input(isel_context *ctx, nir_intrinsic_instr *instr)
5014 {
5015    switch (ctx->shader->info.stage) {
5016    case MESA_SHADER_GEOMETRY:
5017       visit_load_gs_per_vertex_input(ctx, instr);
5018       break;
5019    case MESA_SHADER_TESS_CTRL:
5020       visit_load_tcs_per_vertex_input(ctx, instr);
5021       break;
5022    case MESA_SHADER_TESS_EVAL:
5023       visit_load_tes_per_vertex_input(ctx, instr);
5024       break;
5025    default:
5026       unreachable("Unimplemented shader stage");
5027    }
5028 }
5029 
visit_load_per_vertex_output(isel_context * ctx,nir_intrinsic_instr * instr)5030 void visit_load_per_vertex_output(isel_context *ctx, nir_intrinsic_instr *instr)
5031 {
5032    visit_load_tcs_output(ctx, instr, true);
5033 }
5034 
visit_store_per_vertex_output(isel_context * ctx,nir_intrinsic_instr * instr)5035 void visit_store_per_vertex_output(isel_context *ctx, nir_intrinsic_instr *instr)
5036 {
5037    assert(ctx->stage == tess_control_hs || ctx->stage == vertex_tess_control_hs);
5038    assert(ctx->shader->info.stage == MESA_SHADER_TESS_CTRL);
5039 
5040    visit_store_tcs_output(ctx, instr, true);
5041 }
5042 
visit_load_tess_coord(isel_context * ctx,nir_intrinsic_instr * instr)5043 void visit_load_tess_coord(isel_context *ctx, nir_intrinsic_instr *instr)
5044 {
5045    assert(ctx->shader->info.stage == MESA_SHADER_TESS_EVAL);
5046 
5047    Builder bld(ctx->program, ctx->block);
5048    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
5049 
5050    Operand tes_u(get_arg(ctx, ctx->args->tes_u));
5051    Operand tes_v(get_arg(ctx, ctx->args->tes_v));
5052    Operand tes_w(0u);
5053 
5054    if (ctx->shader->info.tess.primitive_mode == GL_TRIANGLES) {
5055       Temp tmp = bld.vop2(aco_opcode::v_add_f32, bld.def(v1), tes_u, tes_v);
5056       tmp = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1), Operand(0x3f800000u /* 1.0f */), tmp);
5057       tes_w = Operand(tmp);
5058    }
5059 
5060    Temp tess_coord = bld.pseudo(aco_opcode::p_create_vector, Definition(dst), tes_u, tes_v, tes_w);
5061    emit_split_vector(ctx, tess_coord, 3);
5062 }
5063 
load_desc_ptr(isel_context * ctx,unsigned desc_set)5064 Temp load_desc_ptr(isel_context *ctx, unsigned desc_set)
5065 {
5066    if (ctx->program->info->need_indirect_descriptor_sets) {
5067       Builder bld(ctx->program, ctx->block);
5068       Temp ptr64 = convert_pointer_to_64_bit(ctx, get_arg(ctx, ctx->args->descriptor_sets[0]));
5069       Operand off = bld.copy(bld.def(s1), Operand(desc_set << 2));
5070       return bld.smem(aco_opcode::s_load_dword, bld.def(s1), ptr64, off);//, false, false, false);
5071    }
5072 
5073    return get_arg(ctx, ctx->args->descriptor_sets[desc_set]);
5074 }
5075 
5076 
visit_load_resource(isel_context * ctx,nir_intrinsic_instr * instr)5077 void visit_load_resource(isel_context *ctx, nir_intrinsic_instr *instr)
5078 {
5079    Builder bld(ctx->program, ctx->block);
5080    Temp index = get_ssa_temp(ctx, instr->src[0].ssa);
5081    if (!nir_dest_is_divergent(instr->dest))
5082       index = bld.as_uniform(index);
5083    unsigned desc_set = nir_intrinsic_desc_set(instr);
5084    unsigned binding = nir_intrinsic_binding(instr);
5085 
5086    Temp desc_ptr;
5087    radv_pipeline_layout *pipeline_layout = ctx->options->layout;
5088    radv_descriptor_set_layout *layout = pipeline_layout->set[desc_set].layout;
5089    unsigned offset = layout->binding[binding].offset;
5090    unsigned stride;
5091    if (layout->binding[binding].type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC ||
5092        layout->binding[binding].type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
5093       unsigned idx = pipeline_layout->set[desc_set].dynamic_offset_start + layout->binding[binding].dynamic_offset_offset;
5094       desc_ptr = get_arg(ctx, ctx->args->ac.push_constants);
5095       offset = pipeline_layout->push_constant_size + 16 * idx;
5096       stride = 16;
5097    } else {
5098       desc_ptr = load_desc_ptr(ctx, desc_set);
5099       stride = layout->binding[binding].size;
5100    }
5101 
5102    nir_const_value* nir_const_index = nir_src_as_const_value(instr->src[0]);
5103    unsigned const_index = nir_const_index ? nir_const_index->u32 : 0;
5104    if (stride != 1) {
5105       if (nir_const_index) {
5106          const_index = const_index * stride;
5107       } else if (index.type() == RegType::vgpr) {
5108          bool index24bit = layout->binding[binding].array_size <= 0x1000000;
5109          index = bld.v_mul_imm(bld.def(v1), index, stride, index24bit);
5110       } else {
5111          index = bld.sop2(aco_opcode::s_mul_i32, bld.def(s1), Operand(stride), Operand(index));
5112       }
5113    }
5114    if (offset) {
5115       if (nir_const_index) {
5116          const_index = const_index + offset;
5117       } else if (index.type() == RegType::vgpr) {
5118          index = bld.vadd32(bld.def(v1), Operand(offset), index);
5119       } else {
5120          index = bld.sop2(aco_opcode::s_add_i32, bld.def(s1), bld.def(s1, scc), Operand(offset), Operand(index));
5121       }
5122    }
5123 
5124    if (nir_const_index && const_index == 0) {
5125       index = desc_ptr;
5126    } else if (index.type() == RegType::vgpr) {
5127       index = bld.vadd32(bld.def(v1),
5128                          nir_const_index ? Operand(const_index) : Operand(index),
5129                          Operand(desc_ptr));
5130    } else {
5131       index = bld.sop2(aco_opcode::s_add_i32, bld.def(s1), bld.def(s1, scc),
5132                        nir_const_index ? Operand(const_index) : Operand(index),
5133                        Operand(desc_ptr));
5134    }
5135 
5136    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
5137    std::array<Temp,NIR_MAX_VEC_COMPONENTS> elems;
5138    elems[0] = index;
5139    ctx->allocated_vec.emplace(dst.id(), elems);
5140    bld.pseudo(aco_opcode::p_create_vector, Definition(dst), index,
5141               Operand((unsigned)ctx->options->address32_hi));
5142 }
5143 
load_buffer(isel_context * ctx,unsigned num_components,unsigned component_size,Temp dst,Temp rsrc,Temp offset,unsigned align_mul,unsigned align_offset,bool glc=false,bool allow_smem=true,memory_sync_info sync=memory_sync_info ())5144 void load_buffer(isel_context *ctx, unsigned num_components, unsigned component_size,
5145                  Temp dst, Temp rsrc, Temp offset, unsigned align_mul, unsigned align_offset,
5146                  bool glc=false, bool allow_smem=true, memory_sync_info sync=memory_sync_info())
5147 {
5148    Builder bld(ctx->program, ctx->block);
5149 
5150    bool use_smem = dst.type() != RegType::vgpr && (!glc || ctx->options->chip_class >= GFX8) && allow_smem;
5151    if (use_smem)
5152       offset = bld.as_uniform(offset);
5153 
5154    LoadEmitInfo info = {Operand(offset), dst, num_components, component_size, rsrc};
5155    info.glc = glc;
5156    info.sync = sync;
5157    info.align_mul = align_mul;
5158    info.align_offset = align_offset;
5159    if (use_smem)
5160       emit_load(ctx, bld, info, smem_load_params);
5161    else
5162       emit_load(ctx, bld, info, mubuf_load_params);
5163 }
5164 
visit_load_ubo(isel_context * ctx,nir_intrinsic_instr * instr)5165 void visit_load_ubo(isel_context *ctx, nir_intrinsic_instr *instr)
5166 {
5167    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
5168    Temp rsrc = get_ssa_temp(ctx, instr->src[0].ssa);
5169 
5170    Builder bld(ctx->program, ctx->block);
5171 
5172    nir_alu_instr* mov_instr = nir_instr_as_alu(instr->src[0].ssa->parent_instr);
5173    nir_intrinsic_instr* idx_instr = nir_instr_as_intrinsic(mov_instr->src[0].src.ssa->parent_instr);
5174    unsigned desc_set = nir_intrinsic_desc_set(idx_instr);
5175    unsigned binding = nir_intrinsic_binding(idx_instr);
5176    radv_descriptor_set_layout *layout = ctx->options->layout->set[desc_set].layout;
5177 
5178    if (layout->binding[binding].type == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) {
5179       uint32_t desc_type = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
5180                            S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
5181                            S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
5182                            S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
5183       if (ctx->options->chip_class >= GFX10) {
5184          desc_type |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
5185                       S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
5186                       S_008F0C_RESOURCE_LEVEL(1);
5187       } else {
5188          desc_type |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
5189                       S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
5190       }
5191       Temp upper_dwords = bld.pseudo(aco_opcode::p_create_vector, bld.def(s3),
5192                                      Operand(S_008F04_BASE_ADDRESS_HI(ctx->options->address32_hi)),
5193                                      Operand(0xFFFFFFFFu),
5194                                      Operand(desc_type));
5195       rsrc = bld.pseudo(aco_opcode::p_create_vector, bld.def(s4),
5196                         rsrc, upper_dwords);
5197    } else {
5198       rsrc = convert_pointer_to_64_bit(ctx, rsrc);
5199       rsrc = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), rsrc, Operand(0u));
5200    }
5201    unsigned size = instr->dest.ssa.bit_size / 8;
5202    load_buffer(ctx, instr->num_components, size, dst, rsrc, get_ssa_temp(ctx, instr->src[1].ssa),
5203                nir_intrinsic_align_mul(instr), nir_intrinsic_align_offset(instr));
5204 }
5205 
visit_load_push_constant(isel_context * ctx,nir_intrinsic_instr * instr)5206 void visit_load_push_constant(isel_context *ctx, nir_intrinsic_instr *instr)
5207 {
5208    Builder bld(ctx->program, ctx->block);
5209    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
5210    unsigned offset = nir_intrinsic_base(instr);
5211    unsigned count = instr->dest.ssa.num_components;
5212    nir_const_value *index_cv = nir_src_as_const_value(instr->src[0]);
5213 
5214    if (index_cv && instr->dest.ssa.bit_size == 32) {
5215       unsigned start = (offset + index_cv->u32) / 4u;
5216       start -= ctx->args->ac.base_inline_push_consts;
5217       if (start + count <= ctx->args->ac.num_inline_push_consts) {
5218          std::array<Temp,NIR_MAX_VEC_COMPONENTS> elems;
5219          aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, count, 1)};
5220          for (unsigned i = 0; i < count; ++i) {
5221             elems[i] = get_arg(ctx, ctx->args->ac.inline_push_consts[start + i]);
5222             vec->operands[i] = Operand{elems[i]};
5223          }
5224          vec->definitions[0] = Definition(dst);
5225          ctx->block->instructions.emplace_back(std::move(vec));
5226          ctx->allocated_vec.emplace(dst.id(), elems);
5227          return;
5228       }
5229    }
5230 
5231    Temp index = bld.as_uniform(get_ssa_temp(ctx, instr->src[0].ssa));
5232    if (offset != 0) // TODO check if index != 0 as well
5233       index = bld.nuw().sop2(aco_opcode::s_add_i32, bld.def(s1), bld.def(s1, scc), Operand(offset), index);
5234    Temp ptr = convert_pointer_to_64_bit(ctx, get_arg(ctx, ctx->args->ac.push_constants));
5235    Temp vec = dst;
5236    bool trim = false;
5237    bool aligned = true;
5238 
5239    if (instr->dest.ssa.bit_size == 8) {
5240       aligned = index_cv && (offset + index_cv->u32) % 4 == 0;
5241       bool fits_in_dword = count == 1 || (index_cv && ((offset + index_cv->u32) % 4 + count) <= 4);
5242       if (!aligned)
5243          vec = fits_in_dword ? bld.tmp(s1) : bld.tmp(s2);
5244    } else if (instr->dest.ssa.bit_size == 16) {
5245       aligned = index_cv && (offset + index_cv->u32) % 4 == 0;
5246       if (!aligned)
5247          vec = count == 4 ? bld.tmp(s4) : count > 1 ? bld.tmp(s2) : bld.tmp(s1);
5248    }
5249 
5250    aco_opcode op;
5251 
5252    switch (vec.size()) {
5253    case 1:
5254       op = aco_opcode::s_load_dword;
5255       break;
5256    case 2:
5257       op = aco_opcode::s_load_dwordx2;
5258       break;
5259    case 3:
5260       vec = bld.tmp(s4);
5261       trim = true;
5262    case 4:
5263       op = aco_opcode::s_load_dwordx4;
5264       break;
5265    case 6:
5266       vec = bld.tmp(s8);
5267       trim = true;
5268    case 8:
5269       op = aco_opcode::s_load_dwordx8;
5270       break;
5271    default:
5272       unreachable("unimplemented or forbidden load_push_constant.");
5273    }
5274 
5275    static_cast<SMEM_instruction*>(bld.smem(op, Definition(vec), ptr, index).instr)->prevent_overflow = true;
5276 
5277    if (!aligned) {
5278       Operand byte_offset = index_cv ? Operand((offset + index_cv->u32) % 4) : Operand(index);
5279       byte_align_scalar(ctx, vec, byte_offset, dst);
5280       return;
5281    }
5282 
5283    if (trim) {
5284       emit_split_vector(ctx, vec, 4);
5285       RegClass rc = dst.size() == 3 ? s1 : s2;
5286       bld.pseudo(aco_opcode::p_create_vector, Definition(dst),
5287                  emit_extract_vector(ctx, vec, 0, rc),
5288                  emit_extract_vector(ctx, vec, 1, rc),
5289                  emit_extract_vector(ctx, vec, 2, rc));
5290 
5291    }
5292    emit_split_vector(ctx, dst, instr->dest.ssa.num_components);
5293 }
5294 
visit_load_constant(isel_context * ctx,nir_intrinsic_instr * instr)5295 void visit_load_constant(isel_context *ctx, nir_intrinsic_instr *instr)
5296 {
5297    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
5298 
5299    Builder bld(ctx->program, ctx->block);
5300 
5301    uint32_t desc_type = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
5302                         S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
5303                         S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
5304                         S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
5305    if (ctx->options->chip_class >= GFX10) {
5306       desc_type |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
5307                    S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
5308                    S_008F0C_RESOURCE_LEVEL(1);
5309    } else {
5310       desc_type |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
5311                    S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
5312    }
5313 
5314    unsigned base = nir_intrinsic_base(instr);
5315    unsigned range = nir_intrinsic_range(instr);
5316 
5317    Temp offset = get_ssa_temp(ctx, instr->src[0].ssa);
5318    if (base && offset.type() == RegType::sgpr)
5319       offset = bld.nuw().sop2(aco_opcode::s_add_u32, bld.def(s1), bld.def(s1, scc), offset, Operand(base));
5320    else if (base && offset.type() == RegType::vgpr)
5321       offset = bld.vadd32(bld.def(v1), Operand(base), offset);
5322 
5323    Temp rsrc = bld.pseudo(aco_opcode::p_create_vector, bld.def(s4),
5324                           bld.sop1(aco_opcode::p_constaddr, bld.def(s2), bld.def(s1, scc), Operand(ctx->constant_data_offset)),
5325                           Operand(MIN2(base + range, ctx->shader->constant_data_size)),
5326                           Operand(desc_type));
5327    unsigned size = instr->dest.ssa.bit_size / 8;
5328    // TODO: get alignment information for subdword constants
5329    load_buffer(ctx, instr->num_components, size, dst, rsrc, offset, size, 0);
5330 }
5331 
visit_discard_if(isel_context * ctx,nir_intrinsic_instr * instr)5332 void visit_discard_if(isel_context *ctx, nir_intrinsic_instr *instr)
5333 {
5334    if (ctx->cf_info.loop_nest_depth || ctx->cf_info.parent_if.is_divergent)
5335       ctx->cf_info.exec_potentially_empty_discard = true;
5336 
5337    ctx->program->needs_exact = true;
5338 
5339    // TODO: optimize uniform conditions
5340    Builder bld(ctx->program, ctx->block);
5341    Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
5342    assert(src.regClass() == bld.lm);
5343    src = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm));
5344    bld.pseudo(aco_opcode::p_discard_if, src);
5345    ctx->block->kind |= block_kind_uses_discard_if;
5346    return;
5347 }
5348 
visit_discard(isel_context * ctx,nir_intrinsic_instr * instr)5349 void visit_discard(isel_context* ctx, nir_intrinsic_instr *instr)
5350 {
5351    Builder bld(ctx->program, ctx->block);
5352 
5353    if (ctx->cf_info.loop_nest_depth || ctx->cf_info.parent_if.is_divergent)
5354       ctx->cf_info.exec_potentially_empty_discard = true;
5355 
5356    bool divergent = ctx->cf_info.parent_if.is_divergent ||
5357                     ctx->cf_info.parent_loop.has_divergent_continue;
5358 
5359    if (ctx->block->loop_nest_depth && (nir_instr_is_last(&instr->instr) && !divergent)) {
5360       /* we handle discards the same way as jump instructions */
5361       append_logical_end(ctx->block);
5362 
5363       /* in loops, discard behaves like break */
5364       Block *linear_target = ctx->cf_info.parent_loop.exit;
5365       ctx->block->kind |= block_kind_discard;
5366 
5367       /* uniform discard - loop ends here */
5368       assert(nir_instr_is_last(&instr->instr));
5369       ctx->block->kind |= block_kind_uniform;
5370       ctx->cf_info.has_branch = true;
5371       bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
5372       add_linear_edge(ctx->block->index, linear_target);
5373       return;
5374    }
5375 
5376    /* it can currently happen that NIR doesn't remove the unreachable code */
5377    if (!nir_instr_is_last(&instr->instr)) {
5378       ctx->program->needs_exact = true;
5379       /* save exec somewhere temporarily so that it doesn't get
5380        * overwritten before the discard from outer exec masks */
5381       Temp cond = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), Operand(0xFFFFFFFF), Operand(exec, bld.lm));
5382       bld.pseudo(aco_opcode::p_discard_if, cond);
5383       ctx->block->kind |= block_kind_uses_discard_if;
5384       return;
5385    }
5386 
5387    /* This condition is incorrect for uniformly branched discards in a loop
5388     * predicated by a divergent condition, but the above code catches that case
5389     * and the discard would end up turning into a discard_if.
5390     * For example:
5391     * if (divergent) {
5392     *    while (...) {
5393     *       if (uniform) {
5394     *          discard;
5395     *       }
5396     *    }
5397     * }
5398     */
5399    if (!ctx->cf_info.parent_if.is_divergent) {
5400       /* program just ends here */
5401       ctx->block->kind |= block_kind_uniform;
5402       bld.exp(aco_opcode::exp, Operand(v1), Operand(v1), Operand(v1), Operand(v1),
5403               0 /* enabled mask */, 9 /* dest */,
5404               false /* compressed */, true/* done */, true /* valid mask */);
5405       bld.sopp(aco_opcode::s_endpgm);
5406       // TODO: it will potentially be followed by a branch which is dead code to sanitize NIR phis
5407    } else {
5408       ctx->block->kind |= block_kind_discard;
5409       /* branch and linear edge is added by visit_if() */
5410    }
5411 }
5412 
5413 enum aco_descriptor_type {
5414    ACO_DESC_IMAGE,
5415    ACO_DESC_FMASK,
5416    ACO_DESC_SAMPLER,
5417    ACO_DESC_BUFFER,
5418    ACO_DESC_PLANE_0,
5419    ACO_DESC_PLANE_1,
5420    ACO_DESC_PLANE_2,
5421 };
5422 
5423 static bool
should_declare_array(isel_context * ctx,enum glsl_sampler_dim sampler_dim,bool is_array)5424 should_declare_array(isel_context *ctx, enum glsl_sampler_dim sampler_dim, bool is_array) {
5425    if (sampler_dim == GLSL_SAMPLER_DIM_BUF)
5426       return false;
5427    ac_image_dim dim = ac_get_sampler_dim(ctx->options->chip_class, sampler_dim, is_array);
5428    return dim == ac_image_cube ||
5429           dim == ac_image_1darray ||
5430           dim == ac_image_2darray ||
5431           dim == ac_image_2darraymsaa;
5432 }
5433 
get_sampler_desc(isel_context * ctx,nir_deref_instr * deref_instr,enum aco_descriptor_type desc_type,const nir_tex_instr * tex_instr,bool image,bool write)5434 Temp get_sampler_desc(isel_context *ctx, nir_deref_instr *deref_instr,
5435                       enum aco_descriptor_type desc_type,
5436                       const nir_tex_instr *tex_instr, bool image, bool write)
5437 {
5438 /* FIXME: we should lower the deref with some new nir_intrinsic_load_desc
5439    std::unordered_map<uint64_t, Temp>::iterator it = ctx->tex_desc.find((uint64_t) desc_type << 32 | deref_instr->dest.ssa.index);
5440    if (it != ctx->tex_desc.end())
5441       return it->second;
5442 */
5443    Temp index = Temp();
5444    bool index_set = false;
5445    unsigned constant_index = 0;
5446    unsigned descriptor_set;
5447    unsigned base_index;
5448    Builder bld(ctx->program, ctx->block);
5449 
5450    if (!deref_instr) {
5451       assert(tex_instr && !image);
5452       descriptor_set = 0;
5453       base_index = tex_instr->sampler_index;
5454    } else {
5455       while(deref_instr->deref_type != nir_deref_type_var) {
5456          unsigned array_size = glsl_get_aoa_size(deref_instr->type);
5457          if (!array_size)
5458             array_size = 1;
5459 
5460          assert(deref_instr->deref_type == nir_deref_type_array);
5461          nir_const_value *const_value = nir_src_as_const_value(deref_instr->arr.index);
5462          if (const_value) {
5463             constant_index += array_size * const_value->u32;
5464          } else {
5465             Temp indirect = get_ssa_temp(ctx, deref_instr->arr.index.ssa);
5466             if (indirect.type() == RegType::vgpr)
5467                indirect = bld.vop1(aco_opcode::v_readfirstlane_b32, bld.def(s1), indirect);
5468 
5469             if (array_size != 1)
5470                indirect = bld.sop2(aco_opcode::s_mul_i32, bld.def(s1), Operand(array_size), indirect);
5471 
5472             if (!index_set) {
5473                index = indirect;
5474                index_set = true;
5475             } else {
5476                index = bld.sop2(aco_opcode::s_add_i32, bld.def(s1), bld.def(s1, scc), index, indirect);
5477             }
5478          }
5479 
5480          deref_instr = nir_src_as_deref(deref_instr->parent);
5481       }
5482       descriptor_set = deref_instr->var->data.descriptor_set;
5483       base_index = deref_instr->var->data.binding;
5484    }
5485 
5486    Temp list = load_desc_ptr(ctx, descriptor_set);
5487    list = convert_pointer_to_64_bit(ctx, list);
5488 
5489    struct radv_descriptor_set_layout *layout = ctx->options->layout->set[descriptor_set].layout;
5490    struct radv_descriptor_set_binding_layout *binding = layout->binding + base_index;
5491    unsigned offset = binding->offset;
5492    unsigned stride = binding->size;
5493    aco_opcode opcode;
5494    RegClass type;
5495 
5496    assert(base_index < layout->binding_count);
5497 
5498    switch (desc_type) {
5499    case ACO_DESC_IMAGE:
5500       type = s8;
5501       opcode = aco_opcode::s_load_dwordx8;
5502       break;
5503    case ACO_DESC_FMASK:
5504       type = s8;
5505       opcode = aco_opcode::s_load_dwordx8;
5506       offset += 32;
5507       break;
5508    case ACO_DESC_SAMPLER:
5509       type = s4;
5510       opcode = aco_opcode::s_load_dwordx4;
5511       if (binding->type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
5512          offset += radv_combined_image_descriptor_sampler_offset(binding);
5513       break;
5514    case ACO_DESC_BUFFER:
5515       type = s4;
5516       opcode = aco_opcode::s_load_dwordx4;
5517       break;
5518    case ACO_DESC_PLANE_0:
5519    case ACO_DESC_PLANE_1:
5520       type = s8;
5521       opcode = aco_opcode::s_load_dwordx8;
5522       offset += 32 * (desc_type - ACO_DESC_PLANE_0);
5523       break;
5524    case ACO_DESC_PLANE_2:
5525       type = s4;
5526       opcode = aco_opcode::s_load_dwordx4;
5527       offset += 64;
5528       break;
5529    default:
5530       unreachable("invalid desc_type\n");
5531    }
5532 
5533    offset += constant_index * stride;
5534 
5535    if (desc_type == ACO_DESC_SAMPLER && binding->immutable_samplers_offset &&
5536       (!index_set || binding->immutable_samplers_equal)) {
5537       if (binding->immutable_samplers_equal)
5538          constant_index = 0;
5539 
5540       const uint32_t *samplers = radv_immutable_samplers(layout, binding);
5541       return bld.pseudo(aco_opcode::p_create_vector, bld.def(s4),
5542                         Operand(samplers[constant_index * 4 + 0]),
5543                         Operand(samplers[constant_index * 4 + 1]),
5544                         Operand(samplers[constant_index * 4 + 2]),
5545                         Operand(samplers[constant_index * 4 + 3]));
5546    }
5547 
5548    Operand off;
5549    if (!index_set) {
5550       off = bld.copy(bld.def(s1), Operand(offset));
5551    } else {
5552       off = Operand((Temp)bld.sop2(aco_opcode::s_add_i32, bld.def(s1), bld.def(s1, scc), Operand(offset),
5553                                    bld.sop2(aco_opcode::s_mul_i32, bld.def(s1), Operand(stride), index)));
5554    }
5555 
5556    Temp res = bld.smem(opcode, bld.def(type), list, off);
5557 
5558    if (desc_type == ACO_DESC_PLANE_2) {
5559       Temp components[8];
5560       for (unsigned i = 0; i < 8; i++)
5561          components[i] = bld.tmp(s1);
5562       bld.pseudo(aco_opcode::p_split_vector,
5563                  Definition(components[0]),
5564                  Definition(components[1]),
5565                  Definition(components[2]),
5566                  Definition(components[3]),
5567                  res);
5568 
5569       Temp desc2 = get_sampler_desc(ctx, deref_instr, ACO_DESC_PLANE_1, tex_instr, image, write);
5570       bld.pseudo(aco_opcode::p_split_vector,
5571                  bld.def(s1), bld.def(s1), bld.def(s1), bld.def(s1),
5572                  Definition(components[4]),
5573                  Definition(components[5]),
5574                  Definition(components[6]),
5575                  Definition(components[7]),
5576                  desc2);
5577 
5578       res = bld.pseudo(aco_opcode::p_create_vector, bld.def(s8),
5579                        components[0], components[1], components[2], components[3],
5580                        components[4], components[5], components[6], components[7]);
5581    }
5582 
5583    return res;
5584 }
5585 
image_type_to_components_count(enum glsl_sampler_dim dim,bool array)5586 static int image_type_to_components_count(enum glsl_sampler_dim dim, bool array)
5587 {
5588    switch (dim) {
5589    case GLSL_SAMPLER_DIM_BUF:
5590       return 1;
5591    case GLSL_SAMPLER_DIM_1D:
5592       return array ? 2 : 1;
5593    case GLSL_SAMPLER_DIM_2D:
5594       return array ? 3 : 2;
5595    case GLSL_SAMPLER_DIM_MS:
5596       return array ? 4 : 3;
5597    case GLSL_SAMPLER_DIM_3D:
5598    case GLSL_SAMPLER_DIM_CUBE:
5599       return 3;
5600    case GLSL_SAMPLER_DIM_RECT:
5601    case GLSL_SAMPLER_DIM_SUBPASS:
5602       return 2;
5603    case GLSL_SAMPLER_DIM_SUBPASS_MS:
5604       return 3;
5605    default:
5606       break;
5607    }
5608    return 0;
5609 }
5610 
5611 
5612 /* Adjust the sample index according to FMASK.
5613  *
5614  * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
5615  * which is the identity mapping. Each nibble says which physical sample
5616  * should be fetched to get that sample.
5617  *
5618  * For example, 0x11111100 means there are only 2 samples stored and
5619  * the second sample covers 3/4 of the pixel. When reading samples 0
5620  * and 1, return physical sample 0 (determined by the first two 0s
5621  * in FMASK), otherwise return physical sample 1.
5622  *
5623  * The sample index should be adjusted as follows:
5624  *   sample_index = (fmask >> (sample_index * 4)) & 0xF;
5625  */
adjust_sample_index_using_fmask(isel_context * ctx,bool da,std::vector<Temp> & coords,Operand sample_index,Temp fmask_desc_ptr)5626 static Temp adjust_sample_index_using_fmask(isel_context *ctx, bool da, std::vector<Temp>& coords, Operand sample_index, Temp fmask_desc_ptr)
5627 {
5628    Builder bld(ctx->program, ctx->block);
5629    Temp fmask = bld.tmp(v1);
5630    unsigned dim = ctx->options->chip_class >= GFX10
5631                   ? ac_get_sampler_dim(ctx->options->chip_class, GLSL_SAMPLER_DIM_2D, da)
5632                   : 0;
5633 
5634    Temp coord = da ? bld.pseudo(aco_opcode::p_create_vector, bld.def(v3), coords[0], coords[1], coords[2]) :
5635                      bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), coords[0], coords[1]);
5636    aco_ptr<MIMG_instruction> load{create_instruction<MIMG_instruction>(aco_opcode::image_load, Format::MIMG, 3, 1)};
5637    load->operands[0] = Operand(fmask_desc_ptr);
5638    load->operands[1] = Operand(s4); /* no sampler */
5639    load->operands[2] = Operand(coord);
5640    load->definitions[0] = Definition(fmask);
5641    load->glc = false;
5642    load->dlc = false;
5643    load->dmask = 0x1;
5644    load->unrm = true;
5645    load->da = da;
5646    load->dim = dim;
5647    ctx->block->instructions.emplace_back(std::move(load));
5648 
5649    Operand sample_index4;
5650    if (sample_index.isConstant()) {
5651       if (sample_index.constantValue() < 16) {
5652          sample_index4 = Operand(sample_index.constantValue() << 2);
5653       } else {
5654          sample_index4 = Operand(0u);
5655       }
5656    } else if (sample_index.regClass() == s1) {
5657       sample_index4 = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), sample_index, Operand(2u));
5658    } else {
5659       assert(sample_index.regClass() == v1);
5660       sample_index4 = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(2u), sample_index);
5661    }
5662 
5663    Temp final_sample;
5664    if (sample_index4.isConstant() && sample_index4.constantValue() == 0)
5665       final_sample = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(15u), fmask);
5666    else if (sample_index4.isConstant() && sample_index4.constantValue() == 28)
5667       final_sample = bld.vop2(aco_opcode::v_lshrrev_b32, bld.def(v1), Operand(28u), fmask);
5668    else
5669       final_sample = bld.vop3(aco_opcode::v_bfe_u32, bld.def(v1), fmask, sample_index4, Operand(4u));
5670 
5671    /* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
5672     * resource descriptor is 0 (invalid),
5673     */
5674    Temp compare = bld.tmp(bld.lm);
5675    bld.vopc_e64(aco_opcode::v_cmp_lg_u32, Definition(compare),
5676                 Operand(0u), emit_extract_vector(ctx, fmask_desc_ptr, 1, s1)).def(0).setHint(vcc);
5677 
5678    Temp sample_index_v = bld.copy(bld.def(v1), sample_index);
5679 
5680    /* Replace the MSAA sample index. */
5681    return bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), sample_index_v, final_sample, compare);
5682 }
5683 
get_image_coords(isel_context * ctx,const nir_intrinsic_instr * instr,const struct glsl_type * type)5684 static Temp get_image_coords(isel_context *ctx, const nir_intrinsic_instr *instr, const struct glsl_type *type)
5685 {
5686 
5687    Temp src0 = get_ssa_temp(ctx, instr->src[1].ssa);
5688    enum glsl_sampler_dim dim = glsl_get_sampler_dim(type);
5689    bool is_array = glsl_sampler_type_is_array(type);
5690    ASSERTED bool add_frag_pos = (dim == GLSL_SAMPLER_DIM_SUBPASS || dim == GLSL_SAMPLER_DIM_SUBPASS_MS);
5691    assert(!add_frag_pos && "Input attachments should be lowered.");
5692    bool is_ms = (dim == GLSL_SAMPLER_DIM_MS || dim == GLSL_SAMPLER_DIM_SUBPASS_MS);
5693    bool gfx9_1d = ctx->options->chip_class == GFX9 && dim == GLSL_SAMPLER_DIM_1D;
5694    int count = image_type_to_components_count(dim, is_array);
5695    std::vector<Temp> coords(count);
5696    Builder bld(ctx->program, ctx->block);
5697 
5698    if (is_ms) {
5699       count--;
5700       Temp src2 = get_ssa_temp(ctx, instr->src[2].ssa);
5701       /* get sample index */
5702       if (instr->intrinsic == nir_intrinsic_image_deref_load) {
5703          nir_const_value *sample_cv = nir_src_as_const_value(instr->src[2]);
5704          Operand sample_index = sample_cv ? Operand(sample_cv->u32) : Operand(emit_extract_vector(ctx, src2, 0, v1));
5705          std::vector<Temp> fmask_load_address;
5706          for (unsigned i = 0; i < (is_array ? 3 : 2); i++)
5707             fmask_load_address.emplace_back(emit_extract_vector(ctx, src0, i, v1));
5708 
5709          Temp fmask_desc_ptr = get_sampler_desc(ctx, nir_instr_as_deref(instr->src[0].ssa->parent_instr), ACO_DESC_FMASK, nullptr, false, false);
5710          coords[count] = adjust_sample_index_using_fmask(ctx, is_array, fmask_load_address, sample_index, fmask_desc_ptr);
5711       } else {
5712          coords[count] = emit_extract_vector(ctx, src2, 0, v1);
5713       }
5714    }
5715 
5716    if (gfx9_1d) {
5717       coords[0] = emit_extract_vector(ctx, src0, 0, v1);
5718       coords.resize(coords.size() + 1);
5719       coords[1] = bld.copy(bld.def(v1), Operand(0u));
5720       if (is_array)
5721          coords[2] = emit_extract_vector(ctx, src0, 1, v1);
5722    } else {
5723       for (int i = 0; i < count; i++)
5724          coords[i] = emit_extract_vector(ctx, src0, i, v1);
5725    }
5726 
5727    if (instr->intrinsic == nir_intrinsic_image_deref_load ||
5728        instr->intrinsic == nir_intrinsic_image_deref_store) {
5729       int lod_index = instr->intrinsic == nir_intrinsic_image_deref_load ? 3 : 4;
5730       bool level_zero = nir_src_is_const(instr->src[lod_index]) && nir_src_as_uint(instr->src[lod_index]) == 0;
5731 
5732       if (!level_zero)
5733          coords.emplace_back(get_ssa_temp(ctx, instr->src[lod_index].ssa));
5734    }
5735 
5736    aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, coords.size(), 1)};
5737    for (unsigned i = 0; i < coords.size(); i++)
5738       vec->operands[i] = Operand(coords[i]);
5739    Temp res = ctx->program->allocateTmp(RegClass(RegType::vgpr, coords.size()));
5740    vec->definitions[0] = Definition(res);
5741    ctx->block->instructions.emplace_back(std::move(vec));
5742    return res;
5743 }
5744 
5745 
get_memory_sync_info(nir_intrinsic_instr * instr,storage_class storage,unsigned semantics)5746 memory_sync_info get_memory_sync_info(nir_intrinsic_instr *instr, storage_class storage, unsigned semantics)
5747 {
5748    /* atomicrmw might not have NIR_INTRINSIC_ACCESS and there's nothing interesting there anyway */
5749    if (semantics & semantic_atomicrmw)
5750       return memory_sync_info(storage, semantics);
5751 
5752    unsigned access = nir_intrinsic_access(instr);
5753 
5754    if (access & ACCESS_VOLATILE)
5755       semantics |= semantic_volatile;
5756    if (access & ACCESS_CAN_REORDER)
5757       semantics |= semantic_can_reorder | semantic_private;
5758 
5759    return memory_sync_info(storage, semantics);
5760 }
5761 
visit_image_load(isel_context * ctx,nir_intrinsic_instr * instr)5762 void visit_image_load(isel_context *ctx, nir_intrinsic_instr *instr)
5763 {
5764    Builder bld(ctx->program, ctx->block);
5765    const nir_variable *var = nir_deref_instr_get_variable(nir_instr_as_deref(instr->src[0].ssa->parent_instr));
5766    const struct glsl_type *type = glsl_without_array(var->type);
5767    const enum glsl_sampler_dim dim = glsl_get_sampler_dim(type);
5768    bool is_array = glsl_sampler_type_is_array(type);
5769    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
5770 
5771    memory_sync_info sync = get_memory_sync_info(instr, storage_image, 0);
5772    unsigned access = var->data.access | nir_intrinsic_access(instr);
5773 
5774    unsigned expand_mask = nir_ssa_def_components_read(&instr->dest.ssa);
5775    if (dim == GLSL_SAMPLER_DIM_BUF)
5776       expand_mask = (1u << util_last_bit(expand_mask)) - 1;
5777    unsigned dmask = expand_mask;
5778    if (instr->dest.ssa.bit_size == 64) {
5779       expand_mask &= 0x9;
5780       /* only R64_UINT and R64_SINT supported. x is in xy of the result, w in zw */
5781       dmask = ((expand_mask & 0x1) ? 0x3 : 0) | ((expand_mask & 0x8) ? 0xc : 0);
5782    }
5783    unsigned num_components = util_bitcount(dmask);
5784 
5785    Temp tmp;
5786    if (num_components == dst.size() && dst.type() == RegType::vgpr)
5787       tmp = dst;
5788    else
5789       tmp = ctx->program->allocateTmp(RegClass(RegType::vgpr, num_components));
5790 
5791    Temp resource = get_sampler_desc(ctx, nir_instr_as_deref(instr->src[0].ssa->parent_instr),
5792                                     dim == GLSL_SAMPLER_DIM_BUF ? ACO_DESC_BUFFER : ACO_DESC_IMAGE,
5793                                     nullptr, true, true);
5794 
5795    if (dim == GLSL_SAMPLER_DIM_BUF) {
5796       Temp vindex = emit_extract_vector(ctx, get_ssa_temp(ctx, instr->src[1].ssa), 0, v1);
5797 
5798       aco_opcode opcode;
5799       switch (num_components) {
5800       case 1:
5801          opcode = aco_opcode::buffer_load_format_x;
5802          break;
5803       case 2:
5804          opcode = aco_opcode::buffer_load_format_xy;
5805          break;
5806       case 3:
5807          opcode = aco_opcode::buffer_load_format_xyz;
5808          break;
5809       case 4:
5810          opcode = aco_opcode::buffer_load_format_xyzw;
5811          break;
5812       default:
5813          unreachable(">4 channel buffer image load");
5814       }
5815       aco_ptr<MUBUF_instruction> load{create_instruction<MUBUF_instruction>(opcode, Format::MUBUF, 3, 1)};
5816       load->operands[0] = Operand(resource);
5817       load->operands[1] = Operand(vindex);
5818       load->operands[2] = Operand((uint32_t) 0);
5819       load->definitions[0] = Definition(tmp);
5820       load->idxen = true;
5821       load->glc = access & (ACCESS_VOLATILE | ACCESS_COHERENT);
5822       load->dlc = load->glc && ctx->options->chip_class >= GFX10;
5823       load->sync = sync;
5824       ctx->block->instructions.emplace_back(std::move(load));
5825    } else {
5826       Temp coords = get_image_coords(ctx, instr, type);
5827 
5828       bool level_zero = nir_src_is_const(instr->src[3]) && nir_src_as_uint(instr->src[3]) == 0;
5829       aco_opcode opcode = level_zero ? aco_opcode::image_load : aco_opcode::image_load_mip;
5830 
5831       aco_ptr<MIMG_instruction> load{create_instruction<MIMG_instruction>(opcode, Format::MIMG, 3, 1)};
5832       load->operands[0] = Operand(resource);
5833       load->operands[1] = Operand(s4); /* no sampler */
5834       load->operands[2] = Operand(coords);
5835       load->definitions[0] = Definition(tmp);
5836       load->glc = access & (ACCESS_VOLATILE | ACCESS_COHERENT) ? 1 : 0;
5837       load->dlc = load->glc && ctx->options->chip_class >= GFX10;
5838       load->dim = ac_get_image_dim(ctx->options->chip_class, dim, is_array);
5839       load->dmask = dmask;
5840       load->unrm = true;
5841       load->da = should_declare_array(ctx, dim, glsl_sampler_type_is_array(type));
5842       load->sync = sync;
5843       ctx->block->instructions.emplace_back(std::move(load));
5844    }
5845 
5846    expand_vector(ctx, tmp, dst, instr->dest.ssa.num_components, expand_mask);
5847 }
5848 
visit_image_store(isel_context * ctx,nir_intrinsic_instr * instr)5849 void visit_image_store(isel_context *ctx, nir_intrinsic_instr *instr)
5850 {
5851    const nir_variable *var = nir_deref_instr_get_variable(nir_instr_as_deref(instr->src[0].ssa->parent_instr));
5852    const struct glsl_type *type = glsl_without_array(var->type);
5853    const enum glsl_sampler_dim dim = glsl_get_sampler_dim(type);
5854    bool is_array = glsl_sampler_type_is_array(type);
5855    Temp data = get_ssa_temp(ctx, instr->src[3].ssa);
5856 
5857    /* only R64_UINT and R64_SINT supported */
5858    if (instr->src[3].ssa->bit_size == 64 && data.bytes() > 8)
5859       data = emit_extract_vector(ctx, data, 0, RegClass(data.type(), 2));
5860    data = as_vgpr(ctx, data);
5861 
5862    memory_sync_info sync = get_memory_sync_info(instr, storage_image, 0);
5863    unsigned access = var->data.access | nir_intrinsic_access(instr);
5864    bool glc = ctx->options->chip_class == GFX6 || access & (ACCESS_VOLATILE | ACCESS_COHERENT | ACCESS_NON_READABLE) ? 1 : 0;
5865 
5866    if (dim == GLSL_SAMPLER_DIM_BUF) {
5867       Temp rsrc = get_sampler_desc(ctx, nir_instr_as_deref(instr->src[0].ssa->parent_instr), ACO_DESC_BUFFER, nullptr, true, true);
5868       Temp vindex = emit_extract_vector(ctx, get_ssa_temp(ctx, instr->src[1].ssa), 0, v1);
5869       aco_opcode opcode;
5870       switch (data.size()) {
5871       case 1:
5872          opcode = aco_opcode::buffer_store_format_x;
5873          break;
5874       case 2:
5875          opcode = aco_opcode::buffer_store_format_xy;
5876          break;
5877       case 3:
5878          opcode = aco_opcode::buffer_store_format_xyz;
5879          break;
5880       case 4:
5881          opcode = aco_opcode::buffer_store_format_xyzw;
5882          break;
5883       default:
5884          unreachable(">4 channel buffer image store");
5885       }
5886       aco_ptr<MUBUF_instruction> store{create_instruction<MUBUF_instruction>(opcode, Format::MUBUF, 4, 0)};
5887       store->operands[0] = Operand(rsrc);
5888       store->operands[1] = Operand(vindex);
5889       store->operands[2] = Operand((uint32_t) 0);
5890       store->operands[3] = Operand(data);
5891       store->idxen = true;
5892       store->glc = glc;
5893       store->dlc = false;
5894       store->disable_wqm = true;
5895       store->sync = sync;
5896       ctx->program->needs_exact = true;
5897       ctx->block->instructions.emplace_back(std::move(store));
5898       return;
5899    }
5900 
5901    assert(data.type() == RegType::vgpr);
5902    Temp coords = get_image_coords(ctx, instr, type);
5903    Temp resource = get_sampler_desc(ctx, nir_instr_as_deref(instr->src[0].ssa->parent_instr), ACO_DESC_IMAGE, nullptr, true, true);
5904 
5905    bool level_zero = nir_src_is_const(instr->src[4]) && nir_src_as_uint(instr->src[4]) == 0;
5906    aco_opcode opcode = level_zero ? aco_opcode::image_store : aco_opcode::image_store_mip;
5907 
5908    aco_ptr<MIMG_instruction> store{create_instruction<MIMG_instruction>(opcode, Format::MIMG, 3, 0)};
5909    store->operands[0] = Operand(resource);
5910    store->operands[1] = Operand(data);
5911    store->operands[2] = Operand(coords);
5912    store->glc = glc;
5913    store->dlc = false;
5914    store->dim = ac_get_image_dim(ctx->options->chip_class, dim, is_array);
5915    store->dmask = (1 << data.size()) - 1;
5916    store->unrm = true;
5917    store->da = should_declare_array(ctx, dim, glsl_sampler_type_is_array(type));
5918    store->disable_wqm = true;
5919    store->sync = sync;
5920    ctx->program->needs_exact = true;
5921    ctx->block->instructions.emplace_back(std::move(store));
5922    return;
5923 }
5924 
visit_image_atomic(isel_context * ctx,nir_intrinsic_instr * instr)5925 void visit_image_atomic(isel_context *ctx, nir_intrinsic_instr *instr)
5926 {
5927    /* return the previous value if dest is ever used */
5928    bool return_previous = false;
5929    nir_foreach_use_safe(use_src, &instr->dest.ssa) {
5930       return_previous = true;
5931       break;
5932    }
5933    nir_foreach_if_use_safe(use_src, &instr->dest.ssa) {
5934       return_previous = true;
5935       break;
5936    }
5937 
5938    const nir_variable *var = nir_deref_instr_get_variable(nir_instr_as_deref(instr->src[0].ssa->parent_instr));
5939    const struct glsl_type *type = glsl_without_array(var->type);
5940    const enum glsl_sampler_dim dim = glsl_get_sampler_dim(type);
5941    bool is_array = glsl_sampler_type_is_array(type);
5942    Builder bld(ctx->program, ctx->block);
5943 
5944    Temp data = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[3].ssa));
5945    bool is_64bit = data.bytes() == 8;
5946    assert((data.bytes() == 4 || data.bytes() == 8) && "only 32/64-bit image atomics implemented.");
5947 
5948    if (instr->intrinsic == nir_intrinsic_image_deref_atomic_comp_swap)
5949       data = bld.pseudo(aco_opcode::p_create_vector, bld.def(is_64bit ? v4 : v2), get_ssa_temp(ctx, instr->src[4].ssa), data);
5950 
5951    aco_opcode buf_op, buf_op64, image_op;
5952    switch (instr->intrinsic) {
5953       case nir_intrinsic_image_deref_atomic_add:
5954          buf_op = aco_opcode::buffer_atomic_add;
5955          buf_op64 = aco_opcode::buffer_atomic_add_x2;
5956          image_op = aco_opcode::image_atomic_add;
5957          break;
5958       case nir_intrinsic_image_deref_atomic_umin:
5959          buf_op = aco_opcode::buffer_atomic_umin;
5960          buf_op64 = aco_opcode::buffer_atomic_umin_x2;
5961          image_op = aco_opcode::image_atomic_umin;
5962          break;
5963       case nir_intrinsic_image_deref_atomic_imin:
5964          buf_op = aco_opcode::buffer_atomic_smin;
5965          buf_op64 = aco_opcode::buffer_atomic_smin_x2;
5966          image_op = aco_opcode::image_atomic_smin;
5967          break;
5968       case nir_intrinsic_image_deref_atomic_umax:
5969          buf_op = aco_opcode::buffer_atomic_umax;
5970          buf_op64 = aco_opcode::buffer_atomic_umax_x2;
5971          image_op = aco_opcode::image_atomic_umax;
5972          break;
5973       case nir_intrinsic_image_deref_atomic_imax:
5974          buf_op = aco_opcode::buffer_atomic_smax;
5975          buf_op64 = aco_opcode::buffer_atomic_smax_x2;
5976          image_op = aco_opcode::image_atomic_smax;
5977          break;
5978       case nir_intrinsic_image_deref_atomic_and:
5979          buf_op = aco_opcode::buffer_atomic_and;
5980          buf_op64 = aco_opcode::buffer_atomic_and_x2;
5981          image_op = aco_opcode::image_atomic_and;
5982          break;
5983       case nir_intrinsic_image_deref_atomic_or:
5984          buf_op = aco_opcode::buffer_atomic_or;
5985          buf_op64 = aco_opcode::buffer_atomic_or_x2;
5986          image_op = aco_opcode::image_atomic_or;
5987          break;
5988       case nir_intrinsic_image_deref_atomic_xor:
5989          buf_op = aco_opcode::buffer_atomic_xor;
5990          buf_op64 = aco_opcode::buffer_atomic_xor_x2;
5991          image_op = aco_opcode::image_atomic_xor;
5992          break;
5993       case nir_intrinsic_image_deref_atomic_exchange:
5994          buf_op = aco_opcode::buffer_atomic_swap;
5995          buf_op64 = aco_opcode::buffer_atomic_swap_x2;
5996          image_op = aco_opcode::image_atomic_swap;
5997          break;
5998       case nir_intrinsic_image_deref_atomic_comp_swap:
5999          buf_op = aco_opcode::buffer_atomic_cmpswap;
6000          buf_op64 = aco_opcode::buffer_atomic_cmpswap_x2;
6001          image_op = aco_opcode::image_atomic_cmpswap;
6002          break;
6003       default:
6004          unreachable("visit_image_atomic should only be called with nir_intrinsic_image_deref_atomic_* instructions.");
6005    }
6006 
6007    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
6008    memory_sync_info sync = get_memory_sync_info(instr, storage_image, semantic_atomicrmw);
6009 
6010    if (dim == GLSL_SAMPLER_DIM_BUF) {
6011       Temp vindex = emit_extract_vector(ctx, get_ssa_temp(ctx, instr->src[1].ssa), 0, v1);
6012       Temp resource = get_sampler_desc(ctx, nir_instr_as_deref(instr->src[0].ssa->parent_instr), ACO_DESC_BUFFER, nullptr, true, true);
6013       //assert(ctx->options->chip_class < GFX9 && "GFX9 stride size workaround not yet implemented.");
6014       aco_ptr<MUBUF_instruction> mubuf{create_instruction<MUBUF_instruction>(
6015          is_64bit ? buf_op64 : buf_op, Format::MUBUF, 4, return_previous ? 1 : 0)};
6016       mubuf->operands[0] = Operand(resource);
6017       mubuf->operands[1] = Operand(vindex);
6018       mubuf->operands[2] = Operand((uint32_t)0);
6019       mubuf->operands[3] = Operand(data);
6020       if (return_previous)
6021          mubuf->definitions[0] = Definition(dst);
6022       mubuf->offset = 0;
6023       mubuf->idxen = true;
6024       mubuf->glc = return_previous;
6025       mubuf->dlc = false; /* Not needed for atomics */
6026       mubuf->disable_wqm = true;
6027       mubuf->sync = sync;
6028       ctx->program->needs_exact = true;
6029       ctx->block->instructions.emplace_back(std::move(mubuf));
6030       return;
6031    }
6032 
6033    Temp coords = get_image_coords(ctx, instr, type);
6034    Temp resource = get_sampler_desc(ctx, nir_instr_as_deref(instr->src[0].ssa->parent_instr), ACO_DESC_IMAGE, nullptr, true, true);
6035    aco_ptr<MIMG_instruction> mimg{create_instruction<MIMG_instruction>(image_op, Format::MIMG, 3, return_previous ? 1 : 0)};
6036    mimg->operands[0] = Operand(resource);
6037    mimg->operands[1] = Operand(data);
6038    mimg->operands[2] = Operand(coords);
6039    if (return_previous)
6040       mimg->definitions[0] = Definition(dst);
6041    mimg->glc = return_previous;
6042    mimg->dlc = false; /* Not needed for atomics */
6043    mimg->dim = ac_get_image_dim(ctx->options->chip_class, dim, is_array);
6044    mimg->dmask = (1 << data.size()) - 1;
6045    mimg->unrm = true;
6046    mimg->da = should_declare_array(ctx, dim, glsl_sampler_type_is_array(type));
6047    mimg->disable_wqm = true;
6048    mimg->sync = sync;
6049    ctx->program->needs_exact = true;
6050    ctx->block->instructions.emplace_back(std::move(mimg));
6051    return;
6052 }
6053 
get_buffer_size(isel_context * ctx,Temp desc,Temp dst,bool in_elements)6054 void get_buffer_size(isel_context *ctx, Temp desc, Temp dst, bool in_elements)
6055 {
6056    if (in_elements && ctx->options->chip_class == GFX8) {
6057       /* we only have to divide by 1, 2, 4, 8, 12 or 16 */
6058       Builder bld(ctx->program, ctx->block);
6059 
6060       Temp size = emit_extract_vector(ctx, desc, 2, s1);
6061 
6062       Temp size_div3 = bld.vop3(aco_opcode::v_mul_hi_u32, bld.def(v1), bld.copy(bld.def(v1), Operand(0xaaaaaaabu)), size);
6063       size_div3 = bld.sop2(aco_opcode::s_lshr_b32, bld.def(s1), bld.def(s1, scc), bld.as_uniform(size_div3), Operand(1u));
6064 
6065       Temp stride = emit_extract_vector(ctx, desc, 1, s1);
6066       stride = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc), stride, Operand((5u << 16) | 16u));
6067 
6068       Temp is12 = bld.sopc(aco_opcode::s_cmp_eq_i32, bld.def(s1, scc), stride, Operand(12u));
6069       size = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1), size_div3, size, bld.scc(is12));
6070 
6071       Temp shr_dst = dst.type() == RegType::vgpr ? bld.tmp(s1) : dst;
6072       bld.sop2(aco_opcode::s_lshr_b32, Definition(shr_dst), bld.def(s1, scc),
6073                size, bld.sop1(aco_opcode::s_ff1_i32_b32, bld.def(s1), stride));
6074       if (dst.type() == RegType::vgpr)
6075          bld.copy(Definition(dst), shr_dst);
6076 
6077       /* TODO: we can probably calculate this faster with v_skip when stride != 12 */
6078    } else {
6079       emit_extract_vector(ctx, desc, 2, dst);
6080    }
6081 }
6082 
visit_image_size(isel_context * ctx,nir_intrinsic_instr * instr)6083 void visit_image_size(isel_context *ctx, nir_intrinsic_instr *instr)
6084 {
6085    const nir_variable *var = nir_deref_instr_get_variable(nir_instr_as_deref(instr->src[0].ssa->parent_instr));
6086    const struct glsl_type *type = glsl_without_array(var->type);
6087    const enum glsl_sampler_dim dim = glsl_get_sampler_dim(type);
6088    bool is_array = glsl_sampler_type_is_array(type);
6089    Builder bld(ctx->program, ctx->block);
6090 
6091    if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_BUF) {
6092       Temp desc = get_sampler_desc(ctx, nir_instr_as_deref(instr->src[0].ssa->parent_instr), ACO_DESC_BUFFER, NULL, true, false);
6093       return get_buffer_size(ctx, desc, get_ssa_temp(ctx, &instr->dest.ssa), true);
6094    }
6095 
6096    /* LOD */
6097    assert(nir_src_as_uint(instr->src[1]) == 0);
6098    Temp lod = bld.copy(bld.def(v1), Operand(0u));
6099 
6100    /* Resource */
6101    Temp resource = get_sampler_desc(ctx, nir_instr_as_deref(instr->src[0].ssa->parent_instr), ACO_DESC_IMAGE, NULL, true, false);
6102 
6103    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
6104 
6105    aco_ptr<MIMG_instruction> mimg{create_instruction<MIMG_instruction>(aco_opcode::image_get_resinfo, Format::MIMG, 3, 1)};
6106    mimg->operands[0] = Operand(resource);
6107    mimg->operands[1] = Operand(s4); /* no sampler */
6108    mimg->operands[2] = Operand(lod);
6109    uint8_t& dmask = mimg->dmask;
6110    mimg->dim = ac_get_image_dim(ctx->options->chip_class, dim, is_array);
6111    mimg->dmask = (1 << instr->dest.ssa.num_components) - 1;
6112    mimg->da = glsl_sampler_type_is_array(type);
6113    Definition& def = mimg->definitions[0];
6114    ctx->block->instructions.emplace_back(std::move(mimg));
6115 
6116    if (glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_CUBE &&
6117        glsl_sampler_type_is_array(type)) {
6118 
6119       assert(instr->dest.ssa.num_components == 3);
6120       Temp tmp = ctx->program->allocateTmp(v3);
6121       def = Definition(tmp);
6122       emit_split_vector(ctx, tmp, 3);
6123 
6124       /* divide 3rd value by 6 by multiplying with magic number */
6125       Temp c = bld.copy(bld.def(s1), Operand((uint32_t) 0x2AAAAAAB));
6126       Temp by_6 = bld.vop3(aco_opcode::v_mul_hi_i32, bld.def(v1), emit_extract_vector(ctx, tmp, 2, v1), c);
6127 
6128       bld.pseudo(aco_opcode::p_create_vector, Definition(dst),
6129                  emit_extract_vector(ctx, tmp, 0, v1),
6130                  emit_extract_vector(ctx, tmp, 1, v1),
6131                  by_6);
6132 
6133    } else if (ctx->options->chip_class == GFX9 &&
6134               glsl_get_sampler_dim(type) == GLSL_SAMPLER_DIM_1D &&
6135               glsl_sampler_type_is_array(type)) {
6136       assert(instr->dest.ssa.num_components == 2);
6137       def = Definition(dst);
6138       dmask = 0x5;
6139    } else {
6140       def = Definition(dst);
6141    }
6142 
6143    emit_split_vector(ctx, dst, instr->dest.ssa.num_components);
6144 }
6145 
visit_load_ssbo(isel_context * ctx,nir_intrinsic_instr * instr)6146 void visit_load_ssbo(isel_context *ctx, nir_intrinsic_instr *instr)
6147 {
6148    Builder bld(ctx->program, ctx->block);
6149    unsigned num_components = instr->num_components;
6150 
6151    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
6152    Temp rsrc = convert_pointer_to_64_bit(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
6153    rsrc = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), rsrc, Operand(0u));
6154 
6155    unsigned access = nir_intrinsic_access(instr);
6156    bool glc = access & (ACCESS_VOLATILE | ACCESS_COHERENT);
6157    unsigned size = instr->dest.ssa.bit_size / 8;
6158 
6159    uint32_t flags = get_all_buffer_resource_flags(ctx, instr->src[0].ssa, access);
6160    /* GLC bypasses VMEM/SMEM caches, so GLC SMEM loads/stores are coherent with GLC VMEM loads/stores
6161     * TODO: this optimization is disabled for now because we still need to ensure correct ordering
6162     */
6163    bool allow_smem = !(flags & (0 && glc ? has_nonglc_vmem_store : has_vmem_store));
6164    allow_smem |= ((access & ACCESS_RESTRICT) && (access & ACCESS_NON_WRITEABLE)) || (access & ACCESS_CAN_REORDER);
6165 
6166    load_buffer(ctx, num_components, size, dst, rsrc, get_ssa_temp(ctx, instr->src[1].ssa),
6167                nir_intrinsic_align_mul(instr), nir_intrinsic_align_offset(instr), glc, allow_smem,
6168                get_memory_sync_info(instr, storage_buffer, 0));
6169 }
6170 
visit_store_ssbo(isel_context * ctx,nir_intrinsic_instr * instr)6171 void visit_store_ssbo(isel_context *ctx, nir_intrinsic_instr *instr)
6172 {
6173    Builder bld(ctx->program, ctx->block);
6174    Temp data = get_ssa_temp(ctx, instr->src[0].ssa);
6175    unsigned elem_size_bytes = instr->src[0].ssa->bit_size / 8;
6176    unsigned writemask = widen_mask(nir_intrinsic_write_mask(instr), elem_size_bytes);
6177    Temp offset = get_ssa_temp(ctx, instr->src[2].ssa);
6178 
6179    Temp rsrc = convert_pointer_to_64_bit(ctx, get_ssa_temp(ctx, instr->src[1].ssa));
6180    rsrc = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), rsrc, Operand(0u));
6181 
6182    memory_sync_info sync = get_memory_sync_info(instr, storage_buffer, 0);
6183    bool glc = nir_intrinsic_access(instr) & (ACCESS_VOLATILE | ACCESS_COHERENT | ACCESS_NON_READABLE);
6184    uint32_t flags = get_all_buffer_resource_flags(ctx, instr->src[1].ssa, nir_intrinsic_access(instr));
6185    /* GLC bypasses VMEM/SMEM caches, so GLC SMEM loads/stores are coherent with GLC VMEM loads/stores
6186     * TODO: this optimization is disabled for now because we still need to ensure correct ordering
6187     */
6188    bool allow_smem = !(flags & (0 && glc ? has_nonglc_vmem_loadstore : has_vmem_loadstore));
6189 
6190    bool smem = !nir_src_is_divergent(instr->src[2]) &&
6191                ctx->options->chip_class >= GFX8 &&
6192                ctx->options->chip_class < GFX10_3 &&
6193                (elem_size_bytes >= 4 || can_subdword_ssbo_store_use_smem(instr)) &&
6194                allow_smem;
6195    if (smem)
6196       offset = bld.as_uniform(offset);
6197    bool smem_nonfs = smem && ctx->stage != fragment_fs;
6198 
6199    unsigned write_count = 0;
6200    Temp write_datas[32];
6201    unsigned offsets[32];
6202    split_buffer_store(ctx, instr, smem, smem_nonfs ? RegType::sgpr : (smem ? data.type() : RegType::vgpr),
6203                       data, writemask, 16, &write_count, write_datas, offsets);
6204 
6205    for (unsigned i = 0; i < write_count; i++) {
6206       aco_opcode op = get_buffer_store_op(smem, write_datas[i].bytes());
6207       if (smem && ctx->stage == fragment_fs)
6208          op = aco_opcode::p_fs_buffer_store_smem;
6209 
6210       if (smem) {
6211          aco_ptr<SMEM_instruction> store{create_instruction<SMEM_instruction>(op, Format::SMEM, 3, 0)};
6212          store->operands[0] = Operand(rsrc);
6213          if (offsets[i]) {
6214             Temp off = bld.nuw().sop2(aco_opcode::s_add_i32, bld.def(s1), bld.def(s1, scc),
6215                                       offset, Operand(offsets[i]));
6216             store->operands[1] = Operand(off);
6217          } else {
6218             store->operands[1] = Operand(offset);
6219          }
6220          if (op != aco_opcode::p_fs_buffer_store_smem)
6221             store->operands[1].setFixed(m0);
6222          store->operands[2] = Operand(write_datas[i]);
6223          store->glc = glc;
6224          store->dlc = false;
6225          store->disable_wqm = true;
6226          store->sync = sync;
6227          ctx->block->instructions.emplace_back(std::move(store));
6228          ctx->program->wb_smem_l1_on_end = true;
6229          if (op == aco_opcode::p_fs_buffer_store_smem) {
6230             ctx->block->kind |= block_kind_needs_lowering;
6231             ctx->program->needs_exact = true;
6232          }
6233       } else {
6234          aco_ptr<MUBUF_instruction> store{create_instruction<MUBUF_instruction>(op, Format::MUBUF, 4, 0)};
6235          store->operands[0] = Operand(rsrc);
6236          store->operands[1] = offset.type() == RegType::vgpr ? Operand(offset) : Operand(v1);
6237          store->operands[2] = offset.type() == RegType::sgpr ? Operand(offset) : Operand((uint32_t) 0);
6238          store->operands[3] = Operand(write_datas[i]);
6239          store->offset = offsets[i];
6240          store->offen = (offset.type() == RegType::vgpr);
6241          store->glc = glc;
6242          store->dlc = false;
6243          store->disable_wqm = true;
6244          store->sync = sync;
6245          ctx->program->needs_exact = true;
6246          ctx->block->instructions.emplace_back(std::move(store));
6247       }
6248    }
6249 }
6250 
visit_atomic_ssbo(isel_context * ctx,nir_intrinsic_instr * instr)6251 void visit_atomic_ssbo(isel_context *ctx, nir_intrinsic_instr *instr)
6252 {
6253    /* return the previous value if dest is ever used */
6254    bool return_previous = false;
6255    nir_foreach_use_safe(use_src, &instr->dest.ssa) {
6256       return_previous = true;
6257       break;
6258    }
6259    nir_foreach_if_use_safe(use_src, &instr->dest.ssa) {
6260       return_previous = true;
6261       break;
6262    }
6263 
6264    Builder bld(ctx->program, ctx->block);
6265    Temp data = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[2].ssa));
6266 
6267    if (instr->intrinsic == nir_intrinsic_ssbo_atomic_comp_swap)
6268       data = bld.pseudo(aco_opcode::p_create_vector, bld.def(RegType::vgpr, data.size() * 2),
6269                         get_ssa_temp(ctx, instr->src[3].ssa), data);
6270 
6271    Temp offset = get_ssa_temp(ctx, instr->src[1].ssa);
6272    Temp rsrc = convert_pointer_to_64_bit(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
6273    rsrc = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), rsrc, Operand(0u));
6274 
6275    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
6276 
6277    aco_opcode op32, op64;
6278    switch (instr->intrinsic) {
6279       case nir_intrinsic_ssbo_atomic_add:
6280          op32 = aco_opcode::buffer_atomic_add;
6281          op64 = aco_opcode::buffer_atomic_add_x2;
6282          break;
6283       case nir_intrinsic_ssbo_atomic_imin:
6284          op32 = aco_opcode::buffer_atomic_smin;
6285          op64 = aco_opcode::buffer_atomic_smin_x2;
6286          break;
6287       case nir_intrinsic_ssbo_atomic_umin:
6288          op32 = aco_opcode::buffer_atomic_umin;
6289          op64 = aco_opcode::buffer_atomic_umin_x2;
6290          break;
6291       case nir_intrinsic_ssbo_atomic_imax:
6292          op32 = aco_opcode::buffer_atomic_smax;
6293          op64 = aco_opcode::buffer_atomic_smax_x2;
6294          break;
6295       case nir_intrinsic_ssbo_atomic_umax:
6296          op32 = aco_opcode::buffer_atomic_umax;
6297          op64 = aco_opcode::buffer_atomic_umax_x2;
6298          break;
6299       case nir_intrinsic_ssbo_atomic_and:
6300          op32 = aco_opcode::buffer_atomic_and;
6301          op64 = aco_opcode::buffer_atomic_and_x2;
6302          break;
6303       case nir_intrinsic_ssbo_atomic_or:
6304          op32 = aco_opcode::buffer_atomic_or;
6305          op64 = aco_opcode::buffer_atomic_or_x2;
6306          break;
6307       case nir_intrinsic_ssbo_atomic_xor:
6308          op32 = aco_opcode::buffer_atomic_xor;
6309          op64 = aco_opcode::buffer_atomic_xor_x2;
6310          break;
6311       case nir_intrinsic_ssbo_atomic_exchange:
6312          op32 = aco_opcode::buffer_atomic_swap;
6313          op64 = aco_opcode::buffer_atomic_swap_x2;
6314          break;
6315       case nir_intrinsic_ssbo_atomic_comp_swap:
6316          op32 = aco_opcode::buffer_atomic_cmpswap;
6317          op64 = aco_opcode::buffer_atomic_cmpswap_x2;
6318          break;
6319       default:
6320          unreachable("visit_atomic_ssbo should only be called with nir_intrinsic_ssbo_atomic_* instructions.");
6321    }
6322    aco_opcode op = instr->dest.ssa.bit_size == 32 ? op32 : op64;
6323    aco_ptr<MUBUF_instruction> mubuf{create_instruction<MUBUF_instruction>(op, Format::MUBUF, 4, return_previous ? 1 : 0)};
6324    mubuf->operands[0] = Operand(rsrc);
6325    mubuf->operands[1] = offset.type() == RegType::vgpr ? Operand(offset) : Operand(v1);
6326    mubuf->operands[2] = offset.type() == RegType::sgpr ? Operand(offset) : Operand((uint32_t) 0);
6327    mubuf->operands[3] = Operand(data);
6328    if (return_previous)
6329       mubuf->definitions[0] = Definition(dst);
6330    mubuf->offset = 0;
6331    mubuf->offen = (offset.type() == RegType::vgpr);
6332    mubuf->glc = return_previous;
6333    mubuf->dlc = false; /* Not needed for atomics */
6334    mubuf->disable_wqm = true;
6335    mubuf->sync = get_memory_sync_info(instr, storage_buffer, semantic_atomicrmw);
6336    ctx->program->needs_exact = true;
6337    ctx->block->instructions.emplace_back(std::move(mubuf));
6338 }
6339 
visit_get_ssbo_size(isel_context * ctx,nir_intrinsic_instr * instr)6340 void visit_get_ssbo_size(isel_context *ctx, nir_intrinsic_instr *instr) {
6341 
6342    Temp rsrc = get_ssa_temp(ctx, instr->src[0].ssa);
6343    rsrc = emit_extract_vector(ctx, rsrc, 0, RegClass(rsrc.type(), 1));
6344    Temp index = convert_pointer_to_64_bit(ctx, rsrc);
6345 
6346    Builder bld(ctx->program, ctx->block);
6347    Temp desc = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), index, Operand(0u));
6348    get_buffer_size(ctx, desc, get_ssa_temp(ctx, &instr->dest.ssa), false);
6349 }
6350 
visit_load_global(isel_context * ctx,nir_intrinsic_instr * instr)6351 void visit_load_global(isel_context *ctx, nir_intrinsic_instr *instr)
6352 {
6353    Builder bld(ctx->program, ctx->block);
6354    unsigned num_components = instr->num_components;
6355    unsigned component_size = instr->dest.ssa.bit_size / 8;
6356 
6357    LoadEmitInfo info = {Operand(get_ssa_temp(ctx, instr->src[0].ssa)),
6358                         get_ssa_temp(ctx, &instr->dest.ssa),
6359                         num_components, component_size};
6360    info.glc = nir_intrinsic_access(instr) & (ACCESS_VOLATILE | ACCESS_COHERENT);
6361    info.align_mul = nir_intrinsic_align_mul(instr);
6362    info.align_offset = nir_intrinsic_align_offset(instr);
6363    info.sync = get_memory_sync_info(instr, storage_buffer, 0);
6364    /* VMEM stores don't update the SMEM cache and it's difficult to prove that
6365     * it's safe to use SMEM */
6366    bool can_use_smem = nir_intrinsic_access(instr) & ACCESS_NON_WRITEABLE;
6367    if (info.dst.type() == RegType::vgpr || (info.glc && ctx->options->chip_class < GFX8) || !can_use_smem) {
6368       emit_load(ctx, bld, info, global_load_params);
6369    } else {
6370       info.offset = Operand(bld.as_uniform(info.offset));
6371       emit_load(ctx, bld, info, smem_load_params);
6372    }
6373 }
6374 
visit_store_global(isel_context * ctx,nir_intrinsic_instr * instr)6375 void visit_store_global(isel_context *ctx, nir_intrinsic_instr *instr)
6376 {
6377    Builder bld(ctx->program, ctx->block);
6378    unsigned elem_size_bytes = instr->src[0].ssa->bit_size / 8;
6379    unsigned writemask = widen_mask(nir_intrinsic_write_mask(instr), elem_size_bytes);
6380 
6381    Temp data = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
6382    Temp addr = get_ssa_temp(ctx, instr->src[1].ssa);
6383    memory_sync_info sync = get_memory_sync_info(instr, storage_buffer, 0);
6384    bool glc = nir_intrinsic_access(instr) & (ACCESS_VOLATILE | ACCESS_COHERENT | ACCESS_NON_READABLE);
6385 
6386    if (ctx->options->chip_class >= GFX7)
6387       addr = as_vgpr(ctx, addr);
6388 
6389    unsigned write_count = 0;
6390    Temp write_datas[32];
6391    unsigned offsets[32];
6392    split_buffer_store(ctx, instr, false, RegType::vgpr, data, writemask,
6393                       16, &write_count, write_datas, offsets);
6394 
6395    for (unsigned i = 0; i < write_count; i++) {
6396       if (ctx->options->chip_class >= GFX7) {
6397          unsigned offset = offsets[i];
6398          Temp store_addr = addr;
6399          if (offset > 0 && ctx->options->chip_class < GFX9) {
6400             Temp addr0 = bld.tmp(v1), addr1 = bld.tmp(v1);
6401             Temp new_addr0 = bld.tmp(v1), new_addr1 = bld.tmp(v1);
6402             Temp carry = bld.tmp(bld.lm);
6403             bld.pseudo(aco_opcode::p_split_vector, Definition(addr0), Definition(addr1), addr);
6404 
6405             bld.vop2(aco_opcode::v_add_co_u32, Definition(new_addr0), bld.hint_vcc(Definition(carry)),
6406                      Operand(offset), addr0);
6407             bld.vop2(aco_opcode::v_addc_co_u32, Definition(new_addr1), bld.def(bld.lm),
6408                      Operand(0u), addr1,
6409                      carry).def(1).setHint(vcc);
6410 
6411             store_addr = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), new_addr0, new_addr1);
6412 
6413             offset = 0;
6414          }
6415 
6416          bool global = ctx->options->chip_class >= GFX9;
6417          aco_opcode op;
6418          switch (write_datas[i].bytes()) {
6419          case 1:
6420             op = global ? aco_opcode::global_store_byte : aco_opcode::flat_store_byte;
6421             break;
6422          case 2:
6423             op = global ? aco_opcode::global_store_short : aco_opcode::flat_store_short;
6424             break;
6425          case 4:
6426             op = global ? aco_opcode::global_store_dword : aco_opcode::flat_store_dword;
6427             break;
6428          case 8:
6429             op = global ? aco_opcode::global_store_dwordx2 : aco_opcode::flat_store_dwordx2;
6430             break;
6431          case 12:
6432             op = global ? aco_opcode::global_store_dwordx3 : aco_opcode::flat_store_dwordx3;
6433             break;
6434          case 16:
6435             op = global ? aco_opcode::global_store_dwordx4 : aco_opcode::flat_store_dwordx4;
6436             break;
6437          default:
6438             unreachable("store_global not implemented for this size.");
6439          }
6440 
6441          aco_ptr<FLAT_instruction> flat{create_instruction<FLAT_instruction>(op, global ? Format::GLOBAL : Format::FLAT, 3, 0)};
6442          flat->operands[0] = Operand(store_addr);
6443          flat->operands[1] = Operand(s1);
6444          flat->operands[2] = Operand(write_datas[i]);
6445          flat->glc = glc;
6446          flat->dlc = false;
6447          flat->offset = offset;
6448          flat->disable_wqm = true;
6449          flat->sync = sync;
6450          ctx->program->needs_exact = true;
6451          ctx->block->instructions.emplace_back(std::move(flat));
6452       } else {
6453          assert(ctx->options->chip_class == GFX6);
6454 
6455          aco_opcode op = get_buffer_store_op(false, write_datas[i].bytes());
6456 
6457          Temp rsrc = get_gfx6_global_rsrc(bld, addr);
6458 
6459          aco_ptr<MUBUF_instruction> mubuf{create_instruction<MUBUF_instruction>(op, Format::MUBUF, 4, 0)};
6460          mubuf->operands[0] = Operand(rsrc);
6461          mubuf->operands[1] = addr.type() == RegType::vgpr ? Operand(addr) : Operand(v1);
6462          mubuf->operands[2] = Operand(0u);
6463          mubuf->operands[3] = Operand(write_datas[i]);
6464          mubuf->glc = glc;
6465          mubuf->dlc = false;
6466          mubuf->offset = offsets[i];
6467          mubuf->addr64 = addr.type() == RegType::vgpr;
6468          mubuf->disable_wqm = true;
6469          mubuf->sync = sync;
6470          ctx->program->needs_exact = true;
6471          ctx->block->instructions.emplace_back(std::move(mubuf));
6472       }
6473    }
6474 }
6475 
visit_global_atomic(isel_context * ctx,nir_intrinsic_instr * instr)6476 void visit_global_atomic(isel_context *ctx, nir_intrinsic_instr *instr)
6477 {
6478    /* return the previous value if dest is ever used */
6479    bool return_previous = false;
6480    nir_foreach_use_safe(use_src, &instr->dest.ssa) {
6481       return_previous = true;
6482       break;
6483    }
6484    nir_foreach_if_use_safe(use_src, &instr->dest.ssa) {
6485       return_previous = true;
6486       break;
6487    }
6488 
6489    Builder bld(ctx->program, ctx->block);
6490    Temp addr = get_ssa_temp(ctx, instr->src[0].ssa);
6491    Temp data = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[1].ssa));
6492 
6493    if (ctx->options->chip_class >= GFX7)
6494       addr = as_vgpr(ctx, addr);
6495 
6496    if (instr->intrinsic == nir_intrinsic_global_atomic_comp_swap)
6497       data = bld.pseudo(aco_opcode::p_create_vector, bld.def(RegType::vgpr, data.size() * 2),
6498                         get_ssa_temp(ctx, instr->src[2].ssa), data);
6499 
6500    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
6501 
6502    aco_opcode op32, op64;
6503 
6504    if (ctx->options->chip_class >= GFX7) {
6505       bool global = ctx->options->chip_class >= GFX9;
6506       switch (instr->intrinsic) {
6507          case nir_intrinsic_global_atomic_add:
6508             op32 = global ? aco_opcode::global_atomic_add : aco_opcode::flat_atomic_add;
6509             op64 = global ? aco_opcode::global_atomic_add_x2 : aco_opcode::flat_atomic_add_x2;
6510             break;
6511          case nir_intrinsic_global_atomic_imin:
6512             op32 = global ? aco_opcode::global_atomic_smin : aco_opcode::flat_atomic_smin;
6513             op64 = global ? aco_opcode::global_atomic_smin_x2 : aco_opcode::flat_atomic_smin_x2;
6514             break;
6515          case nir_intrinsic_global_atomic_umin:
6516             op32 = global ? aco_opcode::global_atomic_umin : aco_opcode::flat_atomic_umin;
6517             op64 = global ? aco_opcode::global_atomic_umin_x2 : aco_opcode::flat_atomic_umin_x2;
6518             break;
6519          case nir_intrinsic_global_atomic_imax:
6520             op32 = global ? aco_opcode::global_atomic_smax : aco_opcode::flat_atomic_smax;
6521             op64 = global ? aco_opcode::global_atomic_smax_x2 : aco_opcode::flat_atomic_smax_x2;
6522             break;
6523          case nir_intrinsic_global_atomic_umax:
6524             op32 = global ? aco_opcode::global_atomic_umax : aco_opcode::flat_atomic_umax;
6525             op64 = global ? aco_opcode::global_atomic_umax_x2 : aco_opcode::flat_atomic_umax_x2;
6526             break;
6527          case nir_intrinsic_global_atomic_and:
6528             op32 = global ? aco_opcode::global_atomic_and : aco_opcode::flat_atomic_and;
6529             op64 = global ? aco_opcode::global_atomic_and_x2 : aco_opcode::flat_atomic_and_x2;
6530             break;
6531          case nir_intrinsic_global_atomic_or:
6532             op32 = global ? aco_opcode::global_atomic_or : aco_opcode::flat_atomic_or;
6533             op64 = global ? aco_opcode::global_atomic_or_x2 : aco_opcode::flat_atomic_or_x2;
6534             break;
6535          case nir_intrinsic_global_atomic_xor:
6536             op32 = global ? aco_opcode::global_atomic_xor : aco_opcode::flat_atomic_xor;
6537             op64 = global ? aco_opcode::global_atomic_xor_x2 : aco_opcode::flat_atomic_xor_x2;
6538             break;
6539          case nir_intrinsic_global_atomic_exchange:
6540             op32 = global ? aco_opcode::global_atomic_swap : aco_opcode::flat_atomic_swap;
6541             op64 = global ? aco_opcode::global_atomic_swap_x2 : aco_opcode::flat_atomic_swap_x2;
6542             break;
6543          case nir_intrinsic_global_atomic_comp_swap:
6544             op32 = global ? aco_opcode::global_atomic_cmpswap : aco_opcode::flat_atomic_cmpswap;
6545             op64 = global ? aco_opcode::global_atomic_cmpswap_x2 : aco_opcode::flat_atomic_cmpswap_x2;
6546             break;
6547          default:
6548             unreachable("visit_atomic_global should only be called with nir_intrinsic_global_atomic_* instructions.");
6549       }
6550 
6551       aco_opcode op = instr->dest.ssa.bit_size == 32 ? op32 : op64;
6552       aco_ptr<FLAT_instruction> flat{create_instruction<FLAT_instruction>(op, global ? Format::GLOBAL : Format::FLAT, 3, return_previous ? 1 : 0)};
6553       flat->operands[0] = Operand(addr);
6554       flat->operands[1] = Operand(s1);
6555       flat->operands[2] = Operand(data);
6556       if (return_previous)
6557          flat->definitions[0] = Definition(dst);
6558       flat->glc = return_previous;
6559       flat->dlc = false; /* Not needed for atomics */
6560       flat->offset = 0;
6561       flat->disable_wqm = true;
6562       flat->sync = get_memory_sync_info(instr, storage_buffer, semantic_atomicrmw);
6563       ctx->program->needs_exact = true;
6564       ctx->block->instructions.emplace_back(std::move(flat));
6565    } else {
6566       assert(ctx->options->chip_class == GFX6);
6567 
6568       switch (instr->intrinsic) {
6569          case nir_intrinsic_global_atomic_add:
6570             op32 = aco_opcode::buffer_atomic_add;
6571             op64 = aco_opcode::buffer_atomic_add_x2;
6572             break;
6573          case nir_intrinsic_global_atomic_imin:
6574             op32 = aco_opcode::buffer_atomic_smin;
6575             op64 = aco_opcode::buffer_atomic_smin_x2;
6576             break;
6577          case nir_intrinsic_global_atomic_umin:
6578             op32 = aco_opcode::buffer_atomic_umin;
6579             op64 = aco_opcode::buffer_atomic_umin_x2;
6580             break;
6581          case nir_intrinsic_global_atomic_imax:
6582             op32 = aco_opcode::buffer_atomic_smax;
6583             op64 = aco_opcode::buffer_atomic_smax_x2;
6584             break;
6585          case nir_intrinsic_global_atomic_umax:
6586             op32 = aco_opcode::buffer_atomic_umax;
6587             op64 = aco_opcode::buffer_atomic_umax_x2;
6588             break;
6589          case nir_intrinsic_global_atomic_and:
6590             op32 = aco_opcode::buffer_atomic_and;
6591             op64 = aco_opcode::buffer_atomic_and_x2;
6592             break;
6593          case nir_intrinsic_global_atomic_or:
6594             op32 = aco_opcode::buffer_atomic_or;
6595             op64 = aco_opcode::buffer_atomic_or_x2;
6596             break;
6597          case nir_intrinsic_global_atomic_xor:
6598             op32 = aco_opcode::buffer_atomic_xor;
6599             op64 = aco_opcode::buffer_atomic_xor_x2;
6600             break;
6601          case nir_intrinsic_global_atomic_exchange:
6602             op32 = aco_opcode::buffer_atomic_swap;
6603             op64 = aco_opcode::buffer_atomic_swap_x2;
6604             break;
6605          case nir_intrinsic_global_atomic_comp_swap:
6606             op32 = aco_opcode::buffer_atomic_cmpswap;
6607             op64 = aco_opcode::buffer_atomic_cmpswap_x2;
6608             break;
6609          default:
6610             unreachable("visit_atomic_global should only be called with nir_intrinsic_global_atomic_* instructions.");
6611       }
6612 
6613       Temp rsrc = get_gfx6_global_rsrc(bld, addr);
6614 
6615       aco_opcode op = instr->dest.ssa.bit_size == 32 ? op32 : op64;
6616 
6617       aco_ptr<MUBUF_instruction> mubuf{create_instruction<MUBUF_instruction>(op, Format::MUBUF, 4, return_previous ? 1 : 0)};
6618       mubuf->operands[0] = Operand(rsrc);
6619       mubuf->operands[1] = addr.type() == RegType::vgpr ? Operand(addr) : Operand(v1);
6620       mubuf->operands[2] = Operand(0u);
6621       mubuf->operands[3] = Operand(data);
6622       if (return_previous)
6623          mubuf->definitions[0] = Definition(dst);
6624       mubuf->glc = return_previous;
6625       mubuf->dlc = false;
6626       mubuf->offset = 0;
6627       mubuf->addr64 = addr.type() == RegType::vgpr;
6628       mubuf->disable_wqm = true;
6629       mubuf->sync = get_memory_sync_info(instr, storage_buffer, semantic_atomicrmw);
6630       ctx->program->needs_exact = true;
6631       ctx->block->instructions.emplace_back(std::move(mubuf));
6632    }
6633 }
6634 
translate_nir_scope(nir_scope scope)6635 sync_scope translate_nir_scope(nir_scope scope)
6636 {
6637    switch (scope) {
6638    case NIR_SCOPE_NONE:
6639    case NIR_SCOPE_INVOCATION:
6640       return scope_invocation;
6641    case NIR_SCOPE_SUBGROUP:
6642       return scope_subgroup;
6643    case NIR_SCOPE_WORKGROUP:
6644       return scope_workgroup;
6645    case NIR_SCOPE_QUEUE_FAMILY:
6646       return scope_queuefamily;
6647    case NIR_SCOPE_DEVICE:
6648       return scope_device;
6649    case NIR_SCOPE_SHADER_CALL:
6650       unreachable("unsupported scope");
6651    }
6652    unreachable("invalid scope");
6653 }
6654 
emit_scoped_barrier(isel_context * ctx,nir_intrinsic_instr * instr)6655 void emit_scoped_barrier(isel_context *ctx, nir_intrinsic_instr *instr) {
6656    Builder bld(ctx->program, ctx->block);
6657 
6658    unsigned semantics = 0;
6659    unsigned storage = 0;
6660    sync_scope mem_scope = translate_nir_scope(nir_intrinsic_memory_scope(instr));
6661    sync_scope exec_scope = translate_nir_scope(nir_intrinsic_execution_scope(instr));
6662 
6663    unsigned nir_storage = nir_intrinsic_memory_modes(instr);
6664    if (nir_storage & (nir_var_mem_ssbo | nir_var_mem_global))
6665       storage |= storage_buffer | storage_image; //TODO: split this when NIR gets nir_var_mem_image
6666    if (ctx->shader->info.stage == MESA_SHADER_COMPUTE && (nir_storage & nir_var_mem_shared))
6667       storage |= storage_shared;
6668    if (ctx->shader->info.stage == MESA_SHADER_TESS_CTRL && (nir_storage & nir_var_shader_out))
6669       storage |= storage_shared;
6670 
6671    unsigned nir_semantics = nir_intrinsic_memory_semantics(instr);
6672    if (nir_semantics & NIR_MEMORY_ACQUIRE)
6673       semantics |= semantic_acquire | semantic_release;
6674    if (nir_semantics & NIR_MEMORY_RELEASE)
6675       semantics |= semantic_acquire | semantic_release;
6676 
6677    assert(!(nir_semantics & (NIR_MEMORY_MAKE_AVAILABLE | NIR_MEMORY_MAKE_VISIBLE)));
6678 
6679    /* Workgroup barriers can hang merged shaders that can potentially have 0 threads in either half. */
6680    assert(exec_scope != scope_workgroup ||
6681           ctx->shader->info.stage == MESA_SHADER_COMPUTE ||
6682           ctx->shader->info.stage == MESA_SHADER_TESS_CTRL);
6683 
6684    bld.barrier(aco_opcode::p_barrier,
6685                memory_sync_info((storage_class)storage, (memory_semantics)semantics, mem_scope),
6686                exec_scope);
6687 }
6688 
visit_load_shared(isel_context * ctx,nir_intrinsic_instr * instr)6689 void visit_load_shared(isel_context *ctx, nir_intrinsic_instr *instr)
6690 {
6691    // TODO: implement sparse reads using ds_read2_b32 and nir_ssa_def_components_read()
6692    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
6693    Temp address = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
6694    Builder bld(ctx->program, ctx->block);
6695 
6696    unsigned elem_size_bytes = instr->dest.ssa.bit_size / 8;
6697    unsigned align = nir_intrinsic_align_mul(instr) ? nir_intrinsic_align(instr) : elem_size_bytes;
6698    load_lds(ctx, elem_size_bytes, dst, address, nir_intrinsic_base(instr), align);
6699 }
6700 
visit_store_shared(isel_context * ctx,nir_intrinsic_instr * instr)6701 void visit_store_shared(isel_context *ctx, nir_intrinsic_instr *instr)
6702 {
6703    unsigned writemask = nir_intrinsic_write_mask(instr);
6704    Temp data = get_ssa_temp(ctx, instr->src[0].ssa);
6705    Temp address = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[1].ssa));
6706    unsigned elem_size_bytes = instr->src[0].ssa->bit_size / 8;
6707 
6708    unsigned align = nir_intrinsic_align_mul(instr) ? nir_intrinsic_align(instr) : elem_size_bytes;
6709    store_lds(ctx, elem_size_bytes, data, writemask, address, nir_intrinsic_base(instr), align);
6710 }
6711 
visit_shared_atomic(isel_context * ctx,nir_intrinsic_instr * instr)6712 void visit_shared_atomic(isel_context *ctx, nir_intrinsic_instr *instr)
6713 {
6714    unsigned offset = nir_intrinsic_base(instr);
6715    Builder bld(ctx->program, ctx->block);
6716    Operand m = load_lds_size_m0(bld);
6717    Temp data = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[1].ssa));
6718    Temp address = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
6719 
6720    unsigned num_operands = 3;
6721    aco_opcode op32, op64, op32_rtn, op64_rtn;
6722    switch(instr->intrinsic) {
6723       case nir_intrinsic_shared_atomic_add:
6724          op32 = aco_opcode::ds_add_u32;
6725          op64 = aco_opcode::ds_add_u64;
6726          op32_rtn = aco_opcode::ds_add_rtn_u32;
6727          op64_rtn = aco_opcode::ds_add_rtn_u64;
6728          break;
6729       case nir_intrinsic_shared_atomic_imin:
6730          op32 = aco_opcode::ds_min_i32;
6731          op64 = aco_opcode::ds_min_i64;
6732          op32_rtn = aco_opcode::ds_min_rtn_i32;
6733          op64_rtn = aco_opcode::ds_min_rtn_i64;
6734          break;
6735       case nir_intrinsic_shared_atomic_umin:
6736          op32 = aco_opcode::ds_min_u32;
6737          op64 = aco_opcode::ds_min_u64;
6738          op32_rtn = aco_opcode::ds_min_rtn_u32;
6739          op64_rtn = aco_opcode::ds_min_rtn_u64;
6740          break;
6741       case nir_intrinsic_shared_atomic_imax:
6742          op32 = aco_opcode::ds_max_i32;
6743          op64 = aco_opcode::ds_max_i64;
6744          op32_rtn = aco_opcode::ds_max_rtn_i32;
6745          op64_rtn = aco_opcode::ds_max_rtn_i64;
6746          break;
6747       case nir_intrinsic_shared_atomic_umax:
6748          op32 = aco_opcode::ds_max_u32;
6749          op64 = aco_opcode::ds_max_u64;
6750          op32_rtn = aco_opcode::ds_max_rtn_u32;
6751          op64_rtn = aco_opcode::ds_max_rtn_u64;
6752          break;
6753       case nir_intrinsic_shared_atomic_and:
6754          op32 = aco_opcode::ds_and_b32;
6755          op64 = aco_opcode::ds_and_b64;
6756          op32_rtn = aco_opcode::ds_and_rtn_b32;
6757          op64_rtn = aco_opcode::ds_and_rtn_b64;
6758          break;
6759       case nir_intrinsic_shared_atomic_or:
6760          op32 = aco_opcode::ds_or_b32;
6761          op64 = aco_opcode::ds_or_b64;
6762          op32_rtn = aco_opcode::ds_or_rtn_b32;
6763          op64_rtn = aco_opcode::ds_or_rtn_b64;
6764          break;
6765       case nir_intrinsic_shared_atomic_xor:
6766          op32 = aco_opcode::ds_xor_b32;
6767          op64 = aco_opcode::ds_xor_b64;
6768          op32_rtn = aco_opcode::ds_xor_rtn_b32;
6769          op64_rtn = aco_opcode::ds_xor_rtn_b64;
6770          break;
6771       case nir_intrinsic_shared_atomic_exchange:
6772          op32 = aco_opcode::ds_write_b32;
6773          op64 = aco_opcode::ds_write_b64;
6774          op32_rtn = aco_opcode::ds_wrxchg_rtn_b32;
6775          op64_rtn = aco_opcode::ds_wrxchg_rtn_b64;
6776          break;
6777       case nir_intrinsic_shared_atomic_comp_swap:
6778          op32 = aco_opcode::ds_cmpst_b32;
6779          op64 = aco_opcode::ds_cmpst_b64;
6780          op32_rtn = aco_opcode::ds_cmpst_rtn_b32;
6781          op64_rtn = aco_opcode::ds_cmpst_rtn_b64;
6782          num_operands = 4;
6783          break;
6784       case nir_intrinsic_shared_atomic_fadd:
6785          op32 = aco_opcode::ds_add_f32;
6786          op32_rtn = aco_opcode::ds_add_rtn_f32;
6787          op64 = aco_opcode::num_opcodes;
6788          op64_rtn = aco_opcode::num_opcodes;
6789          break;
6790       default:
6791          unreachable("Unhandled shared atomic intrinsic");
6792    }
6793 
6794    /* return the previous value if dest is ever used */
6795    bool return_previous = false;
6796    nir_foreach_use_safe(use_src, &instr->dest.ssa) {
6797       return_previous = true;
6798       break;
6799    }
6800    nir_foreach_if_use_safe(use_src, &instr->dest.ssa) {
6801       return_previous = true;
6802       break;
6803    }
6804 
6805    aco_opcode op;
6806    if (data.size() == 1) {
6807       assert(instr->dest.ssa.bit_size == 32);
6808       op = return_previous ? op32_rtn : op32;
6809    } else {
6810       assert(instr->dest.ssa.bit_size == 64);
6811       op = return_previous ? op64_rtn : op64;
6812    }
6813 
6814    if (offset > 65535) {
6815       address = bld.vadd32(bld.def(v1), Operand(offset), address);
6816       offset = 0;
6817    }
6818 
6819    aco_ptr<DS_instruction> ds;
6820    ds.reset(create_instruction<DS_instruction>(op, Format::DS, num_operands, return_previous ? 1 : 0));
6821    ds->operands[0] = Operand(address);
6822    ds->operands[1] = Operand(data);
6823    if (num_operands == 4)
6824       ds->operands[2] = Operand(get_ssa_temp(ctx, instr->src[2].ssa));
6825    ds->operands[num_operands - 1] = m;
6826    ds->offset0 = offset;
6827    if (return_previous)
6828       ds->definitions[0] = Definition(get_ssa_temp(ctx, &instr->dest.ssa));
6829    ds->sync = memory_sync_info(storage_shared, semantic_atomicrmw);
6830    ctx->block->instructions.emplace_back(std::move(ds));
6831 }
6832 
get_scratch_resource(isel_context * ctx)6833 Temp get_scratch_resource(isel_context *ctx)
6834 {
6835    Builder bld(ctx->program, ctx->block);
6836    Temp scratch_addr = ctx->program->private_segment_buffer;
6837    if (ctx->stage != compute_cs)
6838       scratch_addr = bld.smem(aco_opcode::s_load_dwordx2, bld.def(s2), scratch_addr, Operand(0u));
6839 
6840    uint32_t rsrc_conf = S_008F0C_ADD_TID_ENABLE(1) |
6841                         S_008F0C_INDEX_STRIDE(ctx->program->wave_size == 64 ? 3 : 2);
6842 
6843    if (ctx->program->chip_class >= GFX10) {
6844       rsrc_conf |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
6845                    S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
6846                    S_008F0C_RESOURCE_LEVEL(1);
6847    } else if (ctx->program->chip_class <= GFX7) { /* dfmt modifies stride on GFX8/GFX9 when ADD_TID_EN=1 */
6848       rsrc_conf |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
6849                    S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
6850    }
6851 
6852    /* older generations need element size = 4 bytes. element size removed in GFX9 */
6853    if (ctx->program->chip_class <= GFX8)
6854       rsrc_conf |= S_008F0C_ELEMENT_SIZE(1);
6855 
6856    return bld.pseudo(aco_opcode::p_create_vector, bld.def(s4), scratch_addr, Operand(-1u), Operand(rsrc_conf));
6857 }
6858 
visit_load_scratch(isel_context * ctx,nir_intrinsic_instr * instr)6859 void visit_load_scratch(isel_context *ctx, nir_intrinsic_instr *instr) {
6860    Builder bld(ctx->program, ctx->block);
6861    Temp rsrc = get_scratch_resource(ctx);
6862    Temp offset = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
6863    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
6864 
6865    LoadEmitInfo info = {Operand(offset), dst, instr->dest.ssa.num_components,
6866                         instr->dest.ssa.bit_size / 8u, rsrc};
6867    info.align_mul = nir_intrinsic_align_mul(instr);
6868    info.align_offset = nir_intrinsic_align_offset(instr);
6869    info.swizzle_component_size = ctx->program->chip_class <= GFX8 ? 4 : 0;
6870    info.sync = memory_sync_info(storage_scratch, semantic_private);
6871    info.soffset = ctx->program->scratch_offset;
6872    emit_load(ctx, bld, info, scratch_load_params);
6873 }
6874 
visit_store_scratch(isel_context * ctx,nir_intrinsic_instr * instr)6875 void visit_store_scratch(isel_context *ctx, nir_intrinsic_instr *instr) {
6876    Builder bld(ctx->program, ctx->block);
6877    Temp rsrc = get_scratch_resource(ctx);
6878    Temp data = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
6879    Temp offset = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[1].ssa));
6880 
6881    unsigned elem_size_bytes = instr->src[0].ssa->bit_size / 8;
6882    unsigned writemask = widen_mask(nir_intrinsic_write_mask(instr), elem_size_bytes);
6883 
6884    unsigned write_count = 0;
6885    Temp write_datas[32];
6886    unsigned offsets[32];
6887    unsigned swizzle_component_size = ctx->program->chip_class <= GFX8 ? 4 : 16;
6888    split_buffer_store(ctx, instr, false, RegType::vgpr, data, writemask,
6889                       swizzle_component_size, &write_count, write_datas, offsets);
6890 
6891    for (unsigned i = 0; i < write_count; i++) {
6892       aco_opcode op = get_buffer_store_op(false, write_datas[i].bytes());
6893       Instruction *instr = bld.mubuf(op, rsrc, offset, ctx->program->scratch_offset, write_datas[i], offsets[i], true, true);
6894       static_cast<MUBUF_instruction *>(instr)->sync = memory_sync_info(storage_scratch, semantic_private);
6895    }
6896 }
6897 
visit_load_sample_mask_in(isel_context * ctx,nir_intrinsic_instr * instr)6898 void visit_load_sample_mask_in(isel_context *ctx, nir_intrinsic_instr *instr) {
6899    uint8_t log2_ps_iter_samples;
6900    if (ctx->program->info->ps.force_persample) {
6901       log2_ps_iter_samples =
6902          util_logbase2(ctx->options->key.fs.num_samples);
6903    } else {
6904       log2_ps_iter_samples = ctx->options->key.fs.log2_ps_iter_samples;
6905    }
6906 
6907    Builder bld(ctx->program, ctx->block);
6908 
6909    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
6910 
6911    if (log2_ps_iter_samples) {
6912       /* gl_SampleMaskIn[0] = (SampleCoverage & (1 << gl_SampleID)). */
6913       Temp sample_id = bld.vop3(aco_opcode::v_bfe_u32, bld.def(v1),
6914                                 get_arg(ctx, ctx->args->ac.ancillary), Operand(8u), Operand(4u));
6915       Temp mask = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), sample_id,
6916                            bld.copy(bld.def(v1), Operand(1u)));
6917       bld.vop2(aco_opcode::v_and_b32, Definition(dst), mask, get_arg(ctx, ctx->args->ac.sample_coverage));
6918    } else {
6919       bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.sample_coverage));
6920    }
6921 }
6922 
gs_outprim_vertices(unsigned outprim)6923 unsigned gs_outprim_vertices(unsigned outprim)
6924 {
6925    switch (outprim) {
6926    case 0: /* GL_POINTS */
6927       return 1;
6928    case 3: /* GL_LINE_STRIP */
6929       return 2;
6930    case 5: /* GL_TRIANGLE_STRIP */
6931       return 3;
6932    default:
6933       unreachable("Unsupported GS output primitive type.");
6934    }
6935 }
6936 
ngg_visit_emit_vertex_with_counter(isel_context * ctx,nir_intrinsic_instr * instr)6937 void ngg_visit_emit_vertex_with_counter(isel_context *ctx, nir_intrinsic_instr *instr)
6938 {
6939    Builder bld(ctx->program, ctx->block);
6940    Temp emit_vertex_idx = get_ssa_temp(ctx, instr->src[0].ssa);
6941    Temp emit_vertex_addr = ngg_gs_emit_vertex_lds_addr(ctx, emit_vertex_idx);
6942    unsigned stream = nir_intrinsic_stream_id(instr);
6943    unsigned out_idx = 0;
6944 
6945    for (unsigned i = 0; i <= VARYING_SLOT_VAR31; i++) {
6946       if (ctx->program->info->gs.output_streams[i] != stream) {
6947          continue;
6948       } else if (!ctx->outputs.mask[i] && ctx->program->info->gs.output_usage_mask[i]) {
6949          /* The GS can write this output, but it's empty for the current vertex. */
6950          out_idx++;
6951          continue;
6952       }
6953 
6954       uint32_t wrmask = ctx->program->info->gs.output_usage_mask[i] &
6955                         ctx->outputs.mask[i];
6956 
6957       /* Clear output for the next vertex. */
6958       ctx->outputs.mask[i] = 0;
6959 
6960       if (!wrmask)
6961          continue;
6962 
6963       for (unsigned j = 0; j < 4; j++) {
6964          if (wrmask & (1 << j)) {
6965             Temp elem = ctx->outputs.temps[i * 4u + j];
6966             store_lds(ctx, elem.bytes(), elem, 0x1u, emit_vertex_addr, out_idx * 4u, 4u);
6967          }
6968 
6969          out_idx++;
6970       }
6971    }
6972 
6973    /* Calculate per-vertex primitive flags based on current and total vertex count per primitive:
6974     *   bit 0: whether this vertex finishes a primitive
6975     *   bit 1: whether the primitive is odd (if we are emitting triangle strips, otherwise always 0)
6976     *   bit 2: always 1 (so that we can use it for determining vertex liveness)
6977     */
6978    unsigned total_vtx_per_prim = gs_outprim_vertices(ctx->shader->info.gs.output_primitive);
6979    bool calc_odd = stream == 0 && total_vtx_per_prim == 3;
6980    Temp prim_flag;
6981 
6982    if (nir_src_is_const(instr->src[1])) {
6983       uint8_t current_vtx_per_prim = nir_src_as_uint(instr->src[1]);
6984       uint8_t completes_prim = (current_vtx_per_prim >= (total_vtx_per_prim - 1)) ? 1 : 0;
6985       uint8_t odd = calc_odd & current_vtx_per_prim;
6986       uint8_t flag = completes_prim | (odd << 1) | (1 << 2);
6987       prim_flag = bld.copy(bld.def(v1b), Operand(flag));
6988    } else if (!instr->src[1].ssa->divergent) {
6989       Temp current_vtx_per_prim = bld.as_uniform(get_ssa_temp(ctx, instr->src[1].ssa));
6990       Temp completes_prim = bld.sopc(aco_opcode::s_cmp_le_u32, bld.def(s1, scc), Operand(total_vtx_per_prim - 1), current_vtx_per_prim);
6991       prim_flag = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1), Operand(0b101u), Operand(0b100u), bld.scc(completes_prim));
6992       if (calc_odd) {
6993          Temp odd = bld.sopc(aco_opcode::s_bitcmp1_b32, bld.def(s1, scc), current_vtx_per_prim, Operand(0u));
6994          prim_flag = bld.sop2(aco_opcode::s_lshl1_add_u32, bld.def(s1), bld.def(s1, scc), odd, prim_flag);
6995       }
6996    } else {
6997       Temp current_vtx_per_prim = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[1].ssa));
6998       Temp completes_prim = bld.vopc(aco_opcode::v_cmp_le_u32, bld.hint_vcc(bld.def(bld.lm)), Operand(total_vtx_per_prim - 1), current_vtx_per_prim);
6999       prim_flag = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0b100u), Operand(0b101u), Operand(completes_prim));
7000       if (calc_odd) {
7001          Temp odd = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(1u), current_vtx_per_prim);
7002          prim_flag = bld.vop3(aco_opcode::v_lshl_or_b32, bld.def(v1), odd, Operand(1u), prim_flag);
7003       }
7004    }
7005 
7006    /* Store the per-vertex primitive flags at the end of the vertex data */
7007    prim_flag = bld.pseudo(aco_opcode::p_extract_vector, bld.def(v1b), as_vgpr(ctx, prim_flag), Operand(0u));
7008    unsigned primflag_offset = ctx->ngg_gs_primflags_offset + stream;
7009    store_lds(ctx, 1, prim_flag, 1u, emit_vertex_addr, primflag_offset, 1);
7010 }
7011 
7012 void ngg_gs_clear_primflags(isel_context *ctx, Temp vtx_cnt, unsigned stream);
7013 void ngg_gs_write_shader_query(isel_context *ctx, nir_intrinsic_instr *instr);
7014 
ngg_visit_set_vertex_and_primitive_count(isel_context * ctx,nir_intrinsic_instr * instr)7015 void ngg_visit_set_vertex_and_primitive_count(isel_context *ctx, nir_intrinsic_instr *instr)
7016 {
7017    unsigned stream = nir_intrinsic_stream_id(instr);
7018    if (!ctx->args->shader_info->gs.num_stream_output_components[stream])
7019       return;
7020 
7021    ctx->ngg_gs_known_vtxcnt[stream] = true;
7022 
7023    /* Clear the primitive flags of non-emitted GS vertices. */
7024    if (!nir_src_is_const(instr->src[0]) || nir_src_as_uint(instr->src[0]) < ctx->shader->info.gs.vertices_out) {
7025       Temp vtx_cnt = get_ssa_temp(ctx, instr->src[0].ssa);
7026       ngg_gs_clear_primflags(ctx, vtx_cnt, stream);
7027    }
7028 
7029    ngg_gs_write_shader_query(ctx, instr);
7030 }
7031 
visit_emit_vertex_with_counter(isel_context * ctx,nir_intrinsic_instr * instr)7032 void visit_emit_vertex_with_counter(isel_context *ctx, nir_intrinsic_instr *instr)
7033 {
7034    Builder bld(ctx->program, ctx->block);
7035 
7036    unsigned stream = nir_intrinsic_stream_id(instr);
7037    Temp next_vertex = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
7038    next_vertex = bld.v_mul_imm(bld.def(v1), next_vertex, 4u);
7039    nir_const_value *next_vertex_cv = nir_src_as_const_value(instr->src[0]);
7040 
7041    /* get GSVS ring */
7042    Temp gsvs_ring = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), ctx->program->private_segment_buffer, Operand(RING_GSVS_GS * 16u));
7043 
7044    unsigned num_components =
7045       ctx->program->info->gs.num_stream_output_components[stream];
7046    assert(num_components);
7047 
7048    unsigned stride = 4u * num_components * ctx->shader->info.gs.vertices_out;
7049    unsigned stream_offset = 0;
7050    for (unsigned i = 0; i < stream; i++) {
7051       unsigned prev_stride = 4u * ctx->program->info->gs.num_stream_output_components[i] * ctx->shader->info.gs.vertices_out;
7052       stream_offset += prev_stride * ctx->program->wave_size;
7053    }
7054 
7055    /* Limit on the stride field for <= GFX7. */
7056    assert(stride < (1 << 14));
7057 
7058    Temp gsvs_dwords[4];
7059    for (unsigned i = 0; i < 4; i++)
7060       gsvs_dwords[i] = bld.tmp(s1);
7061    bld.pseudo(aco_opcode::p_split_vector,
7062               Definition(gsvs_dwords[0]),
7063               Definition(gsvs_dwords[1]),
7064               Definition(gsvs_dwords[2]),
7065               Definition(gsvs_dwords[3]),
7066               gsvs_ring);
7067 
7068    if (stream_offset) {
7069       Temp stream_offset_tmp = bld.copy(bld.def(s1), Operand(stream_offset));
7070 
7071       Temp carry = bld.tmp(s1);
7072       gsvs_dwords[0] = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.scc(Definition(carry)), gsvs_dwords[0], stream_offset_tmp);
7073       gsvs_dwords[1] = bld.sop2(aco_opcode::s_addc_u32, bld.def(s1), bld.def(s1, scc), gsvs_dwords[1], Operand(0u), bld.scc(carry));
7074    }
7075 
7076    gsvs_dwords[1] = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), gsvs_dwords[1], Operand(S_008F04_STRIDE(stride)));
7077    gsvs_dwords[2] = bld.copy(bld.def(s1), Operand((uint32_t)ctx->program->wave_size));
7078 
7079    gsvs_ring = bld.pseudo(aco_opcode::p_create_vector, bld.def(s4),
7080                           gsvs_dwords[0], gsvs_dwords[1], gsvs_dwords[2], gsvs_dwords[3]);
7081 
7082    unsigned offset = 0;
7083    for (unsigned i = 0; i <= VARYING_SLOT_VAR31; i++) {
7084       if (ctx->program->info->gs.output_streams[i] != stream)
7085          continue;
7086 
7087       for (unsigned j = 0; j < 4; j++) {
7088          if (!(ctx->program->info->gs.output_usage_mask[i] & (1 << j)))
7089             continue;
7090 
7091          if (ctx->outputs.mask[i] & (1 << j)) {
7092             Operand vaddr_offset = next_vertex_cv ? Operand(v1) : Operand(next_vertex);
7093             unsigned const_offset = (offset + (next_vertex_cv ? next_vertex_cv->u32 : 0u)) * 4u;
7094             if (const_offset >= 4096u) {
7095                if (vaddr_offset.isUndefined())
7096                   vaddr_offset = bld.copy(bld.def(v1), Operand(const_offset / 4096u * 4096u));
7097                else
7098                   vaddr_offset = bld.vadd32(bld.def(v1), Operand(const_offset / 4096u * 4096u), vaddr_offset);
7099                const_offset %= 4096u;
7100             }
7101 
7102             aco_ptr<MTBUF_instruction> mtbuf{create_instruction<MTBUF_instruction>(aco_opcode::tbuffer_store_format_x, Format::MTBUF, 4, 0)};
7103             mtbuf->operands[0] = Operand(gsvs_ring);
7104             mtbuf->operands[1] = vaddr_offset;
7105             mtbuf->operands[2] = Operand(get_arg(ctx, ctx->args->gs2vs_offset));
7106             mtbuf->operands[3] = Operand(ctx->outputs.temps[i * 4u + j]);
7107             mtbuf->offen = !vaddr_offset.isUndefined();
7108             mtbuf->dfmt = V_008F0C_BUF_DATA_FORMAT_32;
7109             mtbuf->nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
7110             mtbuf->offset = const_offset;
7111             mtbuf->glc = true;
7112             mtbuf->slc = true;
7113             mtbuf->sync = memory_sync_info(storage_vmem_output, semantic_can_reorder);
7114             bld.insert(std::move(mtbuf));
7115          }
7116 
7117          offset += ctx->shader->info.gs.vertices_out;
7118       }
7119 
7120       /* outputs for the next vertex are undefined and keeping them around can
7121        * create invalid IR with control flow */
7122       ctx->outputs.mask[i] = 0;
7123    }
7124 
7125    bld.sopp(aco_opcode::s_sendmsg, bld.m0(ctx->gs_wave_id), -1, sendmsg_gs(false, true, stream));
7126 }
7127 
emit_boolean_reduce(isel_context * ctx,nir_op op,unsigned cluster_size,Temp src)7128 Temp emit_boolean_reduce(isel_context *ctx, nir_op op, unsigned cluster_size, Temp src)
7129 {
7130    Builder bld(ctx->program, ctx->block);
7131 
7132    if (cluster_size == 1) {
7133       return src;
7134    } if (op == nir_op_iand && cluster_size == 4) {
7135       //subgroupClusteredAnd(val, 4) -> ~wqm(exec & ~val)
7136       Temp tmp = bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc), Operand(exec, bld.lm), src);
7137       return bld.sop1(Builder::s_not, bld.def(bld.lm), bld.def(s1, scc),
7138                       bld.sop1(Builder::s_wqm, bld.def(bld.lm), bld.def(s1, scc), tmp));
7139    } else if (op == nir_op_ior && cluster_size == 4) {
7140       //subgroupClusteredOr(val, 4) -> wqm(val & exec)
7141       return bld.sop1(Builder::s_wqm, bld.def(bld.lm), bld.def(s1, scc),
7142                       bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm)));
7143    } else if (op == nir_op_iand && cluster_size == ctx->program->wave_size) {
7144       //subgroupAnd(val) -> (exec & ~val) == 0
7145       Temp tmp = bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc), Operand(exec, bld.lm), src).def(1).getTemp();
7146       Temp cond = bool_to_vector_condition(ctx, emit_wqm(ctx, tmp));
7147       return bld.sop1(Builder::s_not, bld.def(bld.lm), bld.def(s1, scc), cond);
7148    } else if (op == nir_op_ior && cluster_size == ctx->program->wave_size) {
7149       //subgroupOr(val) -> (val & exec) != 0
7150       Temp tmp = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm)).def(1).getTemp();
7151       return bool_to_vector_condition(ctx, tmp);
7152    } else if (op == nir_op_ixor && cluster_size == ctx->program->wave_size) {
7153       //subgroupXor(val) -> s_bcnt1_i32_b64(val & exec) & 1
7154       Temp tmp = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm));
7155       tmp = bld.sop1(Builder::s_bcnt1_i32, bld.def(s1), bld.def(s1, scc), tmp);
7156       tmp = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), tmp, Operand(1u)).def(1).getTemp();
7157       return bool_to_vector_condition(ctx, tmp);
7158    } else {
7159       //subgroupClustered{And,Or,Xor}(val, n) ->
7160       //lane_id = v_mbcnt_hi_u32_b32(-1, v_mbcnt_lo_u32_b32(-1, 0)) ;  just v_mbcnt_lo_u32_b32 on wave32
7161       //cluster_offset = ~(n - 1) & lane_id
7162       //cluster_mask = ((1 << n) - 1)
7163       //subgroupClusteredAnd():
7164       //   return ((val | ~exec) >> cluster_offset) & cluster_mask == cluster_mask
7165       //subgroupClusteredOr():
7166       //   return ((val & exec) >> cluster_offset) & cluster_mask != 0
7167       //subgroupClusteredXor():
7168       //   return v_bnt_u32_b32(((val & exec) >> cluster_offset) & cluster_mask, 0) & 1 != 0
7169       Temp lane_id = emit_mbcnt(ctx, bld.tmp(v1));
7170       Temp cluster_offset = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(~uint32_t(cluster_size - 1)), lane_id);
7171 
7172       Temp tmp;
7173       if (op == nir_op_iand)
7174          tmp = bld.sop2(Builder::s_orn2, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm));
7175       else
7176          tmp = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm));
7177 
7178       uint32_t cluster_mask = cluster_size == 32 ? -1 : (1u << cluster_size) - 1u;
7179 
7180       if (ctx->program->chip_class <= GFX7)
7181          tmp = bld.vop3(aco_opcode::v_lshr_b64, bld.def(v2), tmp, cluster_offset);
7182       else if (ctx->program->wave_size == 64)
7183          tmp = bld.vop3(aco_opcode::v_lshrrev_b64, bld.def(v2), cluster_offset, tmp);
7184       else
7185          tmp = bld.vop2_e64(aco_opcode::v_lshrrev_b32, bld.def(v1), cluster_offset, tmp);
7186       tmp = emit_extract_vector(ctx, tmp, 0, v1);
7187       if (cluster_mask != 0xffffffff)
7188          tmp = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(cluster_mask), tmp);
7189 
7190       Definition cmp_def = Definition();
7191       if (op == nir_op_iand) {
7192          cmp_def = bld.vopc(aco_opcode::v_cmp_eq_u32, bld.def(bld.lm), Operand(cluster_mask), tmp).def(0);
7193       } else if (op == nir_op_ior) {
7194          cmp_def = bld.vopc(aco_opcode::v_cmp_lg_u32, bld.def(bld.lm), Operand(0u), tmp).def(0);
7195       } else if (op == nir_op_ixor) {
7196          tmp = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(1u),
7197                         bld.vop3(aco_opcode::v_bcnt_u32_b32, bld.def(v1), tmp, Operand(0u)));
7198          cmp_def = bld.vopc(aco_opcode::v_cmp_lg_u32, bld.def(bld.lm), Operand(0u), tmp).def(0);
7199       }
7200       cmp_def.setHint(vcc);
7201       return cmp_def.getTemp();
7202    }
7203 }
7204 
emit_boolean_exclusive_scan(isel_context * ctx,nir_op op,Temp src)7205 Temp emit_boolean_exclusive_scan(isel_context *ctx, nir_op op, Temp src)
7206 {
7207    Builder bld(ctx->program, ctx->block);
7208    assert(src.regClass() == bld.lm);
7209 
7210    //subgroupExclusiveAnd(val) -> mbcnt(exec & ~val) == 0
7211    //subgroupExclusiveOr(val) -> mbcnt(val & exec) != 0
7212    //subgroupExclusiveXor(val) -> mbcnt(val & exec) & 1 != 0
7213    Temp tmp;
7214    if (op == nir_op_iand)
7215       tmp = bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc), Operand(exec, bld.lm), src);
7216    else
7217       tmp = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm));
7218 
7219    Temp mbcnt = emit_mbcnt(ctx, bld.tmp(v1), Operand(tmp));
7220 
7221    Definition cmp_def = Definition();
7222    if (op == nir_op_iand)
7223       cmp_def = bld.vopc(aco_opcode::v_cmp_eq_u32, bld.def(bld.lm), Operand(0u), mbcnt).def(0);
7224    else if (op == nir_op_ior)
7225       cmp_def = bld.vopc(aco_opcode::v_cmp_lg_u32, bld.def(bld.lm), Operand(0u), mbcnt).def(0);
7226    else if (op == nir_op_ixor)
7227       cmp_def = bld.vopc(aco_opcode::v_cmp_lg_u32, bld.def(bld.lm), Operand(0u),
7228                          bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(1u), mbcnt)).def(0);
7229    cmp_def.setHint(vcc);
7230    return cmp_def.getTemp();
7231 }
7232 
emit_boolean_inclusive_scan(isel_context * ctx,nir_op op,Temp src)7233 Temp emit_boolean_inclusive_scan(isel_context *ctx, nir_op op, Temp src)
7234 {
7235    Builder bld(ctx->program, ctx->block);
7236 
7237    //subgroupInclusiveAnd(val) -> subgroupExclusiveAnd(val) && val
7238    //subgroupInclusiveOr(val) -> subgroupExclusiveOr(val) || val
7239    //subgroupInclusiveXor(val) -> subgroupExclusiveXor(val) ^^ val
7240    Temp tmp = emit_boolean_exclusive_scan(ctx, op, src);
7241    if (op == nir_op_iand)
7242       return bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), tmp, src);
7243    else if (op == nir_op_ior)
7244       return bld.sop2(Builder::s_or, bld.def(bld.lm), bld.def(s1, scc), tmp, src);
7245    else if (op == nir_op_ixor)
7246       return bld.sop2(Builder::s_xor, bld.def(bld.lm), bld.def(s1, scc), tmp, src);
7247 
7248    assert(false);
7249    return Temp();
7250 }
7251 
get_reduce_op(nir_op op,unsigned bit_size)7252 ReduceOp get_reduce_op(nir_op op, unsigned bit_size)
7253 {
7254    switch (op) {
7255    #define CASEI(name) case nir_op_##name: return (bit_size == 32) ? name##32 : (bit_size == 16) ? name##16 : (bit_size == 8) ? name##8 : name##64;
7256    #define CASEF(name) case nir_op_##name: return (bit_size == 32) ? name##32 : (bit_size == 16) ? name##16 : name##64;
7257    CASEI(iadd)
7258    CASEI(imul)
7259    CASEI(imin)
7260    CASEI(umin)
7261    CASEI(imax)
7262    CASEI(umax)
7263    CASEI(iand)
7264    CASEI(ior)
7265    CASEI(ixor)
7266    CASEF(fadd)
7267    CASEF(fmul)
7268    CASEF(fmin)
7269    CASEF(fmax)
7270    default:
7271       unreachable("unknown reduction op");
7272    #undef CASEI
7273    #undef CASEF
7274    }
7275 }
7276 
emit_uniform_subgroup(isel_context * ctx,nir_intrinsic_instr * instr,Temp src)7277 void emit_uniform_subgroup(isel_context *ctx, nir_intrinsic_instr *instr, Temp src)
7278 {
7279    Builder bld(ctx->program, ctx->block);
7280    Definition dst(get_ssa_temp(ctx, &instr->dest.ssa));
7281    assert(dst.regClass().type() != RegType::vgpr);
7282    if (src.regClass().type() == RegType::vgpr)
7283       bld.pseudo(aco_opcode::p_as_uniform, dst, src);
7284    else
7285       bld.copy(dst, src);
7286 }
7287 
emit_addition_uniform_reduce(isel_context * ctx,nir_op op,Definition dst,nir_src src,Temp count)7288 void emit_addition_uniform_reduce(isel_context *ctx, nir_op op, Definition dst, nir_src src, Temp count)
7289 {
7290    Builder bld(ctx->program, ctx->block);
7291    Temp src_tmp = get_ssa_temp(ctx, src.ssa);
7292 
7293    if (op == nir_op_fadd) {
7294       src_tmp = as_vgpr(ctx, src_tmp);
7295       Temp tmp = dst.regClass() == s1 ? bld.tmp(src_tmp.regClass()) : dst.getTemp();
7296 
7297       if (src.ssa->bit_size == 16) {
7298          count = bld.vop1(aco_opcode::v_cvt_f16_u16, bld.def(v2b), count);
7299          bld.vop2(aco_opcode::v_mul_f16, Definition(tmp), count, src_tmp);
7300       } else {
7301          assert(src.ssa->bit_size == 32);
7302          count = bld.vop1(aco_opcode::v_cvt_f32_u32, bld.def(v1), count);
7303          bld.vop2(aco_opcode::v_mul_f32, Definition(tmp), count, src_tmp);
7304       }
7305 
7306       if (tmp != dst.getTemp())
7307          bld.pseudo(aco_opcode::p_as_uniform, dst, tmp);
7308 
7309       return;
7310    }
7311 
7312    if (dst.regClass() == s1)
7313       src_tmp = bld.as_uniform(src_tmp);
7314 
7315    if (op == nir_op_ixor && count.type() == RegType::sgpr)
7316       count = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc),
7317                        count, Operand(1u));
7318    else if (op == nir_op_ixor)
7319       count = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(1u), count);
7320 
7321    assert(dst.getTemp().type() == count.type());
7322 
7323    if (nir_src_is_const(src)) {
7324       if (nir_src_as_uint(src) == 1 && dst.bytes() <= 2)
7325          bld.pseudo(aco_opcode::p_extract_vector, dst, count, Operand(0u));
7326       else if (nir_src_as_uint(src) == 1)
7327          bld.copy(dst, count);
7328       else if (nir_src_as_uint(src) == 0 && dst.bytes() <= 2)
7329          bld.vop1(aco_opcode::v_mov_b32, dst, Operand(0u)); /* RA will use SDWA if possible */
7330       else if (nir_src_as_uint(src) == 0)
7331          bld.copy(dst, Operand(0u));
7332       else if (count.type() == RegType::vgpr)
7333          bld.v_mul_imm(dst, count, nir_src_as_uint(src));
7334       else
7335          bld.sop2(aco_opcode::s_mul_i32, dst, src_tmp, count);
7336    } else if (dst.bytes() <= 2 && ctx->program->chip_class >= GFX10) {
7337       bld.vop3(aco_opcode::v_mul_lo_u16_e64, dst, src_tmp, count);
7338    } else if (dst.bytes() <= 2 && ctx->program->chip_class >= GFX8) {
7339       bld.vop2(aco_opcode::v_mul_lo_u16, dst, src_tmp, count);
7340    } else if (dst.getTemp().type() == RegType::vgpr) {
7341       bld.vop3(aco_opcode::v_mul_lo_u32, dst, src_tmp, count);
7342    } else {
7343       bld.sop2(aco_opcode::s_mul_i32, dst, src_tmp, count);
7344    }
7345 }
7346 
emit_uniform_reduce(isel_context * ctx,nir_intrinsic_instr * instr)7347 bool emit_uniform_reduce(isel_context *ctx, nir_intrinsic_instr *instr)
7348 {
7349    nir_op op = (nir_op)nir_intrinsic_reduction_op(instr);
7350    if (op == nir_op_imul || op == nir_op_fmul)
7351       return false;
7352 
7353    if (op == nir_op_iadd || op == nir_op_ixor || op == nir_op_fadd) {
7354       Builder bld(ctx->program, ctx->block);
7355       Definition dst(get_ssa_temp(ctx, &instr->dest.ssa));
7356       unsigned bit_size = instr->src[0].ssa->bit_size;
7357       if (bit_size > 32)
7358          return false;
7359 
7360       Temp thread_count = bld.sop1(
7361          Builder::s_bcnt1_i32, bld.def(s1), bld.def(s1, scc), Operand(exec, bld.lm));
7362 
7363       emit_addition_uniform_reduce(ctx, op, dst, instr->src[0], thread_count);
7364    } else {
7365       emit_uniform_subgroup(ctx, instr, get_ssa_temp(ctx, instr->src[0].ssa));
7366    }
7367 
7368    return true;
7369 }
7370 
emit_uniform_scan(isel_context * ctx,nir_intrinsic_instr * instr)7371 bool emit_uniform_scan(isel_context *ctx, nir_intrinsic_instr *instr)
7372 {
7373    Builder bld(ctx->program, ctx->block);
7374    Definition dst(get_ssa_temp(ctx, &instr->dest.ssa));
7375    nir_op op = (nir_op)nir_intrinsic_reduction_op(instr);
7376    bool inc = instr->intrinsic == nir_intrinsic_inclusive_scan;
7377 
7378    if (op == nir_op_imul || op == nir_op_fmul)
7379       return false;
7380 
7381    if (op == nir_op_iadd || op == nir_op_ixor || op == nir_op_fadd) {
7382       if (instr->src[0].ssa->bit_size > 32)
7383          return false;
7384 
7385       Temp packed_tid;
7386       if (inc)
7387          packed_tid = emit_mbcnt(ctx, bld.tmp(v1), Operand(exec, bld.lm), Operand(1u));
7388       else
7389          packed_tid = emit_mbcnt(ctx, bld.tmp(v1), Operand(exec, bld.lm));
7390 
7391       emit_addition_uniform_reduce(ctx, op, dst, instr->src[0], packed_tid);
7392       return true;
7393    }
7394 
7395    assert(op == nir_op_imin || op == nir_op_umin ||
7396           op == nir_op_imax || op == nir_op_umax ||
7397           op == nir_op_iand || op == nir_op_ior ||
7398           op == nir_op_fmin || op == nir_op_fmax);
7399 
7400    if (inc) {
7401       emit_uniform_subgroup(ctx, instr, get_ssa_temp(ctx, instr->src[0].ssa));
7402       return true;
7403    }
7404 
7405    /* Copy the source and write the reduction operation identity to the first
7406     * lane. */
7407    Temp lane = bld.sop1(Builder::s_ff1_i32, bld.def(s1), Operand(exec, bld.lm));
7408    Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
7409    ReduceOp reduce_op = get_reduce_op(op, instr->src[0].ssa->bit_size);
7410    if (dst.bytes() == 8) {
7411       Temp lo = bld.tmp(v1), hi = bld.tmp(v1);
7412       bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), src);
7413       uint32_t identity_lo = get_reduction_identity(reduce_op, 0);
7414       uint32_t identity_hi = get_reduction_identity(reduce_op, 1);
7415 
7416       lo = bld.writelane(bld.def(v1), bld.copy(bld.hint_m0(s1), Operand(identity_lo)), lane, lo);
7417       hi = bld.writelane(bld.def(v1), bld.copy(bld.hint_m0(s1), Operand(identity_hi)), lane, hi);
7418       bld.pseudo(aco_opcode::p_create_vector, dst, lo, hi);
7419    } else {
7420       uint32_t identity = get_reduction_identity(reduce_op, 0);
7421       bld.writelane(dst, bld.copy(bld.hint_m0(s1), Operand(identity)), lane, as_vgpr(ctx, src));
7422    }
7423 
7424    return true;
7425 }
7426 
emit_reduction_instr(isel_context * ctx,aco_opcode aco_op,ReduceOp op,unsigned cluster_size,Definition dst,Temp src)7427 Temp emit_reduction_instr(isel_context *ctx, aco_opcode aco_op, ReduceOp op,
7428                           unsigned cluster_size, Definition dst, Temp src)
7429 {
7430    assert(src.bytes() <= 8);
7431    assert(src.type() == RegType::vgpr);
7432 
7433    Builder bld(ctx->program, ctx->block);
7434 
7435    unsigned num_defs = 0;
7436    Definition defs[5];
7437    defs[num_defs++] = dst;
7438    defs[num_defs++] = bld.def(bld.lm); /* used internally to save/restore exec */
7439 
7440    /* scalar identity temporary */
7441    bool need_sitmp = (ctx->program->chip_class <= GFX7 || ctx->program->chip_class >= GFX10) && aco_op != aco_opcode::p_reduce;
7442    if (aco_op == aco_opcode::p_exclusive_scan) {
7443       need_sitmp |=
7444          (op == imin8 || op == imin16 || op == imin32 || op == imin64 ||
7445           op == imax8 || op == imax16 || op == imax32 || op == imax64 ||
7446           op == fmin16 || op == fmin32 || op == fmin64 ||
7447           op == fmax16 || op == fmax32 || op == fmax64 ||
7448           op == fmul16 || op == fmul64);
7449    }
7450    if (need_sitmp)
7451       defs[num_defs++] = bld.def(RegType::sgpr, dst.size());
7452 
7453    /* scc clobber */
7454    defs[num_defs++] = bld.def(s1, scc);
7455 
7456    /* vcc clobber */
7457    bool clobber_vcc = false;
7458    if ((op == iadd32 || op == imul64) && ctx->program->chip_class < GFX9)
7459       clobber_vcc = true;
7460    if (op == iadd64 || op == umin64 || op == umax64 || op == imin64 || op == imax64)
7461       clobber_vcc = true;
7462 
7463    if (clobber_vcc)
7464       defs[num_defs++] = bld.def(bld.lm, vcc);
7465 
7466    Pseudo_reduction_instruction *reduce = create_instruction<Pseudo_reduction_instruction>(aco_op, Format::PSEUDO_REDUCTION, 3, num_defs);
7467    reduce->operands[0] = Operand(src);
7468    /* setup_reduce_temp will update these undef operands if needed */
7469    reduce->operands[1] = Operand(RegClass(RegType::vgpr, dst.size()).as_linear());
7470    reduce->operands[2] = Operand(v1.as_linear());
7471    std::copy(defs, defs + num_defs, reduce->definitions.begin());
7472 
7473    reduce->reduce_op = op;
7474    reduce->cluster_size = cluster_size;
7475    bld.insert(std::move(reduce));
7476 
7477    return dst.getTemp();
7478 }
7479 
emit_interp_center(isel_context * ctx,Temp dst,Temp pos1,Temp pos2)7480 void emit_interp_center(isel_context *ctx, Temp dst, Temp pos1, Temp pos2)
7481 {
7482    Builder bld(ctx->program, ctx->block);
7483    Temp persp_center = get_arg(ctx, ctx->args->ac.persp_center);
7484    Temp p1 = emit_extract_vector(ctx, persp_center, 0, v1);
7485    Temp p2 = emit_extract_vector(ctx, persp_center, 1, v1);
7486 
7487    Temp ddx_1, ddx_2, ddy_1, ddy_2;
7488    uint32_t dpp_ctrl0 = dpp_quad_perm(0, 0, 0, 0);
7489    uint32_t dpp_ctrl1 = dpp_quad_perm(1, 1, 1, 1);
7490    uint32_t dpp_ctrl2 = dpp_quad_perm(2, 2, 2, 2);
7491 
7492    /* Build DD X/Y */
7493    if (ctx->program->chip_class >= GFX8) {
7494       Temp tl_1 = bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), p1, dpp_ctrl0);
7495       ddx_1 = bld.vop2_dpp(aco_opcode::v_sub_f32, bld.def(v1), p1, tl_1, dpp_ctrl1);
7496       ddy_1 = bld.vop2_dpp(aco_opcode::v_sub_f32, bld.def(v1), p1, tl_1, dpp_ctrl2);
7497       Temp tl_2 = bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), p2, dpp_ctrl0);
7498       ddx_2 = bld.vop2_dpp(aco_opcode::v_sub_f32, bld.def(v1), p2, tl_2, dpp_ctrl1);
7499       ddy_2 = bld.vop2_dpp(aco_opcode::v_sub_f32, bld.def(v1), p2, tl_2, dpp_ctrl2);
7500    } else {
7501       Temp tl_1 = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), p1, (1 << 15) | dpp_ctrl0);
7502       ddx_1 = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), p1, (1 << 15) | dpp_ctrl1);
7503       ddx_1 = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1), ddx_1, tl_1);
7504       ddx_2 = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), p1, (1 << 15) | dpp_ctrl2);
7505       ddx_2 = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1), ddx_2, tl_1);
7506       Temp tl_2 = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), p2, (1 << 15) | dpp_ctrl0);
7507       ddy_1 = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), p2, (1 << 15) | dpp_ctrl1);
7508       ddy_1 = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1), ddy_1, tl_2);
7509       ddy_2 = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), p2, (1 << 15) | dpp_ctrl2);
7510       ddy_2 = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1), ddy_2, tl_2);
7511    }
7512 
7513    /* res_k = p_k + ddx_k * pos1 + ddy_k * pos2 */
7514    aco_opcode mad = ctx->program->chip_class >= GFX10_3 ? aco_opcode::v_fma_f32 : aco_opcode::v_mad_f32;
7515    Temp tmp1 = bld.vop3(mad, bld.def(v1), ddx_1, pos1, p1);
7516    Temp tmp2 = bld.vop3(mad, bld.def(v1), ddx_2, pos1, p2);
7517    tmp1 = bld.vop3(mad, bld.def(v1), ddy_1, pos2, tmp1);
7518    tmp2 = bld.vop3(mad, bld.def(v1), ddy_2, pos2, tmp2);
7519    Temp wqm1 = bld.tmp(v1);
7520    emit_wqm(ctx, tmp1, wqm1, true);
7521    Temp wqm2 = bld.tmp(v1);
7522    emit_wqm(ctx, tmp2, wqm2, true);
7523    bld.pseudo(aco_opcode::p_create_vector, Definition(dst), wqm1, wqm2);
7524    return;
7525 }
7526 
visit_intrinsic(isel_context * ctx,nir_intrinsic_instr * instr)7527 void visit_intrinsic(isel_context *ctx, nir_intrinsic_instr *instr)
7528 {
7529    Builder bld(ctx->program, ctx->block);
7530    switch(instr->intrinsic) {
7531    case nir_intrinsic_load_barycentric_sample:
7532    case nir_intrinsic_load_barycentric_pixel:
7533    case nir_intrinsic_load_barycentric_centroid: {
7534       glsl_interp_mode mode = (glsl_interp_mode)nir_intrinsic_interp_mode(instr);
7535       Temp bary = Temp(0, s2);
7536       switch (mode) {
7537       case INTERP_MODE_SMOOTH:
7538       case INTERP_MODE_NONE:
7539          if (instr->intrinsic == nir_intrinsic_load_barycentric_pixel)
7540             bary = get_arg(ctx, ctx->args->ac.persp_center);
7541          else if (instr->intrinsic == nir_intrinsic_load_barycentric_centroid)
7542             bary = ctx->persp_centroid;
7543          else if (instr->intrinsic == nir_intrinsic_load_barycentric_sample)
7544             bary = get_arg(ctx, ctx->args->ac.persp_sample);
7545          break;
7546       case INTERP_MODE_NOPERSPECTIVE:
7547          if (instr->intrinsic == nir_intrinsic_load_barycentric_pixel)
7548             bary = get_arg(ctx, ctx->args->ac.linear_center);
7549          else if (instr->intrinsic == nir_intrinsic_load_barycentric_centroid)
7550             bary = ctx->linear_centroid;
7551          else if (instr->intrinsic == nir_intrinsic_load_barycentric_sample)
7552             bary = get_arg(ctx, ctx->args->ac.linear_sample);
7553          break;
7554       default:
7555          break;
7556       }
7557       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7558       Temp p1 = emit_extract_vector(ctx, bary, 0, v1);
7559       Temp p2 = emit_extract_vector(ctx, bary, 1, v1);
7560       bld.pseudo(aco_opcode::p_create_vector, Definition(dst),
7561                  Operand(p1), Operand(p2));
7562       emit_split_vector(ctx, dst, 2);
7563       break;
7564    }
7565    case nir_intrinsic_load_barycentric_model: {
7566       Temp model = get_arg(ctx, ctx->args->ac.pull_model);
7567 
7568       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7569       Temp p1 = emit_extract_vector(ctx, model, 0, v1);
7570       Temp p2 = emit_extract_vector(ctx, model, 1, v1);
7571       Temp p3 = emit_extract_vector(ctx, model, 2, v1);
7572       bld.pseudo(aco_opcode::p_create_vector, Definition(dst),
7573                  Operand(p1), Operand(p2), Operand(p3));
7574       emit_split_vector(ctx, dst, 3);
7575       break;
7576    }
7577    case nir_intrinsic_load_barycentric_at_sample: {
7578       uint32_t sample_pos_offset = RING_PS_SAMPLE_POSITIONS * 16;
7579       switch (ctx->options->key.fs.num_samples) {
7580          case 2: sample_pos_offset += 1 << 3; break;
7581          case 4: sample_pos_offset += 3 << 3; break;
7582          case 8: sample_pos_offset += 7 << 3; break;
7583          default: break;
7584       }
7585       Temp sample_pos;
7586       Temp addr = get_ssa_temp(ctx, instr->src[0].ssa);
7587       nir_const_value* const_addr = nir_src_as_const_value(instr->src[0]);
7588       Temp private_segment_buffer = ctx->program->private_segment_buffer;
7589       //TODO: bounds checking?
7590       if (addr.type() == RegType::sgpr) {
7591          Operand offset;
7592          if (const_addr) {
7593             sample_pos_offset += const_addr->u32 << 3;
7594             offset = Operand(sample_pos_offset);
7595          } else if (ctx->options->chip_class >= GFX9) {
7596             offset = bld.sop2(aco_opcode::s_lshl3_add_u32, bld.def(s1), bld.def(s1, scc), addr, Operand(sample_pos_offset));
7597          } else {
7598             offset = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), addr, Operand(3u));
7599             offset = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), bld.def(s1, scc), offset, Operand(sample_pos_offset));
7600          }
7601 
7602          Operand off = bld.copy(bld.def(s1), Operand(offset));
7603          sample_pos = bld.smem(aco_opcode::s_load_dwordx2, bld.def(s2), private_segment_buffer, off);
7604 
7605       } else if (ctx->options->chip_class >= GFX9) {
7606          addr = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(3u), addr);
7607          sample_pos = bld.global(aco_opcode::global_load_dwordx2, bld.def(v2), addr, private_segment_buffer, sample_pos_offset);
7608       } else if (ctx->options->chip_class >= GFX7) {
7609          /* addr += private_segment_buffer + sample_pos_offset */
7610          Temp tmp0 = bld.tmp(s1);
7611          Temp tmp1 = bld.tmp(s1);
7612          bld.pseudo(aco_opcode::p_split_vector, Definition(tmp0), Definition(tmp1), private_segment_buffer);
7613          Definition scc_tmp = bld.def(s1, scc);
7614          tmp0 = bld.sop2(aco_opcode::s_add_u32, bld.def(s1), scc_tmp, tmp0, Operand(sample_pos_offset));
7615          tmp1 = bld.sop2(aco_opcode::s_addc_u32, bld.def(s1), bld.def(s1, scc), tmp1, Operand(0u), bld.scc(scc_tmp.getTemp()));
7616          addr = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(3u), addr);
7617          Temp pck0 = bld.tmp(v1);
7618          Temp carry = bld.vadd32(Definition(pck0), tmp0, addr, true).def(1).getTemp();
7619          tmp1 = as_vgpr(ctx, tmp1);
7620          Temp pck1 = bld.vop2_e64(aco_opcode::v_addc_co_u32, bld.def(v1), bld.hint_vcc(bld.def(bld.lm)), tmp1, Operand(0u), carry);
7621          addr = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), pck0, pck1);
7622 
7623          /* sample_pos = flat_load_dwordx2 addr */
7624          sample_pos = bld.flat(aco_opcode::flat_load_dwordx2, bld.def(v2), addr, Operand(s1));
7625       } else {
7626          assert(ctx->options->chip_class == GFX6);
7627 
7628          uint32_t rsrc_conf = S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
7629                               S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
7630          Temp rsrc = bld.pseudo(aco_opcode::p_create_vector, bld.def(s4), private_segment_buffer, Operand(0u), Operand(rsrc_conf));
7631 
7632          addr = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(3u), addr);
7633          addr = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), addr, Operand(0u));
7634 
7635          sample_pos = bld.tmp(v2);
7636 
7637          aco_ptr<MUBUF_instruction> load{create_instruction<MUBUF_instruction>(aco_opcode::buffer_load_dwordx2, Format::MUBUF, 3, 1)};
7638          load->definitions[0] = Definition(sample_pos);
7639          load->operands[0] = Operand(rsrc);
7640          load->operands[1] = Operand(addr);
7641          load->operands[2] = Operand(0u);
7642          load->offset = sample_pos_offset;
7643          load->offen = 0;
7644          load->addr64 = true;
7645          load->glc = false;
7646          load->dlc = false;
7647          load->disable_wqm = false;
7648          ctx->block->instructions.emplace_back(std::move(load));
7649       }
7650 
7651       /* sample_pos -= 0.5 */
7652       Temp pos1 = bld.tmp(RegClass(sample_pos.type(), 1));
7653       Temp pos2 = bld.tmp(RegClass(sample_pos.type(), 1));
7654       bld.pseudo(aco_opcode::p_split_vector, Definition(pos1), Definition(pos2), sample_pos);
7655       pos1 = bld.vop2_e64(aco_opcode::v_sub_f32, bld.def(v1), pos1, Operand(0x3f000000u));
7656       pos2 = bld.vop2_e64(aco_opcode::v_sub_f32, bld.def(v1), pos2, Operand(0x3f000000u));
7657 
7658       emit_interp_center(ctx, get_ssa_temp(ctx, &instr->dest.ssa), pos1, pos2);
7659       break;
7660    }
7661    case nir_intrinsic_load_barycentric_at_offset: {
7662       Temp offset = get_ssa_temp(ctx, instr->src[0].ssa);
7663       RegClass rc = RegClass(offset.type(), 1);
7664       Temp pos1 = bld.tmp(rc), pos2 = bld.tmp(rc);
7665       bld.pseudo(aco_opcode::p_split_vector, Definition(pos1), Definition(pos2), offset);
7666       emit_interp_center(ctx, get_ssa_temp(ctx, &instr->dest.ssa), pos1, pos2);
7667       break;
7668    }
7669    case nir_intrinsic_load_front_face: {
7670       bld.vopc(aco_opcode::v_cmp_lg_u32, Definition(get_ssa_temp(ctx, &instr->dest.ssa)),
7671                Operand(0u), get_arg(ctx, ctx->args->ac.front_face)).def(0).setHint(vcc);
7672       break;
7673    }
7674    case nir_intrinsic_load_view_index: {
7675       if (ctx->stage.has(SWStage::VS) ||
7676           ctx->stage.has(SWStage::GS) ||
7677           ctx->stage.has(SWStage::TCS) ||
7678           ctx->stage.has(SWStage::TES)) {
7679          Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7680          bld.copy(Definition(dst), Operand(get_arg(ctx, ctx->args->ac.view_index)));
7681          break;
7682       }
7683 
7684       /* fallthrough */
7685    }
7686    case nir_intrinsic_load_layer_id: {
7687       unsigned idx = nir_intrinsic_base(instr);
7688       bld.vintrp(aco_opcode::v_interp_mov_f32, Definition(get_ssa_temp(ctx, &instr->dest.ssa)),
7689                  Operand(2u), bld.m0(get_arg(ctx, ctx->args->ac.prim_mask)), idx, 0);
7690       break;
7691    }
7692    case nir_intrinsic_load_frag_coord: {
7693       emit_load_frag_coord(ctx, get_ssa_temp(ctx, &instr->dest.ssa), 4);
7694       break;
7695    }
7696    case nir_intrinsic_load_sample_pos: {
7697       Temp posx = get_arg(ctx, ctx->args->ac.frag_pos[0]);
7698       Temp posy = get_arg(ctx, ctx->args->ac.frag_pos[1]);
7699       bld.pseudo(aco_opcode::p_create_vector, Definition(get_ssa_temp(ctx, &instr->dest.ssa)),
7700                  posx.id() ? bld.vop1(aco_opcode::v_fract_f32, bld.def(v1), posx) : Operand(0u),
7701                  posy.id() ? bld.vop1(aco_opcode::v_fract_f32, bld.def(v1), posy) : Operand(0u));
7702       break;
7703    }
7704    case nir_intrinsic_load_tess_coord:
7705       visit_load_tess_coord(ctx, instr);
7706       break;
7707    case nir_intrinsic_load_interpolated_input:
7708       visit_load_interpolated_input(ctx, instr);
7709       break;
7710    case nir_intrinsic_store_output:
7711       visit_store_output(ctx, instr);
7712       break;
7713    case nir_intrinsic_load_input:
7714    case nir_intrinsic_load_input_vertex:
7715       visit_load_input(ctx, instr);
7716       break;
7717    case nir_intrinsic_load_output:
7718       visit_load_output(ctx, instr);
7719       break;
7720    case nir_intrinsic_load_per_vertex_input:
7721       visit_load_per_vertex_input(ctx, instr);
7722       break;
7723    case nir_intrinsic_load_per_vertex_output:
7724       visit_load_per_vertex_output(ctx, instr);
7725       break;
7726    case nir_intrinsic_store_per_vertex_output:
7727       visit_store_per_vertex_output(ctx, instr);
7728       break;
7729    case nir_intrinsic_load_ubo:
7730       visit_load_ubo(ctx, instr);
7731       break;
7732    case nir_intrinsic_load_push_constant:
7733       visit_load_push_constant(ctx, instr);
7734       break;
7735    case nir_intrinsic_load_constant:
7736       visit_load_constant(ctx, instr);
7737       break;
7738    case nir_intrinsic_vulkan_resource_index:
7739       visit_load_resource(ctx, instr);
7740       break;
7741    case nir_intrinsic_terminate:
7742    case nir_intrinsic_discard:
7743       visit_discard(ctx, instr);
7744       break;
7745    case nir_intrinsic_terminate_if:
7746    case nir_intrinsic_discard_if:
7747       visit_discard_if(ctx, instr);
7748       break;
7749    case nir_intrinsic_load_shared:
7750       visit_load_shared(ctx, instr);
7751       break;
7752    case nir_intrinsic_store_shared:
7753       visit_store_shared(ctx, instr);
7754       break;
7755    case nir_intrinsic_shared_atomic_add:
7756    case nir_intrinsic_shared_atomic_imin:
7757    case nir_intrinsic_shared_atomic_umin:
7758    case nir_intrinsic_shared_atomic_imax:
7759    case nir_intrinsic_shared_atomic_umax:
7760    case nir_intrinsic_shared_atomic_and:
7761    case nir_intrinsic_shared_atomic_or:
7762    case nir_intrinsic_shared_atomic_xor:
7763    case nir_intrinsic_shared_atomic_exchange:
7764    case nir_intrinsic_shared_atomic_comp_swap:
7765    case nir_intrinsic_shared_atomic_fadd:
7766       visit_shared_atomic(ctx, instr);
7767       break;
7768    case nir_intrinsic_image_deref_load:
7769       visit_image_load(ctx, instr);
7770       break;
7771    case nir_intrinsic_image_deref_store:
7772       visit_image_store(ctx, instr);
7773       break;
7774    case nir_intrinsic_image_deref_atomic_add:
7775    case nir_intrinsic_image_deref_atomic_umin:
7776    case nir_intrinsic_image_deref_atomic_imin:
7777    case nir_intrinsic_image_deref_atomic_umax:
7778    case nir_intrinsic_image_deref_atomic_imax:
7779    case nir_intrinsic_image_deref_atomic_and:
7780    case nir_intrinsic_image_deref_atomic_or:
7781    case nir_intrinsic_image_deref_atomic_xor:
7782    case nir_intrinsic_image_deref_atomic_exchange:
7783    case nir_intrinsic_image_deref_atomic_comp_swap:
7784       visit_image_atomic(ctx, instr);
7785       break;
7786    case nir_intrinsic_image_deref_size:
7787       visit_image_size(ctx, instr);
7788       break;
7789    case nir_intrinsic_load_ssbo:
7790       visit_load_ssbo(ctx, instr);
7791       break;
7792    case nir_intrinsic_store_ssbo:
7793       visit_store_ssbo(ctx, instr);
7794       break;
7795    case nir_intrinsic_load_global:
7796       visit_load_global(ctx, instr);
7797       break;
7798    case nir_intrinsic_store_global:
7799       visit_store_global(ctx, instr);
7800       break;
7801    case nir_intrinsic_global_atomic_add:
7802    case nir_intrinsic_global_atomic_imin:
7803    case nir_intrinsic_global_atomic_umin:
7804    case nir_intrinsic_global_atomic_imax:
7805    case nir_intrinsic_global_atomic_umax:
7806    case nir_intrinsic_global_atomic_and:
7807    case nir_intrinsic_global_atomic_or:
7808    case nir_intrinsic_global_atomic_xor:
7809    case nir_intrinsic_global_atomic_exchange:
7810    case nir_intrinsic_global_atomic_comp_swap:
7811       visit_global_atomic(ctx, instr);
7812       break;
7813    case nir_intrinsic_ssbo_atomic_add:
7814    case nir_intrinsic_ssbo_atomic_imin:
7815    case nir_intrinsic_ssbo_atomic_umin:
7816    case nir_intrinsic_ssbo_atomic_imax:
7817    case nir_intrinsic_ssbo_atomic_umax:
7818    case nir_intrinsic_ssbo_atomic_and:
7819    case nir_intrinsic_ssbo_atomic_or:
7820    case nir_intrinsic_ssbo_atomic_xor:
7821    case nir_intrinsic_ssbo_atomic_exchange:
7822    case nir_intrinsic_ssbo_atomic_comp_swap:
7823       visit_atomic_ssbo(ctx, instr);
7824       break;
7825    case nir_intrinsic_load_scratch:
7826       visit_load_scratch(ctx, instr);
7827       break;
7828    case nir_intrinsic_store_scratch:
7829       visit_store_scratch(ctx, instr);
7830       break;
7831    case nir_intrinsic_get_ssbo_size:
7832       visit_get_ssbo_size(ctx, instr);
7833       break;
7834    case nir_intrinsic_scoped_barrier:
7835       emit_scoped_barrier(ctx, instr);
7836       break;
7837    case nir_intrinsic_load_num_work_groups: {
7838       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7839       bld.copy(Definition(dst), Operand(get_arg(ctx, ctx->args->ac.num_work_groups)));
7840       emit_split_vector(ctx, dst, 3);
7841       break;
7842    }
7843    case nir_intrinsic_load_local_invocation_id: {
7844       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7845       bld.copy(Definition(dst), Operand(get_arg(ctx, ctx->args->ac.local_invocation_ids)));
7846       emit_split_vector(ctx, dst, 3);
7847       break;
7848    }
7849    case nir_intrinsic_load_work_group_id: {
7850       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7851       struct ac_arg *args = ctx->args->ac.workgroup_ids;
7852       bld.pseudo(aco_opcode::p_create_vector, Definition(dst),
7853                  args[0].used ? Operand(get_arg(ctx, args[0])) : Operand(0u),
7854                  args[1].used ? Operand(get_arg(ctx, args[1])) : Operand(0u),
7855                  args[2].used ? Operand(get_arg(ctx, args[2])) : Operand(0u));
7856       emit_split_vector(ctx, dst, 3);
7857       break;
7858    }
7859    case nir_intrinsic_load_local_invocation_index: {
7860       Temp id = emit_mbcnt(ctx, bld.tmp(v1));
7861 
7862       /* The tg_size bits [6:11] contain the subgroup id,
7863        * we need this multiplied by the wave size, and then OR the thread id to it.
7864        */
7865       if (ctx->program->wave_size == 64) {
7866          /* After the s_and the bits are already multiplied by 64 (left shifted by 6) so we can just feed that to v_or */
7867          Temp tg_num = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), Operand(0xfc0u),
7868                                 get_arg(ctx, ctx->args->ac.tg_size));
7869          bld.vop2(aco_opcode::v_or_b32, Definition(get_ssa_temp(ctx, &instr->dest.ssa)), tg_num, id);
7870       } else {
7871          /* Extract the bit field and multiply the result by 32 (left shift by 5), then do the OR  */
7872          Temp tg_num = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
7873                                 get_arg(ctx, ctx->args->ac.tg_size), Operand(0x6u | (0x6u << 16)));
7874          bld.vop3(aco_opcode::v_lshl_or_b32, Definition(get_ssa_temp(ctx, &instr->dest.ssa)), tg_num, Operand(0x5u), id);
7875       }
7876       break;
7877    }
7878    case nir_intrinsic_load_subgroup_id: {
7879       if (ctx->stage == compute_cs) {
7880          bld.sop2(aco_opcode::s_bfe_u32, Definition(get_ssa_temp(ctx, &instr->dest.ssa)), bld.def(s1, scc),
7881                   get_arg(ctx, ctx->args->ac.tg_size), Operand(0x6u | (0x6u << 16)));
7882       } else {
7883          bld.copy(Definition(get_ssa_temp(ctx, &instr->dest.ssa)), Operand(0x0u));
7884       }
7885       break;
7886    }
7887    case nir_intrinsic_load_subgroup_invocation: {
7888       emit_mbcnt(ctx, get_ssa_temp(ctx, &instr->dest.ssa));
7889       break;
7890    }
7891    case nir_intrinsic_load_num_subgroups: {
7892       if (ctx->stage == compute_cs)
7893          bld.sop2(aco_opcode::s_and_b32, Definition(get_ssa_temp(ctx, &instr->dest.ssa)), bld.def(s1, scc), Operand(0x3fu),
7894                   get_arg(ctx, ctx->args->ac.tg_size));
7895       else
7896          bld.copy(Definition(get_ssa_temp(ctx, &instr->dest.ssa)), Operand(0x1u));
7897       break;
7898    }
7899    case nir_intrinsic_ballot: {
7900       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
7901       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7902       Definition tmp = bld.def(dst.regClass());
7903       Definition lanemask_tmp = dst.size() == bld.lm.size() ? tmp : bld.def(src.regClass());
7904       if (instr->src[0].ssa->bit_size == 1) {
7905          assert(src.regClass() == bld.lm);
7906          bld.sop2(Builder::s_and, lanemask_tmp, bld.def(s1, scc), Operand(exec, bld.lm), src);
7907       } else if (instr->src[0].ssa->bit_size == 32 && src.regClass() == v1) {
7908          bld.vopc(aco_opcode::v_cmp_lg_u32, lanemask_tmp, Operand(0u), src);
7909       } else if (instr->src[0].ssa->bit_size == 64 && src.regClass() == v2) {
7910          bld.vopc(aco_opcode::v_cmp_lg_u64, lanemask_tmp, Operand(0u), src);
7911       } else {
7912          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
7913       }
7914       if (dst.size() != bld.lm.size()) {
7915          /* Wave32 with ballot size set to 64 */
7916          bld.pseudo(aco_opcode::p_create_vector, Definition(tmp), lanemask_tmp.getTemp(), Operand(0u));
7917       }
7918       emit_wqm(ctx, tmp.getTemp(), dst);
7919       break;
7920    }
7921    case nir_intrinsic_shuffle:
7922    case nir_intrinsic_read_invocation: {
7923       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
7924       if (!nir_src_is_divergent(instr->src[0])) {
7925          emit_uniform_subgroup(ctx, instr, src);
7926       } else {
7927          Temp tid = get_ssa_temp(ctx, instr->src[1].ssa);
7928          if (instr->intrinsic == nir_intrinsic_read_invocation || !nir_src_is_divergent(instr->src[1]))
7929             tid = bld.as_uniform(tid);
7930          Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7931          if (src.regClass() == v1b || src.regClass() == v2b) {
7932             Temp tmp = bld.tmp(v1);
7933             tmp = emit_wqm(ctx, emit_bpermute(ctx, bld, tid, src), tmp);
7934             if (dst.type() == RegType::vgpr)
7935                bld.pseudo(aco_opcode::p_split_vector, Definition(dst), bld.def(src.regClass() == v1b ? v3b : v2b), tmp);
7936             else
7937                bld.pseudo(aco_opcode::p_as_uniform, Definition(dst), tmp);
7938          } else if (src.regClass() == v1) {
7939             emit_wqm(ctx, emit_bpermute(ctx, bld, tid, src), dst);
7940          } else if (src.regClass() == v2) {
7941             Temp lo = bld.tmp(v1), hi = bld.tmp(v1);
7942             bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), src);
7943             lo = emit_wqm(ctx, emit_bpermute(ctx, bld, tid, lo));
7944             hi = emit_wqm(ctx, emit_bpermute(ctx, bld, tid, hi));
7945             bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, hi);
7946             emit_split_vector(ctx, dst, 2);
7947          } else if (instr->dest.ssa.bit_size == 1 && tid.regClass() == s1) {
7948             assert(src.regClass() == bld.lm);
7949             Temp tmp = bld.sopc(Builder::s_bitcmp1, bld.def(s1, scc), src, tid);
7950             bool_to_vector_condition(ctx, emit_wqm(ctx, tmp), dst);
7951          } else if (instr->dest.ssa.bit_size == 1 && tid.regClass() == v1) {
7952             assert(src.regClass() == bld.lm);
7953             Temp tmp;
7954             if (ctx->program->chip_class <= GFX7)
7955                tmp = bld.vop3(aco_opcode::v_lshr_b64, bld.def(v2), src, tid);
7956             else if (ctx->program->wave_size == 64)
7957                tmp = bld.vop3(aco_opcode::v_lshrrev_b64, bld.def(v2), tid, src);
7958             else
7959                tmp = bld.vop2_e64(aco_opcode::v_lshrrev_b32, bld.def(v1), tid, src);
7960             tmp = emit_extract_vector(ctx, tmp, 0, v1);
7961             tmp = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(1u), tmp);
7962             emit_wqm(ctx, bld.vopc(aco_opcode::v_cmp_lg_u32, bld.def(bld.lm), Operand(0u), tmp), dst);
7963          } else {
7964             isel_err(&instr->instr, "Unimplemented NIR instr bit size");
7965          }
7966       }
7967       break;
7968    }
7969    case nir_intrinsic_load_sample_id: {
7970       bld.vop3(aco_opcode::v_bfe_u32, Definition(get_ssa_temp(ctx, &instr->dest.ssa)),
7971                get_arg(ctx, ctx->args->ac.ancillary), Operand(8u), Operand(4u));
7972       break;
7973    }
7974    case nir_intrinsic_load_sample_mask_in: {
7975       visit_load_sample_mask_in(ctx, instr);
7976       break;
7977    }
7978    case nir_intrinsic_read_first_invocation: {
7979       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
7980       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
7981       if (src.regClass() == v1b || src.regClass() == v2b || src.regClass() == v1) {
7982          emit_wqm(ctx,
7983                   bld.vop1(aco_opcode::v_readfirstlane_b32, bld.def(s1), src),
7984                   dst);
7985       } else if (src.regClass() == v2) {
7986          Temp lo = bld.tmp(v1), hi = bld.tmp(v1);
7987          bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), src);
7988          lo = emit_wqm(ctx, bld.vop1(aco_opcode::v_readfirstlane_b32, bld.def(s1), lo));
7989          hi = emit_wqm(ctx, bld.vop1(aco_opcode::v_readfirstlane_b32, bld.def(s1), hi));
7990          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, hi);
7991          emit_split_vector(ctx, dst, 2);
7992       } else if (instr->dest.ssa.bit_size == 1) {
7993          assert(src.regClass() == bld.lm);
7994          Temp tmp = bld.sopc(Builder::s_bitcmp1, bld.def(s1, scc), src,
7995                              bld.sop1(Builder::s_ff1_i32, bld.def(s1), Operand(exec, bld.lm)));
7996          bool_to_vector_condition(ctx, emit_wqm(ctx, tmp), dst);
7997       } else {
7998          bld.copy(Definition(dst), src);
7999       }
8000       break;
8001    }
8002    case nir_intrinsic_vote_all: {
8003       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
8004       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8005       assert(src.regClass() == bld.lm);
8006       assert(dst.regClass() == bld.lm);
8007 
8008       Temp tmp = bld.sop2(Builder::s_andn2, bld.def(bld.lm), bld.def(s1, scc), Operand(exec, bld.lm), src).def(1).getTemp();
8009       Temp cond = bool_to_vector_condition(ctx, emit_wqm(ctx, tmp));
8010       bld.sop1(Builder::s_not, Definition(dst), bld.def(s1, scc), cond);
8011       break;
8012    }
8013    case nir_intrinsic_vote_any: {
8014       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
8015       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8016       assert(src.regClass() == bld.lm);
8017       assert(dst.regClass() == bld.lm);
8018 
8019       Temp tmp = bool_to_scalar_condition(ctx, src);
8020       bool_to_vector_condition(ctx, emit_wqm(ctx, tmp), dst);
8021       break;
8022    }
8023    case nir_intrinsic_reduce:
8024    case nir_intrinsic_inclusive_scan:
8025    case nir_intrinsic_exclusive_scan: {
8026       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
8027       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8028       nir_op op = (nir_op) nir_intrinsic_reduction_op(instr);
8029       unsigned cluster_size = instr->intrinsic == nir_intrinsic_reduce ?
8030          nir_intrinsic_cluster_size(instr) : 0;
8031       cluster_size = util_next_power_of_two(MIN2(cluster_size ? cluster_size : ctx->program->wave_size, ctx->program->wave_size));
8032 
8033       if (!nir_src_is_divergent(instr->src[0]) &&
8034           cluster_size == ctx->program->wave_size && instr->dest.ssa.bit_size != 1) {
8035          /* We use divergence analysis to assign the regclass, so check if it's
8036           * working as expected */
8037          ASSERTED bool expected_divergent = instr->intrinsic == nir_intrinsic_exclusive_scan;
8038          if (instr->intrinsic == nir_intrinsic_inclusive_scan)
8039             expected_divergent = op == nir_op_iadd || op == nir_op_fadd || op == nir_op_ixor;
8040          assert(nir_dest_is_divergent(instr->dest) == expected_divergent);
8041 
8042          if (instr->intrinsic == nir_intrinsic_reduce) {
8043             if (emit_uniform_reduce(ctx, instr))
8044                break;
8045          } else if (emit_uniform_scan(ctx, instr)) {
8046             break;
8047          }
8048       }
8049 
8050       if (instr->dest.ssa.bit_size == 1) {
8051          if (op == nir_op_imul || op == nir_op_umin || op == nir_op_imin)
8052             op = nir_op_iand;
8053          else if (op == nir_op_iadd)
8054             op = nir_op_ixor;
8055          else if (op == nir_op_umax || op == nir_op_imax)
8056             op = nir_op_ior;
8057          assert(op == nir_op_iand || op == nir_op_ior || op == nir_op_ixor);
8058 
8059          switch (instr->intrinsic) {
8060          case nir_intrinsic_reduce:
8061             emit_wqm(ctx, emit_boolean_reduce(ctx, op, cluster_size, src), dst);
8062             break;
8063          case nir_intrinsic_exclusive_scan:
8064             emit_wqm(ctx, emit_boolean_exclusive_scan(ctx, op, src), dst);
8065             break;
8066          case nir_intrinsic_inclusive_scan:
8067             emit_wqm(ctx, emit_boolean_inclusive_scan(ctx, op, src), dst);
8068             break;
8069          default:
8070             assert(false);
8071          }
8072       } else if (cluster_size == 1) {
8073          bld.copy(Definition(dst), src);
8074       } else {
8075          unsigned bit_size = instr->src[0].ssa->bit_size;
8076 
8077          src = emit_extract_vector(ctx, src, 0, RegClass::get(RegType::vgpr, bit_size / 8));
8078 
8079          ReduceOp reduce_op = get_reduce_op(op, bit_size);
8080 
8081          aco_opcode aco_op;
8082          switch (instr->intrinsic) {
8083             case nir_intrinsic_reduce: aco_op = aco_opcode::p_reduce; break;
8084             case nir_intrinsic_inclusive_scan: aco_op = aco_opcode::p_inclusive_scan; break;
8085             case nir_intrinsic_exclusive_scan: aco_op = aco_opcode::p_exclusive_scan; break;
8086             default:
8087                unreachable("unknown reduce intrinsic");
8088          }
8089 
8090          Temp tmp_dst = emit_reduction_instr(ctx, aco_op, reduce_op, cluster_size, bld.def(dst.regClass()), src);
8091          emit_wqm(ctx, tmp_dst, dst);
8092       }
8093       break;
8094    }
8095    case nir_intrinsic_quad_broadcast: {
8096       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
8097       if (!nir_dest_is_divergent(instr->dest)) {
8098          emit_uniform_subgroup(ctx, instr, src);
8099       } else {
8100          Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8101          unsigned lane = nir_src_as_const_value(instr->src[1])->u32;
8102          uint32_t dpp_ctrl = dpp_quad_perm(lane, lane, lane, lane);
8103 
8104          if (instr->dest.ssa.bit_size == 1) {
8105             assert(src.regClass() == bld.lm);
8106             assert(dst.regClass() == bld.lm);
8107             uint32_t half_mask = 0x11111111u << lane;
8108             Temp mask_tmp = bld.pseudo(aco_opcode::p_create_vector, bld.def(s2), Operand(half_mask), Operand(half_mask));
8109             Temp tmp = bld.tmp(bld.lm);
8110             bld.sop1(Builder::s_wqm, Definition(tmp),
8111                      bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), mask_tmp,
8112                               bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm))));
8113             emit_wqm(ctx, tmp, dst);
8114          } else if (instr->dest.ssa.bit_size == 8) {
8115             Temp tmp = bld.tmp(v1);
8116             if (ctx->program->chip_class >= GFX8)
8117                emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl), tmp);
8118             else
8119                emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, (1 << 15) | dpp_ctrl), tmp);
8120             bld.pseudo(aco_opcode::p_split_vector, Definition(dst), bld.def(v3b), tmp);
8121          } else if (instr->dest.ssa.bit_size == 16) {
8122             Temp tmp = bld.tmp(v1);
8123             if (ctx->program->chip_class >= GFX8)
8124                emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl), tmp);
8125             else
8126                emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, (1 << 15) | dpp_ctrl), tmp);
8127             bld.pseudo(aco_opcode::p_split_vector, Definition(dst), bld.def(v2b), tmp);
8128          } else if (instr->dest.ssa.bit_size == 32) {
8129             if (ctx->program->chip_class >= GFX8)
8130                emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl), dst);
8131             else
8132                emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, (1 << 15) | dpp_ctrl), dst);
8133          } else if (instr->dest.ssa.bit_size == 64) {
8134             Temp lo = bld.tmp(v1), hi = bld.tmp(v1);
8135             bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), src);
8136             if (ctx->program->chip_class >= GFX8) {
8137                lo = emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), lo, dpp_ctrl));
8138                hi = emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), hi, dpp_ctrl));
8139             } else {
8140                lo = emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), lo, (1 << 15) | dpp_ctrl));
8141                hi = emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), hi, (1 << 15) | dpp_ctrl));
8142             }
8143             bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, hi);
8144             emit_split_vector(ctx, dst, 2);
8145          } else {
8146             isel_err(&instr->instr, "Unimplemented NIR instr bit size");
8147          }
8148       }
8149       break;
8150    }
8151    case nir_intrinsic_quad_swap_horizontal:
8152    case nir_intrinsic_quad_swap_vertical:
8153    case nir_intrinsic_quad_swap_diagonal:
8154    case nir_intrinsic_quad_swizzle_amd: {
8155       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
8156       if (!nir_dest_is_divergent(instr->dest)) {
8157          emit_uniform_subgroup(ctx, instr, src);
8158          break;
8159       }
8160       uint16_t dpp_ctrl = 0;
8161       switch (instr->intrinsic) {
8162       case nir_intrinsic_quad_swap_horizontal:
8163          dpp_ctrl = dpp_quad_perm(1, 0, 3, 2);
8164          break;
8165       case nir_intrinsic_quad_swap_vertical:
8166          dpp_ctrl = dpp_quad_perm(2, 3, 0, 1);
8167          break;
8168       case nir_intrinsic_quad_swap_diagonal:
8169          dpp_ctrl = dpp_quad_perm(3, 2, 1, 0);
8170          break;
8171       case nir_intrinsic_quad_swizzle_amd:
8172          dpp_ctrl = nir_intrinsic_swizzle_mask(instr);
8173          break;
8174       default:
8175          break;
8176       }
8177       if (ctx->program->chip_class < GFX8)
8178          dpp_ctrl |= (1 << 15);
8179 
8180       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8181       if (instr->dest.ssa.bit_size == 1) {
8182          assert(src.regClass() == bld.lm);
8183          src = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0u), Operand((uint32_t)-1), src);
8184          if (ctx->program->chip_class >= GFX8)
8185             src = bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl);
8186          else
8187             src = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, dpp_ctrl);
8188          Temp tmp = bld.vopc(aco_opcode::v_cmp_lg_u32, bld.def(bld.lm), Operand(0u), src);
8189          emit_wqm(ctx, tmp, dst);
8190       } else if (instr->dest.ssa.bit_size == 8) {
8191          Temp tmp = bld.tmp(v1);
8192          if (ctx->program->chip_class >= GFX8)
8193             emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl), tmp);
8194          else
8195             emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, dpp_ctrl), tmp);
8196          bld.pseudo(aco_opcode::p_split_vector, Definition(dst), bld.def(v3b), tmp);
8197       } else if (instr->dest.ssa.bit_size == 16) {
8198          Temp tmp = bld.tmp(v1);
8199          if (ctx->program->chip_class >= GFX8)
8200             emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl), tmp);
8201          else
8202             emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, dpp_ctrl), tmp);
8203          bld.pseudo(aco_opcode::p_split_vector, Definition(dst), bld.def(v2b), tmp);
8204       } else if (instr->dest.ssa.bit_size == 32) {
8205          Temp tmp;
8206          if (ctx->program->chip_class >= GFX8)
8207             tmp = bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), src, dpp_ctrl);
8208          else
8209             tmp = bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), src, dpp_ctrl);
8210          emit_wqm(ctx, tmp, dst);
8211       } else if (instr->dest.ssa.bit_size == 64) {
8212          Temp lo = bld.tmp(v1), hi = bld.tmp(v1);
8213          bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), src);
8214          if (ctx->program->chip_class >= GFX8) {
8215             lo = emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), lo, dpp_ctrl));
8216             hi = emit_wqm(ctx, bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), hi, dpp_ctrl));
8217          } else {
8218             lo = emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), lo, dpp_ctrl));
8219             hi = emit_wqm(ctx, bld.ds(aco_opcode::ds_swizzle_b32, bld.def(v1), hi, dpp_ctrl));
8220          }
8221          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, hi);
8222          emit_split_vector(ctx, dst, 2);
8223       } else {
8224          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
8225       }
8226       break;
8227    }
8228    case nir_intrinsic_masked_swizzle_amd: {
8229       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
8230       if (!nir_dest_is_divergent(instr->dest)) {
8231          emit_uniform_subgroup(ctx, instr, src);
8232          break;
8233       }
8234       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8235       uint32_t mask = nir_intrinsic_swizzle_mask(instr);
8236       if (instr->dest.ssa.bit_size == 1) {
8237          assert(src.regClass() == bld.lm);
8238          src = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), Operand(0u), Operand((uint32_t)-1), src);
8239          src = emit_masked_swizzle(ctx, bld, src, mask);
8240          Temp tmp = bld.vopc(aco_opcode::v_cmp_lg_u32, bld.def(bld.lm), Operand(0u), src);
8241          emit_wqm(ctx, tmp, dst);
8242       } else if (dst.regClass() == v1b) {
8243          Temp tmp = emit_wqm(ctx, emit_masked_swizzle(ctx, bld, src, mask));
8244          emit_extract_vector(ctx, tmp, 0, dst);
8245       } else if (dst.regClass() == v2b) {
8246          Temp tmp = emit_wqm(ctx, emit_masked_swizzle(ctx, bld, src, mask));
8247          emit_extract_vector(ctx, tmp, 0, dst);
8248       } else if (dst.regClass() == v1) {
8249          emit_wqm(ctx, emit_masked_swizzle(ctx, bld, src, mask), dst);
8250       } else if (dst.regClass() == v2) {
8251          Temp lo = bld.tmp(v1), hi = bld.tmp(v1);
8252          bld.pseudo(aco_opcode::p_split_vector, Definition(lo), Definition(hi), src);
8253          lo = emit_wqm(ctx, emit_masked_swizzle(ctx, bld, lo, mask));
8254          hi = emit_wqm(ctx, emit_masked_swizzle(ctx, bld, hi, mask));
8255          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, hi);
8256          emit_split_vector(ctx, dst, 2);
8257       } else {
8258          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
8259       }
8260       break;
8261    }
8262    case nir_intrinsic_write_invocation_amd: {
8263       Temp src = as_vgpr(ctx, get_ssa_temp(ctx, instr->src[0].ssa));
8264       Temp val = bld.as_uniform(get_ssa_temp(ctx, instr->src[1].ssa));
8265       Temp lane = bld.as_uniform(get_ssa_temp(ctx, instr->src[2].ssa));
8266       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8267       if (dst.regClass() == v1) {
8268          /* src2 is ignored for writelane. RA assigns the same reg for dst */
8269          emit_wqm(ctx, bld.writelane(bld.def(v1), val, lane, src), dst);
8270       } else if (dst.regClass() == v2) {
8271          Temp src_lo = bld.tmp(v1), src_hi = bld.tmp(v1);
8272          Temp val_lo = bld.tmp(s1), val_hi = bld.tmp(s1);
8273          bld.pseudo(aco_opcode::p_split_vector, Definition(src_lo), Definition(src_hi), src);
8274          bld.pseudo(aco_opcode::p_split_vector, Definition(val_lo), Definition(val_hi), val);
8275          Temp lo = emit_wqm(ctx, bld.writelane(bld.def(v1), val_lo, lane, src_hi));
8276          Temp hi = emit_wqm(ctx, bld.writelane(bld.def(v1), val_hi, lane, src_hi));
8277          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), lo, hi);
8278          emit_split_vector(ctx, dst, 2);
8279       } else {
8280          isel_err(&instr->instr, "Unimplemented NIR instr bit size");
8281       }
8282       break;
8283    }
8284    case nir_intrinsic_mbcnt_amd: {
8285       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
8286       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8287       Temp wqm_tmp = emit_mbcnt(ctx, bld.tmp(v1), Operand(src));
8288       emit_wqm(ctx, wqm_tmp, dst);
8289       break;
8290    }
8291    case nir_intrinsic_load_helper_invocation: {
8292       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8293       bld.pseudo(aco_opcode::p_load_helper, Definition(dst));
8294       ctx->block->kind |= block_kind_needs_lowering;
8295       ctx->program->needs_exact = true;
8296       break;
8297    }
8298    case nir_intrinsic_is_helper_invocation: {
8299       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8300       bld.pseudo(aco_opcode::p_is_helper, Definition(dst));
8301       ctx->block->kind |= block_kind_needs_lowering;
8302       ctx->program->needs_exact = true;
8303       break;
8304    }
8305    case nir_intrinsic_demote:
8306       bld.pseudo(aco_opcode::p_demote_to_helper, Operand(-1u));
8307 
8308       if (ctx->cf_info.loop_nest_depth || ctx->cf_info.parent_if.is_divergent)
8309          ctx->cf_info.exec_potentially_empty_discard = true;
8310       ctx->block->kind |= block_kind_uses_demote;
8311       ctx->program->needs_exact = true;
8312       break;
8313    case nir_intrinsic_demote_if: {
8314       Temp src = get_ssa_temp(ctx, instr->src[0].ssa);
8315       assert(src.regClass() == bld.lm);
8316       Temp cond = bld.sop2(Builder::s_and, bld.def(bld.lm), bld.def(s1, scc), src, Operand(exec, bld.lm));
8317       bld.pseudo(aco_opcode::p_demote_to_helper, cond);
8318 
8319       if (ctx->cf_info.loop_nest_depth || ctx->cf_info.parent_if.is_divergent)
8320          ctx->cf_info.exec_potentially_empty_discard = true;
8321       ctx->block->kind |= block_kind_uses_demote;
8322       ctx->program->needs_exact = true;
8323       break;
8324    }
8325    case nir_intrinsic_first_invocation: {
8326       emit_wqm(ctx, bld.sop1(Builder::s_ff1_i32, bld.def(s1), Operand(exec, bld.lm)),
8327                get_ssa_temp(ctx, &instr->dest.ssa));
8328       break;
8329    }
8330    case nir_intrinsic_last_invocation: {
8331       Temp flbit = bld.sop1(Builder::s_flbit_i32, bld.def(s1), Operand(exec, bld.lm));
8332       Temp last = bld.sop2(aco_opcode::s_sub_i32, bld.def(s1), bld.def(s1, scc),
8333                            Operand(ctx->program->wave_size - 1u), flbit);
8334       emit_wqm(ctx, last, get_ssa_temp(ctx, &instr->dest.ssa));
8335       break;
8336    }
8337    case nir_intrinsic_elect: {
8338       Temp first = bld.sop1(Builder::s_ff1_i32, bld.def(s1), Operand(exec, bld.lm));
8339       emit_wqm(ctx, bld.sop2(Builder::s_lshl, bld.def(bld.lm), bld.def(s1, scc), Operand(1u), first),
8340                get_ssa_temp(ctx, &instr->dest.ssa));
8341       break;
8342    }
8343    case nir_intrinsic_shader_clock: {
8344       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8345       if (nir_intrinsic_memory_scope(instr) == NIR_SCOPE_SUBGROUP && ctx->options->chip_class >= GFX10_3) {
8346          /* "((size - 1) << 11) | register" (SHADER_CYCLES is encoded as register 29) */
8347          Temp clock = bld.sopk(aco_opcode::s_getreg_b32, bld.def(s1), ((20 - 1) << 11) | 29);
8348          bld.pseudo(aco_opcode::p_create_vector, Definition(dst), clock, Operand(0u));
8349       } else {
8350          aco_opcode opcode =
8351             nir_intrinsic_memory_scope(instr) == NIR_SCOPE_DEVICE ?
8352                aco_opcode::s_memrealtime : aco_opcode::s_memtime;
8353          bld.smem(opcode, Definition(dst), memory_sync_info(0, semantic_volatile));
8354       }
8355       emit_split_vector(ctx, dst, 2);
8356       break;
8357    }
8358    case nir_intrinsic_load_vertex_id_zero_base: {
8359       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8360       bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.vertex_id));
8361       break;
8362    }
8363    case nir_intrinsic_load_first_vertex: {
8364       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8365       bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.base_vertex));
8366       break;
8367    }
8368    case nir_intrinsic_load_base_instance: {
8369       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8370       bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.start_instance));
8371       break;
8372    }
8373    case nir_intrinsic_load_instance_id: {
8374       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8375       bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.instance_id));
8376       break;
8377    }
8378    case nir_intrinsic_load_draw_id: {
8379       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8380       bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.draw_id));
8381       break;
8382    }
8383    case nir_intrinsic_load_invocation_id: {
8384       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8385 
8386       if (ctx->shader->info.stage == MESA_SHADER_GEOMETRY) {
8387          if (ctx->options->chip_class >= GFX10)
8388             bld.vop2_e64(aco_opcode::v_and_b32, Definition(dst), Operand(127u), get_arg(ctx, ctx->args->ac.gs_invocation_id));
8389          else
8390             bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.gs_invocation_id));
8391       } else if (ctx->shader->info.stage == MESA_SHADER_TESS_CTRL) {
8392          bld.vop3(aco_opcode::v_bfe_u32, Definition(dst),
8393                   get_arg(ctx, ctx->args->ac.tcs_rel_ids), Operand(8u), Operand(5u));
8394       } else {
8395          unreachable("Unsupported stage for load_invocation_id");
8396       }
8397 
8398       break;
8399    }
8400    case nir_intrinsic_load_primitive_id: {
8401       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8402 
8403       switch (ctx->shader->info.stage) {
8404       case MESA_SHADER_GEOMETRY:
8405          bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.gs_prim_id));
8406          break;
8407       case MESA_SHADER_TESS_CTRL:
8408          bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.tcs_patch_id));
8409          break;
8410       case MESA_SHADER_TESS_EVAL:
8411          bld.copy(Definition(dst), get_arg(ctx, ctx->args->ac.tes_patch_id));
8412          break;
8413       default:
8414          unreachable("Unimplemented shader stage for nir_intrinsic_load_primitive_id");
8415       }
8416 
8417       break;
8418    }
8419    case nir_intrinsic_load_patch_vertices_in: {
8420       assert(ctx->shader->info.stage == MESA_SHADER_TESS_CTRL ||
8421              ctx->shader->info.stage == MESA_SHADER_TESS_EVAL);
8422 
8423       Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8424       bld.copy(Definition(dst), Operand(ctx->args->options->key.tcs.input_vertices));
8425       break;
8426    }
8427    case nir_intrinsic_emit_vertex_with_counter: {
8428       if (ctx->stage.hw == HWStage::NGG)
8429          ngg_visit_emit_vertex_with_counter(ctx, instr);
8430       else
8431          visit_emit_vertex_with_counter(ctx, instr);
8432       break;
8433    }
8434    case nir_intrinsic_end_primitive_with_counter: {
8435       if (ctx->stage.hw != HWStage::NGG) {
8436          unsigned stream = nir_intrinsic_stream_id(instr);
8437          bld.sopp(aco_opcode::s_sendmsg, bld.m0(ctx->gs_wave_id), -1, sendmsg_gs(true, false, stream));
8438       }
8439       break;
8440    }
8441    case nir_intrinsic_set_vertex_and_primitive_count: {
8442       if (ctx->stage.hw == HWStage::NGG)
8443          ngg_visit_set_vertex_and_primitive_count(ctx, instr);
8444       /* unused in the legacy pipeline, the HW keeps track of this for us */
8445       break;
8446    }
8447    default:
8448       isel_err(&instr->instr, "Unimplemented intrinsic instr");
8449       abort();
8450 
8451       break;
8452    }
8453 }
8454 
8455 
tex_fetch_ptrs(isel_context * ctx,nir_tex_instr * instr,Temp * res_ptr,Temp * samp_ptr,Temp * fmask_ptr,enum glsl_base_type * stype)8456 void tex_fetch_ptrs(isel_context *ctx, nir_tex_instr *instr,
8457                     Temp *res_ptr, Temp *samp_ptr, Temp *fmask_ptr,
8458                     enum glsl_base_type *stype)
8459 {
8460    nir_deref_instr *texture_deref_instr = NULL;
8461    nir_deref_instr *sampler_deref_instr = NULL;
8462    int plane = -1;
8463 
8464    for (unsigned i = 0; i < instr->num_srcs; i++) {
8465       switch (instr->src[i].src_type) {
8466       case nir_tex_src_texture_deref:
8467          texture_deref_instr = nir_src_as_deref(instr->src[i].src);
8468          break;
8469       case nir_tex_src_sampler_deref:
8470          sampler_deref_instr = nir_src_as_deref(instr->src[i].src);
8471          break;
8472       case nir_tex_src_plane:
8473          plane = nir_src_as_int(instr->src[i].src);
8474          break;
8475       default:
8476          break;
8477       }
8478    }
8479 
8480    *stype = glsl_get_sampler_result_type(texture_deref_instr->type);
8481 
8482    if (!sampler_deref_instr)
8483       sampler_deref_instr = texture_deref_instr;
8484 
8485    if (plane >= 0) {
8486       assert(instr->op != nir_texop_txf_ms &&
8487              instr->op != nir_texop_samples_identical);
8488       assert(instr->sampler_dim  != GLSL_SAMPLER_DIM_BUF);
8489       *res_ptr = get_sampler_desc(ctx, texture_deref_instr, (aco_descriptor_type)(ACO_DESC_PLANE_0 + plane), instr, false, false);
8490    } else if (instr->sampler_dim  == GLSL_SAMPLER_DIM_BUF) {
8491       *res_ptr = get_sampler_desc(ctx, texture_deref_instr, ACO_DESC_BUFFER, instr, false, false);
8492    } else if (instr->op == nir_texop_fragment_mask_fetch) {
8493       *res_ptr = get_sampler_desc(ctx, texture_deref_instr, ACO_DESC_FMASK, instr, false, false);
8494    } else {
8495       *res_ptr = get_sampler_desc(ctx, texture_deref_instr, ACO_DESC_IMAGE, instr, false, false);
8496    }
8497    if (samp_ptr) {
8498       *samp_ptr = get_sampler_desc(ctx, sampler_deref_instr, ACO_DESC_SAMPLER, instr, false, false);
8499 
8500       if (instr->sampler_dim < GLSL_SAMPLER_DIM_RECT && ctx->options->chip_class < GFX8) {
8501          /* fix sampler aniso on SI/CI: samp[0] = samp[0] & img[7] */
8502          Builder bld(ctx->program, ctx->block);
8503 
8504          /* to avoid unnecessary moves, we split and recombine sampler and image */
8505          Temp img[8] = {bld.tmp(s1), bld.tmp(s1), bld.tmp(s1), bld.tmp(s1),
8506                         bld.tmp(s1), bld.tmp(s1), bld.tmp(s1), bld.tmp(s1)};
8507          Temp samp[4] = {bld.tmp(s1), bld.tmp(s1), bld.tmp(s1), bld.tmp(s1)};
8508          bld.pseudo(aco_opcode::p_split_vector, Definition(img[0]), Definition(img[1]),
8509                     Definition(img[2]), Definition(img[3]), Definition(img[4]),
8510                     Definition(img[5]), Definition(img[6]), Definition(img[7]), *res_ptr);
8511          bld.pseudo(aco_opcode::p_split_vector, Definition(samp[0]), Definition(samp[1]),
8512                     Definition(samp[2]), Definition(samp[3]), *samp_ptr);
8513 
8514          samp[0] = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), samp[0], img[7]);
8515          *res_ptr = bld.pseudo(aco_opcode::p_create_vector, bld.def(s8),
8516                                img[0], img[1], img[2], img[3],
8517                                img[4], img[5], img[6], img[7]);
8518          *samp_ptr = bld.pseudo(aco_opcode::p_create_vector, bld.def(s4),
8519                                 samp[0], samp[1], samp[2], samp[3]);
8520       }
8521    }
8522    if (fmask_ptr && (instr->op == nir_texop_txf_ms ||
8523                      instr->op == nir_texop_samples_identical))
8524       *fmask_ptr = get_sampler_desc(ctx, texture_deref_instr, ACO_DESC_FMASK, instr, false, false);
8525 }
8526 
build_cube_select(isel_context * ctx,Temp ma,Temp id,Temp deriv,Temp * out_ma,Temp * out_sc,Temp * out_tc)8527 void build_cube_select(isel_context *ctx, Temp ma, Temp id, Temp deriv,
8528                        Temp *out_ma, Temp *out_sc, Temp *out_tc)
8529 {
8530    Builder bld(ctx->program, ctx->block);
8531 
8532    Temp deriv_x = emit_extract_vector(ctx, deriv, 0, v1);
8533    Temp deriv_y = emit_extract_vector(ctx, deriv, 1, v1);
8534    Temp deriv_z = emit_extract_vector(ctx, deriv, 2, v1);
8535 
8536    Operand neg_one(0xbf800000u);
8537    Operand one(0x3f800000u);
8538    Operand two(0x40000000u);
8539    Operand four(0x40800000u);
8540 
8541    Temp is_ma_positive = bld.vopc(aco_opcode::v_cmp_le_f32, bld.hint_vcc(bld.def(bld.lm)), Operand(0u), ma);
8542    Temp sgn_ma = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1), neg_one, one, is_ma_positive);
8543    Temp neg_sgn_ma = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1), Operand(0u), sgn_ma);
8544 
8545    Temp is_ma_z = bld.vopc(aco_opcode::v_cmp_le_f32, bld.hint_vcc(bld.def(bld.lm)), four, id);
8546    Temp is_ma_y = bld.vopc(aco_opcode::v_cmp_le_f32, bld.def(bld.lm), two, id);
8547    is_ma_y = bld.sop2(Builder::s_andn2, bld.hint_vcc(bld.def(bld.lm)), is_ma_y, is_ma_z);
8548    Temp is_not_ma_x = bld.sop2(aco_opcode::s_or_b64, bld.hint_vcc(bld.def(bld.lm)), bld.def(s1, scc), is_ma_z, is_ma_y);
8549 
8550    // select sc
8551    Temp tmp = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), deriv_z, deriv_x, is_not_ma_x);
8552    Temp sgn = bld.vop2_e64(aco_opcode::v_cndmask_b32, bld.def(v1),
8553                        bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), neg_sgn_ma, sgn_ma, is_ma_z),
8554                        one, is_ma_y);
8555    *out_sc = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), tmp, sgn);
8556 
8557    // select tc
8558    tmp = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), deriv_y, deriv_z, is_ma_y);
8559    sgn = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), neg_one, sgn_ma, is_ma_y);
8560    *out_tc = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), tmp, sgn);
8561 
8562    // select ma
8563    tmp = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1),
8564                   bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), deriv_x, deriv_y, is_ma_y),
8565                   deriv_z, is_ma_z);
8566    tmp = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0x7fffffffu), tmp);
8567    *out_ma = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), two, tmp);
8568 }
8569 
prepare_cube_coords(isel_context * ctx,std::vector<Temp> & coords,Temp * ddx,Temp * ddy,bool is_deriv,bool is_array)8570 void prepare_cube_coords(isel_context *ctx, std::vector<Temp>& coords, Temp* ddx, Temp* ddy, bool is_deriv, bool is_array)
8571 {
8572    Builder bld(ctx->program, ctx->block);
8573    Temp ma, tc, sc, id;
8574    aco_opcode madak = ctx->program->chip_class >= GFX10_3 ? aco_opcode::v_fmaak_f32 : aco_opcode::v_madak_f32;
8575    aco_opcode madmk = ctx->program->chip_class >= GFX10_3 ? aco_opcode::v_fmamk_f32 : aco_opcode::v_madmk_f32;
8576 
8577    if (is_array) {
8578       coords[3] = bld.vop1(aco_opcode::v_rndne_f32, bld.def(v1), coords[3]);
8579 
8580       // see comment in ac_prepare_cube_coords()
8581       if (ctx->options->chip_class <= GFX8)
8582          coords[3] = bld.vop2(aco_opcode::v_max_f32, bld.def(v1), Operand(0u), coords[3]);
8583    }
8584 
8585    ma = bld.vop3(aco_opcode::v_cubema_f32, bld.def(v1), coords[0], coords[1], coords[2]);
8586 
8587    aco_ptr<VOP3A_instruction> vop3a{create_instruction<VOP3A_instruction>(aco_opcode::v_rcp_f32, asVOP3(Format::VOP1), 1, 1)};
8588    vop3a->operands[0] = Operand(ma);
8589    vop3a->abs[0] = true;
8590    Temp invma = bld.tmp(v1);
8591    vop3a->definitions[0] = Definition(invma);
8592    ctx->block->instructions.emplace_back(std::move(vop3a));
8593 
8594    sc = bld.vop3(aco_opcode::v_cubesc_f32, bld.def(v1), coords[0], coords[1], coords[2]);
8595    if (!is_deriv)
8596       sc = bld.vop2(madak, bld.def(v1), sc, invma, Operand(0x3fc00000u/*1.5*/));
8597 
8598    tc = bld.vop3(aco_opcode::v_cubetc_f32, bld.def(v1), coords[0], coords[1], coords[2]);
8599    if (!is_deriv)
8600       tc = bld.vop2(madak, bld.def(v1), tc, invma, Operand(0x3fc00000u/*1.5*/));
8601 
8602    id = bld.vop3(aco_opcode::v_cubeid_f32, bld.def(v1), coords[0], coords[1], coords[2]);
8603 
8604    if (is_deriv) {
8605       sc = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), sc, invma);
8606       tc = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), tc, invma);
8607 
8608       for (unsigned i = 0; i < 2; i++) {
8609          // see comment in ac_prepare_cube_coords()
8610          Temp deriv_ma;
8611          Temp deriv_sc, deriv_tc;
8612          build_cube_select(ctx, ma, id, i ? *ddy : *ddx,
8613                            &deriv_ma, &deriv_sc, &deriv_tc);
8614 
8615          deriv_ma = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), deriv_ma, invma);
8616 
8617          Temp x = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1),
8618                                bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), deriv_sc, invma),
8619                                bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), deriv_ma, sc));
8620          Temp y = bld.vop2(aco_opcode::v_sub_f32, bld.def(v1),
8621                                bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), deriv_tc, invma),
8622                                bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), deriv_ma, tc));
8623          *(i ? ddy : ddx) = bld.pseudo(aco_opcode::p_create_vector, bld.def(v2), x, y);
8624       }
8625 
8626       sc = bld.vop2(aco_opcode::v_add_f32, bld.def(v1), Operand(0x3fc00000u/*1.5*/), sc);
8627       tc = bld.vop2(aco_opcode::v_add_f32, bld.def(v1), Operand(0x3fc00000u/*1.5*/), tc);
8628    }
8629 
8630    if (is_array)
8631       id = bld.vop2(madmk, bld.def(v1), coords[3], id, Operand(0x41000000u/*8.0*/));
8632    coords.resize(3);
8633    coords[0] = sc;
8634    coords[1] = tc;
8635    coords[2] = id;
8636 }
8637 
get_const_vec(nir_ssa_def * vec,nir_const_value * cv[4])8638 void get_const_vec(nir_ssa_def *vec, nir_const_value *cv[4])
8639 {
8640    if (vec->parent_instr->type != nir_instr_type_alu)
8641       return;
8642    nir_alu_instr *vec_instr = nir_instr_as_alu(vec->parent_instr);
8643    if (vec_instr->op != nir_op_vec(vec->num_components))
8644       return;
8645 
8646    for (unsigned i = 0; i < vec->num_components; i++) {
8647       cv[i] = vec_instr->src[i].swizzle[0] == 0 ?
8648               nir_src_as_const_value(vec_instr->src[i].src) : NULL;
8649    }
8650 }
8651 
visit_tex(isel_context * ctx,nir_tex_instr * instr)8652 void visit_tex(isel_context *ctx, nir_tex_instr *instr)
8653 {
8654    Builder bld(ctx->program, ctx->block);
8655    bool has_bias = false, has_lod = false, level_zero = false, has_compare = false,
8656         has_offset = false, has_ddx = false, has_ddy = false, has_derivs = false, has_sample_index = false,
8657         has_clamped_lod = false;
8658    Temp resource, sampler, fmask_ptr, bias = Temp(), compare = Temp(), sample_index = Temp(),
8659         lod = Temp(), offset = Temp(), ddx = Temp(), ddy = Temp(),
8660         clamped_lod = Temp();
8661    std::vector<Temp> coords;
8662    std::vector<Temp> derivs;
8663    nir_const_value *sample_index_cv = NULL;
8664    nir_const_value *const_offset[4] = {NULL, NULL, NULL, NULL};
8665    enum glsl_base_type stype;
8666    tex_fetch_ptrs(ctx, instr, &resource, &sampler, &fmask_ptr, &stype);
8667 
8668    bool tg4_integer_workarounds = ctx->options->chip_class <= GFX8 && instr->op == nir_texop_tg4 &&
8669                                   (stype == GLSL_TYPE_UINT || stype == GLSL_TYPE_INT);
8670    bool tg4_integer_cube_workaround = tg4_integer_workarounds &&
8671                                       instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE;
8672 
8673    for (unsigned i = 0; i < instr->num_srcs; i++) {
8674       switch (instr->src[i].src_type) {
8675       case nir_tex_src_coord: {
8676          Temp coord = get_ssa_temp(ctx, instr->src[i].src.ssa);
8677          for (unsigned i = 0; i < coord.size(); i++)
8678             coords.emplace_back(emit_extract_vector(ctx, coord, i, v1));
8679          break;
8680       }
8681       case nir_tex_src_bias:
8682          bias = get_ssa_temp(ctx, instr->src[i].src.ssa);
8683          has_bias = true;
8684          break;
8685       case nir_tex_src_lod: {
8686          if (nir_src_is_const(instr->src[i].src) && nir_src_as_uint(instr->src[i].src) == 0) {
8687             level_zero = true;
8688          } else {
8689             lod = get_ssa_temp(ctx, instr->src[i].src.ssa);
8690             has_lod = true;
8691          }
8692          break;
8693       }
8694       case nir_tex_src_min_lod:
8695          clamped_lod = get_ssa_temp(ctx, instr->src[i].src.ssa);
8696          has_clamped_lod = true;
8697          break;
8698       case nir_tex_src_comparator:
8699          if (instr->is_shadow) {
8700             compare = get_ssa_temp(ctx, instr->src[i].src.ssa);
8701             has_compare = true;
8702          }
8703          break;
8704       case nir_tex_src_offset:
8705          offset = get_ssa_temp(ctx, instr->src[i].src.ssa);
8706          get_const_vec(instr->src[i].src.ssa, const_offset);
8707          has_offset = true;
8708          break;
8709       case nir_tex_src_ddx:
8710          ddx = get_ssa_temp(ctx, instr->src[i].src.ssa);
8711          has_ddx = true;
8712          break;
8713       case nir_tex_src_ddy:
8714          ddy = get_ssa_temp(ctx, instr->src[i].src.ssa);
8715          has_ddy = true;
8716          break;
8717       case nir_tex_src_ms_index:
8718          sample_index = get_ssa_temp(ctx, instr->src[i].src.ssa);
8719          sample_index_cv = nir_src_as_const_value(instr->src[i].src);
8720          has_sample_index = true;
8721          break;
8722       case nir_tex_src_texture_offset:
8723       case nir_tex_src_sampler_offset:
8724       default:
8725          break;
8726       }
8727    }
8728 
8729    if (instr->op == nir_texop_txs && instr->sampler_dim == GLSL_SAMPLER_DIM_BUF)
8730       return get_buffer_size(ctx, resource, get_ssa_temp(ctx, &instr->dest.ssa), true);
8731 
8732    if (instr->op == nir_texop_texture_samples) {
8733       Temp dword3 = emit_extract_vector(ctx, resource, 3, s1);
8734 
8735       Temp samples_log2 = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc), dword3, Operand(16u | 4u<<16));
8736       Temp samples = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), Operand(1u), samples_log2);
8737       Temp type = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc), dword3, Operand(28u | 4u<<16 /* offset=28, width=4 */));
8738 
8739       Operand default_sample = Operand(1u);
8740       if (ctx->options->robust_buffer_access) {
8741          /* Extract the second dword of the descriptor, if it's
8742 	  * all zero, then it's a null descriptor.
8743 	  */
8744          Temp dword1 = emit_extract_vector(ctx, resource, 1, s1);
8745          Temp is_non_null_descriptor = bld.sopc(aco_opcode::s_cmp_gt_u32, bld.def(s1, scc), dword1, Operand(0u));
8746          default_sample = Operand(is_non_null_descriptor);
8747       }
8748 
8749       Temp is_msaa = bld.sopc(aco_opcode::s_cmp_ge_u32, bld.def(s1, scc), type, Operand(14u));
8750       bld.sop2(aco_opcode::s_cselect_b32, Definition(get_ssa_temp(ctx, &instr->dest.ssa)),
8751                samples, default_sample, bld.scc(is_msaa));
8752       return;
8753    }
8754 
8755    if (has_offset && instr->op != nir_texop_txf && instr->op != nir_texop_txf_ms) {
8756       aco_ptr<Instruction> tmp_instr;
8757       Temp acc, pack = Temp();
8758 
8759       uint32_t pack_const = 0;
8760       for (unsigned i = 0; i < offset.size(); i++) {
8761          if (!const_offset[i])
8762             continue;
8763          pack_const |= (const_offset[i]->u32 & 0x3Fu) << (8u * i);
8764       }
8765 
8766       if (offset.type() == RegType::sgpr) {
8767          for (unsigned i = 0; i < offset.size(); i++) {
8768             if (const_offset[i])
8769                continue;
8770 
8771             acc = emit_extract_vector(ctx, offset, i, s1);
8772             acc = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), acc, Operand(0x3Fu));
8773 
8774             if (i) {
8775                acc = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), acc, Operand(8u * i));
8776             }
8777 
8778             if (pack == Temp()) {
8779                pack = acc;
8780             } else {
8781                pack = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), pack, acc);
8782             }
8783          }
8784 
8785          if (pack_const && pack != Temp())
8786             pack = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), Operand(pack_const), pack);
8787       } else {
8788          for (unsigned i = 0; i < offset.size(); i++) {
8789             if (const_offset[i])
8790                continue;
8791 
8792             acc = emit_extract_vector(ctx, offset, i, v1);
8793             acc = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0x3Fu), acc);
8794 
8795             if (i) {
8796                acc = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(8u * i), acc);
8797             }
8798 
8799             if (pack == Temp()) {
8800                pack = acc;
8801             } else {
8802                pack = bld.vop2(aco_opcode::v_or_b32, bld.def(v1), pack, acc);
8803             }
8804          }
8805 
8806          if (pack_const && pack != Temp())
8807             pack = bld.sop2(aco_opcode::v_or_b32, bld.def(v1), Operand(pack_const), pack);
8808       }
8809       if (pack_const && pack == Temp())
8810          offset = bld.copy(bld.def(v1), Operand(pack_const));
8811       else if (pack == Temp())
8812          has_offset = false;
8813       else
8814          offset = pack;
8815    }
8816 
8817    if (instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE && instr->coord_components)
8818       prepare_cube_coords(ctx, coords, &ddx, &ddy, instr->op == nir_texop_txd, instr->is_array && instr->op != nir_texop_lod);
8819 
8820    /* pack derivatives */
8821    if (has_ddx || has_ddy) {
8822       if (instr->sampler_dim == GLSL_SAMPLER_DIM_1D && ctx->options->chip_class == GFX9) {
8823          assert(has_ddx && has_ddy && ddx.size() == 1 && ddy.size() == 1);
8824          Temp zero = bld.copy(bld.def(v1), Operand(0u));
8825          derivs = {ddx, zero, ddy, zero};
8826       } else {
8827          for (unsigned i = 0; has_ddx && i < ddx.size(); i++)
8828             derivs.emplace_back(emit_extract_vector(ctx, ddx, i, v1));
8829          for (unsigned i = 0; has_ddy && i < ddy.size(); i++)
8830             derivs.emplace_back(emit_extract_vector(ctx, ddy, i, v1));
8831       }
8832       has_derivs = true;
8833    }
8834 
8835    if (instr->coord_components > 1 &&
8836        instr->sampler_dim == GLSL_SAMPLER_DIM_1D &&
8837        instr->is_array &&
8838        instr->op != nir_texop_txf)
8839       coords[1] = bld.vop1(aco_opcode::v_rndne_f32, bld.def(v1), coords[1]);
8840 
8841    if (instr->coord_components > 2 &&
8842       (instr->sampler_dim == GLSL_SAMPLER_DIM_2D ||
8843        instr->sampler_dim == GLSL_SAMPLER_DIM_MS ||
8844        instr->sampler_dim == GLSL_SAMPLER_DIM_SUBPASS ||
8845        instr->sampler_dim == GLSL_SAMPLER_DIM_SUBPASS_MS) &&
8846        instr->is_array &&
8847        instr->op != nir_texop_txf &&
8848        instr->op != nir_texop_txf_ms &&
8849        instr->op != nir_texop_fragment_fetch &&
8850        instr->op != nir_texop_fragment_mask_fetch)
8851       coords[2] = bld.vop1(aco_opcode::v_rndne_f32, bld.def(v1), coords[2]);
8852 
8853    if (ctx->options->chip_class == GFX9 &&
8854        instr->sampler_dim == GLSL_SAMPLER_DIM_1D &&
8855        instr->op != nir_texop_lod && instr->coord_components) {
8856       assert(coords.size() > 0 && coords.size() < 3);
8857 
8858       coords.insert(std::next(coords.begin()), bld.copy(bld.def(v1), instr->op == nir_texop_txf ?
8859                                                                      Operand((uint32_t) 0) :
8860                                                                      Operand((uint32_t) 0x3f000000)));
8861    }
8862 
8863    bool da = should_declare_array(ctx, instr->sampler_dim, instr->is_array);
8864 
8865    if (instr->op == nir_texop_samples_identical)
8866       resource = fmask_ptr;
8867 
8868    else if ((instr->sampler_dim == GLSL_SAMPLER_DIM_MS ||
8869              instr->sampler_dim == GLSL_SAMPLER_DIM_SUBPASS_MS) &&
8870             instr->op != nir_texop_txs &&
8871 	    instr->op != nir_texop_fragment_fetch &&
8872 	    instr->op != nir_texop_fragment_mask_fetch) {
8873       assert(has_sample_index);
8874       Operand op(sample_index);
8875       if (sample_index_cv)
8876          op = Operand(sample_index_cv->u32);
8877       sample_index = adjust_sample_index_using_fmask(ctx, da, coords, op, fmask_ptr);
8878    }
8879 
8880    if (has_offset && (instr->op == nir_texop_txf || instr->op == nir_texop_txf_ms)) {
8881       for (unsigned i = 0; i < std::min(offset.size(), instr->coord_components); i++) {
8882          Temp off = emit_extract_vector(ctx, offset, i, v1);
8883          coords[i] = bld.vadd32(bld.def(v1), coords[i], off);
8884       }
8885       has_offset = false;
8886    }
8887 
8888    /* Build tex instruction */
8889    unsigned dmask = nir_ssa_def_components_read(&instr->dest.ssa);
8890    unsigned dim = ctx->options->chip_class >= GFX10 && instr->sampler_dim != GLSL_SAMPLER_DIM_BUF
8891                   ? ac_get_sampler_dim(ctx->options->chip_class, instr->sampler_dim, instr->is_array)
8892                   : 0;
8893    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
8894    Temp tmp_dst = dst;
8895 
8896    /* gather4 selects the component by dmask and always returns vec4 */
8897    if (instr->op == nir_texop_tg4) {
8898       assert(instr->dest.ssa.num_components == 4);
8899       if (instr->is_shadow)
8900          dmask = 1;
8901       else
8902          dmask = 1 << instr->component;
8903       if (tg4_integer_cube_workaround || dst.type() == RegType::sgpr)
8904          tmp_dst = bld.tmp(v4);
8905    } else if (instr->op == nir_texop_samples_identical) {
8906       tmp_dst = bld.tmp(v1);
8907    } else if (util_bitcount(dmask) != instr->dest.ssa.num_components || dst.type() == RegType::sgpr) {
8908       tmp_dst = bld.tmp(RegClass(RegType::vgpr, util_bitcount(dmask)));
8909    }
8910 
8911    aco_ptr<MIMG_instruction> tex;
8912    if (instr->op == nir_texop_txs || instr->op == nir_texop_query_levels) {
8913       if (!has_lod)
8914          lod = bld.copy(bld.def(v1), Operand(0u));
8915 
8916       bool div_by_6 = instr->op == nir_texop_txs &&
8917                       instr->sampler_dim == GLSL_SAMPLER_DIM_CUBE &&
8918                       instr->is_array &&
8919                       (dmask & (1 << 2));
8920       if (tmp_dst.id() == dst.id() && div_by_6)
8921          tmp_dst = bld.tmp(tmp_dst.regClass());
8922 
8923       tex.reset(create_instruction<MIMG_instruction>(aco_opcode::image_get_resinfo, Format::MIMG, 3, 1));
8924       tex->operands[0] = Operand(resource);
8925       tex->operands[1] = Operand(s4); /* no sampler */
8926       tex->operands[2] = Operand(as_vgpr(ctx,lod));
8927       if (ctx->options->chip_class == GFX9 &&
8928           instr->op == nir_texop_txs &&
8929           instr->sampler_dim == GLSL_SAMPLER_DIM_1D &&
8930           instr->is_array) {
8931          tex->dmask = (dmask & 0x1) | ((dmask & 0x2) << 1);
8932       } else if (instr->op == nir_texop_query_levels) {
8933          tex->dmask = 1 << 3;
8934       } else {
8935          tex->dmask = dmask;
8936       }
8937       tex->da = da;
8938       tex->definitions[0] = Definition(tmp_dst);
8939       tex->dim = dim;
8940       ctx->block->instructions.emplace_back(std::move(tex));
8941 
8942       if (div_by_6) {
8943          /* divide 3rd value by 6 by multiplying with magic number */
8944          emit_split_vector(ctx, tmp_dst, tmp_dst.size());
8945          Temp c = bld.copy(bld.def(s1), Operand((uint32_t) 0x2AAAAAAB));
8946          Temp by_6 = bld.vop3(aco_opcode::v_mul_hi_i32, bld.def(v1), emit_extract_vector(ctx, tmp_dst, 2, v1), c);
8947          assert(instr->dest.ssa.num_components == 3);
8948          Temp tmp = dst.type() == RegType::vgpr ? dst : bld.tmp(v3);
8949          tmp_dst = bld.pseudo(aco_opcode::p_create_vector, Definition(tmp),
8950                               emit_extract_vector(ctx, tmp_dst, 0, v1),
8951                               emit_extract_vector(ctx, tmp_dst, 1, v1),
8952                               by_6);
8953 
8954       }
8955 
8956       expand_vector(ctx, tmp_dst, dst, instr->dest.ssa.num_components, dmask);
8957       return;
8958    }
8959 
8960    Temp tg4_compare_cube_wa64 = Temp();
8961 
8962    if (tg4_integer_workarounds) {
8963       tex.reset(create_instruction<MIMG_instruction>(aco_opcode::image_get_resinfo, Format::MIMG, 3, 1));
8964       tex->operands[0] = Operand(resource);
8965       tex->operands[1] = Operand(s4); /* no sampler */
8966       tex->operands[2] = bld.copy(bld.def(v1), Operand(0u));
8967       tex->dim = dim;
8968       tex->dmask = 0x3;
8969       tex->da = da;
8970       Temp size = bld.tmp(v2);
8971       tex->definitions[0] = Definition(size);
8972       ctx->block->instructions.emplace_back(std::move(tex));
8973       emit_split_vector(ctx, size, size.size());
8974 
8975       Temp half_texel[2];
8976       for (unsigned i = 0; i < 2; i++) {
8977          half_texel[i] = emit_extract_vector(ctx, size, i, v1);
8978          half_texel[i] = bld.vop1(aco_opcode::v_cvt_f32_i32, bld.def(v1), half_texel[i]);
8979          half_texel[i] = bld.vop1(aco_opcode::v_rcp_iflag_f32, bld.def(v1), half_texel[i]);
8980          half_texel[i] = bld.vop2(aco_opcode::v_mul_f32, bld.def(v1), Operand(0xbf000000/*-0.5*/), half_texel[i]);
8981       }
8982 
8983       Temp new_coords[2] = {
8984          bld.vop2(aco_opcode::v_add_f32, bld.def(v1), coords[0], half_texel[0]),
8985          bld.vop2(aco_opcode::v_add_f32, bld.def(v1), coords[1], half_texel[1])
8986       };
8987 
8988       if (tg4_integer_cube_workaround) {
8989          // see comment in ac_nir_to_llvm.c's lower_gather4_integer()
8990          Temp *const desc = (Temp *)alloca(resource.size() * sizeof(Temp));
8991          aco_ptr<Instruction> split{create_instruction<Pseudo_instruction>(aco_opcode::p_split_vector,
8992                                                                            Format::PSEUDO, 1, resource.size())};
8993          split->operands[0] = Operand(resource);
8994          for (unsigned i = 0; i < resource.size(); i++) {
8995             desc[i] = bld.tmp(s1);
8996             split->definitions[i] = Definition(desc[i]);
8997          }
8998          ctx->block->instructions.emplace_back(std::move(split));
8999 
9000          Temp dfmt = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc), desc[1], Operand(20u | (6u << 16)));
9001          Temp compare_cube_wa = bld.sopc(aco_opcode::s_cmp_eq_u32, bld.def(s1, scc), dfmt,
9002                                          Operand((uint32_t)V_008F14_IMG_DATA_FORMAT_8_8_8_8));
9003 
9004          Temp nfmt;
9005          if (stype == GLSL_TYPE_UINT) {
9006             nfmt = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1),
9007                             Operand((uint32_t)V_008F14_IMG_NUM_FORMAT_USCALED),
9008                             Operand((uint32_t)V_008F14_IMG_NUM_FORMAT_UINT),
9009                             bld.scc(compare_cube_wa));
9010          } else {
9011             nfmt = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1),
9012                             Operand((uint32_t)V_008F14_IMG_NUM_FORMAT_SSCALED),
9013                             Operand((uint32_t)V_008F14_IMG_NUM_FORMAT_SINT),
9014                             bld.scc(compare_cube_wa));
9015          }
9016          tg4_compare_cube_wa64 = bld.tmp(bld.lm);
9017          bool_to_vector_condition(ctx, compare_cube_wa, tg4_compare_cube_wa64);
9018 
9019          nfmt = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), nfmt, Operand(26u));
9020 
9021          desc[1] = bld.sop2(aco_opcode::s_and_b32, bld.def(s1), bld.def(s1, scc), desc[1],
9022                             Operand((uint32_t)C_008F14_NUM_FORMAT));
9023          desc[1] = bld.sop2(aco_opcode::s_or_b32, bld.def(s1), bld.def(s1, scc), desc[1], nfmt);
9024 
9025          aco_ptr<Instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector,
9026                                                                          Format::PSEUDO, resource.size(), 1)};
9027          for (unsigned i = 0; i < resource.size(); i++)
9028             vec->operands[i] = Operand(desc[i]);
9029          resource = bld.tmp(resource.regClass());
9030          vec->definitions[0] = Definition(resource);
9031          ctx->block->instructions.emplace_back(std::move(vec));
9032 
9033          new_coords[0] = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1),
9034                                   new_coords[0], coords[0], tg4_compare_cube_wa64);
9035          new_coords[1] = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1),
9036                                   new_coords[1], coords[1], tg4_compare_cube_wa64);
9037       }
9038       coords[0] = new_coords[0];
9039       coords[1] = new_coords[1];
9040    }
9041 
9042    if (instr->sampler_dim == GLSL_SAMPLER_DIM_BUF) {
9043       //FIXME: if (ctx->abi->gfx9_stride_size_workaround) return ac_build_buffer_load_format_gfx9_safe()
9044 
9045       assert(coords.size() == 1);
9046       unsigned last_bit = util_last_bit(nir_ssa_def_components_read(&instr->dest.ssa));
9047       aco_opcode op;
9048       switch (last_bit) {
9049       case 1:
9050          op = aco_opcode::buffer_load_format_x; break;
9051       case 2:
9052          op = aco_opcode::buffer_load_format_xy; break;
9053       case 3:
9054          op = aco_opcode::buffer_load_format_xyz; break;
9055       case 4:
9056          op = aco_opcode::buffer_load_format_xyzw; break;
9057       default:
9058          unreachable("Tex instruction loads more than 4 components.");
9059       }
9060 
9061       /* if the instruction return value matches exactly the nir dest ssa, we can use it directly */
9062       if (last_bit == instr->dest.ssa.num_components && dst.type() == RegType::vgpr)
9063          tmp_dst = dst;
9064       else
9065          tmp_dst = bld.tmp(RegType::vgpr, last_bit);
9066 
9067       aco_ptr<MUBUF_instruction> mubuf{create_instruction<MUBUF_instruction>(op, Format::MUBUF, 3, 1)};
9068       mubuf->operands[0] = Operand(resource);
9069       mubuf->operands[1] = Operand(coords[0]);
9070       mubuf->operands[2] = Operand((uint32_t) 0);
9071       mubuf->definitions[0] = Definition(tmp_dst);
9072       mubuf->idxen = true;
9073       ctx->block->instructions.emplace_back(std::move(mubuf));
9074 
9075       expand_vector(ctx, tmp_dst, dst, instr->dest.ssa.num_components, (1 << last_bit) - 1);
9076       return;
9077    }
9078 
9079    /* gather MIMG address components */
9080    std::vector<Temp> args;
9081    if (has_offset)
9082       args.emplace_back(offset);
9083    if (has_bias)
9084       args.emplace_back(bias);
9085    if (has_compare)
9086       args.emplace_back(compare);
9087    if (has_derivs)
9088       args.insert(args.end(), derivs.begin(), derivs.end());
9089 
9090    args.insert(args.end(), coords.begin(), coords.end());
9091    if (has_sample_index)
9092       args.emplace_back(sample_index);
9093    if (has_lod)
9094       args.emplace_back(lod);
9095    if (has_clamped_lod)
9096       args.emplace_back(clamped_lod);
9097 
9098    Temp arg = bld.tmp(RegClass(RegType::vgpr, args.size()));
9099    aco_ptr<Instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, args.size(), 1)};
9100    vec->definitions[0] = Definition(arg);
9101    for (unsigned i = 0; i < args.size(); i++)
9102       vec->operands[i] = Operand(args[i]);
9103    ctx->block->instructions.emplace_back(std::move(vec));
9104 
9105 
9106    if (instr->op == nir_texop_txf ||
9107        instr->op == nir_texop_txf_ms ||
9108        instr->op == nir_texop_samples_identical ||
9109        instr->op == nir_texop_fragment_fetch ||
9110        instr->op == nir_texop_fragment_mask_fetch) {
9111       aco_opcode op = level_zero || instr->sampler_dim == GLSL_SAMPLER_DIM_MS || instr->sampler_dim == GLSL_SAMPLER_DIM_SUBPASS_MS ? aco_opcode::image_load : aco_opcode::image_load_mip;
9112       tex.reset(create_instruction<MIMG_instruction>(op, Format::MIMG, 3, 1));
9113       tex->operands[0] = Operand(resource);
9114       tex->operands[1] = Operand(s4); /* no sampler */
9115       tex->operands[2] = Operand(arg);
9116       tex->dim = dim;
9117       tex->dmask = dmask;
9118       tex->unrm = true;
9119       tex->da = da;
9120       tex->definitions[0] = Definition(tmp_dst);
9121       ctx->block->instructions.emplace_back(std::move(tex));
9122 
9123       if (instr->op == nir_texop_samples_identical) {
9124          assert(dmask == 1 && dst.regClass() == bld.lm);
9125          assert(dst.id() != tmp_dst.id());
9126 
9127          bld.vopc(aco_opcode::v_cmp_eq_u32, Definition(dst), Operand(0u), tmp_dst).def(0).setHint(vcc);
9128       } else {
9129          expand_vector(ctx, tmp_dst, dst, instr->dest.ssa.num_components, dmask);
9130       }
9131       return;
9132    }
9133 
9134    // TODO: would be better to do this by adding offsets, but needs the opcodes ordered.
9135    aco_opcode opcode = aco_opcode::image_sample;
9136    if (has_offset) { /* image_sample_*_o */
9137       if (has_clamped_lod) {
9138          if (has_compare) {
9139             opcode = aco_opcode::image_sample_c_cl_o;
9140             if (has_derivs)
9141                opcode = aco_opcode::image_sample_c_d_cl_o;
9142             if (has_bias)
9143                opcode = aco_opcode::image_sample_c_b_cl_o;
9144          } else {
9145             opcode = aco_opcode::image_sample_cl_o;
9146             if (has_derivs)
9147                opcode = aco_opcode::image_sample_d_cl_o;
9148             if (has_bias)
9149                opcode = aco_opcode::image_sample_b_cl_o;
9150          }
9151       } else if (has_compare) {
9152          opcode = aco_opcode::image_sample_c_o;
9153          if (has_derivs)
9154             opcode = aco_opcode::image_sample_c_d_o;
9155          if (has_bias)
9156             opcode = aco_opcode::image_sample_c_b_o;
9157          if (level_zero)
9158             opcode = aco_opcode::image_sample_c_lz_o;
9159          if (has_lod)
9160             opcode = aco_opcode::image_sample_c_l_o;
9161       } else {
9162          opcode = aco_opcode::image_sample_o;
9163          if (has_derivs)
9164             opcode = aco_opcode::image_sample_d_o;
9165          if (has_bias)
9166             opcode = aco_opcode::image_sample_b_o;
9167          if (level_zero)
9168             opcode = aco_opcode::image_sample_lz_o;
9169          if (has_lod)
9170             opcode = aco_opcode::image_sample_l_o;
9171       }
9172    } else if (has_clamped_lod) { /* image_sample_*_cl */
9173       if (has_compare) {
9174          opcode = aco_opcode::image_sample_c_cl;
9175          if (has_derivs)
9176             opcode = aco_opcode::image_sample_c_d_cl;
9177          if (has_bias)
9178             opcode = aco_opcode::image_sample_c_b_cl;
9179       } else {
9180          opcode = aco_opcode::image_sample_cl;
9181          if (has_derivs)
9182             opcode = aco_opcode::image_sample_d_cl;
9183          if (has_bias)
9184             opcode = aco_opcode::image_sample_b_cl;
9185       }
9186    } else { /* no offset */
9187       if (has_compare) {
9188          opcode = aco_opcode::image_sample_c;
9189          if (has_derivs)
9190             opcode = aco_opcode::image_sample_c_d;
9191          if (has_bias)
9192             opcode = aco_opcode::image_sample_c_b;
9193          if (level_zero)
9194             opcode = aco_opcode::image_sample_c_lz;
9195          if (has_lod)
9196             opcode = aco_opcode::image_sample_c_l;
9197       } else {
9198          opcode = aco_opcode::image_sample;
9199          if (has_derivs)
9200             opcode = aco_opcode::image_sample_d;
9201          if (has_bias)
9202             opcode = aco_opcode::image_sample_b;
9203          if (level_zero)
9204             opcode = aco_opcode::image_sample_lz;
9205          if (has_lod)
9206             opcode = aco_opcode::image_sample_l;
9207       }
9208    }
9209 
9210    if (instr->op == nir_texop_tg4) {
9211       if (has_offset) { /* image_gather4_*_o */
9212          if (has_compare) {
9213             opcode = aco_opcode::image_gather4_c_lz_o;
9214             if (has_lod)
9215                opcode = aco_opcode::image_gather4_c_l_o;
9216             if (has_bias)
9217                opcode = aco_opcode::image_gather4_c_b_o;
9218          } else {
9219             opcode = aco_opcode::image_gather4_lz_o;
9220             if (has_lod)
9221                opcode = aco_opcode::image_gather4_l_o;
9222             if (has_bias)
9223                opcode = aco_opcode::image_gather4_b_o;
9224          }
9225       } else {
9226          if (has_compare) {
9227             opcode = aco_opcode::image_gather4_c_lz;
9228             if (has_lod)
9229                opcode = aco_opcode::image_gather4_c_l;
9230             if (has_bias)
9231                opcode = aco_opcode::image_gather4_c_b;
9232          } else {
9233             opcode = aco_opcode::image_gather4_lz;
9234             if (has_lod)
9235                opcode = aco_opcode::image_gather4_l;
9236             if (has_bias)
9237                opcode = aco_opcode::image_gather4_b;
9238          }
9239       }
9240    } else if (instr->op == nir_texop_lod) {
9241       opcode = aco_opcode::image_get_lod;
9242    }
9243 
9244    /* we don't need the bias, sample index, compare value or offset to be
9245     * computed in WQM but if the p_create_vector copies the coordinates, then it
9246     * needs to be in WQM */
9247    if (ctx->stage == fragment_fs &&
9248        !has_derivs && !has_lod && !level_zero &&
9249        instr->sampler_dim != GLSL_SAMPLER_DIM_MS &&
9250        instr->sampler_dim != GLSL_SAMPLER_DIM_SUBPASS_MS)
9251       arg = emit_wqm(ctx, arg, bld.tmp(arg.regClass()), true);
9252 
9253    tex.reset(create_instruction<MIMG_instruction>(opcode, Format::MIMG, 3, 1));
9254    tex->operands[0] = Operand(resource);
9255    tex->operands[1] = Operand(sampler);
9256    tex->operands[2] = Operand(arg);
9257    tex->dim = dim;
9258    tex->dmask = dmask;
9259    tex->da = da;
9260    tex->definitions[0] = Definition(tmp_dst);
9261    ctx->block->instructions.emplace_back(std::move(tex));
9262 
9263    if (tg4_integer_cube_workaround) {
9264       assert(tmp_dst.id() != dst.id());
9265       assert(tmp_dst.size() == dst.size() && dst.size() == 4);
9266 
9267       emit_split_vector(ctx, tmp_dst, tmp_dst.size());
9268       Temp val[4];
9269       for (unsigned i = 0; i < dst.size(); i++) {
9270          val[i] = emit_extract_vector(ctx, tmp_dst, i, v1);
9271          Temp cvt_val;
9272          if (stype == GLSL_TYPE_UINT)
9273             cvt_val = bld.vop1(aco_opcode::v_cvt_u32_f32, bld.def(v1), val[i]);
9274          else
9275             cvt_val = bld.vop1(aco_opcode::v_cvt_i32_f32, bld.def(v1), val[i]);
9276          val[i] = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), val[i], cvt_val, tg4_compare_cube_wa64);
9277       }
9278       Temp tmp = dst.regClass() == v4 ? dst : bld.tmp(v4);
9279       tmp_dst = bld.pseudo(aco_opcode::p_create_vector, Definition(tmp),
9280                            val[0], val[1], val[2], val[3]);
9281    }
9282    unsigned mask = instr->op == nir_texop_tg4 ? 0xF : dmask;
9283    expand_vector(ctx, tmp_dst, dst, instr->dest.ssa.num_components, mask);
9284 
9285 }
9286 
9287 
get_phi_operand(isel_context * ctx,nir_ssa_def * ssa,RegClass rc,bool logical)9288 Operand get_phi_operand(isel_context *ctx, nir_ssa_def *ssa, RegClass rc, bool logical)
9289 {
9290    Temp tmp = get_ssa_temp(ctx, ssa);
9291    if (ssa->parent_instr->type == nir_instr_type_ssa_undef) {
9292       return Operand(rc);
9293    } else if (logical && ssa->bit_size == 1 && ssa->parent_instr->type == nir_instr_type_load_const) {
9294       if (ctx->program->wave_size == 64)
9295          return Operand(nir_instr_as_load_const(ssa->parent_instr)->value[0].b ? UINT64_MAX : 0u);
9296       else
9297          return Operand(nir_instr_as_load_const(ssa->parent_instr)->value[0].b ? UINT32_MAX : 0u);
9298    } else {
9299       return Operand(tmp);
9300    }
9301 }
9302 
visit_phi(isel_context * ctx,nir_phi_instr * instr)9303 void visit_phi(isel_context *ctx, nir_phi_instr *instr)
9304 {
9305    aco_ptr<Pseudo_instruction> phi;
9306    Temp dst = get_ssa_temp(ctx, &instr->dest.ssa);
9307    assert(instr->dest.ssa.bit_size != 1 || dst.regClass() == ctx->program->lane_mask);
9308 
9309    bool logical = !dst.is_linear() || nir_dest_is_divergent(instr->dest);
9310    logical |= ctx->block->kind & block_kind_merge;
9311    aco_opcode opcode = logical ? aco_opcode::p_phi : aco_opcode::p_linear_phi;
9312 
9313    /* we want a sorted list of sources, since the predecessor list is also sorted */
9314    std::map<unsigned, nir_ssa_def*> phi_src;
9315    nir_foreach_phi_src(src, instr)
9316       phi_src[src->pred->index] = src->src.ssa;
9317 
9318    std::vector<unsigned>& preds = logical ? ctx->block->logical_preds : ctx->block->linear_preds;
9319    unsigned num_operands = 0;
9320    Operand *const operands = (Operand *)alloca((std::max(exec_list_length(&instr->srcs), (unsigned)preds.size()) + 1) * sizeof(Operand));
9321    unsigned num_defined = 0;
9322    unsigned cur_pred_idx = 0;
9323    for (std::pair<unsigned, nir_ssa_def *> src : phi_src) {
9324       if (cur_pred_idx < preds.size()) {
9325          /* handle missing preds (IF merges with discard/break) and extra preds (loop exit with discard) */
9326          unsigned block = ctx->cf_info.nir_to_aco[src.first];
9327          unsigned skipped = 0;
9328          while (cur_pred_idx + skipped < preds.size() && preds[cur_pred_idx + skipped] != block)
9329             skipped++;
9330          if (cur_pred_idx + skipped < preds.size()) {
9331             for (unsigned i = 0; i < skipped; i++)
9332                operands[num_operands++] = Operand(dst.regClass());
9333             cur_pred_idx += skipped;
9334          } else {
9335             continue;
9336          }
9337       }
9338       /* Handle missing predecessors at the end. This shouldn't happen with loop
9339        * headers and we can't ignore these sources for loop header phis. */
9340       if (!(ctx->block->kind & block_kind_loop_header) && cur_pred_idx >= preds.size())
9341          continue;
9342       cur_pred_idx++;
9343       Operand op = get_phi_operand(ctx, src.second, dst.regClass(), logical);
9344       operands[num_operands++] = op;
9345       num_defined += !op.isUndefined();
9346    }
9347    /* handle block_kind_continue_or_break at loop exit blocks */
9348    while (cur_pred_idx++ < preds.size())
9349       operands[num_operands++] = Operand(dst.regClass());
9350 
9351    /* If the loop ends with a break, still add a linear continue edge in case
9352     * that break is divergent or continue_or_break is used. We'll either remove
9353     * this operand later in visit_loop() if it's not necessary or replace the
9354     * undef with something correct. */
9355    if (!logical && ctx->block->kind & block_kind_loop_header) {
9356       nir_loop *loop = nir_cf_node_as_loop(instr->instr.block->cf_node.parent);
9357       nir_block *last = nir_loop_last_block(loop);
9358       if (last->successors[0] != instr->instr.block)
9359          operands[num_operands++] = Operand(RegClass());
9360    }
9361 
9362    /* we can use a linear phi in some cases if one src is undef */
9363    if (dst.is_linear() && ctx->block->kind & block_kind_merge && num_defined == 1) {
9364       phi.reset(create_instruction<Pseudo_instruction>(aco_opcode::p_linear_phi, Format::PSEUDO, num_operands, 1));
9365 
9366       Block *linear_else = &ctx->program->blocks[ctx->block->linear_preds[1]];
9367       Block *invert = &ctx->program->blocks[linear_else->linear_preds[0]];
9368       assert(invert->kind & block_kind_invert);
9369 
9370       unsigned then_block = invert->linear_preds[0];
9371 
9372       Block* insert_block = NULL;
9373       for (unsigned i = 0; i < num_operands; i++) {
9374          Operand op = operands[i];
9375          if (op.isUndefined())
9376             continue;
9377          insert_block = ctx->block->logical_preds[i] == then_block ? invert : ctx->block;
9378          phi->operands[0] = op;
9379          break;
9380       }
9381       assert(insert_block); /* should be handled by the "num_defined == 0" case above */
9382       phi->operands[1] = Operand(dst.regClass());
9383       phi->definitions[0] = Definition(dst);
9384       insert_block->instructions.emplace(insert_block->instructions.begin(), std::move(phi));
9385       return;
9386    }
9387 
9388    /* try to scalarize vector phis */
9389    if (instr->dest.ssa.bit_size != 1 && dst.size() > 1) {
9390       // TODO: scalarize linear phis on divergent ifs
9391       bool can_scalarize = (opcode == aco_opcode::p_phi || !(ctx->block->kind & block_kind_merge));
9392       std::array<Temp, NIR_MAX_VEC_COMPONENTS> new_vec;
9393       for (unsigned i = 0; can_scalarize && (i < num_operands); i++) {
9394          Operand src = operands[i];
9395          if (src.isTemp() && ctx->allocated_vec.find(src.tempId()) == ctx->allocated_vec.end())
9396             can_scalarize = false;
9397       }
9398       if (can_scalarize) {
9399          unsigned num_components = instr->dest.ssa.num_components;
9400          assert(dst.size() % num_components == 0);
9401          RegClass rc = RegClass(dst.type(), dst.size() / num_components);
9402 
9403          aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, num_components, 1)};
9404          for (unsigned k = 0; k < num_components; k++) {
9405             phi.reset(create_instruction<Pseudo_instruction>(opcode, Format::PSEUDO, num_operands, 1));
9406             for (unsigned i = 0; i < num_operands; i++) {
9407                Operand src = operands[i];
9408                phi->operands[i] = src.isTemp() ? Operand(ctx->allocated_vec[src.tempId()][k]) : Operand(rc);
9409             }
9410             Temp phi_dst = ctx->program->allocateTmp(rc);
9411             phi->definitions[0] = Definition(phi_dst);
9412             ctx->block->instructions.emplace(ctx->block->instructions.begin(), std::move(phi));
9413             new_vec[k] = phi_dst;
9414             vec->operands[k] = Operand(phi_dst);
9415          }
9416          vec->definitions[0] = Definition(dst);
9417          ctx->block->instructions.emplace_back(std::move(vec));
9418          ctx->allocated_vec.emplace(dst.id(), new_vec);
9419          return;
9420       }
9421    }
9422 
9423    phi.reset(create_instruction<Pseudo_instruction>(opcode, Format::PSEUDO, num_operands, 1));
9424    for (unsigned i = 0; i < num_operands; i++)
9425       phi->operands[i] = operands[i];
9426    phi->definitions[0] = Definition(dst);
9427    ctx->block->instructions.emplace(ctx->block->instructions.begin(), std::move(phi));
9428 }
9429 
9430 
visit_undef(isel_context * ctx,nir_ssa_undef_instr * instr)9431 void visit_undef(isel_context *ctx, nir_ssa_undef_instr *instr)
9432 {
9433    Temp dst = get_ssa_temp(ctx, &instr->def);
9434 
9435    assert(dst.type() == RegType::sgpr);
9436 
9437    if (dst.size() == 1) {
9438       Builder(ctx->program, ctx->block).copy(Definition(dst), Operand(0u));
9439    } else {
9440       aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, dst.size(), 1)};
9441       for (unsigned i = 0; i < dst.size(); i++)
9442          vec->operands[i] = Operand(0u);
9443       vec->definitions[0] = Definition(dst);
9444       ctx->block->instructions.emplace_back(std::move(vec));
9445    }
9446 }
9447 
begin_loop(isel_context * ctx,loop_context * lc)9448 void begin_loop(isel_context *ctx, loop_context *lc)
9449 {
9450    //TODO: we might want to wrap the loop around a branch if exec_potentially_empty=true
9451    append_logical_end(ctx->block);
9452    ctx->block->kind |= block_kind_loop_preheader | block_kind_uniform;
9453    Builder bld(ctx->program, ctx->block);
9454    bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
9455    unsigned loop_preheader_idx = ctx->block->index;
9456 
9457    lc->loop_exit.loop_nest_depth = ctx->cf_info.loop_nest_depth;
9458    lc->loop_exit.kind |= (block_kind_loop_exit | (ctx->block->kind & block_kind_top_level));
9459 
9460    Block *loop_header = ctx->program->create_and_insert_block();
9461    loop_header->loop_nest_depth = ctx->cf_info.loop_nest_depth + 1;
9462    loop_header->kind |= block_kind_loop_header;
9463    add_edge(loop_preheader_idx, loop_header);
9464    ctx->block = loop_header;
9465 
9466    append_logical_start(ctx->block);
9467 
9468    lc->header_idx_old = std::exchange(ctx->cf_info.parent_loop.header_idx, loop_header->index);
9469    lc->exit_old = std::exchange(ctx->cf_info.parent_loop.exit, &lc->loop_exit);
9470    lc->divergent_cont_old = std::exchange(ctx->cf_info.parent_loop.has_divergent_continue, false);
9471    lc->divergent_branch_old = std::exchange(ctx->cf_info.parent_loop.has_divergent_branch, false);
9472    lc->divergent_if_old = std::exchange(ctx->cf_info.parent_if.is_divergent, false);
9473    ctx->cf_info.loop_nest_depth++;
9474 }
9475 
end_loop(isel_context * ctx,loop_context * lc)9476 void end_loop(isel_context *ctx, loop_context *lc)
9477 {
9478    //TODO: what if a loop ends with a unconditional or uniformly branched continue and this branch is never taken?
9479    if (!ctx->cf_info.has_branch) {
9480       unsigned loop_header_idx = ctx->cf_info.parent_loop.header_idx;
9481       Builder bld(ctx->program, ctx->block);
9482       append_logical_end(ctx->block);
9483 
9484       if (ctx->cf_info.exec_potentially_empty_discard || ctx->cf_info.exec_potentially_empty_break) {
9485          /* Discards can result in code running with an empty exec mask.
9486           * This would result in divergent breaks not ever being taken. As a
9487           * workaround, break the loop when the loop mask is empty instead of
9488           * always continuing. */
9489          ctx->block->kind |= (block_kind_continue_or_break | block_kind_uniform);
9490          unsigned block_idx = ctx->block->index;
9491 
9492          /* create helper blocks to avoid critical edges */
9493          Block *break_block = ctx->program->create_and_insert_block();
9494          break_block->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9495          break_block->kind = block_kind_uniform;
9496          bld.reset(break_block);
9497          bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
9498          add_linear_edge(block_idx, break_block);
9499          add_linear_edge(break_block->index, &lc->loop_exit);
9500 
9501          Block *continue_block = ctx->program->create_and_insert_block();
9502          continue_block->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9503          continue_block->kind = block_kind_uniform;
9504          bld.reset(continue_block);
9505          bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
9506          add_linear_edge(block_idx, continue_block);
9507          add_linear_edge(continue_block->index, &ctx->program->blocks[loop_header_idx]);
9508 
9509          if (!ctx->cf_info.parent_loop.has_divergent_branch)
9510             add_logical_edge(block_idx, &ctx->program->blocks[loop_header_idx]);
9511          ctx->block = &ctx->program->blocks[block_idx];
9512       } else {
9513          ctx->block->kind |= (block_kind_continue | block_kind_uniform);
9514          if (!ctx->cf_info.parent_loop.has_divergent_branch)
9515             add_edge(ctx->block->index, &ctx->program->blocks[loop_header_idx]);
9516          else
9517             add_linear_edge(ctx->block->index, &ctx->program->blocks[loop_header_idx]);
9518       }
9519 
9520       bld.reset(ctx->block);
9521       bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
9522    }
9523 
9524    ctx->cf_info.has_branch = false;
9525 
9526    // TODO: if the loop has not a single exit, we must add one °°
9527    /* emit loop successor block */
9528    ctx->block = ctx->program->insert_block(std::move(lc->loop_exit));
9529    append_logical_start(ctx->block);
9530 
9531    #if 0
9532    // TODO: check if it is beneficial to not branch on continues
9533    /* trim linear phis in loop header */
9534    for (auto&& instr : loop_entry->instructions) {
9535       if (instr->opcode == aco_opcode::p_linear_phi) {
9536          aco_ptr<Pseudo_instruction> new_phi{create_instruction<Pseudo_instruction>(aco_opcode::p_linear_phi, Format::PSEUDO, loop_entry->linear_predecessors.size(), 1)};
9537          new_phi->definitions[0] = instr->definitions[0];
9538          for (unsigned i = 0; i < new_phi->operands.size(); i++)
9539             new_phi->operands[i] = instr->operands[i];
9540          /* check that the remaining operands are all the same */
9541          for (unsigned i = new_phi->operands.size(); i < instr->operands.size(); i++)
9542             assert(instr->operands[i].tempId() == instr->operands.back().tempId());
9543          instr.swap(new_phi);
9544       } else if (instr->opcode == aco_opcode::p_phi) {
9545          continue;
9546       } else {
9547          break;
9548       }
9549    }
9550    #endif
9551 
9552    ctx->cf_info.parent_loop.header_idx = lc->header_idx_old;
9553    ctx->cf_info.parent_loop.exit = lc->exit_old;
9554    ctx->cf_info.parent_loop.has_divergent_continue = lc->divergent_cont_old;
9555    ctx->cf_info.parent_loop.has_divergent_branch = lc->divergent_branch_old;
9556    ctx->cf_info.parent_if.is_divergent = lc->divergent_if_old;
9557    ctx->cf_info.loop_nest_depth = ctx->cf_info.loop_nest_depth - 1;
9558    if (!ctx->cf_info.loop_nest_depth && !ctx->cf_info.parent_if.is_divergent)
9559       ctx->cf_info.exec_potentially_empty_discard = false;
9560 }
9561 
emit_loop_jump(isel_context * ctx,bool is_break)9562 void emit_loop_jump(isel_context *ctx, bool is_break)
9563 {
9564    Builder bld(ctx->program, ctx->block);
9565    Block *logical_target;
9566    append_logical_end(ctx->block);
9567    unsigned idx = ctx->block->index;
9568 
9569    if (is_break) {
9570       logical_target = ctx->cf_info.parent_loop.exit;
9571       add_logical_edge(idx, logical_target);
9572       ctx->block->kind |= block_kind_break;
9573 
9574       if (!ctx->cf_info.parent_if.is_divergent &&
9575           !ctx->cf_info.parent_loop.has_divergent_continue) {
9576          /* uniform break - directly jump out of the loop */
9577          ctx->block->kind |= block_kind_uniform;
9578          ctx->cf_info.has_branch = true;
9579          bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
9580          add_linear_edge(idx, logical_target);
9581          return;
9582       }
9583       ctx->cf_info.parent_loop.has_divergent_branch = true;
9584    } else {
9585       logical_target = &ctx->program->blocks[ctx->cf_info.parent_loop.header_idx];
9586       add_logical_edge(idx, logical_target);
9587       ctx->block->kind |= block_kind_continue;
9588 
9589       if (!ctx->cf_info.parent_if.is_divergent) {
9590          /* uniform continue - directly jump to the loop header */
9591          ctx->block->kind |= block_kind_uniform;
9592          ctx->cf_info.has_branch = true;
9593          bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
9594          add_linear_edge(idx, logical_target);
9595          return;
9596       }
9597 
9598       /* for potential uniform breaks after this continue,
9599          we must ensure that they are handled correctly */
9600       ctx->cf_info.parent_loop.has_divergent_continue = true;
9601       ctx->cf_info.parent_loop.has_divergent_branch = true;
9602    }
9603 
9604    if (ctx->cf_info.parent_if.is_divergent && !ctx->cf_info.exec_potentially_empty_break) {
9605       ctx->cf_info.exec_potentially_empty_break = true;
9606       ctx->cf_info.exec_potentially_empty_break_depth = ctx->cf_info.loop_nest_depth;
9607    }
9608 
9609    /* remove critical edges from linear CFG */
9610    bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
9611    Block* break_block = ctx->program->create_and_insert_block();
9612    break_block->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9613    break_block->kind |= block_kind_uniform;
9614    add_linear_edge(idx, break_block);
9615    /* the loop_header pointer might be invalidated by this point */
9616    if (!is_break)
9617       logical_target = &ctx->program->blocks[ctx->cf_info.parent_loop.header_idx];
9618    add_linear_edge(break_block->index, logical_target);
9619    bld.reset(break_block);
9620    bld.branch(aco_opcode::p_branch, bld.hint_vcc(bld.def(s2)));
9621 
9622    Block* continue_block = ctx->program->create_and_insert_block();
9623    continue_block->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9624    add_linear_edge(idx, continue_block);
9625    append_logical_start(continue_block);
9626    ctx->block = continue_block;
9627 }
9628 
emit_loop_break(isel_context * ctx)9629 void emit_loop_break(isel_context *ctx)
9630 {
9631    emit_loop_jump(ctx, true);
9632 }
9633 
emit_loop_continue(isel_context * ctx)9634 void emit_loop_continue(isel_context *ctx)
9635 {
9636    emit_loop_jump(ctx, false);
9637 }
9638 
visit_jump(isel_context * ctx,nir_jump_instr * instr)9639 void visit_jump(isel_context *ctx, nir_jump_instr *instr)
9640 {
9641    /* visit_block() would usually do this but divergent jumps updates ctx->block */
9642    ctx->cf_info.nir_to_aco[instr->instr.block->index] = ctx->block->index;
9643 
9644    switch (instr->type) {
9645    case nir_jump_break:
9646       emit_loop_break(ctx);
9647       break;
9648    case nir_jump_continue:
9649       emit_loop_continue(ctx);
9650       break;
9651    default:
9652       isel_err(&instr->instr, "Unknown NIR jump instr");
9653       abort();
9654    }
9655 }
9656 
visit_block(isel_context * ctx,nir_block * block)9657 void visit_block(isel_context *ctx, nir_block *block)
9658 {
9659    nir_foreach_instr(instr, block) {
9660       switch (instr->type) {
9661       case nir_instr_type_alu:
9662          visit_alu_instr(ctx, nir_instr_as_alu(instr));
9663          break;
9664       case nir_instr_type_load_const:
9665          visit_load_const(ctx, nir_instr_as_load_const(instr));
9666          break;
9667       case nir_instr_type_intrinsic:
9668          visit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
9669          break;
9670       case nir_instr_type_tex:
9671          visit_tex(ctx, nir_instr_as_tex(instr));
9672          break;
9673       case nir_instr_type_phi:
9674          visit_phi(ctx, nir_instr_as_phi(instr));
9675          break;
9676       case nir_instr_type_ssa_undef:
9677          visit_undef(ctx, nir_instr_as_ssa_undef(instr));
9678          break;
9679       case nir_instr_type_deref:
9680          break;
9681       case nir_instr_type_jump:
9682          visit_jump(ctx, nir_instr_as_jump(instr));
9683          break;
9684       default:
9685          isel_err(instr, "Unknown NIR instr type");
9686          //abort();
9687       }
9688    }
9689 
9690    if (!ctx->cf_info.parent_loop.has_divergent_branch)
9691       ctx->cf_info.nir_to_aco[block->index] = ctx->block->index;
9692 }
9693 
9694 
9695 
create_continue_phis(isel_context * ctx,unsigned first,unsigned last,aco_ptr<Instruction> & header_phi,Operand * vals)9696 static Operand create_continue_phis(isel_context *ctx, unsigned first, unsigned last,
9697                                     aco_ptr<Instruction>& header_phi, Operand *vals)
9698 {
9699    vals[0] = Operand(header_phi->definitions[0].getTemp());
9700    RegClass rc = vals[0].regClass();
9701 
9702    unsigned loop_nest_depth = ctx->program->blocks[first].loop_nest_depth;
9703 
9704    unsigned next_pred = 1;
9705 
9706    for (unsigned idx = first + 1; idx <= last; idx++) {
9707       Block& block = ctx->program->blocks[idx];
9708       if (block.loop_nest_depth != loop_nest_depth) {
9709          vals[idx - first] = vals[idx - 1 - first];
9710          continue;
9711       }
9712 
9713       if ((block.kind & block_kind_continue) && block.index != last) {
9714          vals[idx - first] = header_phi->operands[next_pred];
9715          next_pred++;
9716          continue;
9717       }
9718 
9719       bool all_same = true;
9720       for (unsigned i = 1; all_same && (i < block.linear_preds.size()); i++)
9721          all_same = vals[block.linear_preds[i] - first] == vals[block.linear_preds[0] - first];
9722 
9723       Operand val;
9724       if (all_same) {
9725          val = vals[block.linear_preds[0] - first];
9726       } else {
9727          aco_ptr<Instruction> phi(create_instruction<Pseudo_instruction>(
9728             aco_opcode::p_linear_phi, Format::PSEUDO, block.linear_preds.size(), 1));
9729          for (unsigned i = 0; i < block.linear_preds.size(); i++)
9730             phi->operands[i] = vals[block.linear_preds[i] - first];
9731          val = Operand(ctx->program->allocateTmp(rc));
9732          phi->definitions[0] = Definition(val.getTemp());
9733          block.instructions.emplace(block.instructions.begin(), std::move(phi));
9734       }
9735       vals[idx - first] = val;
9736    }
9737 
9738    return vals[last - first];
9739 }
9740 
visit_loop(isel_context * ctx,nir_loop * loop)9741 static void visit_loop(isel_context *ctx, nir_loop *loop)
9742 {
9743    loop_context lc;
9744    begin_loop(ctx, &lc);
9745    bool unreachable = visit_cf_list(ctx, &loop->body);
9746 
9747    unsigned loop_header_idx = ctx->cf_info.parent_loop.header_idx;
9748 
9749    /* Fixup phis in loop header from unreachable blocks.
9750     * has_branch/has_divergent_branch also indicates if the loop ends with a
9751     * break/continue instruction, but we don't emit those if unreachable=true */
9752    if (unreachable) {
9753       assert(ctx->cf_info.has_branch || ctx->cf_info.parent_loop.has_divergent_branch);
9754       bool linear = ctx->cf_info.has_branch;
9755       bool logical = ctx->cf_info.has_branch || ctx->cf_info.parent_loop.has_divergent_branch;
9756       for (aco_ptr<Instruction>& instr : ctx->program->blocks[loop_header_idx].instructions) {
9757          if ((logical && instr->opcode == aco_opcode::p_phi) ||
9758              (linear && instr->opcode == aco_opcode::p_linear_phi)) {
9759             /* the last operand should be the one that needs to be removed */
9760             instr->operands.pop_back();
9761          } else if (!is_phi(instr)) {
9762             break;
9763          }
9764       }
9765    }
9766 
9767    /* Fixup linear phis in loop header from expecting a continue. Both this fixup
9768     * and the previous one shouldn't both happen at once because a break in the
9769     * merge block would get CSE'd */
9770    if (nir_loop_last_block(loop)->successors[0] != nir_loop_first_block(loop)) {
9771       unsigned num_vals = ctx->cf_info.has_branch ? 1 : (ctx->block->index - loop_header_idx + 1);
9772       Operand *const vals = (Operand *)alloca(num_vals * sizeof(Operand));
9773       for (aco_ptr<Instruction>& instr : ctx->program->blocks[loop_header_idx].instructions) {
9774          if (instr->opcode == aco_opcode::p_linear_phi) {
9775             if (ctx->cf_info.has_branch)
9776                instr->operands.pop_back();
9777             else
9778                instr->operands.back() = create_continue_phis(ctx, loop_header_idx, ctx->block->index, instr, vals);
9779          } else if (!is_phi(instr)) {
9780             break;
9781          }
9782       }
9783    }
9784 
9785    end_loop(ctx, &lc);
9786 }
9787 
begin_divergent_if_then(isel_context * ctx,if_context * ic,Temp cond)9788 static void begin_divergent_if_then(isel_context *ctx, if_context *ic, Temp cond)
9789 {
9790    ic->cond = cond;
9791 
9792    append_logical_end(ctx->block);
9793    ctx->block->kind |= block_kind_branch;
9794 
9795    /* branch to linear then block */
9796    assert(cond.regClass() == ctx->program->lane_mask);
9797    aco_ptr<Pseudo_branch_instruction> branch;
9798    branch.reset(create_instruction<Pseudo_branch_instruction>(aco_opcode::p_cbranch_z, Format::PSEUDO_BRANCH, 1, 1));
9799    branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
9800    branch->definitions[0].setHint(vcc);
9801    branch->operands[0] = Operand(cond);
9802    ctx->block->instructions.push_back(std::move(branch));
9803 
9804    ic->BB_if_idx = ctx->block->index;
9805    ic->BB_invert = Block();
9806    ic->BB_invert.loop_nest_depth = ctx->cf_info.loop_nest_depth;
9807    /* Invert blocks are intentionally not marked as top level because they
9808     * are not part of the logical cfg. */
9809    ic->BB_invert.kind |= block_kind_invert;
9810    ic->BB_endif = Block();
9811    ic->BB_endif.loop_nest_depth = ctx->cf_info.loop_nest_depth;
9812    ic->BB_endif.kind |= (block_kind_merge | (ctx->block->kind & block_kind_top_level));
9813 
9814    ic->exec_potentially_empty_discard_old = ctx->cf_info.exec_potentially_empty_discard;
9815    ic->exec_potentially_empty_break_old = ctx->cf_info.exec_potentially_empty_break;
9816    ic->exec_potentially_empty_break_depth_old = ctx->cf_info.exec_potentially_empty_break_depth;
9817    ic->divergent_old = ctx->cf_info.parent_if.is_divergent;
9818    ctx->cf_info.parent_if.is_divergent = true;
9819 
9820    /* divergent branches use cbranch_execz */
9821    ctx->cf_info.exec_potentially_empty_discard = false;
9822    ctx->cf_info.exec_potentially_empty_break = false;
9823    ctx->cf_info.exec_potentially_empty_break_depth = UINT16_MAX;
9824 
9825    /** emit logical then block */
9826    Block* BB_then_logical = ctx->program->create_and_insert_block();
9827    BB_then_logical->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9828    add_edge(ic->BB_if_idx, BB_then_logical);
9829    ctx->block = BB_then_logical;
9830    append_logical_start(BB_then_logical);
9831 }
9832 
begin_divergent_if_else(isel_context * ctx,if_context * ic)9833 static void begin_divergent_if_else(isel_context *ctx, if_context *ic)
9834 {
9835    Block *BB_then_logical = ctx->block;
9836    append_logical_end(BB_then_logical);
9837     /* branch from logical then block to invert block */
9838    aco_ptr<Pseudo_branch_instruction> branch;
9839    branch.reset(create_instruction<Pseudo_branch_instruction>(aco_opcode::p_branch, Format::PSEUDO_BRANCH, 0, 1));
9840    branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
9841    branch->definitions[0].setHint(vcc);
9842    BB_then_logical->instructions.emplace_back(std::move(branch));
9843    add_linear_edge(BB_then_logical->index, &ic->BB_invert);
9844    if (!ctx->cf_info.parent_loop.has_divergent_branch)
9845       add_logical_edge(BB_then_logical->index, &ic->BB_endif);
9846    BB_then_logical->kind |= block_kind_uniform;
9847    assert(!ctx->cf_info.has_branch);
9848    ic->then_branch_divergent = ctx->cf_info.parent_loop.has_divergent_branch;
9849    ctx->cf_info.parent_loop.has_divergent_branch = false;
9850 
9851    /** emit linear then block */
9852    Block* BB_then_linear = ctx->program->create_and_insert_block();
9853    BB_then_linear->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9854    BB_then_linear->kind |= block_kind_uniform;
9855    add_linear_edge(ic->BB_if_idx, BB_then_linear);
9856    /* branch from linear then block to invert block */
9857    branch.reset(create_instruction<Pseudo_branch_instruction>(aco_opcode::p_branch, Format::PSEUDO_BRANCH, 0, 1));
9858    branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
9859    branch->definitions[0].setHint(vcc);
9860    BB_then_linear->instructions.emplace_back(std::move(branch));
9861    add_linear_edge(BB_then_linear->index, &ic->BB_invert);
9862 
9863    /** emit invert merge block */
9864    ctx->block = ctx->program->insert_block(std::move(ic->BB_invert));
9865    ic->invert_idx = ctx->block->index;
9866 
9867    /* branch to linear else block (skip else) */
9868    branch.reset(create_instruction<Pseudo_branch_instruction>(aco_opcode::p_cbranch_nz, Format::PSEUDO_BRANCH, 1, 1));
9869    branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
9870    branch->definitions[0].setHint(vcc);
9871    branch->operands[0] = Operand(ic->cond);
9872    ctx->block->instructions.push_back(std::move(branch));
9873 
9874    ic->exec_potentially_empty_discard_old |= ctx->cf_info.exec_potentially_empty_discard;
9875    ic->exec_potentially_empty_break_old |= ctx->cf_info.exec_potentially_empty_break;
9876    ic->exec_potentially_empty_break_depth_old =
9877       std::min(ic->exec_potentially_empty_break_depth_old, ctx->cf_info.exec_potentially_empty_break_depth);
9878    /* divergent branches use cbranch_execz */
9879    ctx->cf_info.exec_potentially_empty_discard = false;
9880    ctx->cf_info.exec_potentially_empty_break = false;
9881    ctx->cf_info.exec_potentially_empty_break_depth = UINT16_MAX;
9882 
9883    /** emit logical else block */
9884    Block* BB_else_logical = ctx->program->create_and_insert_block();
9885    BB_else_logical->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9886    add_logical_edge(ic->BB_if_idx, BB_else_logical);
9887    add_linear_edge(ic->invert_idx, BB_else_logical);
9888    ctx->block = BB_else_logical;
9889    append_logical_start(BB_else_logical);
9890 }
9891 
end_divergent_if(isel_context * ctx,if_context * ic)9892 static void end_divergent_if(isel_context *ctx, if_context *ic)
9893 {
9894    Block *BB_else_logical = ctx->block;
9895    append_logical_end(BB_else_logical);
9896 
9897    /* branch from logical else block to endif block */
9898    aco_ptr<Pseudo_branch_instruction> branch;
9899    branch.reset(create_instruction<Pseudo_branch_instruction>(aco_opcode::p_branch, Format::PSEUDO_BRANCH, 0, 1));
9900    branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
9901    branch->definitions[0].setHint(vcc);
9902    BB_else_logical->instructions.emplace_back(std::move(branch));
9903    add_linear_edge(BB_else_logical->index, &ic->BB_endif);
9904    if (!ctx->cf_info.parent_loop.has_divergent_branch)
9905       add_logical_edge(BB_else_logical->index, &ic->BB_endif);
9906    BB_else_logical->kind |= block_kind_uniform;
9907 
9908    assert(!ctx->cf_info.has_branch);
9909    ctx->cf_info.parent_loop.has_divergent_branch &= ic->then_branch_divergent;
9910 
9911 
9912    /** emit linear else block */
9913    Block* BB_else_linear = ctx->program->create_and_insert_block();
9914    BB_else_linear->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9915    BB_else_linear->kind |= block_kind_uniform;
9916    add_linear_edge(ic->invert_idx, BB_else_linear);
9917 
9918    /* branch from linear else block to endif block */
9919    branch.reset(create_instruction<Pseudo_branch_instruction>(aco_opcode::p_branch, Format::PSEUDO_BRANCH, 0, 1));
9920    branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
9921    branch->definitions[0].setHint(vcc);
9922    BB_else_linear->instructions.emplace_back(std::move(branch));
9923    add_linear_edge(BB_else_linear->index, &ic->BB_endif);
9924 
9925 
9926    /** emit endif merge block */
9927    ctx->block = ctx->program->insert_block(std::move(ic->BB_endif));
9928    append_logical_start(ctx->block);
9929 
9930 
9931    ctx->cf_info.parent_if.is_divergent = ic->divergent_old;
9932    ctx->cf_info.exec_potentially_empty_discard |= ic->exec_potentially_empty_discard_old;
9933    ctx->cf_info.exec_potentially_empty_break |= ic->exec_potentially_empty_break_old;
9934    ctx->cf_info.exec_potentially_empty_break_depth =
9935       std::min(ic->exec_potentially_empty_break_depth_old, ctx->cf_info.exec_potentially_empty_break_depth);
9936    if (ctx->cf_info.loop_nest_depth == ctx->cf_info.exec_potentially_empty_break_depth &&
9937        !ctx->cf_info.parent_if.is_divergent) {
9938       ctx->cf_info.exec_potentially_empty_break = false;
9939       ctx->cf_info.exec_potentially_empty_break_depth = UINT16_MAX;
9940    }
9941    /* uniform control flow never has an empty exec-mask */
9942    if (!ctx->cf_info.loop_nest_depth && !ctx->cf_info.parent_if.is_divergent) {
9943       ctx->cf_info.exec_potentially_empty_discard = false;
9944       ctx->cf_info.exec_potentially_empty_break = false;
9945       ctx->cf_info.exec_potentially_empty_break_depth = UINT16_MAX;
9946    }
9947 }
9948 
begin_uniform_if_then(isel_context * ctx,if_context * ic,Temp cond)9949 static void begin_uniform_if_then(isel_context *ctx, if_context *ic, Temp cond)
9950 {
9951    assert(cond.regClass() == s1);
9952 
9953    append_logical_end(ctx->block);
9954    ctx->block->kind |= block_kind_uniform;
9955 
9956    aco_ptr<Pseudo_branch_instruction> branch;
9957    aco_opcode branch_opcode = aco_opcode::p_cbranch_z;
9958    branch.reset(create_instruction<Pseudo_branch_instruction>(branch_opcode, Format::PSEUDO_BRANCH, 1, 1));
9959    branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
9960    branch->definitions[0].setHint(vcc);
9961    branch->operands[0] = Operand(cond);
9962    branch->operands[0].setFixed(scc);
9963    ctx->block->instructions.emplace_back(std::move(branch));
9964 
9965    ic->BB_if_idx = ctx->block->index;
9966    ic->BB_endif = Block();
9967    ic->BB_endif.loop_nest_depth = ctx->cf_info.loop_nest_depth;
9968    ic->BB_endif.kind |= ctx->block->kind & block_kind_top_level;
9969 
9970    ctx->cf_info.has_branch = false;
9971    ctx->cf_info.parent_loop.has_divergent_branch = false;
9972 
9973    /** emit then block */
9974    Block* BB_then = ctx->program->create_and_insert_block();
9975    BB_then->loop_nest_depth = ctx->cf_info.loop_nest_depth;
9976    add_edge(ic->BB_if_idx, BB_then);
9977    append_logical_start(BB_then);
9978    ctx->block = BB_then;
9979 }
9980 
begin_uniform_if_else(isel_context * ctx,if_context * ic)9981 static void begin_uniform_if_else(isel_context *ctx, if_context *ic)
9982 {
9983    Block *BB_then = ctx->block;
9984 
9985    ic->uniform_has_then_branch = ctx->cf_info.has_branch;
9986    ic->then_branch_divergent = ctx->cf_info.parent_loop.has_divergent_branch;
9987 
9988    if (!ic->uniform_has_then_branch) {
9989       append_logical_end(BB_then);
9990       /* branch from then block to endif block */
9991       aco_ptr<Pseudo_branch_instruction> branch;
9992       branch.reset(create_instruction<Pseudo_branch_instruction>(aco_opcode::p_branch, Format::PSEUDO_BRANCH, 0, 1));
9993       branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
9994       branch->definitions[0].setHint(vcc);
9995       BB_then->instructions.emplace_back(std::move(branch));
9996       add_linear_edge(BB_then->index, &ic->BB_endif);
9997       if (!ic->then_branch_divergent)
9998          add_logical_edge(BB_then->index, &ic->BB_endif);
9999       BB_then->kind |= block_kind_uniform;
10000    }
10001 
10002    ctx->cf_info.has_branch = false;
10003    ctx->cf_info.parent_loop.has_divergent_branch = false;
10004 
10005    /** emit else block */
10006    Block* BB_else = ctx->program->create_and_insert_block();
10007    BB_else->loop_nest_depth = ctx->cf_info.loop_nest_depth;
10008    add_edge(ic->BB_if_idx, BB_else);
10009    append_logical_start(BB_else);
10010    ctx->block = BB_else;
10011 }
10012 
end_uniform_if(isel_context * ctx,if_context * ic)10013 static void end_uniform_if(isel_context *ctx, if_context *ic)
10014 {
10015    Block *BB_else = ctx->block;
10016 
10017    if (!ctx->cf_info.has_branch) {
10018       append_logical_end(BB_else);
10019       /* branch from then block to endif block */
10020       aco_ptr<Pseudo_branch_instruction> branch;
10021       branch.reset(create_instruction<Pseudo_branch_instruction>(aco_opcode::p_branch, Format::PSEUDO_BRANCH, 0, 1));
10022       branch->definitions[0] = Definition(ctx->program->allocateTmp(s2));
10023       branch->definitions[0].setHint(vcc);
10024       BB_else->instructions.emplace_back(std::move(branch));
10025       add_linear_edge(BB_else->index, &ic->BB_endif);
10026       if (!ctx->cf_info.parent_loop.has_divergent_branch)
10027          add_logical_edge(BB_else->index, &ic->BB_endif);
10028       BB_else->kind |= block_kind_uniform;
10029    }
10030 
10031    ctx->cf_info.has_branch &= ic->uniform_has_then_branch;
10032    ctx->cf_info.parent_loop.has_divergent_branch &= ic->then_branch_divergent;
10033 
10034    /** emit endif merge block */
10035    if (!ctx->cf_info.has_branch) {
10036       ctx->block = ctx->program->insert_block(std::move(ic->BB_endif));
10037       append_logical_start(ctx->block);
10038    }
10039 }
10040 
visit_if(isel_context * ctx,nir_if * if_stmt)10041 static bool visit_if(isel_context *ctx, nir_if *if_stmt)
10042 {
10043    Temp cond = get_ssa_temp(ctx, if_stmt->condition.ssa);
10044    Builder bld(ctx->program, ctx->block);
10045    aco_ptr<Pseudo_branch_instruction> branch;
10046    if_context ic;
10047 
10048    if (!nir_src_is_divergent(if_stmt->condition)) { /* uniform condition */
10049       /**
10050        * Uniform conditionals are represented in the following way*) :
10051        *
10052        * The linear and logical CFG:
10053        *                        BB_IF
10054        *                        /    \
10055        *       BB_THEN (logical)      BB_ELSE (logical)
10056        *                        \    /
10057        *                        BB_ENDIF
10058        *
10059        * *) Exceptions may be due to break and continue statements within loops
10060        *    If a break/continue happens within uniform control flow, it branches
10061        *    to the loop exit/entry block. Otherwise, it branches to the next
10062        *    merge block.
10063        **/
10064 
10065       // TODO: in a post-RA optimizer, we could check if the condition is in VCC and omit this instruction
10066       assert(cond.regClass() == ctx->program->lane_mask);
10067       cond = bool_to_scalar_condition(ctx, cond);
10068 
10069       begin_uniform_if_then(ctx, &ic, cond);
10070       visit_cf_list(ctx, &if_stmt->then_list);
10071 
10072       begin_uniform_if_else(ctx, &ic);
10073       visit_cf_list(ctx, &if_stmt->else_list);
10074 
10075       end_uniform_if(ctx, &ic);
10076    } else { /* non-uniform condition */
10077       /**
10078        * To maintain a logical and linear CFG without critical edges,
10079        * non-uniform conditionals are represented in the following way*) :
10080        *
10081        * The linear CFG:
10082        *                        BB_IF
10083        *                        /    \
10084        *       BB_THEN (logical)      BB_THEN (linear)
10085        *                        \    /
10086        *                        BB_INVERT (linear)
10087        *                        /    \
10088        *       BB_ELSE (logical)      BB_ELSE (linear)
10089        *                        \    /
10090        *                        BB_ENDIF
10091        *
10092        * The logical CFG:
10093        *                        BB_IF
10094        *                        /    \
10095        *       BB_THEN (logical)      BB_ELSE (logical)
10096        *                        \    /
10097        *                        BB_ENDIF
10098        *
10099        * *) Exceptions may be due to break and continue statements within loops
10100        **/
10101 
10102       begin_divergent_if_then(ctx, &ic, cond);
10103       visit_cf_list(ctx, &if_stmt->then_list);
10104 
10105       begin_divergent_if_else(ctx, &ic);
10106       visit_cf_list(ctx, &if_stmt->else_list);
10107 
10108       end_divergent_if(ctx, &ic);
10109    }
10110 
10111    return !ctx->cf_info.has_branch && !ctx->block->logical_preds.empty();
10112 }
10113 
visit_cf_list(isel_context * ctx,struct exec_list * list)10114 static bool visit_cf_list(isel_context *ctx,
10115                           struct exec_list *list)
10116 {
10117    foreach_list_typed(nir_cf_node, node, node, list) {
10118       switch (node->type) {
10119       case nir_cf_node_block:
10120          visit_block(ctx, nir_cf_node_as_block(node));
10121          break;
10122       case nir_cf_node_if:
10123          if (!visit_if(ctx, nir_cf_node_as_if(node)))
10124             return true;
10125          break;
10126       case nir_cf_node_loop:
10127          visit_loop(ctx, nir_cf_node_as_loop(node));
10128          break;
10129       default:
10130          unreachable("unimplemented cf list type");
10131       }
10132    }
10133    return false;
10134 }
10135 
export_vs_varying(isel_context * ctx,int slot,bool is_pos,int * next_pos)10136 static void export_vs_varying(isel_context *ctx, int slot, bool is_pos, int *next_pos)
10137 {
10138    assert(ctx->stage.hw == HWStage::VS || ctx->stage.hw == HWStage::NGG);
10139 
10140    int offset = (ctx->stage.has(SWStage::TES) && !ctx->stage.has(SWStage::GS))
10141                 ? ctx->program->info->tes.outinfo.vs_output_param_offset[slot]
10142                 : ctx->program->info->vs.outinfo.vs_output_param_offset[slot];
10143    uint64_t mask = ctx->outputs.mask[slot];
10144    if (!is_pos && !mask)
10145       return;
10146    if (!is_pos && offset == AC_EXP_PARAM_UNDEFINED)
10147       return;
10148    aco_ptr<Export_instruction> exp{create_instruction<Export_instruction>(aco_opcode::exp, Format::EXP, 4, 0)};
10149    exp->enabled_mask = mask;
10150    for (unsigned i = 0; i < 4; ++i) {
10151       if (mask & (1 << i))
10152          exp->operands[i] = Operand(ctx->outputs.temps[slot * 4u + i]);
10153       else
10154          exp->operands[i] = Operand(v1);
10155    }
10156    /* GFX10 (Navi1x) skip POS0 exports if EXEC=0 and DONE=0, causing a hang.
10157     * Setting valid_mask=1 prevents it and has no other effect.
10158     */
10159    exp->valid_mask = ctx->options->chip_class == GFX10 && is_pos && *next_pos == 0;
10160    exp->done = false;
10161    exp->compressed = false;
10162    if (is_pos)
10163       exp->dest = V_008DFC_SQ_EXP_POS + (*next_pos)++;
10164    else
10165       exp->dest = V_008DFC_SQ_EXP_PARAM + offset;
10166    ctx->block->instructions.emplace_back(std::move(exp));
10167 }
10168 
export_vs_psiz_layer_viewport(isel_context * ctx,int * next_pos)10169 static void export_vs_psiz_layer_viewport(isel_context *ctx, int *next_pos)
10170 {
10171    aco_ptr<Export_instruction> exp{create_instruction<Export_instruction>(aco_opcode::exp, Format::EXP, 4, 0)};
10172    exp->enabled_mask = 0;
10173    for (unsigned i = 0; i < 4; ++i)
10174       exp->operands[i] = Operand(v1);
10175    if (ctx->outputs.mask[VARYING_SLOT_PSIZ]) {
10176       exp->operands[0] = Operand(ctx->outputs.temps[VARYING_SLOT_PSIZ * 4u]);
10177       exp->enabled_mask |= 0x1;
10178    }
10179    if (ctx->outputs.mask[VARYING_SLOT_LAYER]) {
10180       exp->operands[2] = Operand(ctx->outputs.temps[VARYING_SLOT_LAYER * 4u]);
10181       exp->enabled_mask |= 0x4;
10182    }
10183    if (ctx->outputs.mask[VARYING_SLOT_VIEWPORT]) {
10184       if (ctx->options->chip_class < GFX9) {
10185          exp->operands[3] = Operand(ctx->outputs.temps[VARYING_SLOT_VIEWPORT * 4u]);
10186          exp->enabled_mask |= 0x8;
10187       } else {
10188          Builder bld(ctx->program, ctx->block);
10189 
10190          Temp out = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(16u),
10191                              Operand(ctx->outputs.temps[VARYING_SLOT_VIEWPORT * 4u]));
10192          if (exp->operands[2].isTemp())
10193             out = bld.vop2(aco_opcode::v_or_b32, bld.def(v1), Operand(out), exp->operands[2]);
10194 
10195          exp->operands[2] = Operand(out);
10196          exp->enabled_mask |= 0x4;
10197       }
10198    }
10199    exp->valid_mask = ctx->options->chip_class == GFX10 && *next_pos == 0;
10200    exp->done = false;
10201    exp->compressed = false;
10202    exp->dest = V_008DFC_SQ_EXP_POS + (*next_pos)++;
10203    ctx->block->instructions.emplace_back(std::move(exp));
10204 }
10205 
create_export_phis(isel_context * ctx)10206 static void create_export_phis(isel_context *ctx)
10207 {
10208    /* Used when exports are needed, but the output temps are defined in a preceding block.
10209     * This function will set up phis in order to access the outputs in the next block.
10210     */
10211 
10212    assert(ctx->block->instructions.back()->opcode == aco_opcode::p_logical_start);
10213    aco_ptr<Instruction> logical_start = aco_ptr<Instruction>(ctx->block->instructions.back().release());
10214    ctx->block->instructions.pop_back();
10215 
10216    Builder bld(ctx->program, ctx->block);
10217 
10218    for (unsigned slot = 0; slot <= VARYING_SLOT_VAR31; ++slot) {
10219       uint64_t mask = ctx->outputs.mask[slot];
10220       for (unsigned i = 0; i < 4; ++i) {
10221          if (!(mask & (1 << i)))
10222             continue;
10223 
10224          Temp old = ctx->outputs.temps[slot * 4 + i];
10225          Temp phi = bld.pseudo(aco_opcode::p_phi, bld.def(v1), old, Operand(v1));
10226          ctx->outputs.temps[slot * 4 + i] = phi;
10227       }
10228    }
10229 
10230    bld.insert(std::move(logical_start));
10231 }
10232 
create_vs_exports(isel_context * ctx)10233 static void create_vs_exports(isel_context *ctx)
10234 {
10235    assert(ctx->stage.hw == HWStage::VS || ctx->stage.hw == HWStage::NGG);
10236 
10237    radv_vs_output_info *outinfo = (ctx->stage.has(SWStage::TES) && !ctx->stage.has(SWStage::GS))
10238                                   ? &ctx->program->info->tes.outinfo
10239                                   : &ctx->program->info->vs.outinfo;
10240 
10241    if (outinfo->export_prim_id && ctx->stage.hw != HWStage::NGG) {
10242       ctx->outputs.mask[VARYING_SLOT_PRIMITIVE_ID] |= 0x1;
10243       if (ctx->stage.has(SWStage::TES))
10244          ctx->outputs.temps[VARYING_SLOT_PRIMITIVE_ID * 4u] = get_arg(ctx, ctx->args->ac.tes_patch_id);
10245       else
10246          ctx->outputs.temps[VARYING_SLOT_PRIMITIVE_ID * 4u] = get_arg(ctx, ctx->args->vs_prim_id);
10247    }
10248 
10249    if (ctx->options->key.has_multiview_view_index) {
10250       ctx->outputs.mask[VARYING_SLOT_LAYER] |= 0x1;
10251       ctx->outputs.temps[VARYING_SLOT_LAYER * 4u] = as_vgpr(ctx, get_arg(ctx, ctx->args->ac.view_index));
10252    }
10253 
10254    /* Hardware requires position data to always be exported, even if the
10255     * application did not write gl_Position.
10256     */
10257    ctx->outputs.mask[VARYING_SLOT_POS] = 0xf;
10258 
10259    /* the order these position exports are created is important */
10260    int next_pos = 0;
10261    export_vs_varying(ctx, VARYING_SLOT_POS, true, &next_pos);
10262    if (outinfo->writes_pointsize || outinfo->writes_layer || outinfo->writes_viewport_index) {
10263       export_vs_psiz_layer_viewport(ctx, &next_pos);
10264    }
10265    if (ctx->num_clip_distances + ctx->num_cull_distances > 0)
10266       export_vs_varying(ctx, VARYING_SLOT_CLIP_DIST0, true, &next_pos);
10267    if (ctx->num_clip_distances + ctx->num_cull_distances > 4)
10268       export_vs_varying(ctx, VARYING_SLOT_CLIP_DIST1, true, &next_pos);
10269 
10270    if (ctx->export_clip_dists) {
10271       if (ctx->num_clip_distances + ctx->num_cull_distances > 0)
10272          export_vs_varying(ctx, VARYING_SLOT_CLIP_DIST0, false, &next_pos);
10273       if (ctx->num_clip_distances + ctx->num_cull_distances > 4)
10274          export_vs_varying(ctx, VARYING_SLOT_CLIP_DIST1, false, &next_pos);
10275    }
10276 
10277    for (unsigned i = 0; i <= VARYING_SLOT_VAR31; ++i) {
10278       if (i < VARYING_SLOT_VAR0 &&
10279           i != VARYING_SLOT_LAYER &&
10280           i != VARYING_SLOT_PRIMITIVE_ID &&
10281           i != VARYING_SLOT_VIEWPORT)
10282          continue;
10283 
10284       export_vs_varying(ctx, i, false, NULL);
10285    }
10286 }
10287 
export_fs_mrt_z(isel_context * ctx)10288 static bool export_fs_mrt_z(isel_context *ctx)
10289 {
10290    Builder bld(ctx->program, ctx->block);
10291    unsigned enabled_channels = 0;
10292    bool compr = false;
10293    Operand values[4];
10294 
10295    for (unsigned i = 0; i < 4; ++i) {
10296       values[i] = Operand(v1);
10297    }
10298 
10299    /* Both stencil and sample mask only need 16-bits. */
10300    if (!ctx->program->info->ps.writes_z &&
10301        (ctx->program->info->ps.writes_stencil ||
10302         ctx->program->info->ps.writes_sample_mask)) {
10303       compr = true; /* COMPR flag */
10304 
10305       if (ctx->program->info->ps.writes_stencil) {
10306          /* Stencil should be in X[23:16]. */
10307          values[0] = Operand(ctx->outputs.temps[FRAG_RESULT_STENCIL * 4u]);
10308          values[0] = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(16u), values[0]);
10309          enabled_channels |= 0x3;
10310       }
10311 
10312       if (ctx->program->info->ps.writes_sample_mask) {
10313          /* SampleMask should be in Y[15:0]. */
10314          values[1] = Operand(ctx->outputs.temps[FRAG_RESULT_SAMPLE_MASK * 4u]);
10315          enabled_channels |= 0xc;
10316      }
10317    } else {
10318       if (ctx->program->info->ps.writes_z) {
10319          values[0] = Operand(ctx->outputs.temps[FRAG_RESULT_DEPTH * 4u]);
10320          enabled_channels |= 0x1;
10321       }
10322 
10323       if (ctx->program->info->ps.writes_stencil) {
10324          values[1] = Operand(ctx->outputs.temps[FRAG_RESULT_STENCIL * 4u]);
10325          enabled_channels |= 0x2;
10326       }
10327 
10328       if (ctx->program->info->ps.writes_sample_mask) {
10329          values[2] = Operand(ctx->outputs.temps[FRAG_RESULT_SAMPLE_MASK * 4u]);
10330          enabled_channels |= 0x4;
10331       }
10332    }
10333 
10334    /* GFX6 (except OLAND and HAINAN) has a bug that it only looks at the X
10335     * writemask component.
10336     */
10337    if (ctx->options->chip_class == GFX6 &&
10338        ctx->options->family != CHIP_OLAND &&
10339        ctx->options->family != CHIP_HAINAN) {
10340             enabled_channels |= 0x1;
10341    }
10342 
10343    bld.exp(aco_opcode::exp, values[0], values[1], values[2], values[3],
10344            enabled_channels, V_008DFC_SQ_EXP_MRTZ, compr);
10345 
10346    return true;
10347 }
10348 
export_fs_mrt_color(isel_context * ctx,int slot)10349 static bool export_fs_mrt_color(isel_context *ctx, int slot)
10350 {
10351    Builder bld(ctx->program, ctx->block);
10352    unsigned write_mask = ctx->outputs.mask[slot];
10353    Operand values[4];
10354 
10355    for (unsigned i = 0; i < 4; ++i) {
10356       if (write_mask & (1 << i)) {
10357          values[i] = Operand(ctx->outputs.temps[slot * 4u + i]);
10358       } else {
10359          values[i] = Operand(v1);
10360       }
10361    }
10362 
10363    unsigned target, col_format;
10364    unsigned enabled_channels = 0;
10365    aco_opcode compr_op = (aco_opcode)0;
10366 
10367    slot -= FRAG_RESULT_DATA0;
10368    target = V_008DFC_SQ_EXP_MRT + slot;
10369    col_format = (ctx->options->key.fs.col_format >> (4 * slot)) & 0xf;
10370 
10371    bool is_int8 = (ctx->options->key.fs.is_int8 >> slot) & 1;
10372    bool is_int10 = (ctx->options->key.fs.is_int10 >> slot) & 1;
10373    bool is_16bit = values[0].regClass() == v2b;
10374 
10375    /* Replace NaN by zero (only 32-bit) to fix game bugs if requested. */
10376    if (ctx->options->enable_mrt_output_nan_fixup &&
10377        !is_16bit &&
10378        (col_format == V_028714_SPI_SHADER_32_R ||
10379         col_format == V_028714_SPI_SHADER_32_GR ||
10380         col_format == V_028714_SPI_SHADER_32_AR ||
10381         col_format == V_028714_SPI_SHADER_32_ABGR ||
10382         col_format == V_028714_SPI_SHADER_FP16_ABGR)) {
10383       for (int i = 0; i < 4; i++) {
10384          if (!(write_mask & (1 << i)))
10385             continue;
10386 
10387          Temp isnan = bld.vopc(aco_opcode::v_cmp_class_f32,
10388                                bld.hint_vcc(bld.def(bld.lm)), values[i],
10389                                bld.copy(bld.def(v1), Operand(3u)));
10390          values[i] = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1), values[i],
10391                               bld.copy(bld.def(v1), Operand(0u)), isnan);
10392       }
10393    }
10394 
10395    switch (col_format)
10396    {
10397    case V_028714_SPI_SHADER_32_R:
10398       enabled_channels = 1;
10399       break;
10400 
10401    case V_028714_SPI_SHADER_32_GR:
10402       enabled_channels = 0x3;
10403       break;
10404 
10405    case V_028714_SPI_SHADER_32_AR:
10406       if (ctx->options->chip_class >= GFX10) {
10407          /* Special case: on GFX10, the outputs are different for 32_AR */
10408          enabled_channels = 0x3;
10409          values[1] = values[3];
10410          values[3] = Operand(v1);
10411       } else {
10412          enabled_channels = 0x9;
10413       }
10414       break;
10415 
10416    case V_028714_SPI_SHADER_FP16_ABGR:
10417       for (int i = 0; i < 2; i++) {
10418          bool enabled = (write_mask >> (i*2)) & 0x3;
10419          if (enabled) {
10420             enabled_channels |= 1 << i;
10421             if (is_16bit) {
10422                values[i] = bld.pseudo(aco_opcode::p_create_vector, bld.def(v1),
10423                                       values[i*2].isUndefined() ? Operand(v2b) : values[i*2],
10424                                       values[i*2+1].isUndefined() ? Operand(v2b): values[i*2+1]);
10425             } else if (ctx->options->chip_class == GFX8 || ctx->options->chip_class == GFX9 ) {
10426                values[i] = bld.vop3(aco_opcode::v_cvt_pkrtz_f16_f32_e64, bld.def(v1),
10427                                     values[i*2].isUndefined() ? Operand(0u) : values[i*2],
10428                                     values[i*2+1].isUndefined() ? Operand(0u): values[i*2+1]);
10429             } else {
10430                values[i] = bld.vop2(aco_opcode::v_cvt_pkrtz_f16_f32, bld.def(v1),
10431                                     values[i*2].isUndefined() ? values[i*2+1] : values[i*2],
10432                                     values[i*2+1].isUndefined() ? values[i*2] : values[i*2+1]);
10433             }
10434          } else {
10435             values[i] = Operand(v1);
10436          }
10437       }
10438       break;
10439 
10440    case V_028714_SPI_SHADER_UNORM16_ABGR:
10441       if (is_16bit && ctx->options->chip_class >= GFX9) {
10442          compr_op = aco_opcode::v_cvt_pknorm_u16_f16;
10443       } else {
10444          compr_op = aco_opcode::v_cvt_pknorm_u16_f32;
10445       }
10446       break;
10447 
10448    case V_028714_SPI_SHADER_SNORM16_ABGR:
10449       if (is_16bit && ctx->options->chip_class >= GFX9) {
10450          compr_op = aco_opcode::v_cvt_pknorm_i16_f16;
10451       } else {
10452          compr_op = aco_opcode::v_cvt_pknorm_i16_f32;
10453       }
10454       break;
10455 
10456    case V_028714_SPI_SHADER_UINT16_ABGR: {
10457       compr_op = aco_opcode::v_cvt_pk_u16_u32;
10458       if (is_int8 || is_int10) {
10459          /* clamp */
10460          uint32_t max_rgb = is_int8 ? 255 : is_int10 ? 1023 : 0;
10461          Temp max_rgb_val = bld.copy(bld.def(s1), Operand(max_rgb));
10462 
10463          for (unsigned i = 0; i < 4; i++) {
10464             if ((write_mask >> i) & 1) {
10465                values[i] = bld.vop2(aco_opcode::v_min_u32, bld.def(v1),
10466                                     i == 3 && is_int10 ? Operand(3u) : Operand(max_rgb_val),
10467                                     values[i]);
10468             }
10469          }
10470       } else if (is_16bit) {
10471          for (unsigned i = 0; i < 4; i++) {
10472             if ((write_mask >> i) & 1) {
10473                Temp tmp = convert_int(ctx, bld, values[i].getTemp(), 16, 32, false);
10474                values[i] = Operand(tmp);
10475             }
10476          }
10477       }
10478       break;
10479    }
10480 
10481    case V_028714_SPI_SHADER_SINT16_ABGR:
10482       compr_op = aco_opcode::v_cvt_pk_i16_i32;
10483       if (is_int8 || is_int10) {
10484          /* clamp */
10485          uint32_t max_rgb = is_int8 ? 127 : is_int10 ? 511 : 0;
10486          uint32_t min_rgb = is_int8 ? -128 :is_int10 ? -512 : 0;
10487          Temp max_rgb_val = bld.copy(bld.def(s1), Operand(max_rgb));
10488          Temp min_rgb_val = bld.copy(bld.def(s1), Operand(min_rgb));
10489 
10490          for (unsigned i = 0; i < 4; i++) {
10491             if ((write_mask >> i) & 1) {
10492                values[i] = bld.vop2(aco_opcode::v_min_i32, bld.def(v1),
10493                                     i == 3 && is_int10 ? Operand(1u) : Operand(max_rgb_val),
10494                                     values[i]);
10495                values[i] = bld.vop2(aco_opcode::v_max_i32, bld.def(v1),
10496                                     i == 3 && is_int10 ? Operand(-2u) : Operand(min_rgb_val),
10497                                     values[i]);
10498             }
10499          }
10500       } else if (is_16bit) {
10501          for (unsigned i = 0; i < 4; i++) {
10502             if ((write_mask >> i) & 1) {
10503                Temp tmp = convert_int(ctx, bld, values[i].getTemp(), 16, 32, true);
10504                values[i] = Operand(tmp);
10505             }
10506          }
10507       }
10508       break;
10509 
10510    case V_028714_SPI_SHADER_32_ABGR:
10511       enabled_channels = 0xF;
10512       break;
10513 
10514    case V_028714_SPI_SHADER_ZERO:
10515    default:
10516       return false;
10517    }
10518 
10519    if ((bool) compr_op) {
10520       for (int i = 0; i < 2; i++) {
10521          /* check if at least one of the values to be compressed is enabled */
10522          bool enabled = (write_mask >> (i*2)) & 0x3;
10523          if (enabled) {
10524             enabled_channels |= 1 << (i*2);
10525             values[i] = bld.vop3(compr_op, bld.def(v1),
10526                                  values[i*2].isUndefined() ? Operand(0u) : values[i*2],
10527                                  values[i*2+1].isUndefined() ? Operand(0u): values[i*2+1]);
10528          } else {
10529             values[i] = Operand(v1);
10530          }
10531       }
10532       values[2] = Operand(v1);
10533       values[3] = Operand(v1);
10534    } else {
10535       for (int i = 0; i < 4; i++)
10536          values[i] = enabled_channels & (1 << i) ? values[i] : Operand(v1);
10537    }
10538 
10539    bld.exp(aco_opcode::exp, values[0], values[1], values[2], values[3],
10540            enabled_channels, target, (bool) compr_op);
10541    return true;
10542 }
10543 
create_fs_null_export(isel_context * ctx)10544 static void create_fs_null_export(isel_context *ctx)
10545 {
10546    /* FS must always have exports.
10547     * So when there are none, we need to add a null export.
10548     */
10549 
10550    Builder bld(ctx->program, ctx->block);
10551    unsigned dest = V_008DFC_SQ_EXP_NULL;
10552    bld.exp(aco_opcode::exp, Operand(v1), Operand(v1), Operand(v1), Operand(v1),
10553            /* enabled_mask */ 0, dest, /* compr */ false, /* done */ true, /* vm */ true);
10554 }
10555 
create_fs_exports(isel_context * ctx)10556 static void create_fs_exports(isel_context *ctx)
10557 {
10558    bool exported = false;
10559 
10560    /* Export depth, stencil and sample mask. */
10561    if (ctx->outputs.mask[FRAG_RESULT_DEPTH] ||
10562        ctx->outputs.mask[FRAG_RESULT_STENCIL] ||
10563        ctx->outputs.mask[FRAG_RESULT_SAMPLE_MASK])
10564       exported |= export_fs_mrt_z(ctx);
10565 
10566    /* Export all color render targets. */
10567    for (unsigned i = FRAG_RESULT_DATA0; i < FRAG_RESULT_DATA7 + 1; ++i)
10568       if (ctx->outputs.mask[i])
10569          exported |= export_fs_mrt_color(ctx, i);
10570 
10571    if (!exported)
10572       create_fs_null_export(ctx);
10573 }
10574 
create_workgroup_barrier(Builder & bld)10575 static void create_workgroup_barrier(Builder& bld)
10576 {
10577    bld.barrier(aco_opcode::p_barrier,
10578                memory_sync_info(storage_shared, semantic_acqrel, scope_workgroup),
10579                scope_workgroup);
10580 }
10581 
write_tcs_tess_factors(isel_context * ctx)10582 static void write_tcs_tess_factors(isel_context *ctx)
10583 {
10584    unsigned outer_comps;
10585    unsigned inner_comps;
10586 
10587    switch (ctx->args->options->key.tcs.primitive_mode) {
10588    case GL_ISOLINES:
10589       outer_comps = 2;
10590       inner_comps = 0;
10591       break;
10592    case GL_TRIANGLES:
10593       outer_comps = 3;
10594       inner_comps = 1;
10595       break;
10596    case GL_QUADS:
10597       outer_comps = 4;
10598       inner_comps = 2;
10599       break;
10600    default:
10601       return;
10602    }
10603 
10604    Builder bld(ctx->program, ctx->block);
10605 
10606    create_workgroup_barrier(bld);
10607 
10608    Temp tcs_rel_ids = get_arg(ctx, ctx->args->ac.tcs_rel_ids);
10609    Temp invocation_id = bld.vop3(aco_opcode::v_bfe_u32, bld.def(v1), tcs_rel_ids, Operand(8u), Operand(5u));
10610 
10611    Temp invocation_id_is_zero = bld.vopc(aco_opcode::v_cmp_eq_u32, bld.hint_vcc(bld.def(bld.lm)), Operand(0u), invocation_id);
10612    if_context ic_invocation_id_is_zero;
10613    begin_divergent_if_then(ctx, &ic_invocation_id_is_zero, invocation_id_is_zero);
10614    bld.reset(ctx->block);
10615 
10616    Temp hs_ring_tess_factor = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), ctx->program->private_segment_buffer, Operand(RING_HS_TESS_FACTOR * 16u));
10617 
10618    std::pair<Temp, unsigned> lds_base = get_tcs_output_lds_offset(ctx);
10619    unsigned stride = inner_comps + outer_comps;
10620    unsigned lds_align = calculate_lds_alignment(ctx, lds_base.second);
10621    Temp tf_inner_vec;
10622    Temp tf_outer_vec;
10623    Temp out[6];
10624    assert(stride <= (sizeof(out) / sizeof(Temp)));
10625 
10626    if (ctx->args->options->key.tcs.primitive_mode == GL_ISOLINES) {
10627       // LINES reversal
10628       tf_outer_vec = load_lds(ctx, 4, bld.tmp(v2), lds_base.first, lds_base.second + ctx->tcs_tess_lvl_out_loc, lds_align);
10629       out[1] = emit_extract_vector(ctx, tf_outer_vec, 0, v1);
10630       out[0] = emit_extract_vector(ctx, tf_outer_vec, 1, v1);
10631    } else {
10632       tf_outer_vec = load_lds(ctx, 4, bld.tmp(RegClass(RegType::vgpr, outer_comps)), lds_base.first, lds_base.second + ctx->tcs_tess_lvl_out_loc, lds_align);
10633       tf_inner_vec = load_lds(ctx, 4, bld.tmp(RegClass(RegType::vgpr, inner_comps)), lds_base.first, lds_base.second + ctx->tcs_tess_lvl_in_loc, lds_align);
10634 
10635       for (unsigned i = 0; i < outer_comps; ++i)
10636          out[i] = emit_extract_vector(ctx, tf_outer_vec, i, v1);
10637       for (unsigned i = 0; i < inner_comps; ++i)
10638          out[outer_comps + i] = emit_extract_vector(ctx, tf_inner_vec, i, v1);
10639    }
10640 
10641    Temp rel_patch_id = get_tess_rel_patch_id(ctx);
10642    Temp tf_base = get_arg(ctx, ctx->args->tess_factor_offset);
10643    Temp byte_offset = bld.v_mul24_imm(bld.def(v1), rel_patch_id, stride * 4u);
10644    unsigned tf_const_offset = 0;
10645 
10646    if (ctx->program->chip_class <= GFX8) {
10647       Temp rel_patch_id_is_zero = bld.vopc(aco_opcode::v_cmp_eq_u32, bld.hint_vcc(bld.def(bld.lm)), Operand(0u), rel_patch_id);
10648       if_context ic_rel_patch_id_is_zero;
10649       begin_divergent_if_then(ctx, &ic_rel_patch_id_is_zero, rel_patch_id_is_zero);
10650       bld.reset(ctx->block);
10651 
10652       /* Store the dynamic HS control word. */
10653       Temp control_word = bld.copy(bld.def(v1), Operand(0x80000000u));
10654       bld.mubuf(aco_opcode::buffer_store_dword,
10655                 /* SRSRC */ hs_ring_tess_factor, /* VADDR */ Operand(v1), /* SOFFSET */ tf_base, /* VDATA */ control_word,
10656                 /* immediate OFFSET */ 0, /* OFFEN */ false, /* swizzled */ false, /* idxen*/ false,
10657                 /* addr64 */ false, /* disable_wqm */ false, /* glc */ true);
10658       tf_const_offset += 4;
10659 
10660       begin_divergent_if_else(ctx, &ic_rel_patch_id_is_zero);
10661       end_divergent_if(ctx, &ic_rel_patch_id_is_zero);
10662       bld.reset(ctx->block);
10663    }
10664 
10665    assert(stride == 2 || stride == 4 || stride == 6);
10666    Temp tf_vec = create_vec_from_array(ctx, out, stride, RegType::vgpr, 4u);
10667    store_vmem_mubuf(ctx, tf_vec, hs_ring_tess_factor, byte_offset, tf_base, tf_const_offset, 4, (1 << stride) - 1, true, memory_sync_info());
10668 
10669    /* Store to offchip for TES to read - only if TES reads them */
10670    if (ctx->args->options->key.tcs.tes_reads_tess_factors) {
10671       Temp hs_ring_tess_offchip = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), ctx->program->private_segment_buffer, Operand(RING_HS_TESS_OFFCHIP * 16u));
10672       Temp oc_lds = get_arg(ctx, ctx->args->oc_lds);
10673 
10674       std::pair<Temp, unsigned> vmem_offs_outer = get_tcs_per_patch_output_vmem_offset(ctx, nullptr, ctx->tcs_tess_lvl_out_loc);
10675       store_vmem_mubuf(ctx, tf_outer_vec, hs_ring_tess_offchip, vmem_offs_outer.first, oc_lds, vmem_offs_outer.second, 4, (1 << outer_comps) - 1, true, memory_sync_info(storage_vmem_output));
10676 
10677       if (likely(inner_comps)) {
10678          std::pair<Temp, unsigned> vmem_offs_inner = get_tcs_per_patch_output_vmem_offset(ctx, nullptr, ctx->tcs_tess_lvl_in_loc);
10679          store_vmem_mubuf(ctx, tf_inner_vec, hs_ring_tess_offchip, vmem_offs_inner.first, oc_lds, vmem_offs_inner.second, 4, (1 << inner_comps) - 1, true, memory_sync_info(storage_vmem_output));
10680       }
10681    }
10682 
10683    begin_divergent_if_else(ctx, &ic_invocation_id_is_zero);
10684    end_divergent_if(ctx, &ic_invocation_id_is_zero);
10685 }
10686 
emit_stream_output(isel_context * ctx,Temp const * so_buffers,Temp const * so_write_offset,const struct radv_stream_output * output)10687 static void emit_stream_output(isel_context *ctx,
10688                                Temp const *so_buffers,
10689                                Temp const *so_write_offset,
10690                                const struct radv_stream_output *output)
10691 {
10692    unsigned num_comps = util_bitcount(output->component_mask);
10693    unsigned writemask = (1 << num_comps) - 1;
10694    unsigned loc = output->location;
10695    unsigned buf = output->buffer;
10696 
10697    assert(num_comps && num_comps <= 4);
10698    if (!num_comps || num_comps > 4)
10699       return;
10700 
10701    unsigned start = ffs(output->component_mask) - 1;
10702 
10703    Temp out[4];
10704    bool all_undef = true;
10705    assert(ctx->stage.hw == HWStage::VS);
10706    for (unsigned i = 0; i < num_comps; i++) {
10707       out[i] = ctx->outputs.temps[loc * 4 + start + i];
10708       all_undef = all_undef && !out[i].id();
10709    }
10710    if (all_undef)
10711       return;
10712 
10713    while (writemask) {
10714       int start, count;
10715       u_bit_scan_consecutive_range(&writemask, &start, &count);
10716       if (count == 3 && ctx->options->chip_class == GFX6) {
10717          /* GFX6 doesn't support storing vec3, split it. */
10718          writemask |= 1u << (start + 2);
10719          count = 2;
10720       }
10721 
10722       unsigned offset = output->offset + start * 4;
10723 
10724       Temp write_data = ctx->program->allocateTmp(RegClass(RegType::vgpr, count));
10725       aco_ptr<Pseudo_instruction> vec{create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector, Format::PSEUDO, count, 1)};
10726       for (int i = 0; i < count; ++i)
10727          vec->operands[i] = (ctx->outputs.mask[loc] & 1 << (start + i)) ? Operand(out[start + i]) : Operand(0u);
10728       vec->definitions[0] = Definition(write_data);
10729       ctx->block->instructions.emplace_back(std::move(vec));
10730 
10731       aco_opcode opcode;
10732       switch (count) {
10733       case 1:
10734          opcode = aco_opcode::buffer_store_dword;
10735          break;
10736       case 2:
10737          opcode = aco_opcode::buffer_store_dwordx2;
10738          break;
10739       case 3:
10740          opcode = aco_opcode::buffer_store_dwordx3;
10741          break;
10742       case 4:
10743          opcode = aco_opcode::buffer_store_dwordx4;
10744          break;
10745       default:
10746          unreachable("Unsupported dword count.");
10747       }
10748 
10749       aco_ptr<MUBUF_instruction> store{create_instruction<MUBUF_instruction>(opcode, Format::MUBUF, 4, 0)};
10750       store->operands[0] = Operand(so_buffers[buf]);
10751       store->operands[1] = Operand(so_write_offset[buf]);
10752       store->operands[2] = Operand((uint32_t) 0);
10753       store->operands[3] = Operand(write_data);
10754       if (offset > 4095) {
10755          /* Don't think this can happen in RADV, but maybe GL? It's easy to do this anyway. */
10756          Builder bld(ctx->program, ctx->block);
10757          store->operands[0] = bld.vadd32(bld.def(v1), Operand(offset), Operand(so_write_offset[buf]));
10758       } else {
10759          store->offset = offset;
10760       }
10761       store->offen = true;
10762       store->glc = true;
10763       store->dlc = false;
10764       store->slc = true;
10765       ctx->block->instructions.emplace_back(std::move(store));
10766    }
10767 }
10768 
emit_streamout(isel_context * ctx,unsigned stream)10769 static void emit_streamout(isel_context *ctx, unsigned stream)
10770 {
10771    Builder bld(ctx->program, ctx->block);
10772 
10773    Temp so_buffers[4];
10774    Temp buf_ptr = convert_pointer_to_64_bit(ctx, get_arg(ctx, ctx->args->streamout_buffers));
10775    for (unsigned i = 0; i < 4; i++) {
10776       unsigned stride = ctx->program->info->so.strides[i];
10777       if (!stride)
10778          continue;
10779 
10780       Operand off = bld.copy(bld.def(s1), Operand(i * 16u));
10781       so_buffers[i] = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), buf_ptr, off);
10782    }
10783 
10784    Temp so_vtx_count = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
10785                                 get_arg(ctx, ctx->args->streamout_config), Operand(0x70010u));
10786 
10787    Temp tid = emit_mbcnt(ctx, bld.tmp(v1));
10788 
10789    Temp can_emit = bld.vopc(aco_opcode::v_cmp_gt_i32, bld.def(bld.lm), so_vtx_count, tid);
10790 
10791    if_context ic;
10792    begin_divergent_if_then(ctx, &ic, can_emit);
10793 
10794    bld.reset(ctx->block);
10795 
10796    Temp so_write_index = bld.vadd32(bld.def(v1), get_arg(ctx, ctx->args->streamout_write_idx), tid);
10797 
10798    Temp so_write_offset[4];
10799 
10800    for (unsigned i = 0; i < 4; i++) {
10801       unsigned stride = ctx->program->info->so.strides[i];
10802       if (!stride)
10803          continue;
10804 
10805       if (stride == 1) {
10806          Temp offset = bld.sop2(aco_opcode::s_add_i32, bld.def(s1), bld.def(s1, scc),
10807                                 get_arg(ctx, ctx->args->streamout_write_idx),
10808                                 get_arg(ctx, ctx->args->streamout_offset[i]));
10809          Temp new_offset = bld.vadd32(bld.def(v1), offset, tid);
10810 
10811          so_write_offset[i] = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(2u), new_offset);
10812       } else {
10813          Temp offset = bld.v_mul_imm(bld.def(v1), so_write_index, stride * 4u);
10814          Temp offset2 = bld.sop2(aco_opcode::s_mul_i32, bld.def(s1), Operand(4u),
10815                                  get_arg(ctx, ctx->args->streamout_offset[i]));
10816          so_write_offset[i] = bld.vadd32(bld.def(v1), offset, offset2);
10817       }
10818    }
10819 
10820    for (unsigned i = 0; i < ctx->program->info->so.num_outputs; i++) {
10821       struct radv_stream_output *output =
10822          &ctx->program->info->so.outputs[i];
10823       if (stream != output->stream)
10824          continue;
10825 
10826       emit_stream_output(ctx, so_buffers, so_write_offset, output);
10827    }
10828 
10829    begin_divergent_if_else(ctx, &ic);
10830    end_divergent_if(ctx, &ic);
10831 }
10832 
add_startpgm(struct isel_context * ctx)10833 Pseudo_instruction *add_startpgm(struct isel_context *ctx)
10834 {
10835    unsigned arg_count = ctx->args->ac.arg_count;
10836    if (ctx->stage == fragment_fs) {
10837       /* LLVM optimizes away unused FS inputs and computes spi_ps_input_addr
10838        * itself and then communicates the results back via the ELF binary.
10839        * Mirror what LLVM does by re-mapping the VGPR arguments here.
10840        *
10841        * TODO: If we made the FS input scanning code into a separate pass that
10842        * could run before argument setup, then this wouldn't be necessary
10843        * anymore.
10844        */
10845       struct ac_shader_args *args = &ctx->args->ac;
10846       arg_count = 0;
10847       for (unsigned i = 0, vgpr_arg = 0, vgpr_reg = 0; i < args->arg_count; i++) {
10848          if (args->args[i].file != AC_ARG_VGPR) {
10849             arg_count++;
10850             continue;
10851          }
10852 
10853          if (!(ctx->program->config->spi_ps_input_addr & (1 << vgpr_arg))) {
10854             args->args[i].skip = true;
10855          } else {
10856             args->args[i].offset = vgpr_reg;
10857             vgpr_reg += args->args[i].size;
10858             arg_count++;
10859          }
10860          vgpr_arg++;
10861       }
10862    }
10863 
10864    aco_ptr<Pseudo_instruction> startpgm{create_instruction<Pseudo_instruction>(aco_opcode::p_startpgm, Format::PSEUDO, 0, arg_count + 1)};
10865    for (unsigned i = 0, arg = 0; i < ctx->args->ac.arg_count; i++) {
10866       if (ctx->args->ac.args[i].skip)
10867          continue;
10868 
10869       enum ac_arg_regfile file = ctx->args->ac.args[i].file;
10870       unsigned size = ctx->args->ac.args[i].size;
10871       unsigned reg = ctx->args->ac.args[i].offset;
10872       RegClass type = RegClass(file == AC_ARG_SGPR ? RegType::sgpr : RegType::vgpr, size);
10873       Temp dst = ctx->program->allocateTmp(type);
10874       ctx->arg_temps[i] = dst;
10875       startpgm->definitions[arg] = Definition(dst);
10876       startpgm->definitions[arg].setFixed(PhysReg{file == AC_ARG_SGPR ? reg : reg + 256});
10877       arg++;
10878    }
10879    startpgm->definitions[arg_count] = Definition{ctx->program->allocateId(ctx->program->lane_mask), exec, ctx->program->lane_mask};
10880    Pseudo_instruction *instr = startpgm.get();
10881    ctx->block->instructions.push_back(std::move(startpgm));
10882 
10883    /* Stash these in the program so that they can be accessed later when
10884     * handling spilling.
10885     */
10886    ctx->program->private_segment_buffer = get_arg(ctx, ctx->args->ring_offsets);
10887    ctx->program->scratch_offset = get_arg(ctx, ctx->args->scratch_offset);
10888 
10889    return instr;
10890 }
10891 
fix_ls_vgpr_init_bug(isel_context * ctx,Pseudo_instruction * startpgm)10892 void fix_ls_vgpr_init_bug(isel_context *ctx, Pseudo_instruction *startpgm)
10893 {
10894    assert(ctx->shader->info.stage == MESA_SHADER_VERTEX);
10895    Builder bld(ctx->program, ctx->block);
10896    constexpr unsigned hs_idx = 1u;
10897    Builder::Result hs_thread_count = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
10898                                               get_arg(ctx, ctx->args->merged_wave_info),
10899                                               Operand((8u << 16) | (hs_idx * 8u)));
10900    Temp ls_has_nonzero_hs_threads = bool_to_vector_condition(ctx, hs_thread_count.def(1).getTemp());
10901 
10902    /* If there are no HS threads, SPI mistakenly loads the LS VGPRs starting at VGPR 0. */
10903 
10904    Temp instance_id = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1),
10905                                get_arg(ctx, ctx->args->rel_auto_id),
10906                                get_arg(ctx, ctx->args->ac.instance_id),
10907                                ls_has_nonzero_hs_threads);
10908    Temp rel_auto_id = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1),
10909                                get_arg(ctx, ctx->args->ac.tcs_rel_ids),
10910                                get_arg(ctx, ctx->args->rel_auto_id),
10911                                ls_has_nonzero_hs_threads);
10912    Temp vertex_id = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1),
10913                              get_arg(ctx, ctx->args->ac.tcs_patch_id),
10914                              get_arg(ctx, ctx->args->ac.vertex_id),
10915                              ls_has_nonzero_hs_threads);
10916 
10917    ctx->arg_temps[ctx->args->ac.instance_id.arg_index] = instance_id;
10918    ctx->arg_temps[ctx->args->rel_auto_id.arg_index] = rel_auto_id;
10919    ctx->arg_temps[ctx->args->ac.vertex_id.arg_index] = vertex_id;
10920 }
10921 
split_arguments(isel_context * ctx,Pseudo_instruction * startpgm)10922 void split_arguments(isel_context *ctx, Pseudo_instruction *startpgm)
10923 {
10924    /* Split all arguments except for the first (ring_offsets) and the last
10925     * (exec) so that the dead channels don't stay live throughout the program.
10926     */
10927    for (int i = 1; i < startpgm->definitions.size() - 1; i++) {
10928       if (startpgm->definitions[i].regClass().size() > 1) {
10929          emit_split_vector(ctx, startpgm->definitions[i].getTemp(),
10930                            startpgm->definitions[i].regClass().size());
10931       }
10932    }
10933 }
10934 
handle_bc_optimize(isel_context * ctx)10935 void handle_bc_optimize(isel_context *ctx)
10936 {
10937    /* needed when SPI_PS_IN_CONTROL.BC_OPTIMIZE_DISABLE is set to 0 */
10938    Builder bld(ctx->program, ctx->block);
10939    uint32_t spi_ps_input_ena = ctx->program->config->spi_ps_input_ena;
10940    bool uses_center = G_0286CC_PERSP_CENTER_ENA(spi_ps_input_ena) || G_0286CC_LINEAR_CENTER_ENA(spi_ps_input_ena);
10941    bool uses_centroid = G_0286CC_PERSP_CENTROID_ENA(spi_ps_input_ena) || G_0286CC_LINEAR_CENTROID_ENA(spi_ps_input_ena);
10942    ctx->persp_centroid = get_arg(ctx, ctx->args->ac.persp_centroid);
10943    ctx->linear_centroid = get_arg(ctx, ctx->args->ac.linear_centroid);
10944    if (uses_center && uses_centroid) {
10945       Temp sel = bld.vopc_e64(aco_opcode::v_cmp_lt_i32, bld.hint_vcc(bld.def(bld.lm)),
10946                               get_arg(ctx, ctx->args->ac.prim_mask), Operand(0u));
10947 
10948       if (G_0286CC_PERSP_CENTROID_ENA(spi_ps_input_ena)) {
10949          Temp new_coord[2];
10950          for (unsigned i = 0; i < 2; i++) {
10951             Temp persp_centroid = emit_extract_vector(ctx, get_arg(ctx, ctx->args->ac.persp_centroid), i, v1);
10952             Temp persp_center = emit_extract_vector(ctx, get_arg(ctx, ctx->args->ac.persp_center), i, v1);
10953             new_coord[i] = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1),
10954                                     persp_centroid, persp_center, sel);
10955          }
10956          ctx->persp_centroid = bld.tmp(v2);
10957          bld.pseudo(aco_opcode::p_create_vector, Definition(ctx->persp_centroid),
10958                     Operand(new_coord[0]), Operand(new_coord[1]));
10959          emit_split_vector(ctx, ctx->persp_centroid, 2);
10960       }
10961 
10962       if (G_0286CC_LINEAR_CENTROID_ENA(spi_ps_input_ena)) {
10963          Temp new_coord[2];
10964          for (unsigned i = 0; i < 2; i++) {
10965             Temp linear_centroid = emit_extract_vector(ctx, get_arg(ctx, ctx->args->ac.linear_centroid), i, v1);
10966             Temp linear_center = emit_extract_vector(ctx, get_arg(ctx, ctx->args->ac.linear_center), i, v1);
10967             new_coord[i] = bld.vop2(aco_opcode::v_cndmask_b32, bld.def(v1),
10968                                     linear_centroid, linear_center, sel);
10969          }
10970          ctx->linear_centroid = bld.tmp(v2);
10971          bld.pseudo(aco_opcode::p_create_vector, Definition(ctx->linear_centroid),
10972                     Operand(new_coord[0]), Operand(new_coord[1]));
10973          emit_split_vector(ctx, ctx->linear_centroid, 2);
10974       }
10975    }
10976 }
10977 
setup_fp_mode(isel_context * ctx,nir_shader * shader)10978 void setup_fp_mode(isel_context *ctx, nir_shader *shader)
10979 {
10980    Program *program = ctx->program;
10981 
10982    unsigned float_controls = shader->info.float_controls_execution_mode;
10983 
10984    program->next_fp_mode.preserve_signed_zero_inf_nan32 =
10985       float_controls & FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP32;
10986    program->next_fp_mode.preserve_signed_zero_inf_nan16_64 =
10987       float_controls & (FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP16 |
10988                         FLOAT_CONTROLS_SIGNED_ZERO_INF_NAN_PRESERVE_FP64);
10989 
10990    program->next_fp_mode.must_flush_denorms32 =
10991       float_controls & FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP32;
10992    program->next_fp_mode.must_flush_denorms16_64 =
10993       float_controls & (FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP16 |
10994                         FLOAT_CONTROLS_DENORM_FLUSH_TO_ZERO_FP64);
10995 
10996    program->next_fp_mode.care_about_round32 =
10997       float_controls & (FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32 | FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP32);
10998 
10999    program->next_fp_mode.care_about_round16_64 =
11000       float_controls & (FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16 | FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64 |
11001                         FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP16 | FLOAT_CONTROLS_ROUNDING_MODE_RTE_FP64);
11002 
11003    /* default to preserving fp16 and fp64 denorms, since it's free for fp64 and
11004     * the precision seems needed for Wolfenstein: Youngblood to render correctly */
11005    if (program->next_fp_mode.must_flush_denorms16_64)
11006       program->next_fp_mode.denorm16_64 = 0;
11007    else
11008       program->next_fp_mode.denorm16_64 = fp_denorm_keep;
11009 
11010    /* preserving fp32 denorms is expensive, so only do it if asked */
11011    if (float_controls & FLOAT_CONTROLS_DENORM_PRESERVE_FP32)
11012       program->next_fp_mode.denorm32 = fp_denorm_keep;
11013    else
11014       program->next_fp_mode.denorm32 = 0;
11015 
11016    if (float_controls & FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP32)
11017       program->next_fp_mode.round32 = fp_round_tz;
11018    else
11019       program->next_fp_mode.round32 = fp_round_ne;
11020 
11021    if (float_controls & (FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP16 | FLOAT_CONTROLS_ROUNDING_MODE_RTZ_FP64))
11022       program->next_fp_mode.round16_64 = fp_round_tz;
11023    else
11024       program->next_fp_mode.round16_64 = fp_round_ne;
11025 
11026    ctx->block->fp_mode = program->next_fp_mode;
11027 }
11028 
cleanup_cfg(Program * program)11029 void cleanup_cfg(Program *program)
11030 {
11031    /* create linear_succs/logical_succs */
11032    for (Block& BB : program->blocks) {
11033       for (unsigned idx : BB.linear_preds)
11034          program->blocks[idx].linear_succs.emplace_back(BB.index);
11035       for (unsigned idx : BB.logical_preds)
11036          program->blocks[idx].logical_succs.emplace_back(BB.index);
11037    }
11038 }
11039 
lanecount_to_mask(isel_context * ctx,Temp count,bool allow64=true)11040 Temp lanecount_to_mask(isel_context *ctx, Temp count, bool allow64 = true)
11041 {
11042    assert(count.regClass() == s1);
11043 
11044    Builder bld(ctx->program, ctx->block);
11045    Temp mask = bld.sop2(aco_opcode::s_bfm_b64, bld.def(s2), count, Operand(0u));
11046    Temp cond;
11047 
11048    if (ctx->program->wave_size == 64) {
11049       /* If we know that all 64 threads can't be active at a time, we just use the mask as-is */
11050       if (!allow64)
11051          return mask;
11052 
11053       /* Special case for 64 active invocations, because 64 doesn't work with s_bfm */
11054       Temp active_64 = bld.sopc(aco_opcode::s_bitcmp1_b32, bld.def(s1, scc), count, Operand(6u /* log2(64) */));
11055       cond = bld.sop2(Builder::s_cselect, bld.def(bld.lm), Operand(-1u), mask, bld.scc(active_64));
11056    } else {
11057       /* We use s_bfm_b64 (not _b32) which works with 32, but we need to extract the lower half of the register */
11058       cond = emit_extract_vector(ctx, mask, 0, bld.lm);
11059    }
11060 
11061    return cond;
11062 }
11063 
merged_wave_info_to_mask(isel_context * ctx,unsigned i)11064 Temp merged_wave_info_to_mask(isel_context *ctx, unsigned i)
11065 {
11066    Builder bld(ctx->program, ctx->block);
11067 
11068    /* lanecount_to_mask() only cares about s0.u[6:0] so we don't need either s_bfe nor s_and here */
11069    Temp count = i == 0
11070                 ? get_arg(ctx, ctx->args->merged_wave_info)
11071                 : bld.sop2(aco_opcode::s_lshr_b32, bld.def(s1), bld.def(s1, scc),
11072                            get_arg(ctx, ctx->args->merged_wave_info), Operand(i * 8u));
11073 
11074    return lanecount_to_mask(ctx, count);
11075 }
11076 
ngg_max_vertex_count(isel_context * ctx)11077 Temp ngg_max_vertex_count(isel_context *ctx)
11078 {
11079    Builder bld(ctx->program, ctx->block);
11080    return bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
11081                    get_arg(ctx, ctx->args->gs_tg_info), Operand(12u | (9u << 16u)));
11082 }
11083 
ngg_max_primitive_count(isel_context * ctx)11084 Temp ngg_max_primitive_count(isel_context *ctx)
11085 {
11086    Builder bld(ctx->program, ctx->block);
11087    return bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
11088                    get_arg(ctx, ctx->args->gs_tg_info), Operand(22u | (9u << 16u)));
11089 }
11090 
ngg_emit_sendmsg_gs_alloc_req(isel_context * ctx,Temp vtx_cnt=Temp (),Temp prm_cnt=Temp ())11091 void ngg_emit_sendmsg_gs_alloc_req(isel_context *ctx, Temp vtx_cnt = Temp(), Temp prm_cnt = Temp())
11092 {
11093    Builder bld(ctx->program, ctx->block);
11094 
11095    /* It is recommended to do the GS_ALLOC_REQ as soon and as quickly as possible, so we set the maximum priority (3). */
11096    bld.sopp(aco_opcode::s_setprio, -1u, 0x3u);
11097 
11098    /* Get the id of the current wave within the threadgroup (workgroup) */
11099    Builder::Result wave_id_in_tg = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
11100                                             get_arg(ctx, ctx->args->merged_wave_info), Operand(24u | (4u << 16)));
11101 
11102    /* Execute the following code only on the first wave (wave id 0),
11103     * use the SCC def to tell if the wave id is zero or not.
11104     */
11105    Temp cond = wave_id_in_tg.def(1).getTemp();
11106    if_context ic;
11107    begin_uniform_if_then(ctx, &ic, cond);
11108    begin_uniform_if_else(ctx, &ic);
11109    bld.reset(ctx->block);
11110 
11111    /* VS/TES: we infer the vertex and primitive count from arguments
11112     * GS: the caller needs to supply them
11113     */
11114    assert(ctx->stage.has(SWStage::GS)
11115           ? (vtx_cnt.id() && prm_cnt.id())
11116           : (!vtx_cnt.id() && !prm_cnt.id()));
11117 
11118    /* Number of vertices output by VS/TES */
11119    if (vtx_cnt.id() == 0)
11120       vtx_cnt = ngg_max_vertex_count(ctx);
11121 
11122    /* Number of primitives output by VS/TES */
11123    if (prm_cnt.id() == 0)
11124       prm_cnt = ngg_max_primitive_count(ctx);
11125 
11126    Temp prm_cnt_0;
11127 
11128    if (ctx->program->chip_class == GFX10 && ctx->stage.has(SWStage::GS) && ctx->ngg_gs_const_prmcnt[0] <= 0) {
11129       /* Navi 1x workaround: make sure to always export at least 1 vertex and triangle */
11130       prm_cnt_0 = bld.sopc(aco_opcode::s_cmp_eq_u32, bld.def(s1, scc), prm_cnt, Operand(0u));
11131       prm_cnt = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1), Operand(1u), prm_cnt, bld.scc(prm_cnt_0));
11132       vtx_cnt = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1), Operand(1u), vtx_cnt, bld.scc(prm_cnt_0));
11133    }
11134 
11135    /* Put the number of vertices and primitives into m0 for the GS_ALLOC_REQ */
11136    Temp tmp = bld.sop2(aco_opcode::s_lshl_b32, bld.def(s1), bld.def(s1, scc), prm_cnt, Operand(12u));
11137    tmp = bld.sop2(aco_opcode::s_or_b32, bld.m0(bld.def(s1)), bld.def(s1, scc), tmp, vtx_cnt);
11138 
11139    /* Request the SPI to allocate space for the primitives and vertices that will be exported by the threadgroup. */
11140    bld.sopp(aco_opcode::s_sendmsg, bld.m0(tmp), -1, sendmsg_gs_alloc_req);
11141 
11142    if (prm_cnt_0.id()) {
11143       /* Navi 1x workaround: export a zero-area triangle when GS has no output. */
11144       Temp first_lane = bld.sop1(Builder::s_ff1_i32, bld.def(s1), Operand(exec, bld.lm));
11145       Temp cond = bld.sop2(Builder::s_lshl, bld.def(bld.lm), bld.def(s1, scc),
11146                            Operand(1u, ctx->program->wave_size == 64), first_lane);
11147       cond = bld.sop2(Builder::s_cselect, bld.def(bld.lm), cond, Operand(0u, ctx->program->wave_size == 64), bld.scc(prm_cnt_0));
11148 
11149       if_context ic_prim_0;
11150       begin_divergent_if_then(ctx, &ic_prim_0, cond);
11151       bld.reset(ctx->block);
11152       ctx->block->kind |= block_kind_export_end;
11153 
11154       Temp zero = bld.copy(bld.def(v1), Operand(0u));
11155       bld.exp(aco_opcode::exp, zero, Operand(v1), Operand(v1), Operand(v1),
11156         1 /* enabled mask */, V_008DFC_SQ_EXP_PRIM /* dest */,
11157         false /* compressed */, true /* done */, false /* valid mask */);
11158       bld.exp(aco_opcode::exp, zero, zero, zero, zero,
11159         0xf /* enabled mask */, V_008DFC_SQ_EXP_POS /* dest */,
11160         false /* compressed */, true /* done */, true /* valid mask */);
11161 
11162       begin_divergent_if_else(ctx, &ic_prim_0);
11163       end_divergent_if(ctx, &ic_prim_0);
11164       bld.reset(ctx->block);
11165    }
11166 
11167    end_uniform_if(ctx, &ic);
11168 
11169    /* After the GS_ALLOC_REQ is done, reset priority to default (0). */
11170    bld.reset(ctx->block);
11171    bld.sopp(aco_opcode::s_setprio, -1u, 0x0u);
11172 }
11173 
ngg_pack_prim_exp_arg(isel_context * ctx,unsigned num_vertices,const Temp vtxindex[],const Temp is_null)11174 Temp ngg_pack_prim_exp_arg(isel_context *ctx, unsigned num_vertices, const Temp vtxindex[], const Temp is_null)
11175 {
11176    Builder bld(ctx->program, ctx->block);
11177 
11178    Temp tmp;
11179    Temp gs_invocation_id;
11180 
11181    if (ctx->stage == vertex_ngg)
11182       gs_invocation_id = get_arg(ctx, ctx->args->ac.gs_invocation_id);
11183 
11184    for (unsigned i = 0; i < num_vertices; ++i) {
11185       assert(vtxindex[i].id());
11186 
11187       if (i)
11188          tmp = bld.vop3(aco_opcode::v_lshl_or_b32, bld.def(v1), vtxindex[i], Operand(10u * i), tmp);
11189       else
11190          tmp = vtxindex[i];
11191 
11192       /* The initial edge flag is always false in tess eval shaders. */
11193       if (ctx->stage == vertex_ngg) {
11194          Temp edgeflag = bld.vop3(aco_opcode::v_bfe_u32, bld.def(v1), gs_invocation_id, Operand(8u + i), Operand(1u));
11195          tmp = bld.vop3(aco_opcode::v_lshl_or_b32, bld.def(v1), edgeflag, Operand(10u * i + 9u), tmp);
11196       }
11197    }
11198 
11199    if (is_null.id())
11200       tmp = bld.vop3(aco_opcode::v_lshl_or_b32, bld.def(v1), is_null, Operand(31u), tmp);
11201 
11202    return tmp;
11203 }
11204 
ngg_emit_prim_export(isel_context * ctx,unsigned num_vertices_per_primitive,const Temp vtxindex[],const Temp is_null=Temp ())11205 void ngg_emit_prim_export(isel_context *ctx, unsigned num_vertices_per_primitive, const Temp vtxindex[], const Temp is_null = Temp())
11206 {
11207    Builder bld(ctx->program, ctx->block);
11208    Temp prim_exp_arg;
11209 
11210    if (!ctx->stage.has(SWStage::GS) && ctx->args->options->key.vs_common_out.as_ngg_passthrough)
11211       prim_exp_arg = get_arg(ctx, ctx->args->gs_vtx_offset[0]);
11212    else
11213       prim_exp_arg = ngg_pack_prim_exp_arg(ctx, num_vertices_per_primitive, vtxindex, is_null);
11214 
11215    bld.exp(aco_opcode::exp, prim_exp_arg, Operand(v1), Operand(v1), Operand(v1),
11216         1 /* enabled mask */, V_008DFC_SQ_EXP_PRIM /* dest */,
11217         false /* compressed */, true/* done */, false /* valid mask */);
11218 }
11219 
ngg_nogs_export_primitives(isel_context * ctx)11220 void ngg_nogs_export_primitives(isel_context *ctx)
11221 {
11222    /* Emit the things that NGG GS threads need to do, for shaders that don't have SW GS.
11223     * These must always come before VS exports.
11224     *
11225     * It is recommended to do these as early as possible. They can be at the beginning when
11226     * there is no SW GS and the shader doesn't write edge flags.
11227     */
11228 
11229    if_context ic;
11230    Temp is_gs_thread = merged_wave_info_to_mask(ctx, 1);
11231    begin_divergent_if_then(ctx, &ic, is_gs_thread);
11232 
11233    Builder bld(ctx->program, ctx->block);
11234    constexpr unsigned max_vertices_per_primitive = 3;
11235    unsigned num_vertices_per_primitive = max_vertices_per_primitive;
11236 
11237    assert(!ctx->stage.has(SWStage::GS));
11238 
11239    if (ctx->stage == vertex_ngg) {
11240       /* TODO: optimize for points & lines */
11241    } else if (ctx->stage == tess_eval_ngg) {
11242       if (ctx->shader->info.tess.point_mode)
11243          num_vertices_per_primitive = 1;
11244       else if (ctx->shader->info.tess.primitive_mode == GL_ISOLINES)
11245          num_vertices_per_primitive = 2;
11246    } else {
11247       unreachable("Unsupported NGG non-GS shader stage");
11248    }
11249 
11250    Temp vtxindex[max_vertices_per_primitive];
11251    if (!ctx->args->options->key.vs_common_out.as_ngg_passthrough) {
11252       vtxindex[0] = bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0xffffu),
11253                            get_arg(ctx, ctx->args->gs_vtx_offset[0]));
11254       vtxindex[1] = num_vertices_per_primitive < 2 ? Temp(0, v1) :
11255                   bld.vop3(aco_opcode::v_bfe_u32, bld.def(v1),
11256                            get_arg(ctx, ctx->args->gs_vtx_offset[0]), Operand(16u), Operand(16u));
11257       vtxindex[2] = num_vertices_per_primitive < 3 ? Temp(0, v1) :
11258                   bld.vop2(aco_opcode::v_and_b32, bld.def(v1), Operand(0xffffu),
11259                            get_arg(ctx, ctx->args->gs_vtx_offset[2]));
11260    }
11261 
11262    /* Export primitive data to the index buffer. */
11263    ngg_emit_prim_export(ctx, num_vertices_per_primitive, vtxindex);
11264 
11265    /* Export primitive ID. */
11266    if (ctx->stage == vertex_ngg && ctx->args->options->key.vs_common_out.export_prim_id) {
11267       /* Copy Primitive IDs from GS threads to the LDS address corresponding to the ES thread of the provoking vertex. */
11268       Temp prim_id = get_arg(ctx, ctx->args->ac.gs_prim_id);
11269       Temp provoking_vtx_index = vtxindex[0];
11270       Temp addr = bld.v_mul_imm(bld.def(v1), provoking_vtx_index, 4u);
11271 
11272       store_lds(ctx, 4, prim_id, 0x1u, addr, 0u, 4u);
11273    }
11274 
11275    begin_divergent_if_else(ctx, &ic);
11276    end_divergent_if(ctx, &ic);
11277 }
11278 
ngg_nogs_export_vertices(isel_context * ctx)11279 void ngg_nogs_export_vertices(isel_context *ctx)
11280 {
11281    Builder bld(ctx->program, ctx->block);
11282 
11283    /* Export VS outputs */
11284    ctx->block->kind |= block_kind_export_end;
11285    create_vs_exports(ctx);
11286 
11287    /* Export primitive ID */
11288    if (ctx->args->options->key.vs_common_out.export_prim_id) {
11289       Temp prim_id;
11290 
11291       if (ctx->stage == vertex_ngg) {
11292          /* Wait for GS threads to store primitive ID in LDS. */
11293          create_workgroup_barrier(bld);
11294 
11295          /* Calculate LDS address where the GS threads stored the primitive ID. */
11296          Temp thread_id_in_tg = thread_id_in_threadgroup(ctx);
11297          Temp addr = bld.v_mul24_imm(bld.def(v1), thread_id_in_tg, 4u);
11298 
11299          /* Load primitive ID from LDS. */
11300          prim_id = load_lds(ctx, 4, bld.tmp(v1), addr, 0u, 4u);
11301       } else if (ctx->stage == tess_eval_ngg) {
11302          /* TES: Just use the patch ID as the primitive ID. */
11303          prim_id = get_arg(ctx, ctx->args->ac.tes_patch_id);
11304       } else {
11305          unreachable("unsupported NGG non-GS shader stage.");
11306       }
11307 
11308       ctx->outputs.mask[VARYING_SLOT_PRIMITIVE_ID] |= 0x1;
11309       ctx->outputs.temps[VARYING_SLOT_PRIMITIVE_ID * 4u] = prim_id;
11310 
11311       export_vs_varying(ctx, VARYING_SLOT_PRIMITIVE_ID, false, nullptr);
11312    }
11313 }
11314 
ngg_nogs_prelude(isel_context * ctx)11315 void ngg_nogs_prelude(isel_context *ctx)
11316 {
11317    ngg_emit_sendmsg_gs_alloc_req(ctx);
11318 
11319    if (ctx->ngg_nogs_early_prim_export)
11320       ngg_nogs_export_primitives(ctx);
11321 }
11322 
ngg_nogs_late_export_finale(isel_context * ctx)11323 void ngg_nogs_late_export_finale(isel_context *ctx)
11324 {
11325    assert(!ctx->ngg_nogs_early_prim_export);
11326 
11327    /* VS exports are output to registers in a predecessor block. Emit phis to get them into this block. */
11328    create_export_phis(ctx);
11329    /* Export VS/TES primitives. */
11330    ngg_nogs_export_primitives(ctx);
11331 
11332    /* What comes next must be executed on ES threads. */
11333    if_context ic;
11334    Temp is_es_thread = merged_wave_info_to_mask(ctx, 0);
11335    begin_divergent_if_then(ctx, &ic, is_es_thread);
11336    ngg_nogs_export_vertices(ctx);
11337    begin_divergent_if_else(ctx, &ic);
11338    end_divergent_if(ctx, &ic);
11339 }
11340 
ngg_gs_workgroup_reduce_and_scan(isel_context * ctx,Temp src_mask)11341 std::pair<Temp, Temp> ngg_gs_workgroup_reduce_and_scan(isel_context *ctx, Temp src_mask)
11342 {
11343    /* Workgroup scan for NGG GS.
11344     * This performs a reduction along with an exclusive scan addition accross the workgroup.
11345     * Assumes that all lanes are enabled (exec = -1) where this is emitted.
11346     *
11347     * Input:  (1) per-lane bool
11348     *             -- 1 if the lane has a live/valid vertex, 0 otherwise
11349     * Output: (1) result of a reduction over the entire workgroup,
11350     *             -- the total number of vertices emitted by the workgroup
11351     *         (2) result of an exclusive scan over the entire workgroup
11352     *             -- used for vertex compaction, in order to determine
11353     *                which lane should export the current lane's vertex
11354     */
11355 
11356    Builder bld(ctx->program, ctx->block);
11357    assert(src_mask.regClass() == bld.lm);
11358 
11359    /* Subgroup reduction and exclusive scan on the per-lane boolean. */
11360    Temp sg_reduction = bld.sop1(Builder::s_bcnt1_i32, bld.def(s1), bld.def(s1, scc), src_mask);
11361    Temp sg_excl = emit_mbcnt(ctx, bld.tmp(v1), Operand(src_mask));
11362 
11363    if (ctx->program->workgroup_size <= ctx->program->wave_size)
11364       return std::make_pair(sg_reduction, sg_excl);
11365 
11366    if_context ic;
11367 
11368    /* Determine if the current lane is the first. */
11369    Temp is_first_lane = bld.copy(bld.def(bld.lm), Operand(1u, ctx->program->wave_size == 64));
11370    Temp wave_id_in_tg = wave_id_in_threadgroup(ctx);
11371    begin_divergent_if_then(ctx, &ic, is_first_lane);
11372    bld.reset(ctx->block);
11373 
11374    /* The first lane of each wave stores the result of its subgroup reduction to LDS (NGG scratch). */
11375    Temp wave_id_in_tg_lds_addr = bld.vop2_e64(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(2u), wave_id_in_tg);
11376    store_lds(ctx, 4u, as_vgpr(ctx, sg_reduction), 0x1u, wave_id_in_tg_lds_addr, ctx->ngg_gs_scratch_addr, 4u);
11377 
11378    begin_divergent_if_else(ctx, &ic);
11379    end_divergent_if(ctx, &ic);
11380    bld.reset(ctx->block);
11381 
11382    /* Wait for all waves to write to LDS. */
11383    create_workgroup_barrier(bld);
11384 
11385    /* Activate one lane per wave. */
11386    Temp wave_count = wave_count_in_threadgroup(ctx);
11387    Temp wave_count_mask = lanecount_to_mask(ctx, wave_count, false);
11388    begin_divergent_if_then(ctx, &ic, wave_count_mask);
11389    bld.reset(ctx->block);
11390 
11391    /* Each lane loads the reduction result from the corresponding wave. */
11392    Temp thread_id_in_wave = emit_mbcnt(ctx, bld.tmp(v1));
11393    Temp loaded_wave_id_lds_addr = bld.v_mul24_imm(bld.def(v1), thread_id_in_wave, 4u);
11394    Temp red_per_w = load_lds(ctx, 4u, bld.tmp(v1), loaded_wave_id_lds_addr, ctx->ngg_gs_scratch_addr, 4u);
11395 
11396    /* Inclusive scan on the per-wave reduction results, only care about the first 8 lanes. */
11397    Temp sgincl = bld.vop2_dpp(aco_opcode::v_add_u32, bld.def(v1), red_per_w, red_per_w, dpp_row_sr(1), 0b0001, 0b0111, true);
11398    sgincl = bld.vop2_dpp(aco_opcode::v_add_u32, bld.def(v1), sgincl, sgincl, dpp_row_sr(2), 0x1, 0xf, true);
11399    sgincl = bld.vop2_dpp(aco_opcode::v_add_u32, bld.def(v1), sgincl, sgincl, dpp_row_sr(4), 0x1, 0xf, true);
11400 
11401    begin_divergent_if_else(ctx, &ic);
11402    end_divergent_if(ctx, &ic);
11403 
11404    /* Create phi which gets us the above reduction results, or undef. */
11405    bld.reset(&ctx->block->instructions, ctx->block->instructions.begin());
11406    sgincl = bld.pseudo(aco_opcode::p_phi, bld.def(sgincl.regClass()), sgincl, Operand(v1));
11407    bld.reset(ctx->block);
11408 
11409    /* Make it an exclusive scan by shifting the results right by one lane. */
11410    Temp per_wave_excl = bld.vop1_dpp(aco_opcode::v_mov_b32, bld.def(v1), sgincl, dpp_row_sr(1), 0x1, 0xf, true);
11411 
11412    /* WG reduction result: the last lane of the above exclusive scan. */
11413    Temp wg_reduction = bld.readlane(bld.def(s1), per_wave_excl, wave_count);
11414 
11415    /* Base of the exclusive WG scan: the above exclusive result corresponding to the current wave. */
11416    Temp wg_excl_base = bld.readlane(bld.def(s1), per_wave_excl, wave_id_in_tg);
11417 
11418    /* WG exclusive scan result: base + subgroup exclusive result. */
11419    Temp wg_excl = bld.vadd32(bld.def(v1), Operand(wg_excl_base), Operand(sg_excl));
11420 
11421    return std::make_pair(wg_reduction, wg_excl);
11422 }
11423 
ngg_gs_clear_primflags(isel_context * ctx,Temp vtx_cnt,unsigned stream)11424 void ngg_gs_clear_primflags(isel_context *ctx, Temp vtx_cnt, unsigned stream)
11425 {
11426    loop_context lc;
11427    if_context ic;
11428    Builder bld(ctx->program, ctx->block);
11429    Temp zero = bld.copy(bld.def(v1b), Operand(uint8_t(0)));
11430    Temp counter_init = bld.copy(bld.def(v1), as_vgpr(ctx, vtx_cnt));
11431 
11432    begin_loop(ctx, &lc);
11433 
11434    Temp incremented_counter = bld.tmp(counter_init.regClass());
11435    bld.reset(&ctx->block->instructions, ctx->block->instructions.begin());
11436    Temp counter = bld.pseudo(aco_opcode::p_phi, bld.def(counter_init.regClass()), Operand(counter_init), incremented_counter);
11437    bld.reset(ctx->block);
11438    Temp break_cond = bld.vopc(aco_opcode::v_cmp_le_u32, bld.def(bld.lm), Operand(ctx->shader->info.gs.vertices_out), counter);
11439 
11440    /* Break when vertices_out <= counter  */
11441    begin_divergent_if_then(ctx, &ic, break_cond);
11442    emit_loop_break(ctx);
11443    begin_divergent_if_else(ctx, &ic);
11444    end_divergent_if(ctx, &ic);
11445    bld.reset(ctx->block);
11446 
11447    /* Store zero to the primitive flag of the current vertex for the current stream */
11448    Temp emit_vertex_addr = ngg_gs_emit_vertex_lds_addr(ctx, counter);
11449    unsigned primflag_offset = ctx->ngg_gs_primflags_offset + stream;
11450    store_lds(ctx, 1, zero, 0xf, emit_vertex_addr, primflag_offset, 1);
11451 
11452    /* Increment counter */
11453    bld.vadd32(Definition(incremented_counter), counter, Operand(1u));
11454 
11455    end_loop(ctx, &lc);
11456 }
11457 
ngg_gs_write_shader_query(isel_context * ctx,nir_intrinsic_instr * instr)11458 void ngg_gs_write_shader_query(isel_context *ctx, nir_intrinsic_instr *instr)
11459 {
11460    /* Each subgroup uses a single GDS atomic to collect the total number of primitives.
11461     * TODO: Consider using primitive compaction at the end instead.
11462     */
11463 
11464    unsigned total_vtx_per_prim = gs_outprim_vertices(ctx->shader->info.gs.output_primitive);
11465    if_context ic_shader_query;
11466    Builder bld(ctx->program, ctx->block);
11467 
11468    Temp shader_query = bld.sopc(aco_opcode::s_bitcmp1_b32, bld.def(s1, scc), get_arg(ctx, ctx->args->ngg_gs_state), Operand(0u));
11469    begin_uniform_if_then(ctx, &ic_shader_query, shader_query);
11470    bld.reset(ctx->block);
11471 
11472    Temp gs_vtx_cnt = get_ssa_temp(ctx, instr->src[0].ssa);
11473    Temp gs_prm_cnt = get_ssa_temp(ctx, instr->src[1].ssa);
11474    Temp sg_prm_cnt;
11475 
11476    /* Calculate the "real" number of emitted primitives from the emitted GS vertices and primitives.
11477     * GS emits points, line strips or triangle strips.
11478     * Real primitives are points, lines or triangles.
11479     */
11480    if (nir_src_is_const(instr->src[0]) && nir_src_is_const(instr->src[1])) {
11481       unsigned gs_vtx_cnt = nir_src_as_uint(instr->src[0]);
11482       unsigned gs_prm_cnt = nir_src_as_uint(instr->src[1]);
11483       Temp prm_cnt = bld.copy(bld.def(s1), Operand(gs_vtx_cnt - gs_prm_cnt * (total_vtx_per_prim - 1u)));
11484       Temp thread_cnt = bld.sop1(Builder::s_bcnt1_i32, bld.def(s1), bld.def(s1, scc), Operand(exec, bld.lm));
11485       sg_prm_cnt = bld.sop2(aco_opcode::s_mul_i32, bld.def(s1), prm_cnt, thread_cnt);
11486    } else {
11487       Temp prm_cnt = gs_vtx_cnt;
11488       if (total_vtx_per_prim > 1)
11489          prm_cnt = bld.vop3(aco_opcode::v_mad_i32_i24, bld.def(v1), gs_prm_cnt, Operand(-1u * (total_vtx_per_prim - 1)), gs_vtx_cnt);
11490       else
11491          prm_cnt = as_vgpr(ctx, prm_cnt);
11492 
11493       /* Reduction calculates the primitive count for the entire subgroup. */
11494       sg_prm_cnt = emit_reduction_instr(ctx, aco_opcode::p_reduce, ReduceOp::iadd32,
11495                                         ctx->program->wave_size, bld.def(s1), prm_cnt);
11496    }
11497 
11498    Temp first_lane = bld.sop1(Builder::s_ff1_i32, bld.def(s1), Operand(exec, bld.lm));
11499    Temp is_first_lane = bld.sop2(Builder::s_lshl, bld.def(bld.lm), bld.def(s1, scc),
11500                                  Operand(1u, ctx->program->wave_size == 64), first_lane);
11501 
11502    if_context ic_last_lane;
11503    begin_divergent_if_then(ctx, &ic_last_lane, is_first_lane);
11504    bld.reset(ctx->block);
11505 
11506    Temp gds_addr = bld.copy(bld.def(v1), Operand(0u));
11507    Operand m = bld.m0((Temp)bld.copy(bld.def(s1, m0), Operand(0x100u)));
11508    bld.ds(aco_opcode::ds_add_u32, gds_addr, as_vgpr(ctx, sg_prm_cnt), m, 0u, 0u, true);
11509 
11510    begin_divergent_if_else(ctx, &ic_last_lane);
11511    end_divergent_if(ctx, &ic_last_lane);
11512 
11513    begin_uniform_if_else(ctx, &ic_shader_query);
11514    end_uniform_if(ctx, &ic_shader_query);
11515 }
11516 
ngg_gs_load_prim_flag_0(isel_context * ctx,Temp tid_in_tg,Temp max_vtxcnt,Temp vertex_lds_addr)11517 Temp ngg_gs_load_prim_flag_0(isel_context *ctx, Temp tid_in_tg, Temp max_vtxcnt, Temp vertex_lds_addr)
11518 {
11519    if_context ic;
11520    Builder bld(ctx->program, ctx->block);
11521 
11522    Temp is_vertex_emit_thread = bld.vopc(aco_opcode::v_cmp_gt_u32, bld.def(bld.lm), max_vtxcnt, tid_in_tg);
11523    begin_divergent_if_then(ctx, &ic, is_vertex_emit_thread);
11524    bld.reset(ctx->block);
11525 
11526    Operand m = load_lds_size_m0(bld);
11527    Temp prim_flag_0 = bld.ds(aco_opcode::ds_read_u8, bld.def(v1), vertex_lds_addr, m, ctx->ngg_gs_primflags_offset);
11528 
11529    begin_divergent_if_else(ctx, &ic);
11530    end_divergent_if(ctx, &ic);
11531 
11532    bld.reset(&ctx->block->instructions, ctx->block->instructions.begin());
11533    prim_flag_0 = bld.pseudo(aco_opcode::p_phi, bld.def(prim_flag_0.regClass()), Operand(prim_flag_0), Operand(0u));
11534 
11535    return prim_flag_0;
11536 }
11537 
ngg_gs_setup_vertex_compaction(isel_context * ctx,Temp vertex_live,Temp tid_in_tg,Temp exporter_tid_in_tg)11538 void ngg_gs_setup_vertex_compaction(isel_context *ctx, Temp vertex_live, Temp tid_in_tg, Temp exporter_tid_in_tg)
11539 {
11540    if_context ic;
11541    Builder bld(ctx->program, ctx->block);
11542    assert(vertex_live.regClass() == bld.lm);
11543 
11544    begin_divergent_if_then(ctx, &ic, vertex_live);
11545    bld.reset(ctx->block);
11546 
11547    /* Setup the vertex compaction.
11548     * Save the current thread's id for the thread which will export the current vertex.
11549     * We reuse stream 1 of the primitive flag of the other thread's vertex for storing this.
11550     */
11551    Temp export_thread_lds_addr = ngg_gs_vertex_lds_addr(ctx, exporter_tid_in_tg);
11552    tid_in_tg = bld.pseudo(aco_opcode::p_extract_vector, bld.def(v1b), tid_in_tg, Operand(0u));
11553    store_lds(ctx, 1u, tid_in_tg, 1u, export_thread_lds_addr, ctx->ngg_gs_primflags_offset + 1u, 1u);
11554 
11555    begin_divergent_if_else(ctx, &ic);
11556    end_divergent_if(ctx, &ic);
11557    bld.reset(ctx->block);
11558 
11559    /* Wait for all waves to setup the vertex compaction. */
11560    create_workgroup_barrier(bld);
11561 }
11562 
ngg_gs_export_primitives(isel_context * ctx,Temp max_prmcnt,Temp tid_in_tg,Temp exporter_tid_in_tg,Temp prim_flag_0)11563 void ngg_gs_export_primitives(isel_context *ctx, Temp max_prmcnt, Temp tid_in_tg, Temp exporter_tid_in_tg,
11564                               Temp prim_flag_0)
11565 {
11566    if_context ic;
11567    Builder bld(ctx->program, ctx->block);
11568    unsigned total_vtx_per_prim = gs_outprim_vertices(ctx->shader->info.gs.output_primitive);
11569    assert(total_vtx_per_prim <= 3);
11570 
11571    Temp is_prim_export_thread = bld.vopc(aco_opcode::v_cmp_gt_u32, bld.def(bld.lm), max_prmcnt, tid_in_tg);
11572    begin_divergent_if_then(ctx, &ic, is_prim_export_thread);
11573    bld.reset(ctx->block);
11574 
11575    Temp is_null_prim = bld.vop2(aco_opcode::v_xor_b32, bld.def(v1), Operand(-1u), prim_flag_0);
11576    Temp indices[3];
11577 
11578    indices[total_vtx_per_prim - 1] = exporter_tid_in_tg;
11579    if (total_vtx_per_prim >= 2)
11580       indices[total_vtx_per_prim - 2] = bld.vsub32(bld.def(v1), exporter_tid_in_tg, Operand(1u));
11581    if (total_vtx_per_prim == 3)
11582       indices[total_vtx_per_prim - 3] = bld.vsub32(bld.def(v1), exporter_tid_in_tg, Operand(2u));
11583 
11584    if (total_vtx_per_prim == 3) {
11585       /* API GS outputs triangle strips, but NGG HW needs triangles.
11586       * We already have triangles due to how we set the primitive flags, but we need to
11587       * make sure the vertex order is so that the front/back is correct, and the provoking vertex is kept.
11588       */
11589 
11590       /* If the primitive is odd, this will increment indices[1] and decrement indices[2] */
11591       Temp is_odd = bld.vop3(aco_opcode::v_bfe_u32, bld.def(v1), Operand(prim_flag_0), Operand(1u), Operand(1u));
11592       indices[1] = bld.vadd32(bld.def(v1), indices[1], Operand(is_odd));
11593       indices[2] = bld.vsub32(bld.def(v1), indices[2], Operand(is_odd));
11594    }
11595 
11596    ngg_emit_prim_export(ctx, total_vtx_per_prim, indices, is_null_prim);
11597 
11598    begin_divergent_if_else(ctx, &ic);
11599    end_divergent_if(ctx, &ic);
11600 }
11601 
ngg_gs_export_vertices(isel_context * ctx,Temp wg_vtx_cnt,Temp tid_in_tg,Temp vertex_lds_addr)11602 void ngg_gs_export_vertices(isel_context *ctx, Temp wg_vtx_cnt, Temp tid_in_tg, Temp vertex_lds_addr)
11603 {
11604    if_context ic;
11605    Builder bld(ctx->program, ctx->block);
11606 
11607    /* See if the current thread has to export a vertex. */
11608    Temp is_vtx_export_thread = bld.vopc(aco_opcode::v_cmp_gt_u32, bld.def(bld.lm), wg_vtx_cnt, tid_in_tg);
11609    begin_divergent_if_then(ctx, &ic, is_vtx_export_thread);
11610    bld.reset(ctx->block);
11611 
11612    /* The index of the vertex that the current thread will export. */
11613    Temp exported_vtx_idx;
11614 
11615    if (ctx->ngg_gs_early_alloc) {
11616       /* No vertex compaction necessary, the thread can export its own vertex. */
11617       exported_vtx_idx = tid_in_tg;
11618    } else {
11619       /* Vertex compaction: read stream 1 of the primitive flags to see which vertex the current thread needs to export */
11620       Operand m = load_lds_size_m0(bld);
11621       exported_vtx_idx = bld.ds(aco_opcode::ds_read_u8, bld.def(v1), vertex_lds_addr, m, ctx->ngg_gs_primflags_offset + 1);
11622    }
11623 
11624    /* Get the LDS address of the vertex that the current thread must export. */
11625    Temp exported_vtx_addr = ngg_gs_vertex_lds_addr(ctx, exported_vtx_idx);
11626 
11627    /* Read the vertex attributes from LDS. */
11628    unsigned out_idx = 0;
11629    for (unsigned i = 0; i <= VARYING_SLOT_VAR31; i++) {
11630       if (ctx->program->info->gs.output_streams[i] != 0)
11631          continue;
11632 
11633       /* Set the output mask to the GS output usage mask. */
11634       unsigned rdmask =
11635          ctx->outputs.mask[i] =
11636          ctx->program->info->gs.output_usage_mask[i];
11637 
11638       if (!rdmask)
11639          continue;
11640 
11641       for (unsigned j = 0; j < 4; j++) {
11642          if (rdmask & (1 << j))
11643             ctx->outputs.temps[i * 4u + j] =
11644                load_lds(ctx, 4u, bld.tmp(v1), exported_vtx_addr, out_idx * 4u, 4u);
11645 
11646          out_idx++;
11647       }
11648    }
11649 
11650    /* Export the vertex parameters. */
11651    create_vs_exports(ctx);
11652    ctx->block->kind |= block_kind_export_end;
11653 
11654    begin_divergent_if_else(ctx, &ic);
11655    end_divergent_if(ctx, &ic);
11656 }
11657 
ngg_gs_prelude(isel_context * ctx)11658 void ngg_gs_prelude(isel_context *ctx)
11659 {
11660    if (!ctx->ngg_gs_early_alloc)
11661       return;
11662 
11663    /* We know the GS writes the maximum possible number of vertices, so
11664     * it's likely that most threads need to export a primitive, too.
11665     * Thus, we won't have to worry about primitive compaction here.
11666     */
11667    Temp num_max_vertices = ngg_max_vertex_count(ctx);
11668    ngg_emit_sendmsg_gs_alloc_req(ctx, num_max_vertices, num_max_vertices);
11669 }
11670 
ngg_gs_finale(isel_context * ctx)11671 void ngg_gs_finale(isel_context *ctx)
11672 {
11673    /* Sanity check. Make sure the vertex/primitive counts are set and the LDS is correctly initialized. */
11674    assert(ctx->ngg_gs_known_vtxcnt[0]);
11675 
11676    if_context ic;
11677    Builder bld(ctx->program, ctx->block);
11678 
11679    /* Wait for all waves to reach the epilogue. */
11680    create_workgroup_barrier(bld);
11681 
11682    /* Thread ID in the entire threadgroup */
11683    Temp tid_in_tg = thread_id_in_threadgroup(ctx);
11684    /* Number of threads that may need to export a vertex or primitive. */
11685    Temp max_vtxcnt = ngg_max_vertex_count(ctx);
11686    /* LDS address of the vertex corresponding to the current thread. */
11687    Temp vertex_lds_addr = ngg_gs_vertex_lds_addr(ctx, tid_in_tg);
11688    /* Primitive flag from stream 0 of the vertex corresponding to the current thread. */
11689    Temp prim_flag_0 = ngg_gs_load_prim_flag_0(ctx, tid_in_tg, max_vtxcnt, vertex_lds_addr);
11690 
11691    bld.reset(ctx->block);
11692 
11693    /* NIR already filters out incomplete primitives and vertices,
11694     * so any vertex whose primitive flag is non-zero is considered live/valid.
11695     */
11696    Temp vertex_live = bld.vopc(aco_opcode::v_cmp_lg_u32, bld.def(bld.lm), Operand(0u), Operand(prim_flag_0));
11697 
11698    /* Total number of vertices emitted by the workgroup. */
11699    Temp wg_vtx_cnt;
11700    /* ID of the thread which will export the current thread's vertex. */
11701    Temp exporter_tid_in_tg;
11702 
11703    if (ctx->ngg_gs_early_alloc) {
11704       /* There is no need for a scan or vertex compaction, we know that
11705        * the GS writes all possible vertices so each thread can export its own vertex.
11706        */
11707       wg_vtx_cnt = max_vtxcnt;
11708       exporter_tid_in_tg = tid_in_tg;
11709    } else {
11710       /* Perform a workgroup reduction and exclusive scan. */
11711       std::pair<Temp, Temp> wg_scan = ngg_gs_workgroup_reduce_and_scan(ctx, vertex_live);
11712       bld.reset(ctx->block);
11713       /* Total number of vertices emitted by the workgroup. */
11714       wg_vtx_cnt = wg_scan.first;
11715       /* ID of the thread which will export the current thread's vertex. */
11716       exporter_tid_in_tg = wg_scan.second;
11717       /* Skip all exports when possible. */
11718       Temp have_exports = bld.sopc(aco_opcode::s_cmp_lg_u32, bld.def(s1, scc), wg_vtx_cnt, Operand(0u));
11719       max_vtxcnt = bld.sop2(aco_opcode::s_cselect_b32, bld.def(s1), max_vtxcnt, Operand(0u), bld.scc(have_exports));
11720 
11721       ngg_emit_sendmsg_gs_alloc_req(ctx, wg_vtx_cnt, max_vtxcnt);
11722       ngg_gs_setup_vertex_compaction(ctx, vertex_live, tid_in_tg, exporter_tid_in_tg);
11723    }
11724 
11725    ngg_gs_export_primitives(ctx, max_vtxcnt, tid_in_tg, exporter_tid_in_tg, prim_flag_0);
11726    ngg_gs_export_vertices(ctx, wg_vtx_cnt, tid_in_tg, vertex_lds_addr);
11727 }
11728 
11729 } /* end namespace */
11730 
select_program(Program * program,unsigned shader_count,struct nir_shader * const * shaders,ac_shader_config * config,struct radv_shader_args * args)11731 void select_program(Program *program,
11732                     unsigned shader_count,
11733                     struct nir_shader *const *shaders,
11734                     ac_shader_config* config,
11735                     struct radv_shader_args *args)
11736 {
11737    isel_context ctx = setup_isel_context(program, shader_count, shaders, config, args, false);
11738    if_context ic_merged_wave_info;
11739    bool ngg_no_gs = ctx.stage.hw == HWStage::NGG && !ctx.stage.has(SWStage::GS);
11740    bool ngg_gs    = ctx.stage.hw == HWStage::NGG &&  ctx.stage.has(SWStage::GS);
11741 
11742    for (unsigned i = 0; i < shader_count; i++) {
11743       nir_shader *nir = shaders[i];
11744       init_context(&ctx, nir);
11745 
11746       setup_fp_mode(&ctx, nir);
11747 
11748       if (!i) {
11749          /* needs to be after init_context() for FS */
11750          Pseudo_instruction *startpgm = add_startpgm(&ctx);
11751          append_logical_start(ctx.block);
11752 
11753          if (unlikely(args->options->has_ls_vgpr_init_bug && ctx.stage == vertex_tess_control_hs))
11754             fix_ls_vgpr_init_bug(&ctx, startpgm);
11755 
11756          split_arguments(&ctx, startpgm);
11757       }
11758 
11759       if (ngg_no_gs)
11760          ngg_nogs_prelude(&ctx);
11761       else if (!i && ngg_gs)
11762          ngg_gs_prelude(&ctx);
11763 
11764       /* In a merged VS+TCS HS, the VS implementation can be completely empty. */
11765       nir_function_impl *func = nir_shader_get_entrypoint(nir);
11766       bool empty_shader = nir_cf_list_is_empty_block(&func->body) &&
11767                           ((nir->info.stage == MESA_SHADER_VERTEX &&
11768                             (ctx.stage == vertex_tess_control_hs || ctx.stage == vertex_geometry_gs)) ||
11769                            (nir->info.stage == MESA_SHADER_TESS_EVAL &&
11770                             ctx.stage == tess_eval_geometry_gs));
11771 
11772       bool check_merged_wave_info = ctx.tcs_in_out_eq ? i == 0 : ((shader_count >= 2 && !empty_shader) || ngg_no_gs);
11773       bool endif_merged_wave_info = ctx.tcs_in_out_eq ? i == 1 : check_merged_wave_info;
11774 
11775       if (i && ngg_gs) {
11776          /* NGG GS waves need to wait for each other after the GS half is done. */
11777          Builder bld(ctx.program, ctx.block);
11778          create_workgroup_barrier(bld);
11779       }
11780 
11781       if (check_merged_wave_info) {
11782          Temp cond = merged_wave_info_to_mask(&ctx, i);
11783          begin_divergent_if_then(&ctx, &ic_merged_wave_info, cond);
11784       }
11785 
11786       if (i) {
11787          Builder bld(ctx.program, ctx.block);
11788 
11789          if (!ngg_gs)
11790             create_workgroup_barrier(bld);
11791 
11792          if (ctx.stage == vertex_geometry_gs || ctx.stage == tess_eval_geometry_gs) {
11793             ctx.gs_wave_id = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1, m0), bld.def(s1, scc), get_arg(&ctx, args->merged_wave_info), Operand((8u << 16) | 16u));
11794          }
11795       } else if (ctx.stage == geometry_gs)
11796          ctx.gs_wave_id = get_arg(&ctx, args->gs_wave_id);
11797 
11798       if (ctx.stage == fragment_fs)
11799          handle_bc_optimize(&ctx);
11800 
11801       visit_cf_list(&ctx, &func->body);
11802 
11803       if (ctx.program->info->so.num_outputs && ctx.stage.hw == HWStage::VS)
11804          emit_streamout(&ctx, 0);
11805 
11806       if (ctx.stage.hw == HWStage::VS) {
11807          create_vs_exports(&ctx);
11808          ctx.block->kind |= block_kind_export_end;
11809       } else if (ngg_no_gs && ctx.ngg_nogs_early_prim_export) {
11810          ngg_nogs_export_vertices(&ctx);
11811       } else if (nir->info.stage == MESA_SHADER_GEOMETRY && !ngg_gs) {
11812          Builder bld(ctx.program, ctx.block);
11813          bld.barrier(aco_opcode::p_barrier,
11814                      memory_sync_info(storage_vmem_output, semantic_release, scope_device));
11815          bld.sopp(aco_opcode::s_sendmsg, bld.m0(ctx.gs_wave_id), -1, sendmsg_gs_done(false, false, 0));
11816       } else if (nir->info.stage == MESA_SHADER_TESS_CTRL) {
11817          write_tcs_tess_factors(&ctx);
11818       }
11819 
11820       if (ctx.stage == fragment_fs) {
11821          create_fs_exports(&ctx);
11822          ctx.block->kind |= block_kind_export_end;
11823       }
11824 
11825       if (endif_merged_wave_info) {
11826          begin_divergent_if_else(&ctx, &ic_merged_wave_info);
11827          end_divergent_if(&ctx, &ic_merged_wave_info);
11828       }
11829 
11830       if (ngg_no_gs && !ctx.ngg_nogs_early_prim_export)
11831          ngg_nogs_late_export_finale(&ctx);
11832       else if (ngg_gs && nir->info.stage == MESA_SHADER_GEOMETRY)
11833          ngg_gs_finale(&ctx);
11834 
11835       if (i == 0 && ctx.stage == vertex_tess_control_hs && ctx.tcs_in_out_eq) {
11836          /* Outputs of the previous stage are inputs to the next stage */
11837          ctx.inputs = ctx.outputs;
11838          ctx.outputs = shader_io_state();
11839       }
11840 
11841       cleanup_context(&ctx);
11842    }
11843 
11844    program->config->float_mode = program->blocks[0].fp_mode.val;
11845 
11846    append_logical_end(ctx.block);
11847    ctx.block->kind |= block_kind_uniform;
11848    Builder bld(ctx.program, ctx.block);
11849    if (ctx.program->wb_smem_l1_on_end)
11850       bld.smem(aco_opcode::s_dcache_wb, memory_sync_info(storage_buffer, semantic_volatile));
11851    bld.sopp(aco_opcode::s_endpgm);
11852 
11853    cleanup_cfg(program);
11854 }
11855 
select_gs_copy_shader(Program * program,struct nir_shader * gs_shader,ac_shader_config * config,struct radv_shader_args * args)11856 void select_gs_copy_shader(Program *program, struct nir_shader *gs_shader,
11857                            ac_shader_config* config,
11858                            struct radv_shader_args *args)
11859 {
11860    isel_context ctx = setup_isel_context(program, 1, &gs_shader, config, args, true);
11861 
11862    ctx.block->fp_mode = program->next_fp_mode;
11863 
11864    add_startpgm(&ctx);
11865    append_logical_start(ctx.block);
11866 
11867    Builder bld(ctx.program, ctx.block);
11868 
11869    Temp gsvs_ring = bld.smem(aco_opcode::s_load_dwordx4, bld.def(s4), program->private_segment_buffer, Operand(RING_GSVS_VS * 16u));
11870 
11871    Operand stream_id(0u);
11872    if (args->shader_info->so.num_outputs)
11873       stream_id = bld.sop2(aco_opcode::s_bfe_u32, bld.def(s1), bld.def(s1, scc),
11874                            get_arg(&ctx, ctx.args->streamout_config), Operand(0x20018u));
11875 
11876    Temp vtx_offset = bld.vop2(aco_opcode::v_lshlrev_b32, bld.def(v1), Operand(2u), get_arg(&ctx, ctx.args->ac.vertex_id));
11877 
11878    std::stack<if_context> if_contexts;
11879 
11880    for (unsigned stream = 0; stream < 4; stream++) {
11881       if (stream_id.isConstant() && stream != stream_id.constantValue())
11882          continue;
11883 
11884       unsigned num_components = args->shader_info->gs.num_stream_output_components[stream];
11885       if (stream > 0 && (!num_components || !args->shader_info->so.num_outputs))
11886          continue;
11887 
11888       memset(ctx.outputs.mask, 0, sizeof(ctx.outputs.mask));
11889 
11890       if (!stream_id.isConstant()) {
11891          Temp cond = bld.sopc(aco_opcode::s_cmp_eq_u32, bld.def(s1, scc), stream_id, Operand(stream));
11892          if_contexts.emplace();
11893          begin_uniform_if_then(&ctx, &if_contexts.top(), cond);
11894          bld.reset(ctx.block);
11895       }
11896 
11897       unsigned offset = 0;
11898       for (unsigned i = 0; i <= VARYING_SLOT_VAR31; ++i) {
11899          if (args->shader_info->gs.output_streams[i] != stream)
11900             continue;
11901 
11902          unsigned output_usage_mask = args->shader_info->gs.output_usage_mask[i];
11903          unsigned length = util_last_bit(output_usage_mask);
11904          for (unsigned j = 0; j < length; ++j) {
11905             if (!(output_usage_mask & (1 << j)))
11906                continue;
11907 
11908             Temp val = bld.tmp(v1);
11909             unsigned const_offset = offset * args->shader_info->gs.vertices_out * 16 * 4;
11910             load_vmem_mubuf(&ctx, val, gsvs_ring, vtx_offset, Temp(), const_offset, 4, 1,
11911                             0u, true, true, true);
11912 
11913             ctx.outputs.mask[i] |= 1 << j;
11914             ctx.outputs.temps[i * 4u + j] = val;
11915 
11916             offset++;
11917          }
11918       }
11919 
11920       if (args->shader_info->so.num_outputs) {
11921          emit_streamout(&ctx, stream);
11922          bld.reset(ctx.block);
11923       }
11924 
11925       if (stream == 0) {
11926          create_vs_exports(&ctx);
11927          ctx.block->kind |= block_kind_export_end;
11928       }
11929 
11930       if (!stream_id.isConstant()) {
11931          begin_uniform_if_else(&ctx, &if_contexts.top());
11932          bld.reset(ctx.block);
11933       }
11934    }
11935 
11936    while (!if_contexts.empty()) {
11937       end_uniform_if(&ctx, &if_contexts.top());
11938       if_contexts.pop();
11939    }
11940 
11941    program->config->float_mode = program->blocks[0].fp_mode.val;
11942 
11943    append_logical_end(ctx.block);
11944    ctx.block->kind |= block_kind_uniform;
11945    bld.reset(ctx.block);
11946    bld.sopp(aco_opcode::s_endpgm);
11947 
11948    cleanup_cfg(program);
11949 }
11950 
select_trap_handler_shader(Program * program,struct nir_shader * shader,ac_shader_config * config,struct radv_shader_args * args)11951 void select_trap_handler_shader(Program *program, struct nir_shader *shader,
11952                                 ac_shader_config* config,
11953                                 struct radv_shader_args *args)
11954 {
11955    assert(args->options->chip_class == GFX8);
11956 
11957    init_program(program, compute_cs, args->shader_info,
11958                 args->options->chip_class, args->options->family, config);
11959 
11960    isel_context ctx = {};
11961    ctx.program = program;
11962    ctx.args = args;
11963    ctx.options = args->options;
11964    ctx.stage = program->stage;
11965 
11966    ctx.block = ctx.program->create_and_insert_block();
11967    ctx.block->loop_nest_depth = 0;
11968    ctx.block->kind = block_kind_top_level;
11969 
11970    program->workgroup_size = 1; /* XXX */
11971 
11972    add_startpgm(&ctx);
11973    append_logical_start(ctx.block);
11974 
11975    Builder bld(ctx.program, ctx.block);
11976 
11977    /* Load the buffer descriptor from TMA. */
11978    bld.smem(aco_opcode::s_load_dwordx4, Definition(PhysReg{ttmp4}, s4),
11979             Operand(PhysReg{tma}, s2), Operand(0u));
11980 
11981    /* Store TTMP0-TTMP1. */
11982    bld.smem(aco_opcode::s_buffer_store_dwordx2, Operand(PhysReg{ttmp4}, s4),
11983             Operand(0u), Operand(PhysReg{ttmp0}, s2), memory_sync_info(), true);
11984 
11985    uint32_t hw_regs_idx[] = {
11986       2, /* HW_REG_STATUS */
11987       3, /* HW_REG_TRAP_STS */
11988       4, /* HW_REG_HW_ID */
11989       7, /* HW_REG_IB_STS */
11990    };
11991 
11992    /* Store some hardware registers. */
11993    for (unsigned i = 0; i < ARRAY_SIZE(hw_regs_idx); i++) {
11994       /* "((size - 1) << 11) | register" */
11995       bld.sopk(aco_opcode::s_getreg_b32, Definition(PhysReg{ttmp8}, s1),
11996                ((20 - 1) << 11) | hw_regs_idx[i]);
11997 
11998       bld.smem(aco_opcode::s_buffer_store_dword, Operand(PhysReg{ttmp4}, s4),
11999                Operand(8u + i * 4), Operand(PhysReg{ttmp8}, s1), memory_sync_info(), true);
12000    }
12001 
12002    program->config->float_mode = program->blocks[0].fp_mode.val;
12003 
12004    append_logical_end(ctx.block);
12005    ctx.block->kind |= block_kind_uniform;
12006    bld.sopp(aco_opcode::s_endpgm);
12007 
12008    cleanup_cfg(program);
12009 }
12010 }
12011