3a9ed091886ab20170c557e22eafd323e01a0656
[platform/upstream/mesa.git] / src / amd / compiler / aco_optimizer.cpp
1 /*
2  * Copyright © 2018 Valve Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  */
24
25 #include "aco_builder.h"
26 #include "aco_ir.h"
27
28 #include "util/half_float.h"
29 #include "util/memstream.h"
30
31 #include <algorithm>
32 #include <array>
33 #include <vector>
34
35 namespace aco {
36
37 #ifndef NDEBUG
38 void
39 perfwarn(Program* program, bool cond, const char* msg, Instruction* instr)
40 {
41    if (cond) {
42       char* out;
43       size_t outsize;
44       struct u_memstream mem;
45       u_memstream_open(&mem, &out, &outsize);
46       FILE* const memf = u_memstream_get(&mem);
47
48       fprintf(memf, "%s: ", msg);
49       aco_print_instr(program->gfx_level, instr, memf);
50       u_memstream_close(&mem);
51
52       aco_perfwarn(program, out);
53       free(out);
54
55       if (debug_flags & DEBUG_PERFWARN)
56          exit(1);
57    }
58 }
59 #endif
60
61 /**
62  * The optimizer works in 4 phases:
63  * (1) The first pass collects information for each ssa-def,
64  *     propagates reg->reg operands of the same type, inline constants
65  *     and neg/abs input modifiers.
66  * (2) The second pass combines instructions like mad, omod, clamp and
67  *     propagates sgpr's on VALU instructions.
68  *     This pass depends on information collected in the first pass.
69  * (3) The third pass goes backwards, and selects instructions,
70  *     i.e. decides if a mad instruction is profitable and eliminates dead code.
71  * (4) The fourth pass cleans up the sequence: literals get applied and dead
72  *     instructions are removed from the sequence.
73  */
74
75 struct mad_info {
76    aco_ptr<Instruction> add_instr;
77    uint32_t mul_temp_id;
78    uint16_t literal_mask;
79    uint16_t fp16_mask;
80
81    mad_info(aco_ptr<Instruction> instr, uint32_t id)
82        : add_instr(std::move(instr)), mul_temp_id(id), literal_mask(0), fp16_mask(0)
83    {}
84 };
85
86 enum Label {
87    label_vec = 1 << 0,
88    label_constant_32bit = 1 << 1,
89    /* label_{abs,neg,mul,omod2,omod4,omod5,clamp} are used for both 16 and
90     * 32-bit operations but this shouldn't cause any issues because we don't
91     * look through any conversions */
92    label_abs = 1 << 2,
93    label_neg = 1 << 3,
94    label_mul = 1 << 4,
95    label_temp = 1 << 5,
96    label_literal = 1 << 6,
97    label_mad = 1 << 7,
98    label_omod2 = 1 << 8,
99    label_omod4 = 1 << 9,
100    label_omod5 = 1 << 10,
101    label_clamp = 1 << 12,
102    label_undefined = 1 << 14,
103    label_vcc = 1 << 15,
104    label_b2f = 1 << 16,
105    label_add_sub = 1 << 17,
106    label_bitwise = 1 << 18,
107    label_minmax = 1 << 19,
108    label_vopc = 1 << 20,
109    label_uniform_bool = 1 << 21,
110    label_constant_64bit = 1 << 22,
111    label_uniform_bitwise = 1 << 23,
112    label_scc_invert = 1 << 24,
113    label_scc_needed = 1 << 26,
114    label_b2i = 1 << 27,
115    label_fcanonicalize = 1 << 28,
116    label_constant_16bit = 1 << 29,
117    label_usedef = 1 << 30,   /* generic label */
118    label_vop3p = 1ull << 31, /* 1ull to prevent sign extension */
119    label_canonicalized = 1ull << 32,
120    label_extract = 1ull << 33,
121    label_insert = 1ull << 34,
122    label_dpp16 = 1ull << 35,
123    label_dpp8 = 1ull << 36,
124    label_f2f32 = 1ull << 37,
125    label_f2f16 = 1ull << 38,
126    label_split = 1ull << 39,
127    label_subgroup_invocation = 1ull << 40,
128 };
129
130 static constexpr uint64_t instr_usedef_labels =
131    label_vec | label_mul | label_add_sub | label_vop3p | label_bitwise | label_uniform_bitwise |
132    label_minmax | label_vopc | label_usedef | label_extract | label_dpp16 | label_dpp8 |
133    label_f2f32 | label_subgroup_invocation;
134 static constexpr uint64_t instr_mod_labels =
135    label_omod2 | label_omod4 | label_omod5 | label_clamp | label_insert | label_f2f16;
136
137 static constexpr uint64_t instr_labels = instr_usedef_labels | instr_mod_labels | label_split;
138 static constexpr uint64_t temp_labels = label_abs | label_neg | label_temp | label_vcc | label_b2f |
139                                         label_uniform_bool | label_scc_invert | label_b2i |
140                                         label_fcanonicalize;
141 static constexpr uint32_t val_labels =
142    label_constant_32bit | label_constant_64bit | label_constant_16bit | label_literal | label_mad;
143
144 static_assert((instr_labels & temp_labels) == 0, "labels cannot intersect");
145 static_assert((instr_labels & val_labels) == 0, "labels cannot intersect");
146 static_assert((temp_labels & val_labels) == 0, "labels cannot intersect");
147
148 struct ssa_info {
149    uint64_t label;
150    union {
151       uint32_t val;
152       Temp temp;
153       Instruction* instr;
154    };
155
156    ssa_info() : label(0) {}
157
158    void add_label(Label new_label)
159    {
160       /* Since all the instr_usedef_labels use instr for the same thing
161        * (indicating the defining instruction), there is usually no need to
162        * clear any other instr labels. */
163       if (new_label & instr_usedef_labels)
164          label &= ~(instr_mod_labels | temp_labels | val_labels); /* instr, temp and val alias */
165
166       if (new_label & instr_mod_labels) {
167          label &= ~instr_labels;
168          label &= ~(temp_labels | val_labels); /* instr, temp and val alias */
169       }
170
171       if (new_label & temp_labels) {
172          label &= ~temp_labels;
173          label &= ~(instr_labels | val_labels); /* instr, temp and val alias */
174       }
175
176       uint32_t const_labels =
177          label_literal | label_constant_32bit | label_constant_64bit | label_constant_16bit;
178       if (new_label & const_labels) {
179          label &= ~val_labels | const_labels;
180          label &= ~(instr_labels | temp_labels); /* instr, temp and val alias */
181       } else if (new_label & val_labels) {
182          label &= ~val_labels;
183          label &= ~(instr_labels | temp_labels); /* instr, temp and val alias */
184       }
185
186       label |= new_label;
187    }
188
189    void set_vec(Instruction* vec)
190    {
191       add_label(label_vec);
192       instr = vec;
193    }
194
195    bool is_vec() { return label & label_vec; }
196
197    void set_constant(amd_gfx_level gfx_level, uint64_t constant)
198    {
199       Operand op16 = Operand::c16(constant);
200       Operand op32 = Operand::get_const(gfx_level, constant, 4);
201       add_label(label_literal);
202       val = constant;
203
204       /* check that no upper bits are lost in case of packed 16bit constants */
205       if (gfx_level >= GFX8 && !op16.isLiteral() &&
206           op16.constantValue16(true) == ((constant >> 16) & 0xffff))
207          add_label(label_constant_16bit);
208
209       if (!op32.isLiteral())
210          add_label(label_constant_32bit);
211
212       if (Operand::is_constant_representable(constant, 8))
213          add_label(label_constant_64bit);
214
215       if (label & label_constant_64bit) {
216          val = Operand::c64(constant).constantValue();
217          if (val != constant)
218             label &= ~(label_literal | label_constant_16bit | label_constant_32bit);
219       }
220    }
221
222    bool is_constant(unsigned bits)
223    {
224       switch (bits) {
225       case 8: return label & label_literal;
226       case 16: return label & label_constant_16bit;
227       case 32: return label & label_constant_32bit;
228       case 64: return label & label_constant_64bit;
229       }
230       return false;
231    }
232
233    bool is_literal(unsigned bits)
234    {
235       bool is_lit = label & label_literal;
236       switch (bits) {
237       case 8: return false;
238       case 16: return is_lit && ~(label & label_constant_16bit);
239       case 32: return is_lit && ~(label & label_constant_32bit);
240       case 64: return false;
241       }
242       return false;
243    }
244
245    bool is_constant_or_literal(unsigned bits)
246    {
247       if (bits == 64)
248          return label & label_constant_64bit;
249       else
250          return label & label_literal;
251    }
252
253    void set_abs(Temp abs_temp)
254    {
255       add_label(label_abs);
256       temp = abs_temp;
257    }
258
259    bool is_abs() { return label & label_abs; }
260
261    void set_neg(Temp neg_temp)
262    {
263       add_label(label_neg);
264       temp = neg_temp;
265    }
266
267    bool is_neg() { return label & label_neg; }
268
269    void set_neg_abs(Temp neg_abs_temp)
270    {
271       add_label((Label)((uint32_t)label_abs | (uint32_t)label_neg));
272       temp = neg_abs_temp;
273    }
274
275    void set_mul(Instruction* mul)
276    {
277       add_label(label_mul);
278       instr = mul;
279    }
280
281    bool is_mul() { return label & label_mul; }
282
283    void set_temp(Temp tmp)
284    {
285       add_label(label_temp);
286       temp = tmp;
287    }
288
289    bool is_temp() { return label & label_temp; }
290
291    void set_mad(uint32_t mad_info_idx)
292    {
293       add_label(label_mad);
294       val = mad_info_idx;
295    }
296
297    bool is_mad() { return label & label_mad; }
298
299    void set_omod2(Instruction* mul)
300    {
301       add_label(label_omod2);
302       instr = mul;
303    }
304
305    bool is_omod2() { return label & label_omod2; }
306
307    void set_omod4(Instruction* mul)
308    {
309       add_label(label_omod4);
310       instr = mul;
311    }
312
313    bool is_omod4() { return label & label_omod4; }
314
315    void set_omod5(Instruction* mul)
316    {
317       add_label(label_omod5);
318       instr = mul;
319    }
320
321    bool is_omod5() { return label & label_omod5; }
322
323    void set_clamp(Instruction* med3)
324    {
325       add_label(label_clamp);
326       instr = med3;
327    }
328
329    bool is_clamp() { return label & label_clamp; }
330
331    void set_f2f16(Instruction* conv)
332    {
333       add_label(label_f2f16);
334       instr = conv;
335    }
336
337    bool is_f2f16() { return label & label_f2f16; }
338
339    void set_undefined() { add_label(label_undefined); }
340
341    bool is_undefined() { return label & label_undefined; }
342
343    void set_vcc(Temp vcc_val)
344    {
345       add_label(label_vcc);
346       temp = vcc_val;
347    }
348
349    bool is_vcc() { return label & label_vcc; }
350
351    void set_b2f(Temp b2f_val)
352    {
353       add_label(label_b2f);
354       temp = b2f_val;
355    }
356
357    bool is_b2f() { return label & label_b2f; }
358
359    void set_add_sub(Instruction* add_sub_instr)
360    {
361       add_label(label_add_sub);
362       instr = add_sub_instr;
363    }
364
365    bool is_add_sub() { return label & label_add_sub; }
366
367    void set_bitwise(Instruction* bitwise_instr)
368    {
369       add_label(label_bitwise);
370       instr = bitwise_instr;
371    }
372
373    bool is_bitwise() { return label & label_bitwise; }
374
375    void set_uniform_bitwise() { add_label(label_uniform_bitwise); }
376
377    bool is_uniform_bitwise() { return label & label_uniform_bitwise; }
378
379    void set_minmax(Instruction* minmax_instr)
380    {
381       add_label(label_minmax);
382       instr = minmax_instr;
383    }
384
385    bool is_minmax() { return label & label_minmax; }
386
387    void set_vopc(Instruction* vopc_instr)
388    {
389       add_label(label_vopc);
390       instr = vopc_instr;
391    }
392
393    bool is_vopc() { return label & label_vopc; }
394
395    void set_scc_needed() { add_label(label_scc_needed); }
396
397    bool is_scc_needed() { return label & label_scc_needed; }
398
399    void set_scc_invert(Temp scc_inv)
400    {
401       add_label(label_scc_invert);
402       temp = scc_inv;
403    }
404
405    bool is_scc_invert() { return label & label_scc_invert; }
406
407    void set_uniform_bool(Temp uniform_bool)
408    {
409       add_label(label_uniform_bool);
410       temp = uniform_bool;
411    }
412
413    bool is_uniform_bool() { return label & label_uniform_bool; }
414
415    void set_b2i(Temp b2i_val)
416    {
417       add_label(label_b2i);
418       temp = b2i_val;
419    }
420
421    bool is_b2i() { return label & label_b2i; }
422
423    void set_usedef(Instruction* label_instr)
424    {
425       add_label(label_usedef);
426       instr = label_instr;
427    }
428
429    bool is_usedef() { return label & label_usedef; }
430
431    void set_vop3p(Instruction* vop3p_instr)
432    {
433       add_label(label_vop3p);
434       instr = vop3p_instr;
435    }
436
437    bool is_vop3p() { return label & label_vop3p; }
438
439    void set_fcanonicalize(Temp tmp)
440    {
441       add_label(label_fcanonicalize);
442       temp = tmp;
443    }
444
445    bool is_fcanonicalize() { return label & label_fcanonicalize; }
446
447    void set_canonicalized() { add_label(label_canonicalized); }
448
449    bool is_canonicalized() { return label & label_canonicalized; }
450
451    void set_f2f32(Instruction* cvt)
452    {
453       add_label(label_f2f32);
454       instr = cvt;
455    }
456
457    bool is_f2f32() { return label & label_f2f32; }
458
459    void set_extract(Instruction* extract)
460    {
461       add_label(label_extract);
462       instr = extract;
463    }
464
465    bool is_extract() { return label & label_extract; }
466
467    void set_insert(Instruction* insert)
468    {
469       add_label(label_insert);
470       instr = insert;
471    }
472
473    bool is_insert() { return label & label_insert; }
474
475    void set_dpp16(Instruction* mov)
476    {
477       add_label(label_dpp16);
478       instr = mov;
479    }
480
481    void set_dpp8(Instruction* mov)
482    {
483       add_label(label_dpp8);
484       instr = mov;
485    }
486
487    bool is_dpp() { return label & (label_dpp16 | label_dpp8); }
488    bool is_dpp16() { return label & label_dpp16; }
489    bool is_dpp8() { return label & label_dpp8; }
490
491    void set_split(Instruction* split)
492    {
493       add_label(label_split);
494       instr = split;
495    }
496
497    bool is_split() { return label & label_split; }
498
499    void set_subgroup_invocation(Instruction* label_instr)
500    {
501       add_label(label_subgroup_invocation);
502       instr = label_instr;
503    }
504
505    bool is_subgroup_invocation() { return label & label_subgroup_invocation; }
506 };
507
508 struct opt_ctx {
509    Program* program;
510    float_mode fp_mode;
511    std::vector<aco_ptr<Instruction>> instructions;
512    ssa_info* info;
513    std::pair<uint32_t, Temp> last_literal;
514    std::vector<mad_info> mad_infos;
515    std::vector<uint16_t> uses;
516 };
517
518 bool
519 can_use_VOP3(opt_ctx& ctx, const aco_ptr<Instruction>& instr)
520 {
521    if (instr->isVOP3())
522       return true;
523
524    if (instr->isVOP3P())
525       return false;
526
527    if (instr->operands.size() && instr->operands[0].isLiteral() && ctx.program->gfx_level < GFX10)
528       return false;
529
530    if (instr->isSDWA())
531       return false;
532
533    if (instr->isDPP() && ctx.program->gfx_level < GFX11)
534       return false;
535
536    return instr->opcode != aco_opcode::v_madmk_f32 && instr->opcode != aco_opcode::v_madak_f32 &&
537           instr->opcode != aco_opcode::v_madmk_f16 && instr->opcode != aco_opcode::v_madak_f16 &&
538           instr->opcode != aco_opcode::v_fmamk_f32 && instr->opcode != aco_opcode::v_fmaak_f32 &&
539           instr->opcode != aco_opcode::v_fmamk_f16 && instr->opcode != aco_opcode::v_fmaak_f16 &&
540           instr->opcode != aco_opcode::v_readlane_b32 &&
541           instr->opcode != aco_opcode::v_writelane_b32 &&
542           instr->opcode != aco_opcode::v_readfirstlane_b32;
543 }
544
545 bool
546 pseudo_propagate_temp(opt_ctx& ctx, aco_ptr<Instruction>& instr, Temp temp, unsigned index)
547 {
548    if (instr->definitions.empty())
549       return false;
550
551    const bool vgpr =
552       instr->opcode == aco_opcode::p_as_uniform ||
553       std::all_of(instr->definitions.begin(), instr->definitions.end(),
554                   [](const Definition& def) { return def.regClass().type() == RegType::vgpr; });
555
556    /* don't propagate VGPRs into SGPR instructions */
557    if (temp.type() == RegType::vgpr && !vgpr)
558       return false;
559
560    bool can_accept_sgpr =
561       ctx.program->gfx_level >= GFX9 ||
562       std::none_of(instr->definitions.begin(), instr->definitions.end(),
563                    [](const Definition& def) { return def.regClass().is_subdword(); });
564
565    switch (instr->opcode) {
566    case aco_opcode::p_phi:
567    case aco_opcode::p_linear_phi:
568    case aco_opcode::p_parallelcopy:
569    case aco_opcode::p_create_vector:
570       if (temp.bytes() != instr->operands[index].bytes())
571          return false;
572       break;
573    case aco_opcode::p_extract_vector:
574    case aco_opcode::p_extract:
575       if (temp.type() == RegType::sgpr && !can_accept_sgpr)
576          return false;
577       break;
578    case aco_opcode::p_split_vector: {
579       if (temp.type() == RegType::sgpr && !can_accept_sgpr)
580          return false;
581       /* don't increase the vector size */
582       if (temp.bytes() > instr->operands[index].bytes())
583          return false;
584       /* We can decrease the vector size as smaller temporaries are only
585        * propagated by p_as_uniform instructions.
586        * If this propagation leads to invalid IR or hits the assertion below,
587        * it means that some undefined bytes within a dword are begin accessed
588        * and a bug in instruction_selection is likely. */
589       int decrease = instr->operands[index].bytes() - temp.bytes();
590       while (decrease > 0) {
591          decrease -= instr->definitions.back().bytes();
592          instr->definitions.pop_back();
593       }
594       assert(decrease == 0);
595       break;
596    }
597    case aco_opcode::p_as_uniform:
598       if (temp.regClass() == instr->definitions[0].regClass())
599          instr->opcode = aco_opcode::p_parallelcopy;
600       break;
601    default: return false;
602    }
603
604    instr->operands[index].setTemp(temp);
605    return true;
606 }
607
608 /* This expects the DPP modifier to be removed. */
609 bool
610 can_apply_sgprs(opt_ctx& ctx, aco_ptr<Instruction>& instr)
611 {
612    assert(instr->isVALU());
613    if (instr->isSDWA() && ctx.program->gfx_level < GFX9)
614       return false;
615    return instr->opcode != aco_opcode::v_readfirstlane_b32 &&
616           instr->opcode != aco_opcode::v_readlane_b32 &&
617           instr->opcode != aco_opcode::v_readlane_b32_e64 &&
618           instr->opcode != aco_opcode::v_writelane_b32 &&
619           instr->opcode != aco_opcode::v_writelane_b32_e64 &&
620           instr->opcode != aco_opcode::v_permlane16_b32 &&
621           instr->opcode != aco_opcode::v_permlanex16_b32 &&
622           instr->opcode != aco_opcode::v_interp_p1_f32 &&
623           instr->opcode != aco_opcode::v_interp_p2_f32 &&
624           instr->opcode != aco_opcode::v_interp_mov_f32 &&
625           instr->opcode != aco_opcode::v_interp_p1ll_f16 &&
626           instr->opcode != aco_opcode::v_interp_p1lv_f16 &&
627           instr->opcode != aco_opcode::v_interp_p2_legacy_f16 &&
628           instr->opcode != aco_opcode::v_interp_p2_f16 &&
629           instr->opcode != aco_opcode::v_interp_p10_f32_inreg &&
630           instr->opcode != aco_opcode::v_interp_p2_f32_inreg &&
631           instr->opcode != aco_opcode::v_interp_p10_f16_f32_inreg &&
632           instr->opcode != aco_opcode::v_interp_p2_f16_f32_inreg &&
633           instr->opcode != aco_opcode::v_interp_p10_rtz_f16_f32_inreg &&
634           instr->opcode != aco_opcode::v_interp_p2_rtz_f16_f32_inreg;
635 }
636
637 bool
638 is_operand_vgpr(Operand op)
639 {
640    return op.isTemp() && op.getTemp().type() == RegType::vgpr;
641 }
642
643 /* only covers special cases */
644 bool
645 alu_can_accept_constant(const aco_ptr<Instruction>& instr, unsigned operand)
646 {
647    /* Fixed operands can't accept constants because we need them
648     * to be in their fixed register.
649     */
650    assert(instr->operands.size() > operand);
651    if (instr->operands[operand].isFixed())
652       return false;
653
654    /* SOPP instructions can't use constants. */
655    if (instr->isSOPP())
656       return false;
657
658    switch (instr->opcode) {
659    case aco_opcode::v_mac_f32:
660    case aco_opcode::v_writelane_b32:
661    case aco_opcode::v_writelane_b32_e64:
662    case aco_opcode::v_cndmask_b32: return operand != 2;
663    case aco_opcode::s_addk_i32:
664    case aco_opcode::s_mulk_i32:
665    case aco_opcode::p_extract_vector:
666    case aco_opcode::p_split_vector:
667    case aco_opcode::v_readlane_b32:
668    case aco_opcode::v_readlane_b32_e64:
669    case aco_opcode::v_readfirstlane_b32:
670    case aco_opcode::p_extract:
671    case aco_opcode::p_insert: return operand != 0;
672    case aco_opcode::p_bpermute_readlane:
673    case aco_opcode::p_bpermute_shared_vgpr:
674    case aco_opcode::p_bpermute_permlane:
675    case aco_opcode::p_interp_gfx11:
676    case aco_opcode::p_dual_src_export_gfx11:
677    case aco_opcode::v_interp_p1_f32:
678    case aco_opcode::v_interp_p2_f32:
679    case aco_opcode::v_interp_mov_f32:
680    case aco_opcode::v_interp_p1ll_f16:
681    case aco_opcode::v_interp_p1lv_f16:
682    case aco_opcode::v_interp_p2_legacy_f16:
683    case aco_opcode::v_interp_p10_f32_inreg:
684    case aco_opcode::v_interp_p2_f32_inreg:
685    case aco_opcode::v_interp_p10_f16_f32_inreg:
686    case aco_opcode::v_interp_p2_f16_f32_inreg:
687    case aco_opcode::v_interp_p10_rtz_f16_f32_inreg:
688    case aco_opcode::v_interp_p2_rtz_f16_f32_inreg: return false;
689    default: return true;
690    }
691 }
692
693 bool
694 valu_can_accept_vgpr(aco_ptr<Instruction>& instr, unsigned operand)
695 {
696    if (instr->opcode == aco_opcode::v_readlane_b32 ||
697        instr->opcode == aco_opcode::v_readlane_b32_e64 ||
698        instr->opcode == aco_opcode::v_writelane_b32 ||
699        instr->opcode == aco_opcode::v_writelane_b32_e64)
700       return operand != 1;
701    if (instr->opcode == aco_opcode::v_permlane16_b32 ||
702        instr->opcode == aco_opcode::v_permlanex16_b32)
703       return operand == 0;
704    return true;
705 }
706
707 /* check constant bus and literal limitations */
708 bool
709 check_vop3_operands(opt_ctx& ctx, unsigned num_operands, Operand* operands)
710 {
711    int limit = ctx.program->gfx_level >= GFX10 ? 2 : 1;
712    Operand literal32(s1);
713    Operand literal64(s2);
714    unsigned num_sgprs = 0;
715    unsigned sgpr[] = {0, 0};
716
717    for (unsigned i = 0; i < num_operands; i++) {
718       Operand op = operands[i];
719
720       if (op.hasRegClass() && op.regClass().type() == RegType::sgpr) {
721          /* two reads of the same SGPR count as 1 to the limit */
722          if (op.tempId() != sgpr[0] && op.tempId() != sgpr[1]) {
723             if (num_sgprs < 2)
724                sgpr[num_sgprs++] = op.tempId();
725             limit--;
726             if (limit < 0)
727                return false;
728          }
729       } else if (op.isLiteral()) {
730          if (ctx.program->gfx_level < GFX10)
731             return false;
732
733          if (!literal32.isUndefined() && literal32.constantValue() != op.constantValue())
734             return false;
735          if (!literal64.isUndefined() && literal64.constantValue() != op.constantValue())
736             return false;
737
738          /* Any number of 32-bit literals counts as only 1 to the limit. Same
739           * (but separately) for 64-bit literals. */
740          if (op.size() == 1 && literal32.isUndefined()) {
741             limit--;
742             literal32 = op;
743          } else if (op.size() == 2 && literal64.isUndefined()) {
744             limit--;
745             literal64 = op;
746          }
747
748          if (limit < 0)
749             return false;
750       }
751    }
752
753    return true;
754 }
755
756 bool
757 parse_base_offset(opt_ctx& ctx, Instruction* instr, unsigned op_index, Temp* base, uint32_t* offset,
758                   bool prevent_overflow)
759 {
760    Operand op = instr->operands[op_index];
761
762    if (!op.isTemp())
763       return false;
764    Temp tmp = op.getTemp();
765    if (!ctx.info[tmp.id()].is_add_sub())
766       return false;
767
768    Instruction* add_instr = ctx.info[tmp.id()].instr;
769
770    unsigned mask = 0x3;
771    bool is_sub = false;
772    switch (add_instr->opcode) {
773    case aco_opcode::v_add_u32:
774    case aco_opcode::v_add_co_u32:
775    case aco_opcode::v_add_co_u32_e64:
776    case aco_opcode::s_add_i32:
777    case aco_opcode::s_add_u32: break;
778    case aco_opcode::v_sub_u32:
779    case aco_opcode::v_sub_i32:
780    case aco_opcode::v_sub_co_u32:
781    case aco_opcode::v_sub_co_u32_e64:
782    case aco_opcode::s_sub_u32:
783    case aco_opcode::s_sub_i32:
784       mask = 0x2;
785       is_sub = true;
786       break;
787    case aco_opcode::v_subrev_u32:
788    case aco_opcode::v_subrev_co_u32:
789    case aco_opcode::v_subrev_co_u32_e64:
790       mask = 0x1;
791       is_sub = true;
792       break;
793    default: return false;
794    }
795    if (prevent_overflow && !add_instr->definitions[0].isNUW())
796       return false;
797
798    if (add_instr->usesModifiers())
799       return false;
800
801    u_foreach_bit (i, mask) {
802       if (add_instr->operands[i].isConstant()) {
803          *offset = add_instr->operands[i].constantValue() * (uint32_t)(is_sub ? -1 : 1);
804       } else if (add_instr->operands[i].isTemp() &&
805                  ctx.info[add_instr->operands[i].tempId()].is_constant_or_literal(32)) {
806          *offset = ctx.info[add_instr->operands[i].tempId()].val * (uint32_t)(is_sub ? -1 : 1);
807       } else {
808          continue;
809       }
810       if (!add_instr->operands[!i].isTemp())
811          continue;
812
813       uint32_t offset2 = 0;
814       if (parse_base_offset(ctx, add_instr, !i, base, &offset2, prevent_overflow)) {
815          *offset += offset2;
816       } else {
817          *base = add_instr->operands[!i].getTemp();
818       }
819       return true;
820    }
821
822    return false;
823 }
824
825 void
826 skip_smem_offset_align(opt_ctx& ctx, SMEM_instruction* smem)
827 {
828    bool soe = smem->operands.size() >= (!smem->definitions.empty() ? 3 : 4);
829    if (soe && !smem->operands[1].isConstant())
830       return;
831    /* We don't need to check the constant offset because the address seems to be calculated with
832     * (offset&-4 + const_offset&-4), not (offset+const_offset)&-4.
833     */
834
835    Operand& op = smem->operands[soe ? smem->operands.size() - 1 : 1];
836    if (!op.isTemp() || !ctx.info[op.tempId()].is_bitwise())
837       return;
838
839    Instruction* bitwise_instr = ctx.info[op.tempId()].instr;
840    if (bitwise_instr->opcode != aco_opcode::s_and_b32)
841       return;
842
843    if (bitwise_instr->operands[0].constantEquals(-4) &&
844        bitwise_instr->operands[1].isOfType(op.regClass().type()))
845       op.setTemp(bitwise_instr->operands[1].getTemp());
846    else if (bitwise_instr->operands[1].constantEquals(-4) &&
847             bitwise_instr->operands[0].isOfType(op.regClass().type()))
848       op.setTemp(bitwise_instr->operands[0].getTemp());
849 }
850
851 void
852 smem_combine(opt_ctx& ctx, aco_ptr<Instruction>& instr)
853 {
854    /* skip &-4 before offset additions: load((a + 16) & -4, 0) */
855    if (!instr->operands.empty())
856       skip_smem_offset_align(ctx, &instr->smem());
857
858    /* propagate constants and combine additions */
859    if (!instr->operands.empty() && instr->operands[1].isTemp()) {
860       SMEM_instruction& smem = instr->smem();
861       ssa_info info = ctx.info[instr->operands[1].tempId()];
862
863       Temp base;
864       uint32_t offset;
865       if (info.is_constant_or_literal(32) &&
866           ((ctx.program->gfx_level == GFX6 && info.val <= 0x3FF) ||
867            (ctx.program->gfx_level == GFX7 && info.val <= 0xFFFFFFFF) ||
868            (ctx.program->gfx_level >= GFX8 && info.val <= 0xFFFFF))) {
869          instr->operands[1] = Operand::c32(info.val);
870       } else if (parse_base_offset(ctx, instr.get(), 1, &base, &offset, true) &&
871                  base.regClass() == s1 && offset <= 0xFFFFF && ctx.program->gfx_level >= GFX9 &&
872                  offset % 4u == 0) {
873          bool soe = smem.operands.size() >= (!smem.definitions.empty() ? 3 : 4);
874          if (soe) {
875             if (ctx.info[smem.operands.back().tempId()].is_constant_or_literal(32) &&
876                 ctx.info[smem.operands.back().tempId()].val == 0) {
877                smem.operands[1] = Operand::c32(offset);
878                smem.operands.back() = Operand(base);
879             }
880          } else {
881             SMEM_instruction* new_instr = create_instruction<SMEM_instruction>(
882                smem.opcode, Format::SMEM, smem.operands.size() + 1, smem.definitions.size());
883             new_instr->operands[0] = smem.operands[0];
884             new_instr->operands[1] = Operand::c32(offset);
885             if (smem.definitions.empty())
886                new_instr->operands[2] = smem.operands[2];
887             new_instr->operands.back() = Operand(base);
888             if (!smem.definitions.empty())
889                new_instr->definitions[0] = smem.definitions[0];
890             new_instr->sync = smem.sync;
891             new_instr->glc = smem.glc;
892             new_instr->dlc = smem.dlc;
893             new_instr->nv = smem.nv;
894             new_instr->disable_wqm = smem.disable_wqm;
895             instr.reset(new_instr);
896          }
897       }
898    }
899
900    /* skip &-4 after offset additions: load(a & -4, 16) */
901    if (!instr->operands.empty())
902       skip_smem_offset_align(ctx, &instr->smem());
903 }
904
905 Operand
906 get_constant_op(opt_ctx& ctx, ssa_info info, uint32_t bits)
907 {
908    if (bits == 64)
909       return Operand::c32_or_c64(info.val, true);
910    return Operand::get_const(ctx.program->gfx_level, info.val, bits / 8u);
911 }
912
913 void
914 propagate_constants_vop3p(opt_ctx& ctx, aco_ptr<Instruction>& instr, ssa_info& info, unsigned i)
915 {
916    if (!info.is_constant_or_literal(32))
917       return;
918
919    assert(instr->operands[i].isTemp());
920    unsigned bits = get_operand_size(instr, i);
921    if (info.is_constant(bits)) {
922       instr->operands[i] = get_constant_op(ctx, info, bits);
923       return;
924    }
925
926    /* The accumulation operand of dot product instructions ignores opsel. */
927    bool cannot_use_opsel =
928       (instr->opcode == aco_opcode::v_dot4_i32_i8 || instr->opcode == aco_opcode::v_dot2_i32_i16 ||
929        instr->opcode == aco_opcode::v_dot4_i32_iu8 || instr->opcode == aco_opcode::v_dot4_u32_u8 ||
930        instr->opcode == aco_opcode::v_dot2_u32_u16) &&
931       i == 2;
932    if (cannot_use_opsel)
933       return;
934
935    /* try to fold inline constants */
936    VALU_instruction* vop3p = &instr->valu();
937    bool opsel_lo = vop3p->opsel_lo[i];
938    bool opsel_hi = vop3p->opsel_hi[i];
939
940    Operand const_op[2];
941    bool const_opsel[2] = {false, false};
942    for (unsigned j = 0; j < 2; j++) {
943       if ((unsigned)opsel_lo != j && (unsigned)opsel_hi != j)
944          continue; /* this half is unused */
945
946       uint16_t val = info.val >> (j ? 16 : 0);
947       Operand op = Operand::get_const(ctx.program->gfx_level, val, bits / 8u);
948       if (bits == 32 && op.isLiteral()) /* try sign extension */
949          op = Operand::get_const(ctx.program->gfx_level, val | 0xffff0000, 4);
950       if (bits == 32 && op.isLiteral()) { /* try shifting left */
951          op = Operand::get_const(ctx.program->gfx_level, val << 16, 4);
952          const_opsel[j] = true;
953       }
954       if (op.isLiteral())
955          return;
956       const_op[j] = op;
957    }
958
959    Operand const_lo = const_op[0];
960    Operand const_hi = const_op[1];
961    bool const_lo_opsel = const_opsel[0];
962    bool const_hi_opsel = const_opsel[1];
963
964    if (opsel_lo == opsel_hi) {
965       /* use the single 16bit value */
966       instr->operands[i] = opsel_lo ? const_hi : const_lo;
967
968       /* opsel must point the same for both halves */
969       opsel_lo = opsel_lo ? const_hi_opsel : const_lo_opsel;
970       opsel_hi = opsel_lo;
971    } else if (const_lo == const_hi) {
972       /* both constants are the same */
973       instr->operands[i] = const_lo;
974
975       /* opsel must point the same for both halves */
976       opsel_lo = const_lo_opsel;
977       opsel_hi = const_lo_opsel;
978    } else if (const_lo.constantValue16(const_lo_opsel) ==
979               const_hi.constantValue16(!const_hi_opsel)) {
980       instr->operands[i] = const_hi;
981
982       /* redirect opsel selection */
983       opsel_lo = opsel_lo ? const_hi_opsel : !const_hi_opsel;
984       opsel_hi = opsel_hi ? const_hi_opsel : !const_hi_opsel;
985    } else if (const_hi.constantValue16(const_hi_opsel) ==
986               const_lo.constantValue16(!const_lo_opsel)) {
987       instr->operands[i] = const_lo;
988
989       /* redirect opsel selection */
990       opsel_lo = opsel_lo ? !const_lo_opsel : const_lo_opsel;
991       opsel_hi = opsel_hi ? !const_lo_opsel : const_lo_opsel;
992    } else if (bits == 16 && const_lo.constantValue() == (const_hi.constantValue() ^ (1 << 15))) {
993       assert(const_lo_opsel == false && const_hi_opsel == false);
994
995       /* const_lo == -const_hi */
996       if (!can_use_input_modifiers(ctx.program->gfx_level, instr->opcode, i))
997          return;
998
999       instr->operands[i] = Operand::c16(const_lo.constantValue() & 0x7FFF);
1000       bool neg_lo = const_lo.constantValue() & (1 << 15);
1001       vop3p->neg_lo[i] ^= opsel_lo ^ neg_lo;
1002       vop3p->neg_hi[i] ^= opsel_hi ^ neg_lo;
1003
1004       /* opsel must point to lo for both operands */
1005       opsel_lo = false;
1006       opsel_hi = false;
1007    }
1008
1009    vop3p->opsel_lo[i] = opsel_lo;
1010    vop3p->opsel_hi[i] = opsel_hi;
1011 }
1012
1013 bool
1014 fixed_to_exec(Operand op)
1015 {
1016    return op.isFixed() && op.physReg() == exec;
1017 }
1018
1019 SubdwordSel
1020 parse_extract(Instruction* instr)
1021 {
1022    if (instr->opcode == aco_opcode::p_extract) {
1023       unsigned size = instr->operands[2].constantValue() / 8;
1024       unsigned offset = instr->operands[1].constantValue() * size;
1025       bool sext = instr->operands[3].constantEquals(1);
1026       return SubdwordSel(size, offset, sext);
1027    } else if (instr->opcode == aco_opcode::p_insert && instr->operands[1].constantEquals(0)) {
1028       return instr->operands[2].constantEquals(8) ? SubdwordSel::ubyte : SubdwordSel::uword;
1029    } else if (instr->opcode == aco_opcode::p_extract_vector) {
1030       unsigned size = instr->definitions[0].bytes();
1031       unsigned offset = instr->operands[1].constantValue() * size;
1032       if (size <= 2)
1033          return SubdwordSel(size, offset, false);
1034    } else if (instr->opcode == aco_opcode::p_split_vector) {
1035       assert(instr->operands[0].bytes() == 4 && instr->definitions[1].bytes() == 2);
1036       return SubdwordSel(2, 2, false);
1037    }
1038
1039    return SubdwordSel();
1040 }
1041
1042 SubdwordSel
1043 parse_insert(Instruction* instr)
1044 {
1045    if (instr->opcode == aco_opcode::p_extract && instr->operands[3].constantEquals(0) &&
1046        instr->operands[1].constantEquals(0)) {
1047       return instr->operands[2].constantEquals(8) ? SubdwordSel::ubyte : SubdwordSel::uword;
1048    } else if (instr->opcode == aco_opcode::p_insert) {
1049       unsigned size = instr->operands[2].constantValue() / 8;
1050       unsigned offset = instr->operands[1].constantValue() * size;
1051       return SubdwordSel(size, offset, false);
1052    } else {
1053       return SubdwordSel();
1054    }
1055 }
1056
1057 bool
1058 can_apply_extract(opt_ctx& ctx, aco_ptr<Instruction>& instr, unsigned idx, ssa_info& info)
1059 {
1060    Temp tmp = info.instr->operands[0].getTemp();
1061    SubdwordSel sel = parse_extract(info.instr);
1062
1063    if (!sel) {
1064       return false;
1065    } else if (sel.size() == 4) {
1066       return true;
1067    } else if ((instr->opcode == aco_opcode::v_cvt_f32_u32 ||
1068                instr->opcode == aco_opcode::v_cvt_f32_i32) &&
1069               sel.size() == 1 && !sel.sign_extend()) {
1070       return true;
1071    } else if (instr->opcode == aco_opcode::v_lshlrev_b32 && instr->operands[0].isConstant() &&
1072               sel.offset() == 0 &&
1073               ((sel.size() == 2 && instr->operands[0].constantValue() >= 16u) ||
1074                (sel.size() == 1 && instr->operands[0].constantValue() >= 24u))) {
1075       return true;
1076    } else if (instr->opcode == aco_opcode::v_mul_u32_u24 && ctx.program->gfx_level >= GFX10 &&
1077               !instr->usesModifiers() && sel.size() == 2 && !sel.sign_extend() &&
1078               (instr->operands[!idx].is16bit() ||
1079                instr->operands[!idx].constantValue() <= UINT16_MAX)) {
1080       return true;
1081    } else if (idx < 2 && can_use_SDWA(ctx.program->gfx_level, instr, true) &&
1082               (tmp.type() == RegType::vgpr || ctx.program->gfx_level >= GFX9)) {
1083       if (instr->isSDWA() && instr->sdwa().sel[idx] != SubdwordSel::dword)
1084          return false;
1085       return true;
1086    } else if (instr->isVALU() && sel.size() == 2 && !instr->valu().opsel[idx] &&
1087               can_use_opsel(ctx.program->gfx_level, instr->opcode, idx)) {
1088       return true;
1089    } else if (instr->opcode == aco_opcode::p_extract) {
1090       SubdwordSel instrSel = parse_extract(instr.get());
1091
1092       /* the outer offset must be within extracted range */
1093       if (instrSel.offset() >= sel.size())
1094          return false;
1095
1096       /* don't remove the sign-extension when increasing the size further */
1097       if (instrSel.size() > sel.size() && !instrSel.sign_extend() && sel.sign_extend())
1098          return false;
1099
1100       return true;
1101    }
1102
1103    return false;
1104 }
1105
1106 /* Combine an p_extract (or p_insert, in some cases) instruction with instr.
1107  * instr(p_extract(...)) -> instr()
1108  */
1109 void
1110 apply_extract(opt_ctx& ctx, aco_ptr<Instruction>& instr, unsigned idx, ssa_info& info)
1111 {
1112    Temp tmp = info.instr->operands[0].getTemp();
1113    SubdwordSel sel = parse_extract(info.instr);
1114    assert(sel);
1115
1116    instr->operands[idx].set16bit(false);
1117    instr->operands[idx].set24bit(false);
1118
1119    ctx.info[tmp.id()].label &= ~label_insert;
1120
1121    if (sel.size() == 4) {
1122       /* full dword selection */
1123    } else if ((instr->opcode == aco_opcode::v_cvt_f32_u32 ||
1124                instr->opcode == aco_opcode::v_cvt_f32_i32) &&
1125               sel.size() == 1 && !sel.sign_extend()) {
1126       switch (sel.offset()) {
1127       case 0: instr->opcode = aco_opcode::v_cvt_f32_ubyte0; break;
1128       case 1: instr->opcode = aco_opcode::v_cvt_f32_ubyte1; break;
1129       case 2: instr->opcode = aco_opcode::v_cvt_f32_ubyte2; break;
1130       case 3: instr->opcode = aco_opcode::v_cvt_f32_ubyte3; break;
1131       }
1132    } else if (instr->opcode == aco_opcode::v_lshlrev_b32 && instr->operands[0].isConstant() &&
1133               sel.offset() == 0 &&
1134               ((sel.size() == 2 && instr->operands[0].constantValue() >= 16u) ||
1135                (sel.size() == 1 && instr->operands[0].constantValue() >= 24u))) {
1136       /* The undesirable upper bits are already shifted out. */
1137       return;
1138    } else if (instr->opcode == aco_opcode::v_mul_u32_u24 && ctx.program->gfx_level >= GFX10 &&
1139               !instr->usesModifiers() && sel.size() == 2 && !sel.sign_extend() &&
1140               (instr->operands[!idx].is16bit() ||
1141                instr->operands[!idx].constantValue() <= UINT16_MAX)) {
1142       Instruction* mad =
1143          create_instruction<VALU_instruction>(aco_opcode::v_mad_u32_u16, Format::VOP3, 3, 1);
1144       mad->definitions[0] = instr->definitions[0];
1145       mad->operands[0] = instr->operands[0];
1146       mad->operands[1] = instr->operands[1];
1147       mad->operands[2] = Operand::zero();
1148       mad->valu().opsel[idx] = sel.offset();
1149       mad->pass_flags = instr->pass_flags;
1150       instr.reset(mad);
1151    } else if (can_use_SDWA(ctx.program->gfx_level, instr, true) &&
1152               (tmp.type() == RegType::vgpr || ctx.program->gfx_level >= GFX9)) {
1153       convert_to_SDWA(ctx.program->gfx_level, instr);
1154       instr->sdwa().sel[idx] = sel;
1155    } else if (instr->isVALU()) {
1156       if (sel.offset()) {
1157          instr->valu().opsel[idx] = true;
1158
1159          /* VOP12C cannot use opsel with SGPRs. */
1160          if (!instr->isVOP3() && !instr->isVINTERP_INREG() &&
1161              !info.instr->operands[0].isOfType(RegType::vgpr))
1162             instr->format = asVOP3(instr->format);
1163       }
1164    } else if (instr->opcode == aco_opcode::p_extract) {
1165       SubdwordSel instrSel = parse_extract(instr.get());
1166
1167       unsigned size = std::min(sel.size(), instrSel.size());
1168       unsigned offset = sel.offset() + instrSel.offset();
1169       unsigned sign_extend =
1170          instrSel.sign_extend() && (sel.sign_extend() || instrSel.size() <= sel.size());
1171
1172       instr->operands[1] = Operand::c32(offset / size);
1173       instr->operands[2] = Operand::c32(size * 8u);
1174       instr->operands[3] = Operand::c32(sign_extend);
1175       return;
1176    }
1177
1178    /* These are the only labels worth keeping at the moment. */
1179    for (Definition& def : instr->definitions) {
1180       ctx.info[def.tempId()].label &=
1181          (label_mul | label_minmax | label_usedef | label_vopc | label_f2f32 | instr_mod_labels);
1182       if (ctx.info[def.tempId()].label & instr_usedef_labels)
1183          ctx.info[def.tempId()].instr = instr.get();
1184    }
1185 }
1186
1187 void
1188 check_sdwa_extract(opt_ctx& ctx, aco_ptr<Instruction>& instr)
1189 {
1190    for (unsigned i = 0; i < instr->operands.size(); i++) {
1191       Operand op = instr->operands[i];
1192       if (!op.isTemp())
1193          continue;
1194       ssa_info& info = ctx.info[op.tempId()];
1195       if (info.is_extract() && (info.instr->operands[0].getTemp().type() == RegType::vgpr ||
1196                                 op.getTemp().type() == RegType::sgpr)) {
1197          if (!can_apply_extract(ctx, instr, i, info))
1198             info.label &= ~label_extract;
1199       }
1200    }
1201 }
1202
1203 bool
1204 does_fp_op_flush_denorms(opt_ctx& ctx, aco_opcode op)
1205 {
1206    switch (op) {
1207    case aco_opcode::v_min_f32:
1208    case aco_opcode::v_max_f32:
1209    case aco_opcode::v_med3_f32:
1210    case aco_opcode::v_min3_f32:
1211    case aco_opcode::v_max3_f32:
1212    case aco_opcode::v_min_f16:
1213    case aco_opcode::v_max_f16: return ctx.program->gfx_level > GFX8;
1214    case aco_opcode::v_cndmask_b32:
1215    case aco_opcode::v_cndmask_b16:
1216    case aco_opcode::v_mov_b32:
1217    case aco_opcode::v_mov_b16: return false;
1218    default: return true;
1219    }
1220 }
1221
1222 bool
1223 can_eliminate_fcanonicalize(opt_ctx& ctx, aco_ptr<Instruction>& instr, Temp tmp, unsigned idx)
1224 {
1225    float_mode* fp = &ctx.fp_mode;
1226    if (ctx.info[tmp.id()].is_canonicalized() ||
1227        (tmp.bytes() == 4 ? fp->denorm32 : fp->denorm16_64) == fp_denorm_keep)
1228       return true;
1229
1230    aco_opcode op = instr->opcode;
1231    return can_use_input_modifiers(ctx.program->gfx_level, instr->opcode, idx) &&
1232           does_fp_op_flush_denorms(ctx, op);
1233 }
1234
1235 bool
1236 can_eliminate_and_exec(opt_ctx& ctx, Temp tmp, unsigned pass_flags)
1237 {
1238    if (ctx.info[tmp.id()].is_vopc()) {
1239       Instruction* vopc_instr = ctx.info[tmp.id()].instr;
1240       /* Remove superfluous s_and when the VOPC instruction uses the same exec and thus
1241        * already produces the same result */
1242       return vopc_instr->pass_flags == pass_flags;
1243    }
1244    if (ctx.info[tmp.id()].is_bitwise()) {
1245       Instruction* instr = ctx.info[tmp.id()].instr;
1246       if (instr->operands.size() != 2 || instr->pass_flags != pass_flags)
1247          return false;
1248       if (!(instr->operands[0].isTemp() && instr->operands[1].isTemp()))
1249          return false;
1250       if (instr->opcode == aco_opcode::s_and_b32 || instr->opcode == aco_opcode::s_and_b64) {
1251          return can_eliminate_and_exec(ctx, instr->operands[0].getTemp(), pass_flags) ||
1252                 can_eliminate_and_exec(ctx, instr->operands[1].getTemp(), pass_flags);
1253       } else {
1254          return can_eliminate_and_exec(ctx, instr->operands[0].getTemp(), pass_flags) &&
1255                 can_eliminate_and_exec(ctx, instr->operands[1].getTemp(), pass_flags);
1256       }
1257    }
1258    return false;
1259 }
1260
1261 bool
1262 is_copy_label(opt_ctx& ctx, aco_ptr<Instruction>& instr, ssa_info& info, unsigned idx)
1263 {
1264    return info.is_temp() ||
1265           (info.is_fcanonicalize() && can_eliminate_fcanonicalize(ctx, instr, info.temp, idx));
1266 }
1267
1268 bool
1269 is_op_canonicalized(opt_ctx& ctx, Operand op)
1270 {
1271    float_mode* fp = &ctx.fp_mode;
1272    if ((op.isTemp() && ctx.info[op.tempId()].is_canonicalized()) ||
1273        (op.bytes() == 4 ? fp->denorm32 : fp->denorm16_64) == fp_denorm_keep)
1274       return true;
1275
1276    if (op.isConstant() || (op.isTemp() && ctx.info[op.tempId()].is_constant_or_literal(32))) {
1277       uint32_t val = op.isTemp() ? ctx.info[op.tempId()].val : op.constantValue();
1278       if (op.bytes() == 2)
1279          return (val & 0x7fff) == 0 || (val & 0x7fff) > 0x3ff;
1280       else if (op.bytes() == 4)
1281          return (val & 0x7fffffff) == 0 || (val & 0x7fffffff) > 0x7fffff;
1282    }
1283    return false;
1284 }
1285
1286 bool
1287 is_scratch_offset_valid(opt_ctx& ctx, Instruction* instr, int64_t offset0, int64_t offset1)
1288 {
1289    bool negative_unaligned_scratch_offset_bug = ctx.program->gfx_level == GFX10;
1290    int32_t min = ctx.program->dev.scratch_global_offset_min;
1291    int32_t max = ctx.program->dev.scratch_global_offset_max;
1292
1293    int64_t offset = offset0 + offset1;
1294
1295    bool has_vgpr_offset = instr && !instr->operands[0].isUndefined();
1296    if (negative_unaligned_scratch_offset_bug && has_vgpr_offset && offset < 0 && offset % 4)
1297       return false;
1298
1299    return offset >= min && offset <= max;
1300 }
1301
1302 bool
1303 detect_clamp(Instruction* instr, unsigned* clamped_idx)
1304 {
1305    VALU_instruction& valu = instr->valu();
1306    if (valu.omod != 0 || valu.opsel != 0)
1307       return false;
1308
1309    unsigned idx = 0;
1310    bool found_zero = false, found_one = false;
1311    bool is_fp16 = instr->opcode == aco_opcode::v_med3_f16;
1312    for (unsigned i = 0; i < 3; i++) {
1313       if (!valu.neg[i] && instr->operands[i].constantEquals(0))
1314          found_zero = true;
1315       else if (!valu.neg[i] &&
1316                instr->operands[i].constantEquals(is_fp16 ? 0x3c00 : 0x3f800000)) /* 1.0 */
1317          found_one = true;
1318       else
1319          idx = i;
1320    }
1321    if (found_zero && found_one && instr->operands[idx].isTemp()) {
1322       *clamped_idx = idx;
1323       return true;
1324    } else {
1325       return false;
1326    }
1327 }
1328
1329 void
1330 label_instruction(opt_ctx& ctx, aco_ptr<Instruction>& instr)
1331 {
1332    if (instr->isSALU() || instr->isVALU() || instr->isPseudo()) {
1333       ASSERTED bool all_const = false;
1334       for (Operand& op : instr->operands)
1335          all_const =
1336             all_const && (!op.isTemp() || ctx.info[op.tempId()].is_constant_or_literal(32));
1337       perfwarn(ctx.program, all_const, "All instruction operands are constant", instr.get());
1338
1339       ASSERTED bool is_copy = instr->opcode == aco_opcode::s_mov_b32 ||
1340                               instr->opcode == aco_opcode::s_mov_b64 ||
1341                               instr->opcode == aco_opcode::v_mov_b32;
1342       perfwarn(ctx.program, is_copy && !instr->usesModifiers(), "Use p_parallelcopy instead",
1343                instr.get());
1344    }
1345
1346    if (instr->isSMEM())
1347       smem_combine(ctx, instr);
1348
1349    for (unsigned i = 0; i < instr->operands.size(); i++) {
1350       if (!instr->operands[i].isTemp())
1351          continue;
1352
1353       ssa_info info = ctx.info[instr->operands[i].tempId()];
1354       /* propagate undef */
1355       if (info.is_undefined() && is_phi(instr))
1356          instr->operands[i] = Operand(instr->operands[i].regClass());
1357       /* propagate reg->reg of same type */
1358       while (info.is_temp() && info.temp.regClass() == instr->operands[i].getTemp().regClass()) {
1359          instr->operands[i].setTemp(ctx.info[instr->operands[i].tempId()].temp);
1360          info = ctx.info[info.temp.id()];
1361       }
1362
1363       /* PSEUDO: propagate temporaries */
1364       if (instr->isPseudo()) {
1365          while (info.is_temp()) {
1366             pseudo_propagate_temp(ctx, instr, info.temp, i);
1367             info = ctx.info[info.temp.id()];
1368          }
1369       }
1370
1371       /* SALU / PSEUDO: propagate inline constants */
1372       if (instr->isSALU() || instr->isPseudo()) {
1373          unsigned bits = get_operand_size(instr, i);
1374          if ((info.is_constant(bits) || (info.is_literal(bits) && instr->isPseudo())) &&
1375              alu_can_accept_constant(instr, i)) {
1376             instr->operands[i] = get_constant_op(ctx, info, bits);
1377             continue;
1378          }
1379       }
1380
1381       /* VALU: propagate neg, abs & inline constants */
1382       else if (instr->isVALU()) {
1383          if (is_copy_label(ctx, instr, info, i) && info.temp.type() == RegType::vgpr &&
1384              valu_can_accept_vgpr(instr, i)) {
1385             instr->operands[i].setTemp(info.temp);
1386             info = ctx.info[info.temp.id()];
1387          }
1388          /* applying SGPRs to VOP1 doesn't increase code size and DCE is helped by doing it earlier */
1389          if (info.is_temp() && info.temp.type() == RegType::sgpr && can_apply_sgprs(ctx, instr) &&
1390              instr->operands.size() == 1) {
1391             instr->format = withoutDPP(instr->format);
1392             instr->operands[i].setTemp(info.temp);
1393             info = ctx.info[info.temp.id()];
1394          }
1395
1396          /* for instructions other than v_cndmask_b32, the size of the instruction should match the
1397           * operand size */
1398          unsigned can_use_mod =
1399             instr->opcode != aco_opcode::v_cndmask_b32 || instr->operands[i].getTemp().bytes() == 4;
1400          can_use_mod =
1401             can_use_mod && can_use_input_modifiers(ctx.program->gfx_level, instr->opcode, i);
1402
1403          if (instr->isSDWA())
1404             can_use_mod = can_use_mod && instr->sdwa().sel[i].size() == 4;
1405          else
1406             can_use_mod = can_use_mod && (instr->isDPP16() || can_use_VOP3(ctx, instr));
1407
1408          unsigned bits = get_operand_size(instr, i);
1409          bool mod_bitsize_compat = instr->operands[i].bytes() * 8 == bits;
1410
1411          if (info.is_neg() && instr->opcode == aco_opcode::v_add_f32 && mod_bitsize_compat) {
1412             instr->opcode = i ? aco_opcode::v_sub_f32 : aco_opcode::v_subrev_f32;
1413             instr->operands[i].setTemp(info.temp);
1414          } else if (info.is_neg() && instr->opcode == aco_opcode::v_add_f16 && mod_bitsize_compat) {
1415             instr->opcode = i ? aco_opcode::v_sub_f16 : aco_opcode::v_subrev_f16;
1416             instr->operands[i].setTemp(info.temp);
1417          } else if (info.is_neg() && can_use_mod && mod_bitsize_compat &&
1418                     can_eliminate_fcanonicalize(ctx, instr, info.temp, i)) {
1419             if (!instr->isDPP() && !instr->isSDWA())
1420                instr->format = asVOP3(instr->format);
1421             instr->operands[i].setTemp(info.temp);
1422             if (!instr->valu().abs[i])
1423                instr->valu().neg[i] = true;
1424          }
1425          if (info.is_abs() && can_use_mod && mod_bitsize_compat &&
1426              can_eliminate_fcanonicalize(ctx, instr, info.temp, i)) {
1427             if (!instr->isDPP() && !instr->isSDWA())
1428                instr->format = asVOP3(instr->format);
1429             instr->operands[i] = Operand(info.temp);
1430             instr->valu().abs[i] = true;
1431             continue;
1432          }
1433
1434          if (instr->isVOP3P()) {
1435             propagate_constants_vop3p(ctx, instr, info, i);
1436             continue;
1437          }
1438
1439          if (info.is_constant(bits) && alu_can_accept_constant(instr, i) &&
1440              (!instr->isSDWA() || ctx.program->gfx_level >= GFX9) && (!instr->isDPP() || i != 1)) {
1441             Operand op = get_constant_op(ctx, info, bits);
1442             perfwarn(ctx.program, instr->opcode == aco_opcode::v_cndmask_b32 && i == 2,
1443                      "v_cndmask_b32 with a constant selector", instr.get());
1444             if (i == 0 || instr->isSDWA() || instr->opcode == aco_opcode::v_readlane_b32 ||
1445                 instr->opcode == aco_opcode::v_writelane_b32) {
1446                instr->format = withoutDPP(instr->format);
1447                instr->operands[i] = op;
1448                continue;
1449             } else if (!instr->isVOP3() && can_swap_operands(instr, &instr->opcode)) {
1450                instr->operands[i] = op;
1451                instr->valu().swapOperands(0, i);
1452                continue;
1453             } else if (can_use_VOP3(ctx, instr)) {
1454                instr->format = asVOP3(instr->format);
1455                instr->operands[i] = op;
1456                continue;
1457             }
1458          }
1459       }
1460
1461       /* MUBUF: propagate constants and combine additions */
1462       else if (instr->isMUBUF()) {
1463          MUBUF_instruction& mubuf = instr->mubuf();
1464          Temp base;
1465          uint32_t offset;
1466          while (info.is_temp())
1467             info = ctx.info[info.temp.id()];
1468
1469          /* According to AMDGPUDAGToDAGISel::SelectMUBUFScratchOffen(), vaddr
1470           * overflow for scratch accesses works only on GFX9+ and saddr overflow
1471           * never works. Since swizzling is the only thing that separates
1472           * scratch accesses and other accesses and swizzling changing how
1473           * addressing works significantly, this probably applies to swizzled
1474           * MUBUF accesses. */
1475          bool vaddr_prevent_overflow = mubuf.swizzled && ctx.program->gfx_level < GFX9;
1476
1477          if (mubuf.offen && mubuf.idxen && i == 1 && info.is_vec() &&
1478              info.instr->operands.size() == 2 && info.instr->operands[0].isTemp() &&
1479              info.instr->operands[0].regClass() == v1 && info.instr->operands[1].isConstant() &&
1480              mubuf.offset + info.instr->operands[1].constantValue() < 4096) {
1481             instr->operands[1] = info.instr->operands[0];
1482             mubuf.offset += info.instr->operands[1].constantValue();
1483             mubuf.offen = false;
1484             continue;
1485          } else if (mubuf.offen && i == 1 && info.is_constant_or_literal(32) &&
1486                     mubuf.offset + info.val < 4096) {
1487             assert(!mubuf.idxen);
1488             instr->operands[1] = Operand(v1);
1489             mubuf.offset += info.val;
1490             mubuf.offen = false;
1491             continue;
1492          } else if (i == 2 && info.is_constant_or_literal(32) && mubuf.offset + info.val < 4096) {
1493             instr->operands[2] = Operand::c32(0);
1494             mubuf.offset += info.val;
1495             continue;
1496          } else if (mubuf.offen && i == 1 &&
1497                     parse_base_offset(ctx, instr.get(), i, &base, &offset,
1498                                       vaddr_prevent_overflow) &&
1499                     base.regClass() == v1 && mubuf.offset + offset < 4096) {
1500             assert(!mubuf.idxen);
1501             instr->operands[1].setTemp(base);
1502             mubuf.offset += offset;
1503             continue;
1504          } else if (i == 2 && parse_base_offset(ctx, instr.get(), i, &base, &offset, true) &&
1505                     base.regClass() == s1 && mubuf.offset + offset < 4096 && !mubuf.swizzled) {
1506             instr->operands[i].setTemp(base);
1507             mubuf.offset += offset;
1508             continue;
1509          }
1510       }
1511
1512       else if (instr->isMTBUF()) {
1513          MTBUF_instruction& mtbuf = instr->mtbuf();
1514          while (info.is_temp())
1515             info = ctx.info[info.temp.id()];
1516
1517          if (mtbuf.offen && mtbuf.idxen && i == 1 && info.is_vec() &&
1518              info.instr->operands.size() == 2 && info.instr->operands[0].isTemp() &&
1519              info.instr->operands[0].regClass() == v1 && info.instr->operands[1].isConstant() &&
1520              mtbuf.offset + info.instr->operands[1].constantValue() < 4096) {
1521             instr->operands[1] = info.instr->operands[0];
1522             mtbuf.offset += info.instr->operands[1].constantValue();
1523             mtbuf.offen = false;
1524             continue;
1525          }
1526       }
1527
1528       /* SCRATCH: propagate constants and combine additions */
1529       else if (instr->isScratch()) {
1530          FLAT_instruction& scratch = instr->scratch();
1531          Temp base;
1532          uint32_t offset;
1533          while (info.is_temp())
1534             info = ctx.info[info.temp.id()];
1535
1536          /* The hardware probably does: 'scratch_base + u2u64(saddr) + i2i64(offset)'. This means
1537           * we can't combine the addition if the unsigned addition overflows and offset is
1538           * positive. In theory, there is also issues if
1539           * 'ilt(offset, 0) && ige(saddr, 0) && ilt(saddr + offset, 0)', but that just
1540           * replaces an already out-of-bounds access with a larger one since 'saddr + offset'
1541           * would be larger than INT32_MAX.
1542           */
1543          if (i <= 1 && parse_base_offset(ctx, instr.get(), i, &base, &offset, true) &&
1544              base.regClass() == instr->operands[i].regClass() &&
1545              is_scratch_offset_valid(ctx, instr.get(), scratch.offset, (int32_t)offset)) {
1546             instr->operands[i].setTemp(base);
1547             scratch.offset += (int32_t)offset;
1548             continue;
1549          } else if (i <= 1 && parse_base_offset(ctx, instr.get(), i, &base, &offset, false) &&
1550                     base.regClass() == instr->operands[i].regClass() && (int32_t)offset < 0 &&
1551                     is_scratch_offset_valid(ctx, instr.get(), scratch.offset, (int32_t)offset)) {
1552             instr->operands[i].setTemp(base);
1553             scratch.offset += (int32_t)offset;
1554             continue;
1555          } else if (i <= 1 && info.is_constant_or_literal(32) &&
1556                     ctx.program->gfx_level >= GFX10_3 &&
1557                     is_scratch_offset_valid(ctx, NULL, scratch.offset, (int32_t)info.val)) {
1558             /* GFX10.3+ can disable both SADDR and ADDR. */
1559             instr->operands[i] = Operand(instr->operands[i].regClass());
1560             scratch.offset += (int32_t)info.val;
1561             continue;
1562          }
1563       }
1564
1565       /* DS: combine additions */
1566       else if (instr->isDS()) {
1567
1568          DS_instruction& ds = instr->ds();
1569          Temp base;
1570          uint32_t offset;
1571          bool has_usable_ds_offset = ctx.program->gfx_level >= GFX7;
1572          if (has_usable_ds_offset && i == 0 &&
1573              parse_base_offset(ctx, instr.get(), i, &base, &offset, false) &&
1574              base.regClass() == instr->operands[i].regClass() &&
1575              instr->opcode != aco_opcode::ds_swizzle_b32) {
1576             if (instr->opcode == aco_opcode::ds_write2_b32 ||
1577                 instr->opcode == aco_opcode::ds_read2_b32 ||
1578                 instr->opcode == aco_opcode::ds_write2_b64 ||
1579                 instr->opcode == aco_opcode::ds_read2_b64 ||
1580                 instr->opcode == aco_opcode::ds_write2st64_b32 ||
1581                 instr->opcode == aco_opcode::ds_read2st64_b32 ||
1582                 instr->opcode == aco_opcode::ds_write2st64_b64 ||
1583                 instr->opcode == aco_opcode::ds_read2st64_b64) {
1584                bool is64bit = instr->opcode == aco_opcode::ds_write2_b64 ||
1585                               instr->opcode == aco_opcode::ds_read2_b64 ||
1586                               instr->opcode == aco_opcode::ds_write2st64_b64 ||
1587                               instr->opcode == aco_opcode::ds_read2st64_b64;
1588                bool st64 = instr->opcode == aco_opcode::ds_write2st64_b32 ||
1589                            instr->opcode == aco_opcode::ds_read2st64_b32 ||
1590                            instr->opcode == aco_opcode::ds_write2st64_b64 ||
1591                            instr->opcode == aco_opcode::ds_read2st64_b64;
1592                unsigned shifts = (is64bit ? 3 : 2) + (st64 ? 6 : 0);
1593                unsigned mask = BITFIELD_MASK(shifts);
1594
1595                if ((offset & mask) == 0 && ds.offset0 + (offset >> shifts) <= 255 &&
1596                    ds.offset1 + (offset >> shifts) <= 255) {
1597                   instr->operands[i].setTemp(base);
1598                   ds.offset0 += offset >> shifts;
1599                   ds.offset1 += offset >> shifts;
1600                }
1601             } else {
1602                if (ds.offset0 + offset <= 65535) {
1603                   instr->operands[i].setTemp(base);
1604                   ds.offset0 += offset;
1605                }
1606             }
1607          }
1608       }
1609
1610       else if (instr->isBranch()) {
1611          if (ctx.info[instr->operands[0].tempId()].is_scc_invert()) {
1612             /* Flip the branch instruction to get rid of the scc_invert instruction */
1613             instr->opcode = instr->opcode == aco_opcode::p_cbranch_z ? aco_opcode::p_cbranch_nz
1614                                                                      : aco_opcode::p_cbranch_z;
1615             instr->operands[0].setTemp(ctx.info[instr->operands[0].tempId()].temp);
1616          }
1617       }
1618    }
1619
1620    /* if this instruction doesn't define anything, return */
1621    if (instr->definitions.empty()) {
1622       check_sdwa_extract(ctx, instr);
1623       return;
1624    }
1625
1626    if (instr->isVALU() || instr->isVINTRP()) {
1627       if (instr_info.can_use_output_modifiers[(int)instr->opcode] || instr->isVINTRP() ||
1628           instr->opcode == aco_opcode::v_cndmask_b32) {
1629          bool canonicalized = true;
1630          if (!does_fp_op_flush_denorms(ctx, instr->opcode)) {
1631             unsigned ops = instr->opcode == aco_opcode::v_cndmask_b32 ? 2 : instr->operands.size();
1632             for (unsigned i = 0; canonicalized && (i < ops); i++)
1633                canonicalized = is_op_canonicalized(ctx, instr->operands[i]);
1634          }
1635          if (canonicalized)
1636             ctx.info[instr->definitions[0].tempId()].set_canonicalized();
1637       }
1638
1639       if (instr->isVOPC()) {
1640          ctx.info[instr->definitions[0].tempId()].set_vopc(instr.get());
1641          check_sdwa_extract(ctx, instr);
1642          return;
1643       }
1644       if (instr->isVOP3P()) {
1645          ctx.info[instr->definitions[0].tempId()].set_vop3p(instr.get());
1646          return;
1647       }
1648    }
1649
1650    switch (instr->opcode) {
1651    case aco_opcode::p_create_vector: {
1652       bool copy_prop = instr->operands.size() == 1 && instr->operands[0].isTemp() &&
1653                        instr->operands[0].regClass() == instr->definitions[0].regClass();
1654       if (copy_prop) {
1655          ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1656          break;
1657       }
1658
1659       /* expand vector operands */
1660       std::vector<Operand> ops;
1661       unsigned offset = 0;
1662       for (const Operand& op : instr->operands) {
1663          /* ensure that any expanded operands are properly aligned */
1664          bool aligned = offset % 4 == 0 || op.bytes() < 4;
1665          offset += op.bytes();
1666          if (aligned && op.isTemp() && ctx.info[op.tempId()].is_vec()) {
1667             Instruction* vec = ctx.info[op.tempId()].instr;
1668             for (const Operand& vec_op : vec->operands)
1669                ops.emplace_back(vec_op);
1670          } else {
1671             ops.emplace_back(op);
1672          }
1673       }
1674
1675       /* combine expanded operands to new vector */
1676       if (ops.size() != instr->operands.size()) {
1677          assert(ops.size() > instr->operands.size());
1678          Definition def = instr->definitions[0];
1679          instr.reset(create_instruction<Pseudo_instruction>(aco_opcode::p_create_vector,
1680                                                             Format::PSEUDO, ops.size(), 1));
1681          for (unsigned i = 0; i < ops.size(); i++) {
1682             if (ops[i].isTemp() && ctx.info[ops[i].tempId()].is_temp() &&
1683                 ops[i].regClass() == ctx.info[ops[i].tempId()].temp.regClass())
1684                ops[i].setTemp(ctx.info[ops[i].tempId()].temp);
1685             instr->operands[i] = ops[i];
1686          }
1687          instr->definitions[0] = def;
1688       } else {
1689          for (unsigned i = 0; i < ops.size(); i++) {
1690             assert(instr->operands[i] == ops[i]);
1691          }
1692       }
1693       ctx.info[instr->definitions[0].tempId()].set_vec(instr.get());
1694
1695       if (instr->operands.size() == 2) {
1696          /* check if this is created from split_vector */
1697          if (instr->operands[1].isTemp() && ctx.info[instr->operands[1].tempId()].is_split()) {
1698             Instruction* split = ctx.info[instr->operands[1].tempId()].instr;
1699             if (instr->operands[0].isTemp() &&
1700                 instr->operands[0].getTemp() == split->definitions[0].getTemp())
1701                ctx.info[instr->definitions[0].tempId()].set_temp(split->operands[0].getTemp());
1702          }
1703       }
1704       break;
1705    }
1706    case aco_opcode::p_split_vector: {
1707       ssa_info& info = ctx.info[instr->operands[0].tempId()];
1708
1709       if (info.is_constant_or_literal(32)) {
1710          uint64_t val = info.val;
1711          for (Definition def : instr->definitions) {
1712             uint32_t mask = u_bit_consecutive(0, def.bytes() * 8u);
1713             ctx.info[def.tempId()].set_constant(ctx.program->gfx_level, val & mask);
1714             val >>= def.bytes() * 8u;
1715          }
1716          break;
1717       } else if (!info.is_vec()) {
1718          if (instr->definitions.size() == 2 && instr->operands[0].isTemp() &&
1719              instr->definitions[0].bytes() == instr->definitions[1].bytes()) {
1720             ctx.info[instr->definitions[1].tempId()].set_split(instr.get());
1721             if (instr->operands[0].bytes() == 4) {
1722                /* D16 subdword split */
1723                ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1724                ctx.info[instr->definitions[1].tempId()].set_extract(instr.get());
1725             }
1726          }
1727          break;
1728       }
1729
1730       Instruction* vec = ctx.info[instr->operands[0].tempId()].instr;
1731       unsigned split_offset = 0;
1732       unsigned vec_offset = 0;
1733       unsigned vec_index = 0;
1734       for (unsigned i = 0; i < instr->definitions.size();
1735            split_offset += instr->definitions[i++].bytes()) {
1736          while (vec_offset < split_offset && vec_index < vec->operands.size())
1737             vec_offset += vec->operands[vec_index++].bytes();
1738
1739          if (vec_offset != split_offset ||
1740              vec->operands[vec_index].bytes() != instr->definitions[i].bytes())
1741             continue;
1742
1743          Operand vec_op = vec->operands[vec_index];
1744          if (vec_op.isConstant()) {
1745             ctx.info[instr->definitions[i].tempId()].set_constant(ctx.program->gfx_level,
1746                                                                   vec_op.constantValue64());
1747          } else if (vec_op.isUndefined()) {
1748             ctx.info[instr->definitions[i].tempId()].set_undefined();
1749          } else {
1750             assert(vec_op.isTemp());
1751             ctx.info[instr->definitions[i].tempId()].set_temp(vec_op.getTemp());
1752          }
1753       }
1754       break;
1755    }
1756    case aco_opcode::p_extract_vector: { /* mov */
1757       ssa_info& info = ctx.info[instr->operands[0].tempId()];
1758       const unsigned index = instr->operands[1].constantValue();
1759       const unsigned dst_offset = index * instr->definitions[0].bytes();
1760
1761       if (info.is_vec()) {
1762          /* check if we index directly into a vector element */
1763          Instruction* vec = info.instr;
1764          unsigned offset = 0;
1765
1766          for (const Operand& op : vec->operands) {
1767             if (offset < dst_offset) {
1768                offset += op.bytes();
1769                continue;
1770             } else if (offset != dst_offset || op.bytes() != instr->definitions[0].bytes()) {
1771                break;
1772             }
1773             instr->operands[0] = op;
1774             break;
1775          }
1776       } else if (info.is_constant_or_literal(32)) {
1777          /* propagate constants */
1778          uint32_t mask = u_bit_consecutive(0, instr->definitions[0].bytes() * 8u);
1779          uint32_t val = (info.val >> (dst_offset * 8u)) & mask;
1780          instr->operands[0] =
1781             Operand::get_const(ctx.program->gfx_level, val, instr->definitions[0].bytes());
1782          ;
1783       }
1784
1785       if (instr->operands[0].bytes() != instr->definitions[0].bytes()) {
1786          if (instr->operands[0].size() != 1)
1787             break;
1788
1789          if (index == 0)
1790             ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1791          else
1792             ctx.info[instr->definitions[0].tempId()].set_extract(instr.get());
1793          break;
1794       }
1795
1796       /* convert this extract into a copy instruction */
1797       instr->opcode = aco_opcode::p_parallelcopy;
1798       instr->operands.pop_back();
1799       FALLTHROUGH;
1800    }
1801    case aco_opcode::p_parallelcopy: /* propagate */
1802       if (instr->operands[0].isTemp() && ctx.info[instr->operands[0].tempId()].is_vec() &&
1803           instr->operands[0].regClass() != instr->definitions[0].regClass()) {
1804          /* We might not be able to copy-propagate if it's a SGPR->VGPR copy, so
1805           * duplicate the vector instead.
1806           */
1807          Instruction* vec = ctx.info[instr->operands[0].tempId()].instr;
1808          aco_ptr<Instruction> old_copy = std::move(instr);
1809
1810          instr.reset(create_instruction<Pseudo_instruction>(
1811             aco_opcode::p_create_vector, Format::PSEUDO, vec->operands.size(), 1));
1812          instr->definitions[0] = old_copy->definitions[0];
1813          std::copy(vec->operands.begin(), vec->operands.end(), instr->operands.begin());
1814          for (unsigned i = 0; i < vec->operands.size(); i++) {
1815             Operand& op = instr->operands[i];
1816             if (op.isTemp() && ctx.info[op.tempId()].is_temp() &&
1817                 ctx.info[op.tempId()].temp.type() == instr->definitions[0].regClass().type())
1818                op.setTemp(ctx.info[op.tempId()].temp);
1819          }
1820          ctx.info[instr->definitions[0].tempId()].set_vec(instr.get());
1821          break;
1822       }
1823       FALLTHROUGH;
1824    case aco_opcode::p_as_uniform:
1825       if (instr->definitions[0].isFixed()) {
1826          /* don't copy-propagate copies into fixed registers */
1827       } else if (instr->operands[0].isConstant()) {
1828          ctx.info[instr->definitions[0].tempId()].set_constant(
1829             ctx.program->gfx_level, instr->operands[0].constantValue64());
1830       } else if (instr->operands[0].isTemp()) {
1831          ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1832          if (ctx.info[instr->operands[0].tempId()].is_canonicalized())
1833             ctx.info[instr->definitions[0].tempId()].set_canonicalized();
1834       } else {
1835          assert(instr->operands[0].isFixed());
1836       }
1837       break;
1838    case aco_opcode::v_mov_b32:
1839       if (instr->isDPP16()) {
1840          /* anything else doesn't make sense in SSA */
1841          assert(instr->dpp16().row_mask == 0xf && instr->dpp16().bank_mask == 0xf);
1842          ctx.info[instr->definitions[0].tempId()].set_dpp16(instr.get());
1843       } else if (instr->isDPP8()) {
1844          ctx.info[instr->definitions[0].tempId()].set_dpp8(instr.get());
1845       }
1846       break;
1847    case aco_opcode::p_is_helper:
1848       if (!ctx.program->needs_wqm)
1849          ctx.info[instr->definitions[0].tempId()].set_constant(ctx.program->gfx_level, 0u);
1850       break;
1851    case aco_opcode::v_mul_f64: ctx.info[instr->definitions[0].tempId()].set_mul(instr.get()); break;
1852    case aco_opcode::v_mul_f16:
1853    case aco_opcode::v_mul_f32:
1854    case aco_opcode::v_mul_legacy_f32: { /* omod */
1855       ctx.info[instr->definitions[0].tempId()].set_mul(instr.get());
1856
1857       /* TODO: try to move the negate/abs modifier to the consumer instead */
1858       bool uses_mods = instr->usesModifiers();
1859       bool fp16 = instr->opcode == aco_opcode::v_mul_f16;
1860
1861       for (unsigned i = 0; i < 2; i++) {
1862          if (instr->operands[!i].isConstant() && instr->operands[i].isTemp()) {
1863             if (!instr->isDPP() && !instr->isSDWA() && !instr->valu().opsel &&
1864                 (instr->operands[!i].constantEquals(fp16 ? 0x3c00 : 0x3f800000) ||   /* 1.0 */
1865                  instr->operands[!i].constantEquals(fp16 ? 0xbc00 : 0xbf800000u))) { /* -1.0 */
1866                bool neg1 = instr->operands[!i].constantEquals(fp16 ? 0xbc00 : 0xbf800000u);
1867
1868                VALU_instruction* vop3 = instr->isVOP3() ? &instr->valu() : NULL;
1869                if (vop3 && (vop3->abs[!i] || vop3->neg[!i] || vop3->clamp || vop3->omod))
1870                   continue;
1871
1872                bool abs = vop3 && vop3->abs[i];
1873                bool neg = neg1 ^ (vop3 && vop3->neg[i]);
1874
1875                Temp other = instr->operands[i].getTemp();
1876                if (abs && neg && other.type() == RegType::vgpr)
1877                   ctx.info[instr->definitions[0].tempId()].set_neg_abs(other);
1878                else if (abs && !neg && other.type() == RegType::vgpr)
1879                   ctx.info[instr->definitions[0].tempId()].set_abs(other);
1880                else if (!abs && neg && other.type() == RegType::vgpr)
1881                   ctx.info[instr->definitions[0].tempId()].set_neg(other);
1882                else if (!abs && !neg)
1883                   ctx.info[instr->definitions[0].tempId()].set_fcanonicalize(other);
1884             } else if (uses_mods || ((fp16 ? ctx.fp_mode.preserve_signed_zero_inf_nan16_64
1885                                            : ctx.fp_mode.preserve_signed_zero_inf_nan32) &&
1886                                      instr->opcode != aco_opcode::v_mul_legacy_f32)) {
1887                continue; /* omod uses a legacy multiplication. */
1888             } else if (instr->operands[!i].constantValue() == 0u) { /* 0.0 */
1889                ctx.info[instr->definitions[0].tempId()].set_constant(ctx.program->gfx_level, 0u);
1890             } else if ((fp16 ? ctx.fp_mode.denorm16_64 : ctx.fp_mode.denorm32) != fp_denorm_flush) {
1891                /* omod has no effect if denormals are enabled. */
1892                continue;
1893             } else if (instr->operands[!i].constantValue() ==
1894                        (fp16 ? 0x4000 : 0x40000000)) { /* 2.0 */
1895                ctx.info[instr->operands[i].tempId()].set_omod2(instr.get());
1896             } else if (instr->operands[!i].constantValue() ==
1897                        (fp16 ? 0x4400 : 0x40800000)) { /* 4.0 */
1898                ctx.info[instr->operands[i].tempId()].set_omod4(instr.get());
1899             } else if (instr->operands[!i].constantValue() ==
1900                        (fp16 ? 0x3800 : 0x3f000000)) { /* 0.5 */
1901                ctx.info[instr->operands[i].tempId()].set_omod5(instr.get());
1902             } else {
1903                continue;
1904             }
1905             break;
1906          }
1907       }
1908       break;
1909    }
1910    case aco_opcode::v_mul_lo_u16:
1911    case aco_opcode::v_mul_lo_u16_e64:
1912    case aco_opcode::v_mul_u32_u24:
1913       ctx.info[instr->definitions[0].tempId()].set_usedef(instr.get());
1914       break;
1915    case aco_opcode::v_med3_f16:
1916    case aco_opcode::v_med3_f32: { /* clamp */
1917       unsigned idx;
1918       if (detect_clamp(instr.get(), &idx) && !instr->valu().abs && !instr->valu().neg)
1919          ctx.info[instr->operands[idx].tempId()].set_clamp(instr.get());
1920       break;
1921    }
1922    case aco_opcode::v_cndmask_b32:
1923       if (instr->operands[0].constantEquals(0) && instr->operands[1].constantEquals(0xFFFFFFFF))
1924          ctx.info[instr->definitions[0].tempId()].set_vcc(instr->operands[2].getTemp());
1925       else if (instr->operands[0].constantEquals(0) &&
1926                instr->operands[1].constantEquals(0x3f800000u))
1927          ctx.info[instr->definitions[0].tempId()].set_b2f(instr->operands[2].getTemp());
1928       else if (instr->operands[0].constantEquals(0) && instr->operands[1].constantEquals(1))
1929          ctx.info[instr->definitions[0].tempId()].set_b2i(instr->operands[2].getTemp());
1930
1931       break;
1932    case aco_opcode::v_cmp_lg_u32:
1933       if (instr->format == Format::VOPC && /* don't optimize VOP3 / SDWA / DPP */
1934           instr->operands[0].constantEquals(0) && instr->operands[1].isTemp() &&
1935           ctx.info[instr->operands[1].tempId()].is_vcc())
1936          ctx.info[instr->definitions[0].tempId()].set_temp(
1937             ctx.info[instr->operands[1].tempId()].temp);
1938       break;
1939    case aco_opcode::p_linear_phi: {
1940       /* lower_bool_phis() can create phis like this */
1941       bool all_same_temp = instr->operands[0].isTemp();
1942       /* this check is needed when moving uniform loop counters out of a divergent loop */
1943       if (all_same_temp)
1944          all_same_temp = instr->definitions[0].regClass() == instr->operands[0].regClass();
1945       for (unsigned i = 1; all_same_temp && (i < instr->operands.size()); i++) {
1946          if (!instr->operands[i].isTemp() ||
1947              instr->operands[i].tempId() != instr->operands[0].tempId())
1948             all_same_temp = false;
1949       }
1950       if (all_same_temp) {
1951          ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
1952       } else {
1953          bool all_undef = instr->operands[0].isUndefined();
1954          for (unsigned i = 1; all_undef && (i < instr->operands.size()); i++) {
1955             if (!instr->operands[i].isUndefined())
1956                all_undef = false;
1957          }
1958          if (all_undef)
1959             ctx.info[instr->definitions[0].tempId()].set_undefined();
1960       }
1961       break;
1962    }
1963    case aco_opcode::v_add_u32:
1964    case aco_opcode::v_add_co_u32:
1965    case aco_opcode::v_add_co_u32_e64:
1966    case aco_opcode::s_add_i32:
1967    case aco_opcode::s_add_u32:
1968    case aco_opcode::v_subbrev_co_u32:
1969    case aco_opcode::v_sub_u32:
1970    case aco_opcode::v_sub_i32:
1971    case aco_opcode::v_sub_co_u32:
1972    case aco_opcode::v_sub_co_u32_e64:
1973    case aco_opcode::s_sub_u32:
1974    case aco_opcode::s_sub_i32:
1975    case aco_opcode::v_subrev_u32:
1976    case aco_opcode::v_subrev_co_u32:
1977    case aco_opcode::v_subrev_co_u32_e64:
1978       ctx.info[instr->definitions[0].tempId()].set_add_sub(instr.get());
1979       break;
1980    case aco_opcode::s_not_b32:
1981    case aco_opcode::s_not_b64:
1982       if (ctx.info[instr->operands[0].tempId()].is_uniform_bool()) {
1983          ctx.info[instr->definitions[0].tempId()].set_uniform_bitwise();
1984          ctx.info[instr->definitions[1].tempId()].set_scc_invert(
1985             ctx.info[instr->operands[0].tempId()].temp);
1986       } else if (ctx.info[instr->operands[0].tempId()].is_uniform_bitwise()) {
1987          ctx.info[instr->definitions[0].tempId()].set_uniform_bitwise();
1988          ctx.info[instr->definitions[1].tempId()].set_scc_invert(
1989             ctx.info[instr->operands[0].tempId()].instr->definitions[1].getTemp());
1990       }
1991       ctx.info[instr->definitions[0].tempId()].set_bitwise(instr.get());
1992       break;
1993    case aco_opcode::s_and_b32:
1994    case aco_opcode::s_and_b64:
1995       if (fixed_to_exec(instr->operands[1]) && instr->operands[0].isTemp()) {
1996          if (ctx.info[instr->operands[0].tempId()].is_uniform_bool()) {
1997             /* Try to get rid of the superfluous s_cselect + s_and_b64 that comes from turning a
1998              * uniform bool into divergent */
1999             ctx.info[instr->definitions[1].tempId()].set_temp(
2000                ctx.info[instr->operands[0].tempId()].temp);
2001             ctx.info[instr->definitions[0].tempId()].set_uniform_bool(
2002                ctx.info[instr->operands[0].tempId()].temp);
2003             break;
2004          } else if (ctx.info[instr->operands[0].tempId()].is_uniform_bitwise()) {
2005             /* Try to get rid of the superfluous s_and_b64, since the uniform bitwise instruction
2006              * already produces the same SCC */
2007             ctx.info[instr->definitions[1].tempId()].set_temp(
2008                ctx.info[instr->operands[0].tempId()].instr->definitions[1].getTemp());
2009             ctx.info[instr->definitions[0].tempId()].set_uniform_bool(
2010                ctx.info[instr->operands[0].tempId()].instr->definitions[1].getTemp());
2011             break;
2012          } else if ((ctx.program->stage.num_sw_stages() > 1 ||
2013                      ctx.program->stage.hw == AC_HW_NEXT_GEN_GEOMETRY_SHADER) &&
2014                     instr->pass_flags == 1) {
2015             /* In case of merged shaders, pass_flags=1 means that all lanes are active (exec=-1), so
2016              * s_and is unnecessary. */
2017             ctx.info[instr->definitions[0].tempId()].set_temp(instr->operands[0].getTemp());
2018             break;
2019          }
2020       }
2021       FALLTHROUGH;
2022    case aco_opcode::s_or_b32:
2023    case aco_opcode::s_or_b64:
2024    case aco_opcode::s_xor_b32:
2025    case aco_opcode::s_xor_b64:
2026       if (std::all_of(instr->operands.begin(), instr->operands.end(),
2027                       [&ctx](const Operand& op)
2028                       {
2029                          return op.isTemp() && (ctx.info[op.tempId()].is_uniform_bool() ||
2030                                                 ctx.info[op.tempId()].is_uniform_bitwise());
2031                       })) {
2032          ctx.info[instr->definitions[0].tempId()].set_uniform_bitwise();
2033       }
2034       ctx.info[instr->definitions[0].tempId()].set_bitwise(instr.get());
2035       break;
2036    case aco_opcode::s_lshl_b32:
2037    case aco_opcode::v_or_b32:
2038    case aco_opcode::v_lshlrev_b32:
2039    case aco_opcode::v_bcnt_u32_b32:
2040    case aco_opcode::v_and_b32:
2041    case aco_opcode::v_xor_b32:
2042    case aco_opcode::v_not_b32:
2043       ctx.info[instr->definitions[0].tempId()].set_usedef(instr.get());
2044       break;
2045    case aco_opcode::v_min_f32:
2046    case aco_opcode::v_min_f16:
2047    case aco_opcode::v_min_u32:
2048    case aco_opcode::v_min_i32:
2049    case aco_opcode::v_min_u16:
2050    case aco_opcode::v_min_i16:
2051    case aco_opcode::v_min_u16_e64:
2052    case aco_opcode::v_min_i16_e64:
2053    case aco_opcode::v_max_f32:
2054    case aco_opcode::v_max_f16:
2055    case aco_opcode::v_max_u32:
2056    case aco_opcode::v_max_i32:
2057    case aco_opcode::v_max_u16:
2058    case aco_opcode::v_max_i16:
2059    case aco_opcode::v_max_u16_e64:
2060    case aco_opcode::v_max_i16_e64:
2061       ctx.info[instr->definitions[0].tempId()].set_minmax(instr.get());
2062       break;
2063    case aco_opcode::s_cselect_b64:
2064    case aco_opcode::s_cselect_b32:
2065       if (instr->operands[0].constantEquals((unsigned)-1) && instr->operands[1].constantEquals(0)) {
2066          /* Found a cselect that operates on a uniform bool that comes from eg. s_cmp */
2067          ctx.info[instr->definitions[0].tempId()].set_uniform_bool(instr->operands[2].getTemp());
2068       }
2069       if (instr->operands[2].isTemp() && ctx.info[instr->operands[2].tempId()].is_scc_invert()) {
2070          /* Flip the operands to get rid of the scc_invert instruction */
2071          std::swap(instr->operands[0], instr->operands[1]);
2072          instr->operands[2].setTemp(ctx.info[instr->operands[2].tempId()].temp);
2073       }
2074       break;
2075    case aco_opcode::s_mul_i32:
2076       /* Testing every uint32_t shows that 0x3f800000*n is never a denormal.
2077        * This pattern is created from a uniform nir_op_b2f. */
2078       if (instr->operands[0].constantEquals(0x3f800000u))
2079          ctx.info[instr->definitions[0].tempId()].set_canonicalized();
2080       break;
2081    case aco_opcode::p_extract: {
2082       if (instr->definitions[0].bytes() == 4) {
2083          ctx.info[instr->definitions[0].tempId()].set_extract(instr.get());
2084          if (instr->operands[0].regClass() == v1 && parse_insert(instr.get()))
2085             ctx.info[instr->operands[0].tempId()].set_insert(instr.get());
2086       }
2087       break;
2088    }
2089    case aco_opcode::p_insert: {
2090       if (instr->operands[0].bytes() == 4) {
2091          if (instr->operands[0].regClass() == v1)
2092             ctx.info[instr->operands[0].tempId()].set_insert(instr.get());
2093          if (parse_extract(instr.get()))
2094             ctx.info[instr->definitions[0].tempId()].set_extract(instr.get());
2095          ctx.info[instr->definitions[0].tempId()].set_bitwise(instr.get());
2096       }
2097       break;
2098    }
2099    case aco_opcode::ds_read_u8:
2100    case aco_opcode::ds_read_u8_d16:
2101    case aco_opcode::ds_read_u16:
2102    case aco_opcode::ds_read_u16_d16: {
2103       ctx.info[instr->definitions[0].tempId()].set_usedef(instr.get());
2104       break;
2105    }
2106    case aco_opcode::v_mbcnt_lo_u32_b32: {
2107       if (instr->operands[0].constantEquals(-1) && instr->operands[1].constantEquals(0)) {
2108          if (ctx.program->wave_size == 32)
2109             ctx.info[instr->definitions[0].tempId()].set_subgroup_invocation(instr.get());
2110          else
2111             ctx.info[instr->definitions[0].tempId()].set_usedef(instr.get());
2112       }
2113       break;
2114    }
2115    case aco_opcode::v_mbcnt_hi_u32_b32:
2116    case aco_opcode::v_mbcnt_hi_u32_b32_e64: {
2117       if (instr->operands[0].constantEquals(-1) && instr->operands[1].isTemp() &&
2118           ctx.info[instr->operands[1].tempId()].is_usedef()) {
2119          Instruction* usedef_instr = ctx.info[instr->operands[1].tempId()].instr;
2120          if (usedef_instr->opcode == aco_opcode::v_mbcnt_lo_u32_b32 &&
2121              usedef_instr->operands[0].constantEquals(-1) &&
2122              usedef_instr->operands[1].constantEquals(0))
2123             ctx.info[instr->definitions[0].tempId()].set_subgroup_invocation(instr.get());
2124       }
2125       break;
2126    }
2127    case aco_opcode::v_cvt_f16_f32: {
2128       if (instr->operands[0].isTemp())
2129          ctx.info[instr->operands[0].tempId()].set_f2f16(instr.get());
2130       break;
2131    }
2132    case aco_opcode::v_cvt_f32_f16: {
2133       if (instr->operands[0].isTemp())
2134          ctx.info[instr->definitions[0].tempId()].set_f2f32(instr.get());
2135       break;
2136    }
2137    default: break;
2138    }
2139
2140    /* Don't remove label_extract if we can't apply the extract to
2141     * neg/abs instructions because we'll likely combine it into another valu. */
2142    if (!(ctx.info[instr->definitions[0].tempId()].label & (label_neg | label_abs)))
2143       check_sdwa_extract(ctx, instr);
2144 }
2145
2146 unsigned
2147 original_temp_id(opt_ctx& ctx, Temp tmp)
2148 {
2149    if (ctx.info[tmp.id()].is_temp())
2150       return ctx.info[tmp.id()].temp.id();
2151    else
2152       return tmp.id();
2153 }
2154
2155 void
2156 decrease_op_uses_if_dead(opt_ctx& ctx, Instruction* instr)
2157 {
2158    if (is_dead(ctx.uses, instr)) {
2159       for (const Operand& op : instr->operands) {
2160          if (op.isTemp())
2161             ctx.uses[op.tempId()]--;
2162       }
2163    }
2164 }
2165
2166 void
2167 decrease_uses(opt_ctx& ctx, Instruction* instr)
2168 {
2169    ctx.uses[instr->definitions[0].tempId()]--;
2170    decrease_op_uses_if_dead(ctx, instr);
2171 }
2172
2173 Operand
2174 copy_operand(opt_ctx& ctx, Operand op)
2175 {
2176    if (op.isTemp())
2177       ctx.uses[op.tempId()]++;
2178    return op;
2179 }
2180
2181 Instruction*
2182 follow_operand(opt_ctx& ctx, Operand op, bool ignore_uses = false)
2183 {
2184    if (!op.isTemp() || !(ctx.info[op.tempId()].label & instr_usedef_labels))
2185       return nullptr;
2186    if (!ignore_uses && ctx.uses[op.tempId()] > 1)
2187       return nullptr;
2188
2189    Instruction* instr = ctx.info[op.tempId()].instr;
2190
2191    if (instr->definitions.size() == 2) {
2192       assert(instr->definitions[0].isTemp() && instr->definitions[0].tempId() == op.tempId());
2193       if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
2194          return nullptr;
2195    }
2196
2197    for (Operand& operand : instr->operands) {
2198       if (fixed_to_exec(operand))
2199          return nullptr;
2200    }
2201
2202    return instr;
2203 }
2204
2205 /* s_or_b64(neq(a, a), neq(b, b)) -> v_cmp_u_f32(a, b)
2206  * s_and_b64(eq(a, a), eq(b, b)) -> v_cmp_o_f32(a, b) */
2207 bool
2208 combine_ordering_test(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2209 {
2210    if (instr->definitions[0].regClass() != ctx.program->lane_mask)
2211       return false;
2212    if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
2213       return false;
2214
2215    bool is_or = instr->opcode == aco_opcode::s_or_b64 || instr->opcode == aco_opcode::s_or_b32;
2216
2217    bitarray8 opsel = 0;
2218    Instruction* op_instr[2];
2219    Temp op[2];
2220
2221    unsigned bitsize = 0;
2222    for (unsigned i = 0; i < 2; i++) {
2223       op_instr[i] = follow_operand(ctx, instr->operands[i], true);
2224       if (!op_instr[i])
2225          return false;
2226
2227       aco_opcode expected_cmp = is_or ? aco_opcode::v_cmp_neq_f32 : aco_opcode::v_cmp_eq_f32;
2228       unsigned op_bitsize = get_cmp_bitsize(op_instr[i]->opcode);
2229
2230       if (get_f32_cmp(op_instr[i]->opcode) != expected_cmp)
2231          return false;
2232       if (bitsize && op_bitsize != bitsize)
2233          return false;
2234       if (!op_instr[i]->operands[0].isTemp() || !op_instr[i]->operands[1].isTemp())
2235          return false;
2236
2237       if (op_instr[i]->isSDWA() || op_instr[i]->isDPP())
2238          return false;
2239
2240       VALU_instruction& valu = op_instr[i]->valu();
2241       if (valu.neg[0] != valu.neg[1] || valu.abs[0] != valu.abs[1] ||
2242           valu.opsel[0] != valu.opsel[1])
2243          return false;
2244       opsel[i] = valu.opsel[0];
2245
2246       Temp op0 = op_instr[i]->operands[0].getTemp();
2247       Temp op1 = op_instr[i]->operands[1].getTemp();
2248       if (original_temp_id(ctx, op0) != original_temp_id(ctx, op1))
2249          return false;
2250
2251       op[i] = op1;
2252       bitsize = op_bitsize;
2253    }
2254
2255    if (op[1].type() == RegType::sgpr) {
2256       std::swap(op[0], op[1]);
2257       opsel[0].swap(opsel[1]);
2258    }
2259    unsigned num_sgprs = (op[0].type() == RegType::sgpr) + (op[1].type() == RegType::sgpr);
2260    if (num_sgprs > (ctx.program->gfx_level >= GFX10 ? 2 : 1))
2261       return false;
2262
2263    aco_opcode new_op = aco_opcode::num_opcodes;
2264    switch (bitsize) {
2265    case 16: new_op = is_or ? aco_opcode::v_cmp_u_f16 : aco_opcode::v_cmp_o_f16; break;
2266    case 32: new_op = is_or ? aco_opcode::v_cmp_u_f32 : aco_opcode::v_cmp_o_f32; break;
2267    case 64: new_op = is_or ? aco_opcode::v_cmp_u_f64 : aco_opcode::v_cmp_o_f64; break;
2268    }
2269    bool needs_vop3 = num_sgprs > 1 || (opsel[0] && op[0].type() != RegType::vgpr);
2270    VALU_instruction* new_instr = create_instruction<VALU_instruction>(
2271       new_op, needs_vop3 ? asVOP3(Format::VOPC) : Format::VOPC, 2, 1);
2272
2273    new_instr->opsel = opsel;
2274    new_instr->operands[0] = copy_operand(ctx, Operand(op[0]));
2275    new_instr->operands[1] = copy_operand(ctx, Operand(op[1]));
2276    new_instr->definitions[0] = instr->definitions[0];
2277    new_instr->pass_flags = instr->pass_flags;
2278
2279    decrease_uses(ctx, op_instr[0]);
2280    decrease_uses(ctx, op_instr[1]);
2281
2282    ctx.info[instr->definitions[0].tempId()].label = 0;
2283    ctx.info[instr->definitions[0].tempId()].set_vopc(new_instr);
2284
2285    instr.reset(new_instr);
2286
2287    return true;
2288 }
2289
2290 /* s_or_b64(v_cmp_u_f32(a, b), cmp(a, b)) -> get_unordered(cmp)(a, b)
2291  * s_and_b64(v_cmp_o_f32(a, b), cmp(a, b)) -> get_ordered(cmp)(a, b) */
2292 bool
2293 combine_comparison_ordering(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2294 {
2295    if (instr->definitions[0].regClass() != ctx.program->lane_mask)
2296       return false;
2297    if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
2298       return false;
2299
2300    bool is_or = instr->opcode == aco_opcode::s_or_b64 || instr->opcode == aco_opcode::s_or_b32;
2301    aco_opcode expected_nan_test = is_or ? aco_opcode::v_cmp_u_f32 : aco_opcode::v_cmp_o_f32;
2302
2303    Instruction* nan_test = follow_operand(ctx, instr->operands[0], true);
2304    Instruction* cmp = follow_operand(ctx, instr->operands[1], true);
2305    if (!nan_test || !cmp)
2306       return false;
2307    if (nan_test->isSDWA() || cmp->isSDWA())
2308       return false;
2309
2310    if (get_f32_cmp(cmp->opcode) == expected_nan_test)
2311       std::swap(nan_test, cmp);
2312    else if (get_f32_cmp(nan_test->opcode) != expected_nan_test)
2313       return false;
2314
2315    if (!is_fp_cmp(cmp->opcode) || get_cmp_bitsize(cmp->opcode) != get_cmp_bitsize(nan_test->opcode))
2316       return false;
2317
2318    if (!nan_test->operands[0].isTemp() || !nan_test->operands[1].isTemp())
2319       return false;
2320    if (!cmp->operands[0].isTemp() || !cmp->operands[1].isTemp())
2321       return false;
2322
2323    unsigned prop_cmp0 = original_temp_id(ctx, cmp->operands[0].getTemp());
2324    unsigned prop_cmp1 = original_temp_id(ctx, cmp->operands[1].getTemp());
2325    unsigned prop_nan0 = original_temp_id(ctx, nan_test->operands[0].getTemp());
2326    unsigned prop_nan1 = original_temp_id(ctx, nan_test->operands[1].getTemp());
2327    VALU_instruction& cmp_valu = cmp->valu();
2328    VALU_instruction& nan_valu = nan_test->valu();
2329    if ((prop_cmp0 != prop_nan0 || cmp_valu.opsel[0] != nan_valu.opsel[0]) &&
2330        (prop_cmp0 != prop_nan1 || cmp_valu.opsel[0] != nan_valu.opsel[1]))
2331       return false;
2332    if ((prop_cmp1 != prop_nan0 || cmp_valu.opsel[1] != nan_valu.opsel[0]) &&
2333        (prop_cmp1 != prop_nan1 || cmp_valu.opsel[1] != nan_valu.opsel[1]))
2334       return false;
2335    if (prop_cmp0 == prop_cmp1 && cmp_valu.opsel[0] == cmp_valu.opsel[1])
2336       return false;
2337
2338    aco_opcode new_op = is_or ? get_unordered(cmp->opcode) : get_ordered(cmp->opcode);
2339    VALU_instruction* new_instr = create_instruction<VALU_instruction>(
2340       new_op, cmp->isVOP3() ? asVOP3(Format::VOPC) : Format::VOPC, 2, 1);
2341    new_instr->neg = cmp_valu.neg;
2342    new_instr->abs = cmp_valu.abs;
2343    new_instr->clamp = cmp_valu.clamp;
2344    new_instr->omod = cmp_valu.omod;
2345    new_instr->opsel = cmp_valu.opsel;
2346    new_instr->operands[0] = copy_operand(ctx, cmp->operands[0]);
2347    new_instr->operands[1] = copy_operand(ctx, cmp->operands[1]);
2348    new_instr->definitions[0] = instr->definitions[0];
2349    new_instr->pass_flags = instr->pass_flags;
2350
2351    decrease_uses(ctx, nan_test);
2352    decrease_uses(ctx, cmp);
2353
2354    ctx.info[instr->definitions[0].tempId()].label = 0;
2355    ctx.info[instr->definitions[0].tempId()].set_vopc(new_instr);
2356
2357    instr.reset(new_instr);
2358
2359    return true;
2360 }
2361
2362 /* Optimize v_cmp of constant with subgroup invocation to a constant mask.
2363  * Ideally, we can trade v_cmp for a constant (or literal).
2364  * In a less ideal case, we trade v_cmp for a SALU instruction, which is still a win.
2365  */
2366 bool
2367 optimize_cmp_subgroup_invocation(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2368 {
2369    /* This optimization only applies to VOPC with 2 operands. */
2370    if (instr->operands.size() != 2)
2371       return false;
2372
2373    /* Find the constant operand or return early if there isn't one. */
2374    const int const_op_idx = instr->operands[0].isConstant()   ? 0
2375                             : instr->operands[1].isConstant() ? 1
2376                                                               : -1;
2377    if (const_op_idx == -1)
2378       return false;
2379
2380    /* Find the operand that has the subgroup invocation. */
2381    const int mbcnt_op_idx = 1 - const_op_idx;
2382    const Operand mbcnt_op = instr->operands[mbcnt_op_idx];
2383    if (!mbcnt_op.isTemp() || !ctx.info[mbcnt_op.tempId()].is_subgroup_invocation())
2384       return false;
2385
2386    /* Adjust opcode so we don't have to care about const_op_idx below. */
2387    const aco_opcode op = const_op_idx == 0 ? get_swapped(instr->opcode) : instr->opcode;
2388    const unsigned wave_size = ctx.program->wave_size;
2389    const unsigned val = instr->operands[const_op_idx].constantValue();
2390
2391    /* Find suitable constant bitmask corresponding to the value. */
2392    unsigned first_bit = 0, num_bits = 0;
2393    switch (op) {
2394    case aco_opcode::v_cmp_eq_u32:
2395    case aco_opcode::v_cmp_eq_i32:
2396       first_bit = val;
2397       num_bits = val >= wave_size ? 0 : 1;
2398       break;
2399    case aco_opcode::v_cmp_le_u32:
2400    case aco_opcode::v_cmp_le_i32:
2401       first_bit = 0;
2402       num_bits = val >= wave_size ? wave_size : (val + 1);
2403       break;
2404    case aco_opcode::v_cmp_lt_u32:
2405    case aco_opcode::v_cmp_lt_i32:
2406       first_bit = 0;
2407       num_bits = val >= wave_size ? wave_size : val;
2408       break;
2409    case aco_opcode::v_cmp_ge_u32:
2410    case aco_opcode::v_cmp_ge_i32:
2411       first_bit = val;
2412       num_bits = val >= wave_size ? 0 : (wave_size - val);
2413       break;
2414    case aco_opcode::v_cmp_gt_u32:
2415    case aco_opcode::v_cmp_gt_i32:
2416       first_bit = val + 1;
2417       num_bits = val >= wave_size ? 0 : (wave_size - val - 1);
2418       break;
2419    default: return false;
2420    }
2421
2422    Instruction* cpy = NULL;
2423    const uint64_t mask = BITFIELD64_RANGE(first_bit, num_bits);
2424    if (wave_size == 64 && mask > 0x7fffffff && mask != -1ull) {
2425       /* Mask can't be represented as a 64-bit constant or literal, use s_bfm_b64. */
2426       cpy = create_instruction<SOP2_instruction>(aco_opcode::s_bfm_b64, Format::SOP2, 2, 1);
2427       cpy->operands[0] = Operand::c32(num_bits);
2428       cpy->operands[1] = Operand::c32(first_bit);
2429    } else {
2430       /* Copy mask as a literal constant. */
2431       cpy =
2432          create_instruction<Pseudo_instruction>(aco_opcode::p_parallelcopy, Format::PSEUDO, 1, 1);
2433       cpy->operands[0] = wave_size == 32 ? Operand::c32((uint32_t)mask) : Operand::c64(mask);
2434    }
2435
2436    cpy->definitions[0] = instr->definitions[0];
2437    ctx.info[instr->definitions[0].tempId()].label = 0;
2438    decrease_uses(ctx, ctx.info[mbcnt_op.tempId()].instr);
2439    instr.reset(cpy);
2440
2441    return true;
2442 }
2443
2444 bool
2445 is_operand_constant(opt_ctx& ctx, Operand op, unsigned bit_size, uint64_t* value)
2446 {
2447    if (op.isConstant()) {
2448       *value = op.constantValue64();
2449       return true;
2450    } else if (op.isTemp()) {
2451       unsigned id = original_temp_id(ctx, op.getTemp());
2452       if (!ctx.info[id].is_constant_or_literal(bit_size))
2453          return false;
2454       *value = get_constant_op(ctx, ctx.info[id], bit_size).constantValue64();
2455       return true;
2456    }
2457    return false;
2458 }
2459
2460 bool
2461 is_constant_nan(uint64_t value, unsigned bit_size)
2462 {
2463    if (bit_size == 16)
2464       return ((value >> 10) & 0x1f) == 0x1f && (value & 0x3ff);
2465    else if (bit_size == 32)
2466       return ((value >> 23) & 0xff) == 0xff && (value & 0x7fffff);
2467    else
2468       return ((value >> 52) & 0x7ff) == 0x7ff && (value & 0xfffffffffffff);
2469 }
2470
2471 /* s_or_b64(v_cmp_neq_f32(a, a), cmp(a, #b)) and b is not NaN -> get_unordered(cmp)(a, b)
2472  * s_and_b64(v_cmp_eq_f32(a, a), cmp(a, #b)) and b is not NaN -> get_ordered(cmp)(a, b) */
2473 bool
2474 combine_constant_comparison_ordering(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2475 {
2476    if (instr->definitions[0].regClass() != ctx.program->lane_mask)
2477       return false;
2478    if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
2479       return false;
2480
2481    bool is_or = instr->opcode == aco_opcode::s_or_b64 || instr->opcode == aco_opcode::s_or_b32;
2482
2483    Instruction* nan_test = follow_operand(ctx, instr->operands[0], true);
2484    Instruction* cmp = follow_operand(ctx, instr->operands[1], true);
2485
2486    if (!nan_test || !cmp || nan_test->isSDWA() || cmp->isSDWA() || nan_test->isDPP() ||
2487        cmp->isDPP())
2488       return false;
2489
2490    aco_opcode expected_nan_test = is_or ? aco_opcode::v_cmp_neq_f32 : aco_opcode::v_cmp_eq_f32;
2491    if (get_f32_cmp(cmp->opcode) == expected_nan_test)
2492       std::swap(nan_test, cmp);
2493    else if (get_f32_cmp(nan_test->opcode) != expected_nan_test)
2494       return false;
2495
2496    unsigned bit_size = get_cmp_bitsize(cmp->opcode);
2497    if (!is_fp_cmp(cmp->opcode) || get_cmp_bitsize(nan_test->opcode) != bit_size)
2498       return false;
2499
2500    if (!nan_test->operands[0].isTemp() || !nan_test->operands[1].isTemp())
2501       return false;
2502    if (!cmp->operands[0].isTemp() && !cmp->operands[1].isTemp())
2503       return false;
2504
2505    unsigned prop_nan0 = original_temp_id(ctx, nan_test->operands[0].getTemp());
2506    unsigned prop_nan1 = original_temp_id(ctx, nan_test->operands[1].getTemp());
2507    if (prop_nan0 != prop_nan1)
2508       return false;
2509
2510    VALU_instruction& vop3 = nan_test->valu();
2511    if (vop3.neg[0] != vop3.neg[1] || vop3.abs[0] != vop3.abs[1] || vop3.opsel[0] != vop3.opsel[1])
2512       return false;
2513
2514    int constant_operand = -1;
2515    for (unsigned i = 0; i < 2; i++) {
2516       if (cmp->operands[i].isTemp() &&
2517           original_temp_id(ctx, cmp->operands[i].getTemp()) == prop_nan0 &&
2518           cmp->valu().opsel[i] == nan_test->valu().opsel[0]) {
2519          constant_operand = !i;
2520          break;
2521       }
2522    }
2523    if (constant_operand == -1)
2524       return false;
2525
2526    uint64_t constant_value;
2527    if (!is_operand_constant(ctx, cmp->operands[constant_operand], bit_size, &constant_value))
2528       return false;
2529    if (is_constant_nan(constant_value >> (cmp->valu().opsel[constant_operand] * 16), bit_size))
2530       return false;
2531
2532    aco_opcode new_op = is_or ? get_unordered(cmp->opcode) : get_ordered(cmp->opcode);
2533    Instruction* new_instr = create_instruction<VALU_instruction>(new_op, cmp->format, 2, 1);
2534    new_instr->valu().neg = cmp->valu().neg;
2535    new_instr->valu().abs = cmp->valu().abs;
2536    new_instr->valu().clamp = cmp->valu().clamp;
2537    new_instr->valu().omod = cmp->valu().omod;
2538    new_instr->valu().opsel = cmp->valu().opsel;
2539    new_instr->operands[0] = copy_operand(ctx, cmp->operands[0]);
2540    new_instr->operands[1] = copy_operand(ctx, cmp->operands[1]);
2541    new_instr->definitions[0] = instr->definitions[0];
2542    new_instr->pass_flags = instr->pass_flags;
2543
2544    decrease_uses(ctx, nan_test);
2545    decrease_uses(ctx, cmp);
2546
2547    ctx.info[instr->definitions[0].tempId()].label = 0;
2548    ctx.info[instr->definitions[0].tempId()].set_vopc(new_instr);
2549
2550    instr.reset(new_instr);
2551
2552    return true;
2553 }
2554
2555 /* s_not(cmp(a, b)) -> get_inverse(cmp)(a, b) */
2556 bool
2557 combine_inverse_comparison(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2558 {
2559    if (ctx.uses[instr->definitions[1].tempId()])
2560       return false;
2561    if (!instr->operands[0].isTemp() || ctx.uses[instr->operands[0].tempId()] != 1)
2562       return false;
2563
2564    Instruction* cmp = follow_operand(ctx, instr->operands[0]);
2565    if (!cmp)
2566       return false;
2567
2568    aco_opcode new_opcode = get_inverse(cmp->opcode);
2569    if (new_opcode == aco_opcode::num_opcodes)
2570       return false;
2571
2572    /* Invert compare instruction and assign this instruction's definition */
2573    cmp->opcode = new_opcode;
2574    ctx.info[instr->definitions[0].tempId()] = ctx.info[cmp->definitions[0].tempId()];
2575    std::swap(instr->definitions[0], cmp->definitions[0]);
2576
2577    ctx.uses[instr->operands[0].tempId()]--;
2578    return true;
2579 }
2580
2581 /* op1(op2(1, 2), 0) if swap = false
2582  * op1(0, op2(1, 2)) if swap = true */
2583 bool
2584 match_op3_for_vop3(opt_ctx& ctx, aco_opcode op1, aco_opcode op2, Instruction* op1_instr, bool swap,
2585                    const char* shuffle_str, Operand operands[3], bitarray8& neg, bitarray8& abs,
2586                    bitarray8& opsel, bool* op1_clamp, uint8_t* op1_omod, bool* inbetween_neg,
2587                    bool* inbetween_abs, bool* inbetween_opsel, bool* precise)
2588 {
2589    /* checks */
2590    if (op1_instr->opcode != op1)
2591       return false;
2592
2593    Instruction* op2_instr = follow_operand(ctx, op1_instr->operands[swap]);
2594    if (!op2_instr || op2_instr->opcode != op2)
2595       return false;
2596
2597    VALU_instruction* op1_valu = op1_instr->isVALU() ? &op1_instr->valu() : NULL;
2598    VALU_instruction* op2_valu = op2_instr->isVALU() ? &op2_instr->valu() : NULL;
2599
2600    if (op1_instr->isSDWA() || op2_instr->isSDWA())
2601       return false;
2602    if (op1_instr->isDPP() || op2_instr->isDPP())
2603       return false;
2604
2605    /* don't support inbetween clamp/omod */
2606    if (op2_valu && (op2_valu->clamp || op2_valu->omod))
2607       return false;
2608
2609    /* get operands and modifiers and check inbetween modifiers */
2610    *op1_clamp = op1_valu ? (bool)op1_valu->clamp : false;
2611    *op1_omod = op1_valu ? (unsigned)op1_valu->omod : 0u;
2612
2613    if (inbetween_neg)
2614       *inbetween_neg = op1_valu ? op1_valu->neg[swap] : false;
2615    else if (op1_valu && op1_valu->neg[swap])
2616       return false;
2617
2618    if (inbetween_abs)
2619       *inbetween_abs = op1_valu ? op1_valu->abs[swap] : false;
2620    else if (op1_valu && op1_valu->abs[swap])
2621       return false;
2622
2623    if (inbetween_opsel)
2624       *inbetween_opsel = op1_valu ? op1_valu->opsel[swap] : false;
2625    else if (op1_valu && op1_valu->opsel[swap])
2626       return false;
2627
2628    *precise = op1_instr->definitions[0].isPrecise() || op2_instr->definitions[0].isPrecise();
2629
2630    int shuffle[3];
2631    shuffle[shuffle_str[0] - '0'] = 0;
2632    shuffle[shuffle_str[1] - '0'] = 1;
2633    shuffle[shuffle_str[2] - '0'] = 2;
2634
2635    operands[shuffle[0]] = op1_instr->operands[!swap];
2636    neg[shuffle[0]] = op1_valu ? op1_valu->neg[!swap] : false;
2637    abs[shuffle[0]] = op1_valu ? op1_valu->abs[!swap] : false;
2638    opsel[shuffle[0]] = op1_valu ? op1_valu->opsel[!swap] : false;
2639
2640    for (unsigned i = 0; i < 2; i++) {
2641       operands[shuffle[i + 1]] = op2_instr->operands[i];
2642       neg[shuffle[i + 1]] = op2_valu ? op2_valu->neg[i] : false;
2643       abs[shuffle[i + 1]] = op2_valu ? op2_valu->abs[i] : false;
2644       opsel[shuffle[i + 1]] = op2_valu ? op2_valu->opsel[i] : false;
2645    }
2646
2647    /* check operands */
2648    if (!check_vop3_operands(ctx, 3, operands))
2649       return false;
2650
2651    return true;
2652 }
2653
2654 void
2655 create_vop3_for_op3(opt_ctx& ctx, aco_opcode opcode, aco_ptr<Instruction>& instr,
2656                     Operand operands[3], uint8_t neg, uint8_t abs, uint8_t opsel, bool clamp,
2657                     unsigned omod)
2658 {
2659    VALU_instruction* new_instr = create_instruction<VALU_instruction>(opcode, Format::VOP3, 3, 1);
2660    new_instr->neg = neg;
2661    new_instr->abs = abs;
2662    new_instr->clamp = clamp;
2663    new_instr->omod = omod;
2664    new_instr->opsel = opsel;
2665    new_instr->operands[0] = operands[0];
2666    new_instr->operands[1] = operands[1];
2667    new_instr->operands[2] = operands[2];
2668    new_instr->definitions[0] = instr->definitions[0];
2669    new_instr->pass_flags = instr->pass_flags;
2670    ctx.info[instr->definitions[0].tempId()].label = 0;
2671
2672    instr.reset(new_instr);
2673 }
2674
2675 bool
2676 combine_three_valu_op(opt_ctx& ctx, aco_ptr<Instruction>& instr, aco_opcode op2, aco_opcode new_op,
2677                       const char* shuffle, uint8_t ops)
2678 {
2679    for (unsigned swap = 0; swap < 2; swap++) {
2680       if (!((1 << swap) & ops))
2681          continue;
2682
2683       Operand operands[3];
2684       bool clamp, precise;
2685       bitarray8 neg = 0, abs = 0, opsel = 0;
2686       uint8_t omod = 0;
2687       if (match_op3_for_vop3(ctx, instr->opcode, op2, instr.get(), swap, shuffle, operands, neg,
2688                              abs, opsel, &clamp, &omod, NULL, NULL, NULL, &precise)) {
2689          ctx.uses[instr->operands[swap].tempId()]--;
2690          create_vop3_for_op3(ctx, new_op, instr, operands, neg, abs, opsel, clamp, omod);
2691          return true;
2692       }
2693    }
2694    return false;
2695 }
2696
2697 /* creates v_lshl_add_u32, v_lshl_or_b32 or v_and_or_b32 */
2698 bool
2699 combine_add_or_then_and_lshl(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2700 {
2701    bool is_or = instr->opcode == aco_opcode::v_or_b32;
2702    aco_opcode new_op_lshl = is_or ? aco_opcode::v_lshl_or_b32 : aco_opcode::v_lshl_add_u32;
2703
2704    if (is_or && combine_three_valu_op(ctx, instr, aco_opcode::s_and_b32, aco_opcode::v_and_or_b32,
2705                                       "120", 1 | 2))
2706       return true;
2707    if (is_or && combine_three_valu_op(ctx, instr, aco_opcode::v_and_b32, aco_opcode::v_and_or_b32,
2708                                       "120", 1 | 2))
2709       return true;
2710    if (combine_three_valu_op(ctx, instr, aco_opcode::s_lshl_b32, new_op_lshl, "120", 1 | 2))
2711       return true;
2712    if (combine_three_valu_op(ctx, instr, aco_opcode::v_lshlrev_b32, new_op_lshl, "210", 1 | 2))
2713       return true;
2714
2715    if (instr->isSDWA() || instr->isDPP())
2716       return false;
2717
2718    /* v_or_b32(p_extract(a, 0, 8/16, 0), b) -> v_and_or_b32(a, 0xff/0xffff, b)
2719     * v_or_b32(p_insert(a, 0, 8/16), b) -> v_and_or_b32(a, 0xff/0xffff, b)
2720     * v_or_b32(p_insert(a, 24/16, 8/16), b) -> v_lshl_or_b32(a, 24/16, b)
2721     * v_add_u32(p_insert(a, 24/16, 8/16), b) -> v_lshl_add_b32(a, 24/16, b)
2722     */
2723    for (unsigned i = 0; i < 2; i++) {
2724       Instruction* extins = follow_operand(ctx, instr->operands[i]);
2725       if (!extins)
2726          continue;
2727
2728       aco_opcode op;
2729       Operand operands[3];
2730
2731       if (extins->opcode == aco_opcode::p_insert &&
2732           (extins->operands[1].constantValue() + 1) * extins->operands[2].constantValue() == 32) {
2733          op = new_op_lshl;
2734          operands[1] =
2735             Operand::c32(extins->operands[1].constantValue() * extins->operands[2].constantValue());
2736       } else if (is_or &&
2737                  (extins->opcode == aco_opcode::p_insert ||
2738                   (extins->opcode == aco_opcode::p_extract &&
2739                    extins->operands[3].constantEquals(0))) &&
2740                  extins->operands[1].constantEquals(0)) {
2741          op = aco_opcode::v_and_or_b32;
2742          operands[1] = Operand::c32(extins->operands[2].constantEquals(8) ? 0xffu : 0xffffu);
2743       } else {
2744          continue;
2745       }
2746
2747       operands[0] = extins->operands[0];
2748       operands[2] = instr->operands[!i];
2749
2750       if (!check_vop3_operands(ctx, 3, operands))
2751          continue;
2752
2753       uint8_t neg = 0, abs = 0, opsel = 0, omod = 0;
2754       bool clamp = false;
2755       if (instr->isVOP3())
2756          clamp = instr->valu().clamp;
2757
2758       ctx.uses[instr->operands[i].tempId()]--;
2759       create_vop3_for_op3(ctx, op, instr, operands, neg, abs, opsel, clamp, omod);
2760       return true;
2761    }
2762
2763    return false;
2764 }
2765
2766 /* v_xor(a, s_not(b)) -> v_xnor(a, b)
2767  * v_xor(a, v_not(b)) -> v_xnor(a, b)
2768  */
2769 bool
2770 combine_xor_not(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2771 {
2772    if (instr->usesModifiers())
2773       return false;
2774
2775    for (unsigned i = 0; i < 2; i++) {
2776       Instruction* op_instr = follow_operand(ctx, instr->operands[i], true);
2777       if (!op_instr ||
2778           (op_instr->opcode != aco_opcode::v_not_b32 &&
2779            op_instr->opcode != aco_opcode::s_not_b32) ||
2780           op_instr->usesModifiers() || op_instr->operands[0].isLiteral())
2781          continue;
2782
2783       instr->opcode = aco_opcode::v_xnor_b32;
2784       instr->operands[i] = copy_operand(ctx, op_instr->operands[0]);
2785       decrease_uses(ctx, op_instr);
2786       if (instr->operands[0].isOfType(RegType::vgpr))
2787          std::swap(instr->operands[0], instr->operands[1]);
2788       if (!instr->operands[1].isOfType(RegType::vgpr))
2789          instr->format = asVOP3(instr->format);
2790
2791       return true;
2792    }
2793
2794    return false;
2795 }
2796
2797 /* v_not(v_xor(a, b)) -> v_xnor(a, b) */
2798 bool
2799 combine_not_xor(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2800 {
2801    if (instr->usesModifiers())
2802       return false;
2803
2804    Instruction* op_instr = follow_operand(ctx, instr->operands[0]);
2805    if (!op_instr || op_instr->opcode != aco_opcode::v_xor_b32 || op_instr->isSDWA())
2806       return false;
2807
2808    ctx.uses[instr->operands[0].tempId()]--;
2809    std::swap(instr->definitions[0], op_instr->definitions[0]);
2810    op_instr->opcode = aco_opcode::v_xnor_b32;
2811
2812    return true;
2813 }
2814
2815 bool
2816 combine_minmax(opt_ctx& ctx, aco_ptr<Instruction>& instr, aco_opcode opposite, aco_opcode op3src,
2817                aco_opcode minmax)
2818 {
2819    /* TODO: this can handle SDWA min/max instructions by using opsel */
2820
2821    /* min(min(a, b), c) -> min3(a, b, c)
2822     * max(max(a, b), c) -> max3(a, b, c)
2823     * gfx11: min(-min(a, b), c) -> maxmin(-a, -b, c)
2824     * gfx11: max(-max(a, b), c) -> minmax(-a, -b, c)
2825     */
2826    for (unsigned swap = 0; swap < 2; swap++) {
2827       Operand operands[3];
2828       bool clamp, precise;
2829       bitarray8 opsel = 0, neg = 0, abs = 0;
2830       uint8_t omod = 0;
2831       bool inbetween_neg;
2832       if (match_op3_for_vop3(ctx, instr->opcode, instr->opcode, instr.get(), swap, "120", operands,
2833                              neg, abs, opsel, &clamp, &omod, &inbetween_neg, NULL, NULL,
2834                              &precise) &&
2835           (!inbetween_neg ||
2836            (minmax != aco_opcode::num_opcodes && ctx.program->gfx_level >= GFX11))) {
2837          ctx.uses[instr->operands[swap].tempId()]--;
2838          if (inbetween_neg) {
2839             neg[0] = !neg[0];
2840             neg[1] = !neg[1];
2841             create_vop3_for_op3(ctx, minmax, instr, operands, neg, abs, opsel, clamp, omod);
2842          } else {
2843             create_vop3_for_op3(ctx, op3src, instr, operands, neg, abs, opsel, clamp, omod);
2844          }
2845          return true;
2846       }
2847    }
2848
2849    /* min(-max(a, b), c) -> min3(-a, -b, c)
2850     * max(-min(a, b), c) -> max3(-a, -b, c)
2851     * gfx11: min(max(a, b), c) -> maxmin(a, b, c)
2852     * gfx11: max(min(a, b), c) -> minmax(a, b, c)
2853     */
2854    for (unsigned swap = 0; swap < 2; swap++) {
2855       Operand operands[3];
2856       bool clamp, precise;
2857       bitarray8 opsel = 0, neg = 0, abs = 0;
2858       uint8_t omod = 0;
2859       bool inbetween_neg;
2860       if (match_op3_for_vop3(ctx, instr->opcode, opposite, instr.get(), swap, "120", operands, neg,
2861                              abs, opsel, &clamp, &omod, &inbetween_neg, NULL, NULL, &precise) &&
2862           (inbetween_neg ||
2863            (minmax != aco_opcode::num_opcodes && ctx.program->gfx_level >= GFX11))) {
2864          ctx.uses[instr->operands[swap].tempId()]--;
2865          if (inbetween_neg) {
2866             neg[0] = !neg[0];
2867             neg[1] = !neg[1];
2868             create_vop3_for_op3(ctx, op3src, instr, operands, neg, abs, opsel, clamp, omod);
2869          } else {
2870             create_vop3_for_op3(ctx, minmax, instr, operands, neg, abs, opsel, clamp, omod);
2871          }
2872          return true;
2873       }
2874    }
2875    return false;
2876 }
2877
2878 /* s_not_b32(s_and_b32(a, b)) -> s_nand_b32(a, b)
2879  * s_not_b32(s_or_b32(a, b)) -> s_nor_b32(a, b)
2880  * s_not_b32(s_xor_b32(a, b)) -> s_xnor_b32(a, b)
2881  * s_not_b64(s_and_b64(a, b)) -> s_nand_b64(a, b)
2882  * s_not_b64(s_or_b64(a, b)) -> s_nor_b64(a, b)
2883  * s_not_b64(s_xor_b64(a, b)) -> s_xnor_b64(a, b) */
2884 bool
2885 combine_salu_not_bitwise(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2886 {
2887    /* checks */
2888    if (!instr->operands[0].isTemp())
2889       return false;
2890    if (instr->definitions[1].isTemp() && ctx.uses[instr->definitions[1].tempId()])
2891       return false;
2892
2893    Instruction* op2_instr = follow_operand(ctx, instr->operands[0]);
2894    if (!op2_instr)
2895       return false;
2896    switch (op2_instr->opcode) {
2897    case aco_opcode::s_and_b32:
2898    case aco_opcode::s_or_b32:
2899    case aco_opcode::s_xor_b32:
2900    case aco_opcode::s_and_b64:
2901    case aco_opcode::s_or_b64:
2902    case aco_opcode::s_xor_b64: break;
2903    default: return false;
2904    }
2905
2906    /* create instruction */
2907    std::swap(instr->definitions[0], op2_instr->definitions[0]);
2908    std::swap(instr->definitions[1], op2_instr->definitions[1]);
2909    ctx.uses[instr->operands[0].tempId()]--;
2910    ctx.info[op2_instr->definitions[0].tempId()].label = 0;
2911
2912    switch (op2_instr->opcode) {
2913    case aco_opcode::s_and_b32: op2_instr->opcode = aco_opcode::s_nand_b32; break;
2914    case aco_opcode::s_or_b32: op2_instr->opcode = aco_opcode::s_nor_b32; break;
2915    case aco_opcode::s_xor_b32: op2_instr->opcode = aco_opcode::s_xnor_b32; break;
2916    case aco_opcode::s_and_b64: op2_instr->opcode = aco_opcode::s_nand_b64; break;
2917    case aco_opcode::s_or_b64: op2_instr->opcode = aco_opcode::s_nor_b64; break;
2918    case aco_opcode::s_xor_b64: op2_instr->opcode = aco_opcode::s_xnor_b64; break;
2919    default: break;
2920    }
2921
2922    return true;
2923 }
2924
2925 /* s_and_b32(a, s_not_b32(b)) -> s_andn2_b32(a, b)
2926  * s_or_b32(a, s_not_b32(b)) -> s_orn2_b32(a, b)
2927  * s_and_b64(a, s_not_b64(b)) -> s_andn2_b64(a, b)
2928  * s_or_b64(a, s_not_b64(b)) -> s_orn2_b64(a, b) */
2929 bool
2930 combine_salu_n2(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2931 {
2932    if (instr->definitions[0].isTemp() && ctx.info[instr->definitions[0].tempId()].is_uniform_bool())
2933       return false;
2934
2935    for (unsigned i = 0; i < 2; i++) {
2936       Instruction* op2_instr = follow_operand(ctx, instr->operands[i]);
2937       if (!op2_instr || (op2_instr->opcode != aco_opcode::s_not_b32 &&
2938                          op2_instr->opcode != aco_opcode::s_not_b64))
2939          continue;
2940       if (ctx.uses[op2_instr->definitions[1].tempId()])
2941          continue;
2942
2943       if (instr->operands[!i].isLiteral() && op2_instr->operands[0].isLiteral() &&
2944           instr->operands[!i].constantValue() != op2_instr->operands[0].constantValue())
2945          continue;
2946
2947       ctx.uses[instr->operands[i].tempId()]--;
2948       instr->operands[0] = instr->operands[!i];
2949       instr->operands[1] = op2_instr->operands[0];
2950       ctx.info[instr->definitions[0].tempId()].label = 0;
2951
2952       switch (instr->opcode) {
2953       case aco_opcode::s_and_b32: instr->opcode = aco_opcode::s_andn2_b32; break;
2954       case aco_opcode::s_or_b32: instr->opcode = aco_opcode::s_orn2_b32; break;
2955       case aco_opcode::s_and_b64: instr->opcode = aco_opcode::s_andn2_b64; break;
2956       case aco_opcode::s_or_b64: instr->opcode = aco_opcode::s_orn2_b64; break;
2957       default: break;
2958       }
2959
2960       return true;
2961    }
2962    return false;
2963 }
2964
2965 /* s_add_{i32,u32}(a, s_lshl_b32(b, <n>)) -> s_lshl<n>_add_u32(a, b) */
2966 bool
2967 combine_salu_lshl_add(opt_ctx& ctx, aco_ptr<Instruction>& instr)
2968 {
2969    if (instr->opcode == aco_opcode::s_add_i32 && ctx.uses[instr->definitions[1].tempId()])
2970       return false;
2971
2972    for (unsigned i = 0; i < 2; i++) {
2973       Instruction* op2_instr = follow_operand(ctx, instr->operands[i], true);
2974       if (!op2_instr || op2_instr->opcode != aco_opcode::s_lshl_b32 ||
2975           ctx.uses[op2_instr->definitions[1].tempId()])
2976          continue;
2977       if (!op2_instr->operands[1].isConstant())
2978          continue;
2979
2980       uint32_t shift = op2_instr->operands[1].constantValue();
2981       if (shift < 1 || shift > 4)
2982          continue;
2983
2984       if (instr->operands[!i].isLiteral() && op2_instr->operands[0].isLiteral() &&
2985           instr->operands[!i].constantValue() != op2_instr->operands[0].constantValue())
2986          continue;
2987
2988       instr->operands[1] = instr->operands[!i];
2989       instr->operands[0] = copy_operand(ctx, op2_instr->operands[0]);
2990       decrease_uses(ctx, op2_instr);
2991       ctx.info[instr->definitions[0].tempId()].label = 0;
2992
2993       instr->opcode = std::array<aco_opcode, 4>{
2994          aco_opcode::s_lshl1_add_u32, aco_opcode::s_lshl2_add_u32, aco_opcode::s_lshl3_add_u32,
2995          aco_opcode::s_lshl4_add_u32}[shift - 1];
2996
2997       return true;
2998    }
2999    return false;
3000 }
3001
3002 /* s_abs_i32(s_sub_[iu]32(a, b)) -> s_absdiff_i32(a, b)
3003  * s_abs_i32(s_add_[iu]32(a, #b)) -> s_absdiff_i32(a, -b)
3004  */
3005 bool
3006 combine_sabsdiff(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3007 {
3008    if (!instr->operands[0].isTemp() || !ctx.info[instr->operands[0].tempId()].is_add_sub())
3009       return false;
3010
3011    Instruction* op_instr = follow_operand(ctx, instr->operands[0], false);
3012    if (!op_instr)
3013       return false;
3014
3015    if (op_instr->opcode == aco_opcode::s_add_i32 || op_instr->opcode == aco_opcode::s_add_u32) {
3016       for (unsigned i = 0; i < 2; i++) {
3017          uint64_t constant;
3018          if (op_instr->operands[!i].isLiteral() ||
3019              !is_operand_constant(ctx, op_instr->operands[i], 32, &constant))
3020             continue;
3021
3022          if (op_instr->operands[i].isTemp())
3023             ctx.uses[op_instr->operands[i].tempId()]--;
3024          op_instr->operands[0] = op_instr->operands[!i];
3025          op_instr->operands[1] = Operand::c32(-int32_t(constant));
3026          goto use_absdiff;
3027       }
3028       return false;
3029    }
3030
3031 use_absdiff:
3032    op_instr->opcode = aco_opcode::s_absdiff_i32;
3033    std::swap(instr->definitions[0], op_instr->definitions[0]);
3034    std::swap(instr->definitions[1], op_instr->definitions[1]);
3035    ctx.uses[instr->operands[0].tempId()]--;
3036
3037    return true;
3038 }
3039
3040 bool
3041 combine_add_sub_b2i(opt_ctx& ctx, aco_ptr<Instruction>& instr, aco_opcode new_op, uint8_t ops)
3042 {
3043    if (instr->usesModifiers())
3044       return false;
3045
3046    for (unsigned i = 0; i < 2; i++) {
3047       if (!((1 << i) & ops))
3048          continue;
3049       if (instr->operands[i].isTemp() && ctx.info[instr->operands[i].tempId()].is_b2i() &&
3050           ctx.uses[instr->operands[i].tempId()] == 1) {
3051
3052          aco_ptr<Instruction> new_instr;
3053          if (instr->operands[!i].isTemp() &&
3054              instr->operands[!i].getTemp().type() == RegType::vgpr) {
3055             new_instr.reset(create_instruction<VALU_instruction>(new_op, Format::VOP2, 3, 2));
3056          } else if (ctx.program->gfx_level >= GFX10 ||
3057                     (instr->operands[!i].isConstant() && !instr->operands[!i].isLiteral())) {
3058             new_instr.reset(
3059                create_instruction<VALU_instruction>(new_op, asVOP3(Format::VOP2), 3, 2));
3060          } else {
3061             return false;
3062          }
3063          ctx.uses[instr->operands[i].tempId()]--;
3064          new_instr->definitions[0] = instr->definitions[0];
3065          if (instr->definitions.size() == 2) {
3066             new_instr->definitions[1] = instr->definitions[1];
3067          } else {
3068             new_instr->definitions[1] =
3069                Definition(ctx.program->allocateTmp(ctx.program->lane_mask));
3070             /* Make sure the uses vector is large enough and the number of
3071              * uses properly initialized to 0.
3072              */
3073             ctx.uses.push_back(0);
3074          }
3075          new_instr->operands[0] = Operand::zero();
3076          new_instr->operands[1] = instr->operands[!i];
3077          new_instr->operands[2] = Operand(ctx.info[instr->operands[i].tempId()].temp);
3078          new_instr->pass_flags = instr->pass_flags;
3079          instr = std::move(new_instr);
3080          ctx.info[instr->definitions[0].tempId()].set_add_sub(instr.get());
3081          return true;
3082       }
3083    }
3084
3085    return false;
3086 }
3087
3088 bool
3089 combine_add_bcnt(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3090 {
3091    if (instr->usesModifiers())
3092       return false;
3093
3094    for (unsigned i = 0; i < 2; i++) {
3095       Instruction* op_instr = follow_operand(ctx, instr->operands[i]);
3096       if (op_instr && op_instr->opcode == aco_opcode::v_bcnt_u32_b32 &&
3097           !op_instr->usesModifiers() && op_instr->operands[0].isTemp() &&
3098           op_instr->operands[0].getTemp().type() == RegType::vgpr &&
3099           op_instr->operands[1].constantEquals(0)) {
3100          aco_ptr<Instruction> new_instr{
3101             create_instruction<VALU_instruction>(aco_opcode::v_bcnt_u32_b32, Format::VOP3, 2, 1)};
3102          ctx.uses[instr->operands[i].tempId()]--;
3103          new_instr->operands[0] = op_instr->operands[0];
3104          new_instr->operands[1] = instr->operands[!i];
3105          new_instr->definitions[0] = instr->definitions[0];
3106          new_instr->pass_flags = instr->pass_flags;
3107          instr = std::move(new_instr);
3108          ctx.info[instr->definitions[0].tempId()].label = 0;
3109
3110          return true;
3111       }
3112    }
3113
3114    return false;
3115 }
3116
3117 bool
3118 get_minmax_info(aco_opcode op, aco_opcode* min, aco_opcode* max, aco_opcode* min3, aco_opcode* max3,
3119                 aco_opcode* med3, aco_opcode* minmax, bool* some_gfx9_only)
3120 {
3121    switch (op) {
3122 #define MINMAX(type, gfx9)                                                                         \
3123    case aco_opcode::v_min_##type:                                                                  \
3124    case aco_opcode::v_max_##type:                                                                  \
3125       *min = aco_opcode::v_min_##type;                                                             \
3126       *max = aco_opcode::v_max_##type;                                                             \
3127       *med3 = aco_opcode::v_med3_##type;                                                           \
3128       *min3 = aco_opcode::v_min3_##type;                                                           \
3129       *max3 = aco_opcode::v_max3_##type;                                                           \
3130       *minmax = op == *min ? aco_opcode::v_maxmin_##type : aco_opcode::v_minmax_##type;            \
3131       *some_gfx9_only = gfx9;                                                                      \
3132       return true;
3133 #define MINMAX_INT16(type, gfx9)                                                                   \
3134    case aco_opcode::v_min_##type:                                                                  \
3135    case aco_opcode::v_max_##type:                                                                  \
3136       *min = aco_opcode::v_min_##type;                                                             \
3137       *max = aco_opcode::v_max_##type;                                                             \
3138       *med3 = aco_opcode::v_med3_##type;                                                           \
3139       *min3 = aco_opcode::v_min3_##type;                                                           \
3140       *max3 = aco_opcode::v_max3_##type;                                                           \
3141       *minmax = aco_opcode::num_opcodes;                                                           \
3142       *some_gfx9_only = gfx9;                                                                      \
3143       return true;
3144 #define MINMAX_INT16_E64(type, gfx9)                                                               \
3145    case aco_opcode::v_min_##type##_e64:                                                            \
3146    case aco_opcode::v_max_##type##_e64:                                                            \
3147       *min = aco_opcode::v_min_##type##_e64;                                                       \
3148       *max = aco_opcode::v_max_##type##_e64;                                                       \
3149       *med3 = aco_opcode::v_med3_##type;                                                           \
3150       *min3 = aco_opcode::v_min3_##type;                                                           \
3151       *max3 = aco_opcode::v_max3_##type;                                                           \
3152       *minmax = aco_opcode::num_opcodes;                                                           \
3153       *some_gfx9_only = gfx9;                                                                      \
3154       return true;
3155       MINMAX(f32, false)
3156       MINMAX(u32, false)
3157       MINMAX(i32, false)
3158       MINMAX(f16, true)
3159       MINMAX_INT16(u16, true)
3160       MINMAX_INT16(i16, true)
3161       MINMAX_INT16_E64(u16, true)
3162       MINMAX_INT16_E64(i16, true)
3163 #undef MINMAX_INT16_E64
3164 #undef MINMAX_INT16
3165 #undef MINMAX
3166    default: return false;
3167    }
3168 }
3169
3170 /* when ub > lb:
3171  * v_min_{f,u,i}{16,32}(v_max_{f,u,i}{16,32}(a, lb), ub) -> v_med3_{f,u,i}{16,32}(a, lb, ub)
3172  * v_max_{f,u,i}{16,32}(v_min_{f,u,i}{16,32}(a, ub), lb) -> v_med3_{f,u,i}{16,32}(a, lb, ub)
3173  */
3174 bool
3175 combine_clamp(opt_ctx& ctx, aco_ptr<Instruction>& instr, aco_opcode min, aco_opcode max,
3176               aco_opcode med)
3177 {
3178    /* TODO: GLSL's clamp(x, minVal, maxVal) and SPIR-V's
3179     * FClamp(x, minVal, maxVal)/NClamp(x, minVal, maxVal) are undefined if
3180     * minVal > maxVal, which means we can always select it to a v_med3_f32 */
3181    aco_opcode other_op;
3182    if (instr->opcode == min)
3183       other_op = max;
3184    else if (instr->opcode == max)
3185       other_op = min;
3186    else
3187       return false;
3188
3189    for (unsigned swap = 0; swap < 2; swap++) {
3190       Operand operands[3];
3191       bool clamp, precise;
3192       bitarray8 opsel = 0, neg = 0, abs = 0;
3193       uint8_t omod = 0;
3194       if (match_op3_for_vop3(ctx, instr->opcode, other_op, instr.get(), swap, "012", operands, neg,
3195                              abs, opsel, &clamp, &omod, NULL, NULL, NULL, &precise)) {
3196          /* max(min(src, upper), lower) returns upper if src is NaN, but
3197           * med3(src, lower, upper) returns lower.
3198           */
3199          if (precise && instr->opcode != min &&
3200              (min == aco_opcode::v_min_f16 || min == aco_opcode::v_min_f32))
3201             continue;
3202
3203          int const0_idx = -1, const1_idx = -1;
3204          uint32_t const0 = 0, const1 = 0;
3205          for (int i = 0; i < 3; i++) {
3206             uint32_t val;
3207             bool hi16 = opsel & (1 << i);
3208             if (operands[i].isConstant()) {
3209                val = hi16 ? operands[i].constantValue16(true) : operands[i].constantValue();
3210             } else if (operands[i].isTemp() &&
3211                        ctx.info[operands[i].tempId()].is_constant_or_literal(32)) {
3212                val = ctx.info[operands[i].tempId()].val >> (hi16 ? 16 : 0);
3213             } else {
3214                continue;
3215             }
3216             if (const0_idx >= 0) {
3217                const1_idx = i;
3218                const1 = val;
3219             } else {
3220                const0_idx = i;
3221                const0 = val;
3222             }
3223          }
3224          if (const0_idx < 0 || const1_idx < 0)
3225             continue;
3226
3227          int lower_idx = const0_idx;
3228          switch (min) {
3229          case aco_opcode::v_min_f32:
3230          case aco_opcode::v_min_f16: {
3231             float const0_f, const1_f;
3232             if (min == aco_opcode::v_min_f32) {
3233                memcpy(&const0_f, &const0, 4);
3234                memcpy(&const1_f, &const1, 4);
3235             } else {
3236                const0_f = _mesa_half_to_float(const0);
3237                const1_f = _mesa_half_to_float(const1);
3238             }
3239             if (abs[const0_idx])
3240                const0_f = fabsf(const0_f);
3241             if (abs[const1_idx])
3242                const1_f = fabsf(const1_f);
3243             if (neg[const0_idx])
3244                const0_f = -const0_f;
3245             if (neg[const1_idx])
3246                const1_f = -const1_f;
3247             lower_idx = const0_f < const1_f ? const0_idx : const1_idx;
3248             break;
3249          }
3250          case aco_opcode::v_min_u32: {
3251             lower_idx = const0 < const1 ? const0_idx : const1_idx;
3252             break;
3253          }
3254          case aco_opcode::v_min_u16:
3255          case aco_opcode::v_min_u16_e64: {
3256             lower_idx = (uint16_t)const0 < (uint16_t)const1 ? const0_idx : const1_idx;
3257             break;
3258          }
3259          case aco_opcode::v_min_i32: {
3260             int32_t const0_i =
3261                const0 & 0x80000000u ? -2147483648 + (int32_t)(const0 & 0x7fffffffu) : const0;
3262             int32_t const1_i =
3263                const1 & 0x80000000u ? -2147483648 + (int32_t)(const1 & 0x7fffffffu) : const1;
3264             lower_idx = const0_i < const1_i ? const0_idx : const1_idx;
3265             break;
3266          }
3267          case aco_opcode::v_min_i16:
3268          case aco_opcode::v_min_i16_e64: {
3269             int16_t const0_i = const0 & 0x8000u ? -32768 + (int16_t)(const0 & 0x7fffu) : const0;
3270             int16_t const1_i = const1 & 0x8000u ? -32768 + (int16_t)(const1 & 0x7fffu) : const1;
3271             lower_idx = const0_i < const1_i ? const0_idx : const1_idx;
3272             break;
3273          }
3274          default: break;
3275          }
3276          int upper_idx = lower_idx == const0_idx ? const1_idx : const0_idx;
3277
3278          if (instr->opcode == min) {
3279             if (upper_idx != 0 || lower_idx == 0)
3280                return false;
3281          } else {
3282             if (upper_idx == 0 || lower_idx != 0)
3283                return false;
3284          }
3285
3286          ctx.uses[instr->operands[swap].tempId()]--;
3287          create_vop3_for_op3(ctx, med, instr, operands, neg, abs, opsel, clamp, omod);
3288
3289          return true;
3290       }
3291    }
3292
3293    return false;
3294 }
3295
3296 void
3297 apply_sgprs(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3298 {
3299    bool is_shift64 = instr->opcode == aco_opcode::v_lshlrev_b64 ||
3300                      instr->opcode == aco_opcode::v_lshrrev_b64 ||
3301                      instr->opcode == aco_opcode::v_ashrrev_i64;
3302
3303    /* find candidates and create the set of sgprs already read */
3304    unsigned sgpr_ids[2] = {0, 0};
3305    uint32_t operand_mask = 0;
3306    bool has_literal = false;
3307    for (unsigned i = 0; i < instr->operands.size(); i++) {
3308       if (instr->operands[i].isLiteral())
3309          has_literal = true;
3310       if (!instr->operands[i].isTemp())
3311          continue;
3312       if (instr->operands[i].getTemp().type() == RegType::sgpr) {
3313          if (instr->operands[i].tempId() != sgpr_ids[0])
3314             sgpr_ids[!!sgpr_ids[0]] = instr->operands[i].tempId();
3315       }
3316       ssa_info& info = ctx.info[instr->operands[i].tempId()];
3317       if (is_copy_label(ctx, instr, info, i) && info.temp.type() == RegType::sgpr)
3318          operand_mask |= 1u << i;
3319       if (info.is_extract() && info.instr->operands[0].getTemp().type() == RegType::sgpr)
3320          operand_mask |= 1u << i;
3321    }
3322    unsigned max_sgprs = 1;
3323    if (ctx.program->gfx_level >= GFX10 && !is_shift64)
3324       max_sgprs = 2;
3325    if (has_literal)
3326       max_sgprs--;
3327
3328    unsigned num_sgprs = !!sgpr_ids[0] + !!sgpr_ids[1];
3329
3330    /* keep on applying sgprs until there is nothing left to be done */
3331    while (operand_mask) {
3332       uint32_t sgpr_idx = 0;
3333       uint32_t sgpr_info_id = 0;
3334       uint32_t mask = operand_mask;
3335       /* choose a sgpr */
3336       while (mask) {
3337          unsigned i = u_bit_scan(&mask);
3338          uint16_t uses = ctx.uses[instr->operands[i].tempId()];
3339          if (sgpr_info_id == 0 || uses < ctx.uses[sgpr_info_id]) {
3340             sgpr_idx = i;
3341             sgpr_info_id = instr->operands[i].tempId();
3342          }
3343       }
3344       operand_mask &= ~(1u << sgpr_idx);
3345
3346       ssa_info& info = ctx.info[sgpr_info_id];
3347
3348       /* Applying two sgprs require making it VOP3, so don't do it unless it's
3349        * definitively beneficial.
3350        * TODO: this is too conservative because later the use count could be reduced to 1 */
3351       if (!info.is_extract() && num_sgprs && ctx.uses[sgpr_info_id] > 1 && !instr->isVOP3() &&
3352           !instr->isSDWA() && instr->format != Format::VOP3P)
3353          break;
3354
3355       Temp sgpr = info.is_extract() ? info.instr->operands[0].getTemp() : info.temp;
3356       bool new_sgpr = sgpr.id() != sgpr_ids[0] && sgpr.id() != sgpr_ids[1];
3357       if (new_sgpr && num_sgprs >= max_sgprs)
3358          continue;
3359
3360       if (sgpr_idx == 0)
3361          instr->format = withoutDPP(instr->format);
3362
3363       if (sgpr_idx == 1 && instr->isDPP())
3364          continue;
3365
3366       if (sgpr_idx == 0 || instr->isVOP3() || instr->isSDWA() || instr->isVOP3P() ||
3367           info.is_extract()) {
3368          /* can_apply_extract() checks SGPR encoding restrictions */
3369          if (info.is_extract() && can_apply_extract(ctx, instr, sgpr_idx, info))
3370             apply_extract(ctx, instr, sgpr_idx, info);
3371          else if (info.is_extract())
3372             continue;
3373          instr->operands[sgpr_idx] = Operand(sgpr);
3374       } else if (can_swap_operands(instr, &instr->opcode) && !instr->valu().opsel[sgpr_idx]) {
3375          instr->operands[sgpr_idx] = instr->operands[0];
3376          instr->operands[0] = Operand(sgpr);
3377          instr->valu().opsel[0].swap(instr->valu().opsel[sgpr_idx]);
3378          /* swap bits using a 4-entry LUT */
3379          uint32_t swapped = (0x3120 >> (operand_mask & 0x3)) & 0xf;
3380          operand_mask = (operand_mask & ~0x3) | swapped;
3381       } else if (can_use_VOP3(ctx, instr) && !info.is_extract()) {
3382          instr->format = asVOP3(instr->format);
3383          instr->operands[sgpr_idx] = Operand(sgpr);
3384       } else {
3385          continue;
3386       }
3387
3388       if (new_sgpr)
3389          sgpr_ids[num_sgprs++] = sgpr.id();
3390       ctx.uses[sgpr_info_id]--;
3391       ctx.uses[sgpr.id()]++;
3392
3393       /* TODO: handle when it's a VGPR */
3394       if ((ctx.info[sgpr.id()].label & (label_extract | label_temp)) &&
3395           ctx.info[sgpr.id()].temp.type() == RegType::sgpr)
3396          operand_mask |= 1u << sgpr_idx;
3397    }
3398 }
3399
3400 /* apply omod / clamp modifiers if the def is used only once and the instruction can have modifiers */
3401 bool
3402 apply_omod_clamp(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3403 {
3404    if (instr->definitions.empty() || ctx.uses[instr->definitions[0].tempId()] != 1 ||
3405        !instr_info.can_use_output_modifiers[(int)instr->opcode])
3406       return false;
3407
3408    bool can_vop3 = can_use_VOP3(ctx, instr);
3409    bool is_mad_mix =
3410       instr->opcode == aco_opcode::v_fma_mix_f32 || instr->opcode == aco_opcode::v_fma_mixlo_f16;
3411    if (!instr->isSDWA() && !is_mad_mix && !can_vop3)
3412       return false;
3413
3414    /* SDWA omod is GFX9+. */
3415    bool can_use_omod = (can_vop3 || ctx.program->gfx_level >= GFX9) && !instr->isVOP3P();
3416
3417    ssa_info& def_info = ctx.info[instr->definitions[0].tempId()];
3418
3419    uint64_t omod_labels = label_omod2 | label_omod4 | label_omod5;
3420    if (!def_info.is_clamp() && !(can_use_omod && (def_info.label & omod_labels)))
3421       return false;
3422    /* if the omod/clamp instruction is dead, then the single user of this
3423     * instruction is a different instruction */
3424    if (!ctx.uses[def_info.instr->definitions[0].tempId()])
3425       return false;
3426
3427    if (def_info.instr->definitions[0].bytes() != instr->definitions[0].bytes())
3428       return false;
3429
3430    /* MADs/FMAs are created later, so we don't have to update the original add */
3431    assert(!ctx.info[instr->definitions[0].tempId()].is_mad());
3432
3433    if (!instr->isSDWA() && !instr->isVOP3P())
3434       instr->format = asVOP3(instr->format);
3435
3436    if (!def_info.is_clamp() && (instr->valu().clamp || instr->valu().omod))
3437       return false;
3438
3439    if (def_info.is_omod2())
3440       instr->valu().omod = 1;
3441    else if (def_info.is_omod4())
3442       instr->valu().omod = 2;
3443    else if (def_info.is_omod5())
3444       instr->valu().omod = 3;
3445    else if (def_info.is_clamp())
3446       instr->valu().clamp = true;
3447
3448    instr->definitions[0].swapTemp(def_info.instr->definitions[0]);
3449    ctx.info[instr->definitions[0].tempId()].label &= label_clamp | label_insert | label_f2f16;
3450    ctx.uses[def_info.instr->definitions[0].tempId()]--;
3451
3452    return true;
3453 }
3454
3455 /* Combine an p_insert (or p_extract, in some cases) instruction with instr.
3456  * p_insert(instr(...)) -> instr_insert().
3457  */
3458 bool
3459 apply_insert(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3460 {
3461    if (instr->definitions.empty() || ctx.uses[instr->definitions[0].tempId()] != 1)
3462       return false;
3463
3464    ssa_info& def_info = ctx.info[instr->definitions[0].tempId()];
3465    if (!def_info.is_insert())
3466       return false;
3467    /* if the insert instruction is dead, then the single user of this
3468     * instruction is a different instruction */
3469    if (!ctx.uses[def_info.instr->definitions[0].tempId()])
3470       return false;
3471
3472    /* MADs/FMAs are created later, so we don't have to update the original add */
3473    assert(!ctx.info[instr->definitions[0].tempId()].is_mad());
3474
3475    SubdwordSel sel = parse_insert(def_info.instr);
3476    assert(sel);
3477
3478    if (!can_use_SDWA(ctx.program->gfx_level, instr, true))
3479       return false;
3480
3481    convert_to_SDWA(ctx.program->gfx_level, instr);
3482    if (instr->sdwa().dst_sel.size() != 4)
3483       return false;
3484    instr->sdwa().dst_sel = sel;
3485
3486    instr->definitions[0].swapTemp(def_info.instr->definitions[0]);
3487    ctx.info[instr->definitions[0].tempId()].label = 0;
3488    ctx.uses[def_info.instr->definitions[0].tempId()]--;
3489
3490    return true;
3491 }
3492
3493 /* Remove superfluous extract after ds_read like so:
3494  * p_extract(ds_read_uN(), 0, N, 0) -> ds_read_uN()
3495  */
3496 bool
3497 apply_ds_extract(opt_ctx& ctx, aco_ptr<Instruction>& extract)
3498 {
3499    /* Check if p_extract has a usedef operand and is the only user. */
3500    if (!ctx.info[extract->operands[0].tempId()].is_usedef() ||
3501        ctx.uses[extract->operands[0].tempId()] > 1)
3502       return false;
3503
3504    /* Check if the usedef is a DS instruction. */
3505    Instruction* ds = ctx.info[extract->operands[0].tempId()].instr;
3506    if (ds->format != Format::DS)
3507       return false;
3508
3509    unsigned extract_idx = extract->operands[1].constantValue();
3510    unsigned bits_extracted = extract->operands[2].constantValue();
3511    unsigned sign_ext = extract->operands[3].constantValue();
3512    unsigned dst_bitsize = extract->definitions[0].bytes() * 8u;
3513
3514    /* TODO: These are doable, but probably don't occur too often. */
3515    if (extract_idx || sign_ext || dst_bitsize != 32)
3516       return false;
3517
3518    unsigned bits_loaded = 0;
3519    if (ds->opcode == aco_opcode::ds_read_u8 || ds->opcode == aco_opcode::ds_read_u8_d16)
3520       bits_loaded = 8;
3521    else if (ds->opcode == aco_opcode::ds_read_u16 || ds->opcode == aco_opcode::ds_read_u16_d16)
3522       bits_loaded = 16;
3523    else
3524       return false;
3525
3526    /* Shrink the DS load if the extracted bit size is smaller. */
3527    bits_loaded = MIN2(bits_loaded, bits_extracted);
3528
3529    /* Change the DS opcode so it writes the full register. */
3530    if (bits_loaded == 8)
3531       ds->opcode = aco_opcode::ds_read_u8;
3532    else if (bits_loaded == 16)
3533       ds->opcode = aco_opcode::ds_read_u16;
3534    else
3535       unreachable("Forgot to add DS opcode above.");
3536
3537    /* The DS now produces the exact same thing as the extract, remove the extract. */
3538    std::swap(ds->definitions[0], extract->definitions[0]);
3539    ctx.uses[extract->definitions[0].tempId()] = 0;
3540    ctx.info[ds->definitions[0].tempId()].label = 0;
3541    return true;
3542 }
3543
3544 /* v_and(a, v_subbrev_co(0, 0, vcc)) -> v_cndmask(0, a, vcc) */
3545 bool
3546 combine_and_subbrev(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3547 {
3548    if (instr->usesModifiers())
3549       return false;
3550
3551    for (unsigned i = 0; i < 2; i++) {
3552       Instruction* op_instr = follow_operand(ctx, instr->operands[i], true);
3553       if (op_instr && op_instr->opcode == aco_opcode::v_subbrev_co_u32 &&
3554           op_instr->operands[0].constantEquals(0) && op_instr->operands[1].constantEquals(0) &&
3555           !op_instr->usesModifiers()) {
3556
3557          aco_ptr<Instruction> new_instr;
3558          if (instr->operands[!i].isTemp() &&
3559              instr->operands[!i].getTemp().type() == RegType::vgpr) {
3560             new_instr.reset(
3561                create_instruction<VALU_instruction>(aco_opcode::v_cndmask_b32, Format::VOP2, 3, 1));
3562          } else if (ctx.program->gfx_level >= GFX10 ||
3563                     (instr->operands[!i].isConstant() && !instr->operands[!i].isLiteral())) {
3564             new_instr.reset(create_instruction<VALU_instruction>(aco_opcode::v_cndmask_b32,
3565                                                                  asVOP3(Format::VOP2), 3, 1));
3566          } else {
3567             return false;
3568          }
3569
3570          new_instr->operands[0] = Operand::zero();
3571          new_instr->operands[1] = instr->operands[!i];
3572          new_instr->operands[2] = copy_operand(ctx, op_instr->operands[2]);
3573          new_instr->definitions[0] = instr->definitions[0];
3574          new_instr->pass_flags = instr->pass_flags;
3575          instr = std::move(new_instr);
3576          decrease_uses(ctx, op_instr);
3577          ctx.info[instr->definitions[0].tempId()].label = 0;
3578          return true;
3579       }
3580    }
3581
3582    return false;
3583 }
3584
3585 /* v_and(a, not(b)) -> v_bfi_b32(b, 0, a)
3586  * v_or(a, not(b)) -> v_bfi_b32(b, a, -1)
3587  */
3588 bool
3589 combine_v_andor_not(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3590 {
3591    if (instr->usesModifiers())
3592       return false;
3593
3594    for (unsigned i = 0; i < 2; i++) {
3595       Instruction* op_instr = follow_operand(ctx, instr->operands[i], true);
3596       if (op_instr && !op_instr->usesModifiers() &&
3597           (op_instr->opcode == aco_opcode::v_not_b32 ||
3598            op_instr->opcode == aco_opcode::s_not_b32)) {
3599
3600          Operand ops[3] = {
3601             op_instr->operands[0],
3602             Operand::zero(),
3603             instr->operands[!i],
3604          };
3605          if (instr->opcode == aco_opcode::v_or_b32) {
3606             ops[1] = instr->operands[!i];
3607             ops[2] = Operand::c32(-1);
3608          }
3609          if (!check_vop3_operands(ctx, 3, ops))
3610             continue;
3611
3612          Instruction* new_instr =
3613             create_instruction<VALU_instruction>(aco_opcode::v_bfi_b32, Format::VOP3, 3, 1);
3614
3615          if (op_instr->operands[0].isTemp())
3616             ctx.uses[op_instr->operands[0].tempId()]++;
3617          for (unsigned j = 0; j < 3; j++)
3618             new_instr->operands[j] = ops[j];
3619          new_instr->definitions[0] = instr->definitions[0];
3620          new_instr->pass_flags = instr->pass_flags;
3621          instr.reset(new_instr);
3622          decrease_uses(ctx, op_instr);
3623          ctx.info[instr->definitions[0].tempId()].label = 0;
3624          return true;
3625       }
3626    }
3627
3628    return false;
3629 }
3630
3631 /* v_add_co(c, s_lshl(a, b)) -> v_mad_u32_u24(a, 1<<b, c)
3632  * v_add_co(c, v_lshlrev(a, b)) -> v_mad_u32_u24(b, 1<<a, c)
3633  * v_sub(c, s_lshl(a, b)) -> v_mad_i32_i24(a, -(1<<b), c)
3634  * v_sub(c, v_lshlrev(a, b)) -> v_mad_i32_i24(b, -(1<<a), c)
3635  */
3636 bool
3637 combine_add_lshl(opt_ctx& ctx, aco_ptr<Instruction>& instr, bool is_sub)
3638 {
3639    if (instr->usesModifiers())
3640       return false;
3641
3642    /* Substractions: start at operand 1 to avoid mixup such as
3643     * turning v_sub(v_lshlrev(a, b), c) into v_mad_i32_i24(b, -(1<<a), c)
3644     */
3645    unsigned start_op_idx = is_sub ? 1 : 0;
3646
3647    /* Don't allow 24-bit operands on subtraction because
3648     * v_mad_i32_i24 applies a sign extension.
3649     */
3650    bool allow_24bit = !is_sub;
3651
3652    for (unsigned i = start_op_idx; i < 2; i++) {
3653       Instruction* op_instr = follow_operand(ctx, instr->operands[i]);
3654       if (!op_instr)
3655          continue;
3656
3657       if (op_instr->opcode != aco_opcode::s_lshl_b32 &&
3658           op_instr->opcode != aco_opcode::v_lshlrev_b32)
3659          continue;
3660
3661       int shift_op_idx = op_instr->opcode == aco_opcode::s_lshl_b32 ? 1 : 0;
3662
3663       if (op_instr->operands[shift_op_idx].isConstant() &&
3664           ((allow_24bit && op_instr->operands[!shift_op_idx].is24bit()) ||
3665            op_instr->operands[!shift_op_idx].is16bit())) {
3666          uint32_t multiplier = 1 << (op_instr->operands[shift_op_idx].constantValue() % 32u);
3667          if (is_sub)
3668             multiplier = -multiplier;
3669          if (is_sub ? (multiplier < 0xff800000) : (multiplier > 0xffffff))
3670             continue;
3671
3672          Operand ops[3] = {
3673             op_instr->operands[!shift_op_idx],
3674             Operand::c32(multiplier),
3675             instr->operands[!i],
3676          };
3677          if (!check_vop3_operands(ctx, 3, ops))
3678             return false;
3679
3680          ctx.uses[instr->operands[i].tempId()]--;
3681
3682          aco_opcode mad_op = is_sub ? aco_opcode::v_mad_i32_i24 : aco_opcode::v_mad_u32_u24;
3683          aco_ptr<VALU_instruction> new_instr{
3684             create_instruction<VALU_instruction>(mad_op, Format::VOP3, 3, 1)};
3685          for (unsigned op_idx = 0; op_idx < 3; ++op_idx)
3686             new_instr->operands[op_idx] = ops[op_idx];
3687          new_instr->definitions[0] = instr->definitions[0];
3688          new_instr->pass_flags = instr->pass_flags;
3689          instr = std::move(new_instr);
3690          ctx.info[instr->definitions[0].tempId()].label = 0;
3691          return true;
3692       }
3693    }
3694
3695    return false;
3696 }
3697
3698 void
3699 propagate_swizzles(VALU_instruction* instr, bool opsel_lo, bool opsel_hi)
3700 {
3701    /* propagate swizzles which apply to a result down to the instruction's operands:
3702     * result = a.xy + b.xx -> result.yx = a.yx + b.xx */
3703    uint8_t tmp_lo = instr->opsel_lo;
3704    uint8_t tmp_hi = instr->opsel_hi;
3705    uint8_t neg_lo = instr->neg_lo;
3706    uint8_t neg_hi = instr->neg_hi;
3707    if (opsel_lo == 1) {
3708       instr->opsel_lo = tmp_hi;
3709       instr->neg_lo = neg_hi;
3710    }
3711    if (opsel_hi == 0) {
3712       instr->opsel_hi = tmp_lo;
3713       instr->neg_hi = neg_lo;
3714    }
3715 }
3716
3717 void
3718 combine_vop3p(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3719 {
3720    VALU_instruction* vop3p = &instr->valu();
3721
3722    /* apply clamp */
3723    if (instr->opcode == aco_opcode::v_pk_mul_f16 && instr->operands[1].constantEquals(0x3C00) &&
3724        vop3p->clamp && instr->operands[0].isTemp() && ctx.uses[instr->operands[0].tempId()] == 1 &&
3725        !vop3p->opsel_lo[1] && !vop3p->opsel_hi[1]) {
3726
3727       ssa_info& info = ctx.info[instr->operands[0].tempId()];
3728       if (info.is_vop3p() && instr_info.can_use_output_modifiers[(int)info.instr->opcode]) {
3729          VALU_instruction* candidate = &ctx.info[instr->operands[0].tempId()].instr->valu();
3730          candidate->clamp = true;
3731          propagate_swizzles(candidate, vop3p->opsel_lo[0], vop3p->opsel_hi[0]);
3732          instr->definitions[0].swapTemp(candidate->definitions[0]);
3733          ctx.info[candidate->definitions[0].tempId()].instr = candidate;
3734          ctx.uses[instr->definitions[0].tempId()]--;
3735          return;
3736       }
3737    }
3738
3739    /* check for fneg modifiers */
3740    for (unsigned i = 0; i < instr->operands.size(); i++) {
3741       if (!can_use_input_modifiers(ctx.program->gfx_level, instr->opcode, i))
3742          continue;
3743       Operand& op = instr->operands[i];
3744       if (!op.isTemp())
3745          continue;
3746
3747       ssa_info& info = ctx.info[op.tempId()];
3748       if (info.is_vop3p() && info.instr->opcode == aco_opcode::v_pk_mul_f16 &&
3749           info.instr->operands[1].constantEquals(0x3C00)) {
3750
3751          VALU_instruction* fneg = &info.instr->valu();
3752
3753          if (fneg->opsel_lo[1] || fneg->opsel_hi[1])
3754             continue;
3755
3756          Operand ops[3];
3757          for (unsigned j = 0; j < instr->operands.size(); j++)
3758             ops[j] = instr->operands[j];
3759          ops[i] = info.instr->operands[0];
3760          if (!check_vop3_operands(ctx, instr->operands.size(), ops))
3761             continue;
3762
3763          if (fneg->clamp)
3764             continue;
3765          instr->operands[i] = fneg->operands[0];
3766
3767          /* opsel_lo/hi is either 0 or 1:
3768           * if 0 - pick selection from fneg->lo
3769           * if 1 - pick selection from fneg->hi
3770           */
3771          bool opsel_lo = vop3p->opsel_lo[i];
3772          bool opsel_hi = vop3p->opsel_hi[i];
3773          bool neg_lo = fneg->neg_lo[0] ^ fneg->neg_lo[1];
3774          bool neg_hi = fneg->neg_hi[0] ^ fneg->neg_hi[1];
3775          vop3p->neg_lo[i] ^= opsel_lo ? neg_hi : neg_lo;
3776          vop3p->neg_hi[i] ^= opsel_hi ? neg_hi : neg_lo;
3777          vop3p->opsel_lo[i] ^= opsel_lo ? !fneg->opsel_hi[0] : fneg->opsel_lo[0];
3778          vop3p->opsel_hi[i] ^= opsel_hi ? !fneg->opsel_hi[0] : fneg->opsel_lo[0];
3779
3780          if (--ctx.uses[fneg->definitions[0].tempId()])
3781             ctx.uses[fneg->operands[0].tempId()]++;
3782       }
3783    }
3784
3785    if (instr->opcode == aco_opcode::v_pk_add_f16 || instr->opcode == aco_opcode::v_pk_add_u16) {
3786       bool fadd = instr->opcode == aco_opcode::v_pk_add_f16;
3787       if (fadd && instr->definitions[0].isPrecise())
3788          return;
3789
3790       Instruction* mul_instr = nullptr;
3791       unsigned add_op_idx = 0;
3792       bitarray8 mul_neg_lo = 0, mul_neg_hi = 0, mul_opsel_lo = 0, mul_opsel_hi = 0;
3793       uint32_t uses = UINT32_MAX;
3794
3795       /* find the 'best' mul instruction to combine with the add */
3796       for (unsigned i = 0; i < 2; i++) {
3797          Instruction* op_instr = follow_operand(ctx, instr->operands[i], true);
3798          if (!op_instr)
3799             continue;
3800
3801          if (ctx.info[instr->operands[i].tempId()].is_vop3p()) {
3802             if (fadd) {
3803                if (op_instr->opcode != aco_opcode::v_pk_mul_f16 ||
3804                    op_instr->definitions[0].isPrecise())
3805                   continue;
3806             } else {
3807                if (op_instr->opcode != aco_opcode::v_pk_mul_lo_u16)
3808                   continue;
3809             }
3810
3811             Operand op[3] = {op_instr->operands[0], op_instr->operands[1], instr->operands[1 - i]};
3812             if (ctx.uses[instr->operands[i].tempId()] >= uses || !check_vop3_operands(ctx, 3, op))
3813                continue;
3814
3815             /* no clamp allowed between mul and add */
3816             if (op_instr->valu().clamp)
3817                continue;
3818
3819             mul_instr = op_instr;
3820             add_op_idx = 1 - i;
3821             uses = ctx.uses[instr->operands[i].tempId()];
3822             mul_neg_lo = mul_instr->valu().neg_lo;
3823             mul_neg_hi = mul_instr->valu().neg_hi;
3824             mul_opsel_lo = mul_instr->valu().opsel_lo;
3825             mul_opsel_hi = mul_instr->valu().opsel_hi;
3826          } else if (instr->operands[i].bytes() == 2) {
3827             if ((fadd && (op_instr->opcode != aco_opcode::v_mul_f16 ||
3828                           op_instr->definitions[0].isPrecise())) ||
3829                 (!fadd && op_instr->opcode != aco_opcode::v_mul_lo_u16 &&
3830                  op_instr->opcode != aco_opcode::v_mul_lo_u16_e64))
3831                continue;
3832
3833             if (op_instr->valu().clamp || op_instr->valu().omod || op_instr->valu().abs)
3834                continue;
3835
3836             if (op_instr->isDPP() || (op_instr->isSDWA() && (op_instr->sdwa().sel[0].size() < 2 ||
3837                                                              op_instr->sdwa().sel[1].size() < 2)))
3838                continue;
3839
3840             Operand op[3] = {op_instr->operands[0], op_instr->operands[1], instr->operands[1 - i]};
3841             if (ctx.uses[instr->operands[i].tempId()] >= uses || !check_vop3_operands(ctx, 3, op))
3842                continue;
3843
3844             mul_instr = op_instr;
3845             add_op_idx = 1 - i;
3846             uses = ctx.uses[instr->operands[i].tempId()];
3847             mul_neg_lo = mul_instr->valu().neg;
3848             mul_neg_hi = mul_instr->valu().neg;
3849             if (mul_instr->isSDWA()) {
3850                for (unsigned j = 0; j < 2; j++)
3851                   mul_opsel_lo[j] = mul_instr->sdwa().sel[j].offset();
3852             } else {
3853                mul_opsel_lo = mul_instr->valu().opsel;
3854             }
3855             mul_opsel_hi = mul_opsel_lo;
3856          }
3857       }
3858
3859       if (!mul_instr)
3860          return;
3861
3862       /* turn mul + packed add into v_pk_fma_f16 */
3863       aco_opcode mad = fadd ? aco_opcode::v_pk_fma_f16 : aco_opcode::v_pk_mad_u16;
3864       aco_ptr<VALU_instruction> fma{create_instruction<VALU_instruction>(mad, Format::VOP3P, 3, 1)};
3865       fma->operands[0] = copy_operand(ctx, mul_instr->operands[0]);
3866       fma->operands[1] = copy_operand(ctx, mul_instr->operands[1]);
3867       fma->operands[2] = instr->operands[add_op_idx];
3868       fma->clamp = vop3p->clamp;
3869       fma->neg_lo = mul_neg_lo;
3870       fma->neg_hi = mul_neg_hi;
3871       fma->opsel_lo = mul_opsel_lo;
3872       fma->opsel_hi = mul_opsel_hi;
3873       propagate_swizzles(fma.get(), vop3p->opsel_lo[1 - add_op_idx],
3874                          vop3p->opsel_hi[1 - add_op_idx]);
3875       fma->opsel_lo[2] = vop3p->opsel_lo[add_op_idx];
3876       fma->opsel_hi[2] = vop3p->opsel_hi[add_op_idx];
3877       fma->neg_lo[2] = vop3p->neg_lo[add_op_idx];
3878       fma->neg_hi[2] = vop3p->neg_hi[add_op_idx];
3879       fma->neg_lo[1] = fma->neg_lo[1] ^ vop3p->neg_lo[1 - add_op_idx];
3880       fma->neg_hi[1] = fma->neg_hi[1] ^ vop3p->neg_hi[1 - add_op_idx];
3881       fma->definitions[0] = instr->definitions[0];
3882       fma->pass_flags = instr->pass_flags;
3883       instr = std::move(fma);
3884       ctx.info[instr->definitions[0].tempId()].set_vop3p(instr.get());
3885       decrease_uses(ctx, mul_instr);
3886       return;
3887    }
3888 }
3889
3890 bool
3891 can_use_mad_mix(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3892 {
3893    if (ctx.program->gfx_level < GFX9)
3894       return false;
3895
3896    /* v_mad_mix* on GFX9 always flushes denormals for 16-bit inputs/outputs */
3897    if (ctx.program->gfx_level == GFX9 && ctx.fp_mode.denorm16_64)
3898       return false;
3899
3900    switch (instr->opcode) {
3901    case aco_opcode::v_add_f32:
3902    case aco_opcode::v_sub_f32:
3903    case aco_opcode::v_subrev_f32:
3904    case aco_opcode::v_mul_f32:
3905    case aco_opcode::v_fma_f32: break;
3906    case aco_opcode::v_fma_mix_f32:
3907    case aco_opcode::v_fma_mixlo_f16: return true;
3908    default: return false;
3909    }
3910
3911    if (instr->opcode == aco_opcode::v_fma_f32 && !ctx.program->dev.fused_mad_mix &&
3912        instr->definitions[0].isPrecise())
3913       return false;
3914
3915    return !instr->valu().omod && !instr->isSDWA() && !instr->isDPP();
3916 }
3917
3918 void
3919 to_mad_mix(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3920 {
3921    bool is_add = instr->opcode != aco_opcode::v_mul_f32 && instr->opcode != aco_opcode::v_fma_f32;
3922
3923    aco_ptr<VALU_instruction> vop3p{
3924       create_instruction<VALU_instruction>(aco_opcode::v_fma_mix_f32, Format::VOP3P, 3, 1)};
3925
3926    for (unsigned i = 0; i < instr->operands.size(); i++) {
3927       vop3p->operands[is_add + i] = instr->operands[i];
3928       vop3p->neg_lo[is_add + i] = instr->valu().neg[i];
3929       vop3p->neg_hi[is_add + i] = instr->valu().abs[i];
3930    }
3931    if (instr->opcode == aco_opcode::v_mul_f32) {
3932       vop3p->operands[2] = Operand::zero();
3933       vop3p->neg_lo[2] = true;
3934    } else if (is_add) {
3935       vop3p->operands[0] = Operand::c32(0x3f800000);
3936       if (instr->opcode == aco_opcode::v_sub_f32)
3937          vop3p->neg_lo[2] ^= true;
3938       else if (instr->opcode == aco_opcode::v_subrev_f32)
3939          vop3p->neg_lo[1] ^= true;
3940    }
3941    vop3p->definitions[0] = instr->definitions[0];
3942    vop3p->clamp = instr->valu().clamp;
3943    vop3p->pass_flags = instr->pass_flags;
3944    instr = std::move(vop3p);
3945
3946    ctx.info[instr->definitions[0].tempId()].label &= label_f2f16 | label_clamp | label_mul;
3947    if (ctx.info[instr->definitions[0].tempId()].label & label_mul)
3948       ctx.info[instr->definitions[0].tempId()].instr = instr.get();
3949 }
3950
3951 bool
3952 combine_output_conversion(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3953 {
3954    ssa_info& def_info = ctx.info[instr->definitions[0].tempId()];
3955    if (!def_info.is_f2f16())
3956       return false;
3957    Instruction* conv = def_info.instr;
3958
3959    if (!can_use_mad_mix(ctx, instr) || ctx.uses[instr->definitions[0].tempId()] != 1)
3960       return false;
3961
3962    if (!ctx.uses[conv->definitions[0].tempId()])
3963       return false;
3964
3965    if (conv->usesModifiers())
3966       return false;
3967
3968    if (!instr->isVOP3P())
3969       to_mad_mix(ctx, instr);
3970
3971    instr->opcode = aco_opcode::v_fma_mixlo_f16;
3972    instr->definitions[0].swapTemp(conv->definitions[0]);
3973    if (conv->definitions[0].isPrecise())
3974       instr->definitions[0].setPrecise(true);
3975    ctx.info[instr->definitions[0].tempId()].label &= label_clamp;
3976    ctx.uses[conv->definitions[0].tempId()]--;
3977
3978    return true;
3979 }
3980
3981 void
3982 combine_mad_mix(opt_ctx& ctx, aco_ptr<Instruction>& instr)
3983 {
3984    if (!can_use_mad_mix(ctx, instr))
3985       return;
3986
3987    for (unsigned i = 0; i < instr->operands.size(); i++) {
3988       if (!instr->operands[i].isTemp())
3989          continue;
3990       Temp tmp = instr->operands[i].getTemp();
3991       if (!ctx.info[tmp.id()].is_f2f32())
3992          continue;
3993
3994       Instruction* conv = ctx.info[tmp.id()].instr;
3995       if (conv->valu().clamp || conv->valu().omod) {
3996          continue;
3997       } else if (conv->isSDWA() &&
3998                  (conv->sdwa().dst_sel.size() != 4 || conv->sdwa().sel[0].size() != 2)) {
3999          continue;
4000       } else if (conv->isDPP()) {
4001          continue;
4002       }
4003
4004       if (get_operand_size(instr, i) != 32)
4005          continue;
4006
4007       /* Conversion to VOP3P will add inline constant operands, but that shouldn't affect
4008        * check_vop3_operands(). */
4009       Operand op[3];
4010       for (unsigned j = 0; j < instr->operands.size(); j++)
4011          op[j] = instr->operands[j];
4012       op[i] = conv->operands[0];
4013       if (!check_vop3_operands(ctx, instr->operands.size(), op))
4014          continue;
4015
4016       if (!instr->isVOP3P()) {
4017          bool is_add =
4018             instr->opcode != aco_opcode::v_mul_f32 && instr->opcode != aco_opcode::v_fma_f32;
4019          to_mad_mix(ctx, instr);
4020          i += is_add;
4021       }
4022
4023       if (--ctx.uses[tmp.id()])
4024          ctx.uses[conv->operands[0].tempId()]++;
4025       instr->operands[i].setTemp(conv->operands[0].getTemp());
4026       if (conv->definitions[0].isPrecise())
4027          instr->definitions[0].setPrecise(true);
4028       instr->valu().opsel_hi[i] = true;
4029       if (conv->isSDWA() && conv->sdwa().sel[0].offset() == 2)
4030          instr->valu().opsel_lo[i] = true;
4031       else
4032          instr->valu().opsel_lo[i] = conv->valu().opsel[0];
4033       bool neg = conv->valu().neg[0];
4034       bool abs = conv->valu().abs[0];
4035       if (!instr->valu().abs[i]) {
4036          instr->valu().neg[i] ^= neg;
4037          instr->valu().abs[i] = abs;
4038       }
4039    }
4040 }
4041
4042 // TODO: we could possibly move the whole label_instruction pass to combine_instruction:
4043 // this would mean that we'd have to fix the instruction uses while value propagation
4044
4045 /* also returns true for inf */
4046 bool
4047 is_pow_of_two(opt_ctx& ctx, Operand op)
4048 {
4049    if (op.isTemp() && ctx.info[op.tempId()].is_constant_or_literal(op.bytes() * 8))
4050       return is_pow_of_two(ctx, get_constant_op(ctx, ctx.info[op.tempId()], op.bytes() * 8));
4051    else if (!op.isConstant())
4052       return false;
4053
4054    uint64_t val = op.constantValue64();
4055
4056    if (op.bytes() == 4) {
4057       uint32_t exponent = (val & 0x7f800000) >> 23;
4058       uint32_t fraction = val & 0x007fffff;
4059       return (exponent >= 127) && (fraction == 0);
4060    } else if (op.bytes() == 2) {
4061       uint32_t exponent = (val & 0x7c00) >> 10;
4062       uint32_t fraction = val & 0x03ff;
4063       return (exponent >= 15) && (fraction == 0);
4064    } else {
4065       assert(op.bytes() == 8);
4066       uint64_t exponent = (val & UINT64_C(0x7ff0000000000000)) >> 52;
4067       uint64_t fraction = val & UINT64_C(0x000fffffffffffff);
4068       return (exponent >= 1023) && (fraction == 0);
4069    }
4070 }
4071
4072 void
4073 combine_instruction(opt_ctx& ctx, aco_ptr<Instruction>& instr)
4074 {
4075    if (instr->definitions.empty() || is_dead(ctx.uses, instr.get()))
4076       return;
4077
4078    if (instr->isVALU()) {
4079       /* Apply SDWA. Do this after label_instruction() so it can remove
4080        * label_extract if not all instructions can take SDWA. */
4081       for (unsigned i = 0; i < instr->operands.size(); i++) {
4082          Operand& op = instr->operands[i];
4083          if (!op.isTemp())
4084             continue;
4085          ssa_info& info = ctx.info[op.tempId()];
4086          if (!info.is_extract())
4087             continue;
4088          /* if there are that many uses, there are likely better combinations */
4089          // TODO: delay applying extract to a point where we know better
4090          if (ctx.uses[op.tempId()] > 4) {
4091             info.label &= ~label_extract;
4092             continue;
4093          }
4094          if (info.is_extract() &&
4095              (info.instr->operands[0].getTemp().type() == RegType::vgpr ||
4096               instr->operands[i].getTemp().type() == RegType::sgpr) &&
4097              can_apply_extract(ctx, instr, i, info)) {
4098             /* Increase use count of the extract's operand if the extract still has uses. */
4099             apply_extract(ctx, instr, i, info);
4100             if (--ctx.uses[instr->operands[i].tempId()])
4101                ctx.uses[info.instr->operands[0].tempId()]++;
4102             instr->operands[i].setTemp(info.instr->operands[0].getTemp());
4103          }
4104       }
4105
4106       if (can_apply_sgprs(ctx, instr))
4107          apply_sgprs(ctx, instr);
4108       combine_mad_mix(ctx, instr);
4109       while (apply_omod_clamp(ctx, instr) || combine_output_conversion(ctx, instr))
4110          ;
4111       apply_insert(ctx, instr);
4112    }
4113
4114    if (instr->isVOP3P() && instr->opcode != aco_opcode::v_fma_mix_f32 &&
4115        instr->opcode != aco_opcode::v_fma_mixlo_f16)
4116       return combine_vop3p(ctx, instr);
4117
4118    if (instr->isSDWA() || instr->isDPP())
4119       return;
4120
4121    if (instr->opcode == aco_opcode::p_extract) {
4122       ssa_info& info = ctx.info[instr->operands[0].tempId()];
4123       if (info.is_extract() && can_apply_extract(ctx, instr, 0, info)) {
4124          apply_extract(ctx, instr, 0, info);
4125          if (--ctx.uses[instr->operands[0].tempId()])
4126             ctx.uses[info.instr->operands[0].tempId()]++;
4127          instr->operands[0].setTemp(info.instr->operands[0].getTemp());
4128       }
4129
4130       apply_ds_extract(ctx, instr);
4131    }
4132
4133    if (instr->isVOPC()) {
4134       if (optimize_cmp_subgroup_invocation(ctx, instr))
4135          return;
4136    }
4137
4138    /* TODO: There are still some peephole optimizations that could be done:
4139     * - abs(a - b) -> s_absdiff_i32
4140     * - various patterns for s_bitcmp{0,1}_b32 and s_bitset{0,1}_b32
4141     * - patterns for v_alignbit_b32 and v_alignbyte_b32
4142     * These aren't probably too interesting though.
4143     * There are also patterns for v_cmp_class_f{16,32,64}. This is difficult but
4144     * probably more useful than the previously mentioned optimizations.
4145     * The various comparison optimizations also currently only work with 32-bit
4146     * floats. */
4147
4148    /* neg(mul(a, b)) -> mul(neg(a), b), abs(mul(a, b)) -> mul(abs(a), abs(b)) */
4149    if ((ctx.info[instr->definitions[0].tempId()].label & (label_neg | label_abs)) &&
4150        ctx.uses[instr->operands[1].tempId()] == 1) {
4151       Temp val = ctx.info[instr->definitions[0].tempId()].temp;
4152
4153       if (!ctx.info[val.id()].is_mul())
4154          return;
4155
4156       Instruction* mul_instr = ctx.info[val.id()].instr;
4157
4158       if (mul_instr->operands[0].isLiteral())
4159          return;
4160       if (mul_instr->valu().clamp)
4161          return;
4162       if (mul_instr->isSDWA() || mul_instr->isDPP())
4163          return;
4164       if (mul_instr->opcode == aco_opcode::v_mul_legacy_f32 &&
4165           ctx.fp_mode.preserve_signed_zero_inf_nan32)
4166          return;
4167       if (mul_instr->definitions[0].bytes() != instr->definitions[0].bytes())
4168          return;
4169
4170       /* convert to mul(neg(a), b), mul(abs(a), abs(b)) or mul(neg(abs(a)), abs(b)) */
4171       ctx.uses[mul_instr->definitions[0].tempId()]--;
4172       Definition def = instr->definitions[0];
4173       bool is_neg = ctx.info[instr->definitions[0].tempId()].is_neg();
4174       bool is_abs = ctx.info[instr->definitions[0].tempId()].is_abs();
4175       uint32_t pass_flags = instr->pass_flags;
4176       Format format = mul_instr->format == Format::VOP2 ? asVOP3(Format::VOP2) : mul_instr->format;
4177       instr.reset(create_instruction<VALU_instruction>(mul_instr->opcode, format,
4178                                                        mul_instr->operands.size(), 1));
4179       std::copy(mul_instr->operands.cbegin(), mul_instr->operands.cend(), instr->operands.begin());
4180       instr->pass_flags = pass_flags;
4181       instr->definitions[0] = def;
4182       VALU_instruction& new_mul = instr->valu();
4183       VALU_instruction& mul = mul_instr->valu();
4184       new_mul.neg = mul.neg;
4185       new_mul.abs = mul.abs;
4186       new_mul.omod = mul.omod;
4187       new_mul.opsel = mul.opsel;
4188       new_mul.opsel_lo = mul.opsel_lo;
4189       new_mul.opsel_hi = mul.opsel_hi;
4190       if (is_abs) {
4191          new_mul.neg[0] = new_mul.neg[1] = false;
4192          new_mul.abs[0] = new_mul.abs[1] = true;
4193       }
4194       new_mul.neg[0] ^= is_neg;
4195       new_mul.clamp = false;
4196
4197       ctx.info[instr->definitions[0].tempId()].set_mul(instr.get());
4198       return;
4199    }
4200
4201    /* combine mul+add -> mad */
4202    bool is_add_mix =
4203       (instr->opcode == aco_opcode::v_fma_mix_f32 ||
4204        instr->opcode == aco_opcode::v_fma_mixlo_f16) &&
4205       !instr->valu().neg_lo[0] &&
4206       ((instr->operands[0].constantEquals(0x3f800000) && !instr->valu().opsel_hi[0]) ||
4207        (instr->operands[0].constantEquals(0x3C00) && instr->valu().opsel_hi[0] &&
4208         !instr->valu().opsel_lo[0]));
4209    bool mad32 = instr->opcode == aco_opcode::v_add_f32 || instr->opcode == aco_opcode::v_sub_f32 ||
4210                 instr->opcode == aco_opcode::v_subrev_f32;
4211    bool mad16 = instr->opcode == aco_opcode::v_add_f16 || instr->opcode == aco_opcode::v_sub_f16 ||
4212                 instr->opcode == aco_opcode::v_subrev_f16;
4213    bool mad64 = instr->opcode == aco_opcode::v_add_f64;
4214    if (is_add_mix || mad16 || mad32 || mad64) {
4215       Instruction* mul_instr = nullptr;
4216       unsigned add_op_idx = 0;
4217       uint32_t uses = UINT32_MAX;
4218       bool emit_fma = false;
4219       /* find the 'best' mul instruction to combine with the add */
4220       for (unsigned i = is_add_mix ? 1 : 0; i < instr->operands.size(); i++) {
4221          if (!instr->operands[i].isTemp() || !ctx.info[instr->operands[i].tempId()].is_mul())
4222             continue;
4223          ssa_info& info = ctx.info[instr->operands[i].tempId()];
4224
4225          /* no clamp/omod allowed between mul and add */
4226          if (info.instr->isVOP3() && (info.instr->valu().clamp || info.instr->valu().omod))
4227             continue;
4228          if (info.instr->isVOP3P() && info.instr->valu().clamp)
4229             continue;
4230          /* v_fma_mix_f32/etc can't do omod */
4231          if (info.instr->isVOP3P() && instr->isVOP3() && instr->valu().omod)
4232             continue;
4233          /* don't promote fp16 to fp32 or remove fp32->fp16->fp32 conversions */
4234          if (is_add_mix && info.instr->definitions[0].bytes() == 2)
4235             continue;
4236
4237          if (get_operand_size(instr, i) != info.instr->definitions[0].bytes() * 8)
4238             continue;
4239
4240          bool legacy = info.instr->opcode == aco_opcode::v_mul_legacy_f32;
4241          bool mad_mix = is_add_mix || info.instr->isVOP3P();
4242
4243          /* Multiplication by power-of-two should never need rounding. 1/power-of-two also works,
4244           * but using fma removes denormal flushing (0xfffffe * 0.5 + 0x810001a2).
4245           */
4246          bool is_fma_precise = is_pow_of_two(ctx, info.instr->operands[0]) ||
4247                                is_pow_of_two(ctx, info.instr->operands[1]);
4248
4249          bool has_fma = mad16 || mad64 || (legacy && ctx.program->gfx_level >= GFX10_3) ||
4250                         (mad32 && !legacy && !mad_mix && ctx.program->dev.has_fast_fma32) ||
4251                         (mad_mix && ctx.program->dev.fused_mad_mix);
4252          bool has_mad = mad_mix ? !ctx.program->dev.fused_mad_mix
4253                                 : ((mad32 && ctx.program->gfx_level < GFX10_3) ||
4254                                    (mad16 && ctx.program->gfx_level <= GFX9));
4255          bool can_use_fma =
4256             has_fma &&
4257             (!(info.instr->definitions[0].isPrecise() || instr->definitions[0].isPrecise()) ||
4258              is_fma_precise);
4259          bool can_use_mad =
4260             has_mad && (mad_mix || mad32 ? ctx.fp_mode.denorm32 : ctx.fp_mode.denorm16_64) == 0;
4261          if (mad_mix && legacy)
4262             continue;
4263          if (!can_use_fma && !can_use_mad)
4264             continue;
4265
4266          unsigned candidate_add_op_idx = is_add_mix ? (3 - i) : (1 - i);
4267          Operand op[3] = {info.instr->operands[0], info.instr->operands[1],
4268                           instr->operands[candidate_add_op_idx]};
4269          if (info.instr->isSDWA() || info.instr->isDPP() || !check_vop3_operands(ctx, 3, op) ||
4270              ctx.uses[instr->operands[i].tempId()] > uses)
4271             continue;
4272
4273          if (ctx.uses[instr->operands[i].tempId()] == uses) {
4274             unsigned cur_idx = mul_instr->definitions[0].tempId();
4275             unsigned new_idx = info.instr->definitions[0].tempId();
4276             if (cur_idx > new_idx)
4277                continue;
4278          }
4279
4280          mul_instr = info.instr;
4281          add_op_idx = candidate_add_op_idx;
4282          uses = ctx.uses[instr->operands[i].tempId()];
4283          emit_fma = !can_use_mad;
4284       }
4285
4286       if (mul_instr) {
4287          /* turn mul+add into v_mad/v_fma */
4288          Operand op[3] = {mul_instr->operands[0], mul_instr->operands[1],
4289                           instr->operands[add_op_idx]};
4290          ctx.uses[mul_instr->definitions[0].tempId()]--;
4291          if (ctx.uses[mul_instr->definitions[0].tempId()]) {
4292             if (op[0].isTemp())
4293                ctx.uses[op[0].tempId()]++;
4294             if (op[1].isTemp())
4295                ctx.uses[op[1].tempId()]++;
4296          }
4297
4298          bool neg[3] = {false, false, false};
4299          bool abs[3] = {false, false, false};
4300          unsigned omod = 0;
4301          bool clamp = false;
4302          bitarray8 opsel_lo = 0;
4303          bitarray8 opsel_hi = 0;
4304          bitarray8 opsel = 0;
4305          unsigned mul_op_idx = (instr->isVOP3P() ? 3 : 1) - add_op_idx;
4306
4307          VALU_instruction& valu_mul = mul_instr->valu();
4308          neg[0] = valu_mul.neg[0];
4309          neg[1] = valu_mul.neg[1];
4310          abs[0] = valu_mul.abs[0];
4311          abs[1] = valu_mul.abs[1];
4312          opsel_lo = valu_mul.opsel_lo & 0x3;
4313          opsel_hi = valu_mul.opsel_hi & 0x3;
4314          opsel = valu_mul.opsel & 0x3;
4315
4316          VALU_instruction& valu = instr->valu();
4317          neg[2] = valu.neg[add_op_idx];
4318          abs[2] = valu.abs[add_op_idx];
4319          opsel_lo[2] = valu.opsel_lo[add_op_idx];
4320          opsel_hi[2] = valu.opsel_hi[add_op_idx];
4321          opsel[2] = valu.opsel[add_op_idx];
4322          opsel[3] = valu.opsel[3];
4323          omod = valu.omod;
4324          clamp = valu.clamp;
4325          /* abs of the multiplication result */
4326          if (valu.abs[mul_op_idx]) {
4327             neg[0] = false;
4328             neg[1] = false;
4329             abs[0] = true;
4330             abs[1] = true;
4331          }
4332          /* neg of the multiplication result */
4333          neg[1] ^= valu.neg[mul_op_idx];
4334
4335          if (instr->opcode == aco_opcode::v_sub_f32 || instr->opcode == aco_opcode::v_sub_f16)
4336             neg[1 + add_op_idx] = neg[1 + add_op_idx] ^ true;
4337          else if (instr->opcode == aco_opcode::v_subrev_f32 ||
4338                   instr->opcode == aco_opcode::v_subrev_f16)
4339             neg[2 - add_op_idx] = neg[2 - add_op_idx] ^ true;
4340
4341          aco_ptr<Instruction> add_instr = std::move(instr);
4342          aco_ptr<VALU_instruction> mad;
4343          if (add_instr->isVOP3P() || mul_instr->isVOP3P()) {
4344             assert(!omod);
4345             assert(!opsel);
4346
4347             aco_opcode mad_op = add_instr->definitions[0].bytes() == 2 ? aco_opcode::v_fma_mixlo_f16
4348                                                                        : aco_opcode::v_fma_mix_f32;
4349             mad.reset(create_instruction<VALU_instruction>(mad_op, Format::VOP3P, 3, 1));
4350          } else {
4351             assert(!opsel_lo);
4352             assert(!opsel_hi);
4353
4354             aco_opcode mad_op = emit_fma ? aco_opcode::v_fma_f32 : aco_opcode::v_mad_f32;
4355             if (mul_instr->opcode == aco_opcode::v_mul_legacy_f32) {
4356                assert(emit_fma == (ctx.program->gfx_level >= GFX10_3));
4357                mad_op = emit_fma ? aco_opcode::v_fma_legacy_f32 : aco_opcode::v_mad_legacy_f32;
4358             } else if (mad16) {
4359                mad_op = emit_fma ? (ctx.program->gfx_level == GFX8 ? aco_opcode::v_fma_legacy_f16
4360                                                                    : aco_opcode::v_fma_f16)
4361                                  : (ctx.program->gfx_level == GFX8 ? aco_opcode::v_mad_legacy_f16
4362                                                                    : aco_opcode::v_mad_f16);
4363             } else if (mad64) {
4364                mad_op = aco_opcode::v_fma_f64;
4365             }
4366
4367             mad.reset(create_instruction<VALU_instruction>(mad_op, Format::VOP3, 3, 1));
4368          }
4369
4370          for (unsigned i = 0; i < 3; i++) {
4371             mad->operands[i] = op[i];
4372             mad->neg[i] = neg[i];
4373             mad->abs[i] = abs[i];
4374          }
4375          mad->omod = omod;
4376          mad->clamp = clamp;
4377          mad->opsel_lo = opsel_lo;
4378          mad->opsel_hi = opsel_hi;
4379          mad->opsel = opsel;
4380          mad->definitions[0] = add_instr->definitions[0];
4381          mad->definitions[0].setPrecise(add_instr->definitions[0].isPrecise() ||
4382                                         mul_instr->definitions[0].isPrecise());
4383          mad->pass_flags = add_instr->pass_flags;
4384
4385          instr = std::move(mad);
4386
4387          /* mark this ssa_def to be re-checked for profitability and literals */
4388          ctx.mad_infos.emplace_back(std::move(add_instr), mul_instr->definitions[0].tempId());
4389          ctx.info[instr->definitions[0].tempId()].set_mad(ctx.mad_infos.size() - 1);
4390          return;
4391       }
4392    }
4393    /* v_mul_f32(v_cndmask_b32(0, 1.0, cond), a) -> v_cndmask_b32(0, a, cond) */
4394    else if (((instr->opcode == aco_opcode::v_mul_f32 &&
4395               !ctx.fp_mode.preserve_signed_zero_inf_nan32) ||
4396              instr->opcode == aco_opcode::v_mul_legacy_f32) &&
4397             !instr->usesModifiers() && !ctx.fp_mode.must_flush_denorms32) {
4398       for (unsigned i = 0; i < 2; i++) {
4399          if (instr->operands[i].isTemp() && ctx.info[instr->operands[i].tempId()].is_b2f() &&
4400              ctx.uses[instr->operands[i].tempId()] == 1 && instr->operands[!i].isTemp() &&
4401              instr->operands[!i].getTemp().type() == RegType::vgpr) {
4402             ctx.uses[instr->operands[i].tempId()]--;
4403             ctx.uses[ctx.info[instr->operands[i].tempId()].temp.id()]++;
4404
4405             aco_ptr<VALU_instruction> new_instr{
4406                create_instruction<VALU_instruction>(aco_opcode::v_cndmask_b32, Format::VOP2, 3, 1)};
4407             new_instr->operands[0] = Operand::zero();
4408             new_instr->operands[1] = instr->operands[!i];
4409             new_instr->operands[2] = Operand(ctx.info[instr->operands[i].tempId()].temp);
4410             new_instr->definitions[0] = instr->definitions[0];
4411             new_instr->pass_flags = instr->pass_flags;
4412             instr = std::move(new_instr);
4413             ctx.info[instr->definitions[0].tempId()].label = 0;
4414             return;
4415          }
4416       }
4417    } else if (instr->opcode == aco_opcode::v_or_b32 && ctx.program->gfx_level >= GFX9) {
4418       if (combine_three_valu_op(ctx, instr, aco_opcode::s_or_b32, aco_opcode::v_or3_b32, "012",
4419                                 1 | 2)) {
4420       } else if (combine_three_valu_op(ctx, instr, aco_opcode::v_or_b32, aco_opcode::v_or3_b32,
4421                                        "012", 1 | 2)) {
4422       } else if (combine_add_or_then_and_lshl(ctx, instr)) {
4423       } else if (combine_v_andor_not(ctx, instr)) {
4424       }
4425    } else if (instr->opcode == aco_opcode::v_xor_b32 && ctx.program->gfx_level >= GFX10) {
4426       if (combine_three_valu_op(ctx, instr, aco_opcode::v_xor_b32, aco_opcode::v_xor3_b32, "012",
4427                                 1 | 2)) {
4428       } else if (combine_three_valu_op(ctx, instr, aco_opcode::s_xor_b32, aco_opcode::v_xor3_b32,
4429                                        "012", 1 | 2)) {
4430       } else if (combine_xor_not(ctx, instr)) {
4431       }
4432    } else if (instr->opcode == aco_opcode::v_not_b32 && ctx.program->gfx_level >= GFX10) {
4433       combine_not_xor(ctx, instr);
4434    } else if (instr->opcode == aco_opcode::v_add_u16) {
4435       combine_three_valu_op(
4436          ctx, instr, aco_opcode::v_mul_lo_u16,
4437          ctx.program->gfx_level == GFX8 ? aco_opcode::v_mad_legacy_u16 : aco_opcode::v_mad_u16,
4438          "120", 1 | 2);
4439    } else if (instr->opcode == aco_opcode::v_add_u16_e64) {
4440       combine_three_valu_op(ctx, instr, aco_opcode::v_mul_lo_u16_e64, aco_opcode::v_mad_u16, "120",
4441                             1 | 2);
4442    } else if (instr->opcode == aco_opcode::v_add_u32) {
4443       if (combine_add_sub_b2i(ctx, instr, aco_opcode::v_addc_co_u32, 1 | 2)) {
4444       } else if (combine_add_bcnt(ctx, instr)) {
4445       } else if (combine_three_valu_op(ctx, instr, aco_opcode::v_mul_u32_u24,
4446                                        aco_opcode::v_mad_u32_u24, "120", 1 | 2)) {
4447       } else if (ctx.program->gfx_level >= GFX9 && !instr->usesModifiers()) {
4448          if (combine_three_valu_op(ctx, instr, aco_opcode::s_xor_b32, aco_opcode::v_xad_u32, "120",
4449                                    1 | 2)) {
4450          } else if (combine_three_valu_op(ctx, instr, aco_opcode::v_xor_b32, aco_opcode::v_xad_u32,
4451                                           "120", 1 | 2)) {
4452          } else if (combine_three_valu_op(ctx, instr, aco_opcode::s_add_i32, aco_opcode::v_add3_u32,
4453                                           "012", 1 | 2)) {
4454          } else if (combine_three_valu_op(ctx, instr, aco_opcode::s_add_u32, aco_opcode::v_add3_u32,
4455                                           "012", 1 | 2)) {
4456          } else if (combine_three_valu_op(ctx, instr, aco_opcode::v_add_u32, aco_opcode::v_add3_u32,
4457                                           "012", 1 | 2)) {
4458          } else if (combine_add_or_then_and_lshl(ctx, instr)) {
4459          }
4460       }
4461    } else if (instr->opcode == aco_opcode::v_add_co_u32 ||
4462               instr->opcode == aco_opcode::v_add_co_u32_e64) {
4463       bool carry_out = ctx.uses[instr->definitions[1].tempId()] > 0;
4464       if (combine_add_sub_b2i(ctx, instr, aco_opcode::v_addc_co_u32, 1 | 2)) {
4465       } else if (!carry_out && combine_add_bcnt(ctx, instr)) {
4466       } else if (!carry_out && combine_three_valu_op(ctx, instr, aco_opcode::v_mul_u32_u24,
4467                                                      aco_opcode::v_mad_u32_u24, "120", 1 | 2)) {
4468       } else if (!carry_out && combine_add_lshl(ctx, instr, false)) {
4469       }
4470    } else if (instr->opcode == aco_opcode::v_sub_u32 || instr->opcode == aco_opcode::v_sub_co_u32 ||
4471               instr->opcode == aco_opcode::v_sub_co_u32_e64) {
4472       bool carry_out =
4473          instr->opcode != aco_opcode::v_sub_u32 && ctx.uses[instr->definitions[1].tempId()] > 0;
4474       if (combine_add_sub_b2i(ctx, instr, aco_opcode::v_subbrev_co_u32, 2)) {
4475       } else if (!carry_out && combine_add_lshl(ctx, instr, true)) {
4476       }
4477    } else if (instr->opcode == aco_opcode::v_subrev_u32 ||
4478               instr->opcode == aco_opcode::v_subrev_co_u32 ||
4479               instr->opcode == aco_opcode::v_subrev_co_u32_e64) {
4480       combine_add_sub_b2i(ctx, instr, aco_opcode::v_subbrev_co_u32, 1);
4481    } else if (instr->opcode == aco_opcode::v_lshlrev_b32 && ctx.program->gfx_level >= GFX9) {
4482       combine_three_valu_op(ctx, instr, aco_opcode::v_add_u32, aco_opcode::v_add_lshl_u32, "120",
4483                             2);
4484    } else if ((instr->opcode == aco_opcode::s_add_u32 || instr->opcode == aco_opcode::s_add_i32) &&
4485               ctx.program->gfx_level >= GFX9) {
4486       combine_salu_lshl_add(ctx, instr);
4487    } else if (instr->opcode == aco_opcode::s_not_b32 || instr->opcode == aco_opcode::s_not_b64) {
4488       if (!combine_salu_not_bitwise(ctx, instr))
4489          combine_inverse_comparison(ctx, instr);
4490    } else if (instr->opcode == aco_opcode::s_and_b32 || instr->opcode == aco_opcode::s_or_b32 ||
4491               instr->opcode == aco_opcode::s_and_b64 || instr->opcode == aco_opcode::s_or_b64) {
4492       if (combine_ordering_test(ctx, instr)) {
4493       } else if (combine_comparison_ordering(ctx, instr)) {
4494       } else if (combine_constant_comparison_ordering(ctx, instr)) {
4495       } else if (combine_salu_n2(ctx, instr)) {
4496       }
4497    } else if (instr->opcode == aco_opcode::s_abs_i32) {
4498       combine_sabsdiff(ctx, instr);
4499    } else if (instr->opcode == aco_opcode::v_and_b32) {
4500       if (combine_and_subbrev(ctx, instr)) {
4501       } else if (combine_v_andor_not(ctx, instr)) {
4502       }
4503    } else if (instr->opcode == aco_opcode::v_fma_f32 || instr->opcode == aco_opcode::v_fma_f16) {
4504       /* set existing v_fma_f32 with label_mad so we can create v_fmamk_f32/v_fmaak_f32.
4505        * since ctx.uses[mad_info::mul_temp_id] is always 0, we don't have to worry about
4506        * select_instruction() using mad_info::add_instr.
4507        */
4508       ctx.mad_infos.emplace_back(nullptr, 0);
4509       ctx.info[instr->definitions[0].tempId()].set_mad(ctx.mad_infos.size() - 1);
4510    } else if (instr->opcode == aco_opcode::v_med3_f32 || instr->opcode == aco_opcode::v_med3_f16) {
4511       unsigned idx;
4512       if (detect_clamp(instr.get(), &idx)) {
4513          instr->format = asVOP3(Format::VOP2);
4514          instr->operands[0] = instr->operands[idx];
4515          instr->operands[1] = Operand::zero();
4516          instr->opcode =
4517             instr->opcode == aco_opcode::v_med3_f32 ? aco_opcode::v_add_f32 : aco_opcode::v_add_f16;
4518          instr->valu().clamp = true;
4519          instr->valu().abs = (uint8_t)instr->valu().abs[idx];
4520          instr->valu().neg = (uint8_t)instr->valu().neg[idx];
4521          instr->operands.pop_back();
4522       }
4523    } else {
4524       aco_opcode min, max, min3, max3, med3, minmax;
4525       bool some_gfx9_only;
4526       if (get_minmax_info(instr->opcode, &min, &max, &min3, &max3, &med3, &minmax,
4527                           &some_gfx9_only) &&
4528           (!some_gfx9_only || ctx.program->gfx_level >= GFX9)) {
4529          if (combine_minmax(ctx, instr, instr->opcode == min ? max : min,
4530                             instr->opcode == min ? min3 : max3, minmax)) {
4531          } else {
4532             combine_clamp(ctx, instr, min, max, med3);
4533          }
4534       }
4535    }
4536 }
4537
4538 bool
4539 to_uniform_bool_instr(opt_ctx& ctx, aco_ptr<Instruction>& instr)
4540 {
4541    /* Check every operand to make sure they are suitable. */
4542    for (Operand& op : instr->operands) {
4543       if (!op.isTemp())
4544          return false;
4545       if (!ctx.info[op.tempId()].is_uniform_bool() && !ctx.info[op.tempId()].is_uniform_bitwise())
4546          return false;
4547    }
4548
4549    switch (instr->opcode) {
4550    case aco_opcode::s_and_b32:
4551    case aco_opcode::s_and_b64: instr->opcode = aco_opcode::s_and_b32; break;
4552    case aco_opcode::s_or_b32:
4553    case aco_opcode::s_or_b64: instr->opcode = aco_opcode::s_or_b32; break;
4554    case aco_opcode::s_xor_b32:
4555    case aco_opcode::s_xor_b64: instr->opcode = aco_opcode::s_absdiff_i32; break;
4556    default:
4557       /* Don't transform other instructions. They are very unlikely to appear here. */
4558       return false;
4559    }
4560
4561    for (Operand& op : instr->operands) {
4562       ctx.uses[op.tempId()]--;
4563
4564       if (ctx.info[op.tempId()].is_uniform_bool()) {
4565          /* Just use the uniform boolean temp. */
4566          op.setTemp(ctx.info[op.tempId()].temp);
4567       } else if (ctx.info[op.tempId()].is_uniform_bitwise()) {
4568          /* Use the SCC definition of the predecessor instruction.
4569           * This allows the predecessor to get picked up by the same optimization (if it has no
4570           * divergent users), and it also makes sure that the current instruction will keep working
4571           * even if the predecessor won't be transformed.
4572           */
4573          Instruction* pred_instr = ctx.info[op.tempId()].instr;
4574          assert(pred_instr->definitions.size() >= 2);
4575          assert(pred_instr->definitions[1].isFixed() &&
4576                 pred_instr->definitions[1].physReg() == scc);
4577          op.setTemp(pred_instr->definitions[1].getTemp());
4578       } else {
4579          unreachable("Invalid operand on uniform bitwise instruction.");
4580       }
4581
4582       ctx.uses[op.tempId()]++;
4583    }
4584
4585    instr->definitions[0].setTemp(Temp(instr->definitions[0].tempId(), s1));
4586    assert(instr->operands[0].regClass() == s1);
4587    assert(instr->operands[1].regClass() == s1);
4588    return true;
4589 }
4590
4591 void
4592 select_instruction(opt_ctx& ctx, aco_ptr<Instruction>& instr)
4593 {
4594    const uint32_t threshold = 4;
4595
4596    if (is_dead(ctx.uses, instr.get())) {
4597       instr.reset();
4598       return;
4599    }
4600
4601    /* convert split_vector into a copy or extract_vector if only one definition is ever used */
4602    if (instr->opcode == aco_opcode::p_split_vector) {
4603       unsigned num_used = 0;
4604       unsigned idx = 0;
4605       unsigned split_offset = 0;
4606       for (unsigned i = 0, offset = 0; i < instr->definitions.size();
4607            offset += instr->definitions[i++].bytes()) {
4608          if (ctx.uses[instr->definitions[i].tempId()]) {
4609             num_used++;
4610             idx = i;
4611             split_offset = offset;
4612          }
4613       }
4614       bool done = false;
4615       if (num_used == 1 && ctx.info[instr->operands[0].tempId()].is_vec() &&
4616           ctx.uses[instr->operands[0].tempId()] == 1) {
4617          Instruction* vec = ctx.info[instr->operands[0].tempId()].instr;
4618
4619          unsigned off = 0;
4620          Operand op;
4621          for (Operand& vec_op : vec->operands) {
4622             if (off == split_offset) {
4623                op = vec_op;
4624                break;
4625             }
4626             off += vec_op.bytes();
4627          }
4628          if (off != instr->operands[0].bytes() && op.bytes() == instr->definitions[idx].bytes()) {
4629             ctx.uses[instr->operands[0].tempId()]--;
4630             for (Operand& vec_op : vec->operands) {
4631                if (vec_op.isTemp())
4632                   ctx.uses[vec_op.tempId()]--;
4633             }
4634             if (op.isTemp())
4635                ctx.uses[op.tempId()]++;
4636
4637             aco_ptr<Pseudo_instruction> extract{create_instruction<Pseudo_instruction>(
4638                aco_opcode::p_create_vector, Format::PSEUDO, 1, 1)};
4639             extract->operands[0] = op;
4640             extract->definitions[0] = instr->definitions[idx];
4641             instr = std::move(extract);
4642
4643             done = true;
4644          }
4645       }
4646
4647       if (!done && num_used == 1 &&
4648           instr->operands[0].bytes() % instr->definitions[idx].bytes() == 0 &&
4649           split_offset % instr->definitions[idx].bytes() == 0) {
4650          aco_ptr<Pseudo_instruction> extract{create_instruction<Pseudo_instruction>(
4651             aco_opcode::p_extract_vector, Format::PSEUDO, 2, 1)};
4652          extract->operands[0] = instr->operands[0];
4653          extract->operands[1] =
4654             Operand::c32((uint32_t)split_offset / instr->definitions[idx].bytes());
4655          extract->definitions[0] = instr->definitions[idx];
4656          instr = std::move(extract);
4657       }
4658    }
4659
4660    mad_info* mad_info = NULL;
4661    if (!instr->definitions.empty() && ctx.info[instr->definitions[0].tempId()].is_mad()) {
4662       mad_info = &ctx.mad_infos[ctx.info[instr->definitions[0].tempId()].val];
4663       /* re-check mad instructions */
4664       if (ctx.uses[mad_info->mul_temp_id] && mad_info->add_instr) {
4665          ctx.uses[mad_info->mul_temp_id]++;
4666          if (instr->operands[0].isTemp())
4667             ctx.uses[instr->operands[0].tempId()]--;
4668          if (instr->operands[1].isTemp())
4669             ctx.uses[instr->operands[1].tempId()]--;
4670          instr.swap(mad_info->add_instr);
4671          mad_info = NULL;
4672       }
4673       /* check literals */
4674       else if (!instr->isDPP() && !instr->isVOP3P() && instr->opcode != aco_opcode::v_fma_f64 &&
4675                instr->opcode != aco_opcode::v_mad_legacy_f32 &&
4676                instr->opcode != aco_opcode::v_fma_legacy_f32) {
4677          /* FMA can only take literals on GFX10+ */
4678          if ((instr->opcode == aco_opcode::v_fma_f32 || instr->opcode == aco_opcode::v_fma_f16) &&
4679              ctx.program->gfx_level < GFX10)
4680             return;
4681          /* There are no v_fmaak_legacy_f16/v_fmamk_legacy_f16 and on chips where VOP3 can take
4682           * literals (GFX10+), these instructions don't exist.
4683           */
4684          if (instr->opcode == aco_opcode::v_fma_legacy_f16)
4685             return;
4686
4687          uint32_t literal_mask = 0;
4688          uint32_t fp16_mask = 0;
4689          uint32_t sgpr_mask = 0;
4690          uint32_t vgpr_mask = 0;
4691          uint32_t literal_uses = UINT32_MAX;
4692          uint32_t literal_value = 0;
4693
4694          /* Iterate in reverse to prefer v_madak/v_fmaak. */
4695          for (int i = 2; i >= 0; i--) {
4696             Operand& op = instr->operands[i];
4697             if (!op.isTemp())
4698                continue;
4699             if (ctx.info[op.tempId()].is_literal(get_operand_size(instr, i))) {
4700                uint32_t new_literal = ctx.info[op.tempId()].val;
4701                float value = uif(new_literal);
4702                uint16_t fp16_val = _mesa_float_to_half(value);
4703                bool is_denorm = (fp16_val & 0x7fff) != 0 && (fp16_val & 0x7fff) <= 0x3ff;
4704                if (_mesa_half_to_float(fp16_val) == value &&
4705                    (!is_denorm || (ctx.fp_mode.denorm16_64 & fp_denorm_keep_in)))
4706                   fp16_mask |= 1 << i;
4707
4708                if (!literal_mask || literal_value == new_literal) {
4709                   literal_value = new_literal;
4710                   literal_uses = MIN2(literal_uses, ctx.uses[op.tempId()]);
4711                   literal_mask |= 1 << i;
4712                   continue;
4713                }
4714             }
4715             sgpr_mask |= op.isOfType(RegType::sgpr) << i;
4716             vgpr_mask |= op.isOfType(RegType::vgpr) << i;
4717          }
4718
4719          /* The constant bus limitations before GFX10 disallows SGPRs. */
4720          if (sgpr_mask && ctx.program->gfx_level < GFX10)
4721             literal_mask = 0;
4722
4723          /* Encoding needs a vgpr. */
4724          if (!vgpr_mask)
4725             literal_mask = 0;
4726
4727          /* v_madmk/v_fmamk needs a vgpr in the third source. */
4728          if (!(literal_mask & 0b100) && !(vgpr_mask & 0b100))
4729             literal_mask = 0;
4730
4731          /* opsel with GFX11+ is the only modifier supported by fmamk/fmaak*/
4732          if (instr->valu().abs || instr->valu().neg || instr->valu().omod || instr->valu().clamp ||
4733              (instr->valu().opsel && ctx.program->gfx_level < GFX11))
4734             literal_mask = 0;
4735
4736          if (instr->valu().opsel & ~vgpr_mask)
4737             literal_mask = 0;
4738
4739          /* We can't use three unique fp16 literals */
4740          if (fp16_mask == 0b111)
4741             fp16_mask = 0b11;
4742
4743          if ((instr->opcode == aco_opcode::v_fma_f32 ||
4744               (instr->opcode == aco_opcode::v_mad_f32 && !instr->definitions[0].isPrecise())) &&
4745              !instr->valu().omod && ctx.program->gfx_level >= GFX10 &&
4746              util_bitcount(fp16_mask) > std::max<uint32_t>(util_bitcount(literal_mask), 1)) {
4747             assert(ctx.program->dev.fused_mad_mix);
4748             u_foreach_bit (i, fp16_mask)
4749                ctx.uses[instr->operands[i].tempId()]--;
4750             mad_info->fp16_mask = fp16_mask;
4751             return;
4752          }
4753
4754          /* Limit the number of literals to apply to not increase the code
4755           * size too much, but always apply literals for v_mad->v_madak
4756           * because both instructions are 64-bit and this doesn't increase
4757           * code size.
4758           * TODO: try to apply the literals earlier to lower the number of
4759           * uses below threshold
4760           */
4761          if (literal_mask && (literal_uses < threshold || (literal_mask & 0b100))) {
4762             u_foreach_bit (i, literal_mask)
4763                ctx.uses[instr->operands[i].tempId()]--;
4764             mad_info->literal_mask = literal_mask;
4765             return;
4766          }
4767       }
4768    }
4769
4770    /* Mark SCC needed, so the uniform boolean transformation won't swap the definitions
4771     * when it isn't beneficial */
4772    if (instr->isBranch() && instr->operands.size() && instr->operands[0].isTemp() &&
4773        instr->operands[0].isFixed() && instr->operands[0].physReg() == scc) {
4774       ctx.info[instr->operands[0].tempId()].set_scc_needed();
4775       return;
4776    } else if ((instr->opcode == aco_opcode::s_cselect_b64 ||
4777                instr->opcode == aco_opcode::s_cselect_b32) &&
4778               instr->operands[2].isTemp()) {
4779       ctx.info[instr->operands[2].tempId()].set_scc_needed();
4780    }
4781
4782    /* check for literals */
4783    if (!instr->isSALU() && !instr->isVALU())
4784       return;
4785
4786    /* Transform uniform bitwise boolean operations to 32-bit when there are no divergent uses. */
4787    if (instr->definitions.size() && ctx.uses[instr->definitions[0].tempId()] == 0 &&
4788        ctx.info[instr->definitions[0].tempId()].is_uniform_bitwise()) {
4789       bool transform_done = to_uniform_bool_instr(ctx, instr);
4790
4791       if (transform_done && !ctx.info[instr->definitions[1].tempId()].is_scc_needed()) {
4792          /* Swap the two definition IDs in order to avoid overusing the SCC.
4793           * This reduces extra moves generated by RA. */
4794          uint32_t def0_id = instr->definitions[0].getTemp().id();
4795          uint32_t def1_id = instr->definitions[1].getTemp().id();
4796          instr->definitions[0].setTemp(Temp(def1_id, s1));
4797          instr->definitions[1].setTemp(Temp(def0_id, s1));
4798       }
4799
4800       return;
4801    }
4802
4803    /* This optimization is done late in order to be able to apply otherwise
4804     * unsafe optimizations such as the inverse comparison optimization.
4805     */
4806    if (instr->opcode == aco_opcode::s_and_b32 || instr->opcode == aco_opcode::s_and_b64) {
4807       if (instr->operands[0].isTemp() && fixed_to_exec(instr->operands[1]) &&
4808           ctx.uses[instr->operands[0].tempId()] == 1 &&
4809           ctx.uses[instr->definitions[1].tempId()] == 0 &&
4810           can_eliminate_and_exec(ctx, instr->operands[0].getTemp(), instr->pass_flags)) {
4811          ctx.uses[instr->operands[0].tempId()]--;
4812          ctx.info[instr->operands[0].tempId()].instr->definitions[0].setTemp(
4813             instr->definitions[0].getTemp());
4814          instr.reset();
4815          return;
4816       }
4817    }
4818
4819    /* Combine DPP copies into VALU. This should be done after creating MAD/FMA. */
4820    if (instr->isVALU() && !instr->isDPP()) {
4821       for (unsigned i = 0; i < instr->operands.size(); i++) {
4822          if (!instr->operands[i].isTemp())
4823             continue;
4824          ssa_info info = ctx.info[instr->operands[i].tempId()];
4825
4826          if (!info.is_dpp() || info.instr->pass_flags != instr->pass_flags)
4827             continue;
4828
4829          /* We won't eliminate the DPP mov if the operand is used twice */
4830          bool op_used_twice = false;
4831          for (unsigned j = 0; j < instr->operands.size(); j++)
4832             op_used_twice |= i != j && instr->operands[i] == instr->operands[j];
4833          if (op_used_twice)
4834             continue;
4835
4836          if (i != 0) {
4837             if (!can_swap_operands(instr, &instr->opcode, 0, i))
4838                continue;
4839             instr->valu().swapOperands(0, i);
4840          }
4841
4842          if (!can_use_DPP(ctx.program->gfx_level, instr, info.is_dpp8()))
4843             continue;
4844
4845          bool dpp8 = info.is_dpp8();
4846          bool input_mods = can_use_input_modifiers(ctx.program->gfx_level, instr->opcode, 0) &&
4847                            get_operand_size(instr, 0) == 32;
4848          bool mov_uses_mods = info.instr->valu().neg[0] || info.instr->valu().abs[0];
4849          if (((dpp8 && ctx.program->gfx_level < GFX11) || !input_mods) && mov_uses_mods)
4850             continue;
4851
4852          convert_to_DPP(ctx.program->gfx_level, instr, dpp8);
4853
4854          if (dpp8) {
4855             DPP8_instruction* dpp = &instr->dpp8();
4856             for (unsigned j = 0; j < 8; ++j)
4857                dpp->lane_sel[j] = info.instr->dpp8().lane_sel[j];
4858             if (mov_uses_mods)
4859                instr->format = asVOP3(instr->format);
4860          } else {
4861             DPP16_instruction* dpp = &instr->dpp16();
4862             dpp->dpp_ctrl = info.instr->dpp16().dpp_ctrl;
4863             dpp->bound_ctrl = info.instr->dpp16().bound_ctrl;
4864          }
4865
4866          instr->valu().neg[0] ^= info.instr->valu().neg[0] && !instr->valu().abs[0];
4867          instr->valu().abs[0] |= info.instr->valu().abs[0];
4868
4869          if (--ctx.uses[info.instr->definitions[0].tempId()])
4870             ctx.uses[info.instr->operands[0].tempId()]++;
4871          instr->operands[0].setTemp(info.instr->operands[0].getTemp());
4872          break;
4873       }
4874    }
4875
4876    /* Use v_fma_mix for f2f32/f2f16 if it has higher throughput.
4877     * Do this late to not disturb other optimizations.
4878     */
4879    if ((instr->opcode == aco_opcode::v_cvt_f32_f16 || instr->opcode == aco_opcode::v_cvt_f16_f32) &&
4880        ctx.program->gfx_level >= GFX11 && ctx.program->wave_size == 64 && !instr->valu().omod &&
4881        !instr->isDPP()) {
4882       bool is_f2f16 = instr->opcode == aco_opcode::v_cvt_f16_f32;
4883       Instruction* fma = create_instruction<VALU_instruction>(
4884          is_f2f16 ? aco_opcode::v_fma_mixlo_f16 : aco_opcode::v_fma_mix_f32, Format::VOP3P, 3, 1);
4885       fma->definitions[0] = instr->definitions[0];
4886       fma->operands[0] = instr->operands[0];
4887       fma->valu().opsel_hi[0] = !is_f2f16;
4888       fma->valu().opsel_lo[0] = instr->valu().opsel[0];
4889       fma->valu().clamp = instr->valu().clamp;
4890       fma->valu().abs[0] = instr->valu().abs[0];
4891       fma->valu().neg[0] = instr->valu().neg[0];
4892       fma->operands[1] = Operand::c32(fui(1.0f));
4893       fma->operands[2] = Operand::zero();
4894       /* fma_mix is only dual issued if dst and acc type match */
4895       fma->valu().opsel_hi[2] = is_f2f16;
4896       fma->valu().neg[2] = true;
4897       instr.reset(fma);
4898       ctx.info[instr->definitions[0].tempId()].label = 0;
4899    }
4900
4901    if (instr->isSDWA() || (instr->isVOP3() && ctx.program->gfx_level < GFX10) ||
4902        (instr->isVOP3P() && ctx.program->gfx_level < GFX10))
4903       return; /* some encodings can't ever take literals */
4904
4905    /* we do not apply the literals yet as we don't know if it is profitable */
4906    Operand current_literal(s1);
4907
4908    unsigned literal_id = 0;
4909    unsigned literal_uses = UINT32_MAX;
4910    Operand literal(s1);
4911    unsigned num_operands = 1;
4912    if (instr->isSALU() || (ctx.program->gfx_level >= GFX10 &&
4913                            (can_use_VOP3(ctx, instr) || instr->isVOP3P()) && !instr->isDPP()))
4914       num_operands = instr->operands.size();
4915    /* catch VOP2 with a 3rd SGPR operand (e.g. v_cndmask_b32, v_addc_co_u32) */
4916    else if (instr->isVALU() && instr->operands.size() >= 3)
4917       return;
4918
4919    unsigned sgpr_ids[2] = {0, 0};
4920    bool is_literal_sgpr = false;
4921    uint32_t mask = 0;
4922
4923    /* choose a literal to apply */
4924    for (unsigned i = 0; i < num_operands; i++) {
4925       Operand op = instr->operands[i];
4926       unsigned bits = get_operand_size(instr, i);
4927
4928       if (instr->isVALU() && op.isTemp() && op.getTemp().type() == RegType::sgpr &&
4929           op.tempId() != sgpr_ids[0])
4930          sgpr_ids[!!sgpr_ids[0]] = op.tempId();
4931
4932       if (op.isLiteral()) {
4933          current_literal = op;
4934          continue;
4935       } else if (!op.isTemp() || !ctx.info[op.tempId()].is_literal(bits)) {
4936          continue;
4937       }
4938
4939       if (!alu_can_accept_constant(instr, i))
4940          continue;
4941
4942       if (ctx.uses[op.tempId()] < literal_uses) {
4943          is_literal_sgpr = op.getTemp().type() == RegType::sgpr;
4944          mask = 0;
4945          literal = Operand::c32(ctx.info[op.tempId()].val);
4946          literal_uses = ctx.uses[op.tempId()];
4947          literal_id = op.tempId();
4948       }
4949
4950       mask |= (op.tempId() == literal_id) << i;
4951    }
4952
4953    /* don't go over the constant bus limit */
4954    bool is_shift64 = instr->opcode == aco_opcode::v_lshlrev_b64 ||
4955                      instr->opcode == aco_opcode::v_lshrrev_b64 ||
4956                      instr->opcode == aco_opcode::v_ashrrev_i64;
4957    unsigned const_bus_limit = instr->isVALU() ? 1 : UINT32_MAX;
4958    if (ctx.program->gfx_level >= GFX10 && !is_shift64)
4959       const_bus_limit = 2;
4960
4961    unsigned num_sgprs = !!sgpr_ids[0] + !!sgpr_ids[1];
4962    if (num_sgprs == const_bus_limit && !is_literal_sgpr)
4963       return;
4964
4965    if (literal_id && literal_uses < threshold &&
4966        (current_literal.isUndefined() ||
4967         (current_literal.size() == literal.size() &&
4968          current_literal.constantValue() == literal.constantValue()))) {
4969       /* mark the literal to be applied */
4970       while (mask) {
4971          unsigned i = u_bit_scan(&mask);
4972          if (instr->operands[i].isTemp() && instr->operands[i].tempId() == literal_id)
4973             ctx.uses[instr->operands[i].tempId()]--;
4974       }
4975    }
4976 }
4977
4978 static aco_opcode
4979 sopk_opcode_for_sopc(aco_opcode opcode)
4980 {
4981 #define CTOK(op)                                                                                   \
4982    case aco_opcode::s_cmp_##op##_i32: return aco_opcode::s_cmpk_##op##_i32;                        \
4983    case aco_opcode::s_cmp_##op##_u32: return aco_opcode::s_cmpk_##op##_u32;
4984    switch (opcode) {
4985       CTOK(eq)
4986       CTOK(lg)
4987       CTOK(gt)
4988       CTOK(ge)
4989       CTOK(lt)
4990       CTOK(le)
4991    default: return aco_opcode::num_opcodes;
4992    }
4993 #undef CTOK
4994 }
4995
4996 static bool
4997 sopc_is_signed(aco_opcode opcode)
4998 {
4999 #define SOPC(op)                                                                                   \
5000    case aco_opcode::s_cmp_##op##_i32: return true;                                                 \
5001    case aco_opcode::s_cmp_##op##_u32: return false;
5002    switch (opcode) {
5003       SOPC(eq)
5004       SOPC(lg)
5005       SOPC(gt)
5006       SOPC(ge)
5007       SOPC(lt)
5008       SOPC(le)
5009    default: unreachable("Not a valid SOPC instruction.");
5010    }
5011 #undef SOPC
5012 }
5013
5014 static aco_opcode
5015 sopc_32_swapped(aco_opcode opcode)
5016 {
5017 #define SOPC(op1, op2)                                                                             \
5018    case aco_opcode::s_cmp_##op1##_i32: return aco_opcode::s_cmp_##op2##_i32;                       \
5019    case aco_opcode::s_cmp_##op1##_u32: return aco_opcode::s_cmp_##op2##_u32;
5020    switch (opcode) {
5021       SOPC(eq, eq)
5022       SOPC(lg, lg)
5023       SOPC(gt, lt)
5024       SOPC(ge, le)
5025       SOPC(lt, gt)
5026       SOPC(le, ge)
5027    default: return aco_opcode::num_opcodes;
5028    }
5029 #undef SOPC
5030 }
5031
5032 static void
5033 try_convert_sopc_to_sopk(aco_ptr<Instruction>& instr)
5034 {
5035    if (sopk_opcode_for_sopc(instr->opcode) == aco_opcode::num_opcodes)
5036       return;
5037
5038    if (instr->operands[0].isLiteral()) {
5039       std::swap(instr->operands[0], instr->operands[1]);
5040       instr->opcode = sopc_32_swapped(instr->opcode);
5041    }
5042
5043    if (!instr->operands[1].isLiteral())
5044       return;
5045
5046    if (instr->operands[0].isFixed() && instr->operands[0].physReg() >= 128)
5047       return;
5048
5049    uint32_t value = instr->operands[1].constantValue();
5050
5051    const uint32_t i16_mask = 0xffff8000u;
5052
5053    bool value_is_i16 = (value & i16_mask) == 0 || (value & i16_mask) == i16_mask;
5054    bool value_is_u16 = !(value & 0xffff0000u);
5055
5056    if (!value_is_i16 && !value_is_u16)
5057       return;
5058
5059    if (!value_is_i16 && sopc_is_signed(instr->opcode)) {
5060       if (instr->opcode == aco_opcode::s_cmp_lg_i32)
5061          instr->opcode = aco_opcode::s_cmp_lg_u32;
5062       else if (instr->opcode == aco_opcode::s_cmp_eq_i32)
5063          instr->opcode = aco_opcode::s_cmp_eq_u32;
5064       else
5065          return;
5066    } else if (!value_is_u16 && !sopc_is_signed(instr->opcode)) {
5067       if (instr->opcode == aco_opcode::s_cmp_lg_u32)
5068          instr->opcode = aco_opcode::s_cmp_lg_i32;
5069       else if (instr->opcode == aco_opcode::s_cmp_eq_u32)
5070          instr->opcode = aco_opcode::s_cmp_eq_i32;
5071       else
5072          return;
5073    }
5074
5075    static_assert(sizeof(SOPK_instruction) <= sizeof(SOPC_instruction),
5076                  "Invalid direct instruction cast.");
5077    instr->format = Format::SOPK;
5078    SOPK_instruction* instr_sopk = &instr->sopk();
5079
5080    instr_sopk->imm = instr_sopk->operands[1].constantValue() & 0xffff;
5081    instr_sopk->opcode = sopk_opcode_for_sopc(instr_sopk->opcode);
5082    instr_sopk->operands.pop_back();
5083 }
5084
5085 static void
5086 unswizzle_vop3p_literals(opt_ctx& ctx, aco_ptr<Instruction>& instr)
5087 {
5088    /* This opt is only beneficial for v_pk_fma_f16 because we can use v_pk_fmac_f16 if the
5089     * instruction doesn't use swizzles. */
5090    if (instr->opcode != aco_opcode::v_pk_fma_f16)
5091       return;
5092
5093    VALU_instruction& vop3p = instr->valu();
5094
5095    unsigned literal_swizzle = ~0u;
5096    for (unsigned i = 0; i < instr->operands.size(); i++) {
5097       if (!instr->operands[i].isLiteral())
5098          continue;
5099       unsigned new_swizzle = vop3p.opsel_lo[i] | (vop3p.opsel_hi[i] << 1);
5100       if (literal_swizzle != ~0u && new_swizzle != literal_swizzle)
5101          return; /* Literal swizzles conflict. */
5102       literal_swizzle = new_swizzle;
5103    }
5104
5105    if (literal_swizzle == 0b10 || literal_swizzle == ~0u)
5106       return; /* already unswizzled */
5107
5108    for (unsigned i = 0; i < instr->operands.size(); i++) {
5109       if (!instr->operands[i].isLiteral())
5110          continue;
5111       uint32_t literal = instr->operands[i].constantValue();
5112       literal = (literal >> (16 * (literal_swizzle & 0x1)) & 0xffff) |
5113                 (literal >> (8 * (literal_swizzle & 0x2)) << 16);
5114       instr->operands[i] = Operand::literal32(literal);
5115       vop3p.opsel_lo[i] = false;
5116       vop3p.opsel_hi[i] = true;
5117    }
5118 }
5119
5120 void
5121 apply_literals(opt_ctx& ctx, aco_ptr<Instruction>& instr)
5122 {
5123    /* Cleanup Dead Instructions */
5124    if (!instr)
5125       return;
5126
5127    /* apply literals on MAD */
5128    if (!instr->definitions.empty() && ctx.info[instr->definitions[0].tempId()].is_mad()) {
5129       mad_info* info = &ctx.mad_infos[ctx.info[instr->definitions[0].tempId()].val];
5130       const bool madak = (info->literal_mask & 0b100);
5131       bool has_dead_literal = false;
5132       u_foreach_bit (i, info->literal_mask | info->fp16_mask)
5133          has_dead_literal |= ctx.uses[instr->operands[i].tempId()] == 0;
5134
5135       if (has_dead_literal && info->fp16_mask) {
5136          instr->format = Format::VOP3P;
5137          instr->opcode = aco_opcode::v_fma_mix_f32;
5138
5139          uint32_t literal = 0;
5140          bool second = false;
5141          u_foreach_bit (i, info->fp16_mask) {
5142             float value = uif(ctx.info[instr->operands[i].tempId()].val);
5143             literal |= _mesa_float_to_half(value) << (second * 16);
5144             instr->valu().opsel_lo[i] = second;
5145             instr->valu().opsel_hi[i] = true;
5146             second = true;
5147          }
5148
5149          for (unsigned i = 0; i < 3; i++) {
5150             if (info->fp16_mask & (1 << i))
5151                instr->operands[i] = Operand::literal32(literal);
5152          }
5153
5154          ctx.instructions.emplace_back(std::move(instr));
5155          return;
5156       }
5157
5158       if (has_dead_literal || madak) {
5159          aco_opcode new_op = madak ? aco_opcode::v_madak_f32 : aco_opcode::v_madmk_f32;
5160          if (instr->opcode == aco_opcode::v_fma_f32)
5161             new_op = madak ? aco_opcode::v_fmaak_f32 : aco_opcode::v_fmamk_f32;
5162          else if (instr->opcode == aco_opcode::v_mad_f16 ||
5163                   instr->opcode == aco_opcode::v_mad_legacy_f16)
5164             new_op = madak ? aco_opcode::v_madak_f16 : aco_opcode::v_madmk_f16;
5165          else if (instr->opcode == aco_opcode::v_fma_f16)
5166             new_op = madak ? aco_opcode::v_fmaak_f16 : aco_opcode::v_fmamk_f16;
5167
5168          uint32_t literal = ctx.info[instr->operands[ffs(info->literal_mask) - 1].tempId()].val;
5169          instr->format = Format::VOP2;
5170          instr->opcode = new_op;
5171          for (unsigned i = 0; i < 3; i++) {
5172             if (info->literal_mask & (1 << i))
5173                instr->operands[i] = Operand::literal32(literal);
5174          }
5175          if (madak) { /* add literal -> madak */
5176             if (!instr->operands[1].isOfType(RegType::vgpr))
5177                instr->valu().swapOperands(0, 1);
5178          } else { /* mul literal -> madmk */
5179             if (!(info->literal_mask & 0b10))
5180                instr->valu().swapOperands(0, 1);
5181             instr->valu().swapOperands(1, 2);
5182          }
5183          ctx.instructions.emplace_back(std::move(instr));
5184          return;
5185       }
5186    }
5187
5188    /* apply literals on other SALU/VALU */
5189    if (instr->isSALU() || instr->isVALU()) {
5190       for (unsigned i = 0; i < instr->operands.size(); i++) {
5191          Operand op = instr->operands[i];
5192          unsigned bits = get_operand_size(instr, i);
5193          if (op.isTemp() && ctx.info[op.tempId()].is_literal(bits) && ctx.uses[op.tempId()] == 0) {
5194             Operand literal = Operand::literal32(ctx.info[op.tempId()].val);
5195             instr->format = withoutDPP(instr->format);
5196             if (instr->isVALU() && i > 0 && instr->format != Format::VOP3P)
5197                instr->format = asVOP3(instr->format);
5198             instr->operands[i] = literal;
5199          }
5200       }
5201    }
5202
5203    if (instr->isSOPC())
5204       try_convert_sopc_to_sopk(instr);
5205
5206    /* allow more s_addk_i32 optimizations if carry isn't used */
5207    if (instr->opcode == aco_opcode::s_add_u32 && ctx.uses[instr->definitions[1].tempId()] == 0 &&
5208        (instr->operands[0].isLiteral() || instr->operands[1].isLiteral()))
5209       instr->opcode = aco_opcode::s_add_i32;
5210
5211    if (instr->isVOP3P())
5212       unswizzle_vop3p_literals(ctx, instr);
5213
5214    ctx.instructions.emplace_back(std::move(instr));
5215 }
5216
5217 void
5218 optimize(Program* program)
5219 {
5220    opt_ctx ctx;
5221    ctx.program = program;
5222    std::vector<ssa_info> info(program->peekAllocationId());
5223    ctx.info = info.data();
5224
5225    /* 1. Bottom-Up DAG pass (forward) to label all ssa-defs */
5226    for (Block& block : program->blocks) {
5227       ctx.fp_mode = block.fp_mode;
5228       for (aco_ptr<Instruction>& instr : block.instructions)
5229          label_instruction(ctx, instr);
5230    }
5231
5232    ctx.uses = dead_code_analysis(program);
5233
5234    /* 2. Combine v_mad, omod, clamp and propagate sgpr on VALU instructions */
5235    for (Block& block : program->blocks) {
5236       ctx.fp_mode = block.fp_mode;
5237       for (aco_ptr<Instruction>& instr : block.instructions)
5238          combine_instruction(ctx, instr);
5239    }
5240
5241    /* 3. Top-Down DAG pass (backward) to select instructions (includes DCE) */
5242    for (auto block_rit = program->blocks.rbegin(); block_rit != program->blocks.rend();
5243         ++block_rit) {
5244       Block* block = &(*block_rit);
5245       ctx.fp_mode = block->fp_mode;
5246       for (auto instr_rit = block->instructions.rbegin(); instr_rit != block->instructions.rend();
5247            ++instr_rit)
5248          select_instruction(ctx, *instr_rit);
5249    }
5250
5251    /* 4. Add literals to instructions */
5252    for (Block& block : program->blocks) {
5253       ctx.instructions.reserve(block.instructions.size());
5254       ctx.fp_mode = block.fp_mode;
5255       for (aco_ptr<Instruction>& instr : block.instructions)
5256          apply_literals(ctx, instr);
5257       block.instructions = std::move(ctx.instructions);
5258    }
5259 }
5260
5261 } // namespace aco