xref: /aosp_15_r20/external/mesa3d/src/intel/compiler/elk/elk_fs_copy_propagation.cpp (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright © 2012 Intel 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 /** @file elk_fs_copy_propagation.cpp
25  *
26  * Support for global copy propagation in two passes: A local pass that does
27  * intra-block copy (and constant) propagation, and a global pass that uses
28  * dataflow analysis on the copies available at the end of each block to re-do
29  * local copy propagation with more copies available.
30  *
31  * See Muchnick's Advanced Compiler Design and Implementation, section
32  * 12.5 (p356).
33  */
34 
35 #include "util/bitset.h"
36 #include "util/u_math.h"
37 #include "util/rb_tree.h"
38 #include "elk_fs.h"
39 #include "elk_fs_live_variables.h"
40 #include "elk_cfg.h"
41 #include "elk_eu.h"
42 
43 using namespace elk;
44 
45 namespace { /* avoid conflict with opt_copy_propagation_elements */
46 struct acp_entry {
47    struct rb_node by_dst;
48    struct rb_node by_src;
49    elk_fs_reg dst;
50    elk_fs_reg src;
51    unsigned global_idx;
52    unsigned size_written;
53    unsigned size_read;
54    enum elk_opcode opcode;
55    bool is_partial_write;
56    bool force_writemask_all;
57 };
58 
59 /**
60  * Compare two acp_entry::src.nr
61  *
62  * This is intended to be used as the comparison function for rb_tree.
63  */
64 static int
cmp_entry_dst_entry_dst(const struct rb_node * a_node,const struct rb_node * b_node)65 cmp_entry_dst_entry_dst(const struct rb_node *a_node, const struct rb_node *b_node)
66 {
67    const struct acp_entry *a_entry =
68       rb_node_data(struct acp_entry, a_node, by_dst);
69 
70    const struct acp_entry *b_entry =
71       rb_node_data(struct acp_entry, b_node, by_dst);
72 
73    return a_entry->dst.nr - b_entry->dst.nr;
74 }
75 
76 static int
cmp_entry_dst_nr(const struct rb_node * a_node,const void * b_key)77 cmp_entry_dst_nr(const struct rb_node *a_node, const void *b_key)
78 {
79    const struct acp_entry *a_entry =
80       rb_node_data(struct acp_entry, a_node, by_dst);
81 
82    return a_entry->dst.nr - (uintptr_t) b_key;
83 }
84 
85 static int
cmp_entry_src_entry_src(const struct rb_node * a_node,const struct rb_node * b_node)86 cmp_entry_src_entry_src(const struct rb_node *a_node, const struct rb_node *b_node)
87 {
88    const struct acp_entry *a_entry =
89       rb_node_data(struct acp_entry, a_node, by_src);
90 
91    const struct acp_entry *b_entry =
92       rb_node_data(struct acp_entry, b_node, by_src);
93 
94    return a_entry->src.nr - b_entry->src.nr;
95 }
96 
97 /**
98  * Compare an acp_entry::src.nr with a raw nr.
99  *
100  * This is intended to be used as the comparison function for rb_tree.
101  */
102 static int
cmp_entry_src_nr(const struct rb_node * a_node,const void * b_key)103 cmp_entry_src_nr(const struct rb_node *a_node, const void *b_key)
104 {
105    const struct acp_entry *a_entry =
106       rb_node_data(struct acp_entry, a_node, by_src);
107 
108    return a_entry->src.nr - (uintptr_t) b_key;
109 }
110 
111 class acp_forward_iterator {
112 public:
acp_forward_iterator(struct rb_node * n,unsigned offset)113    acp_forward_iterator(struct rb_node *n, unsigned offset)
114       : curr(n), next(nullptr), offset(offset)
115    {
116       next = rb_node_next_or_null(curr);
117    }
118 
operator ++()119    acp_forward_iterator &operator++()
120    {
121       curr = next;
122       next = rb_node_next_or_null(curr);
123 
124       return *this;
125    }
126 
operator !=(const acp_forward_iterator & other) const127    bool operator!=(const acp_forward_iterator &other) const
128    {
129       return curr != other.curr;
130    }
131 
operator *() const132    struct acp_entry *operator*() const
133    {
134       /* This open-codes part of rb_node_data. */
135       return curr != NULL ? (struct acp_entry *)(((char *)curr) - offset)
136                           : NULL;
137    }
138 
139 private:
140    struct rb_node *curr;
141    struct rb_node *next;
142    unsigned offset;
143 };
144 
145 struct acp {
146    struct rb_tree by_dst;
147    struct rb_tree by_src;
148 
acp__anon652d27ac0111::acp149    acp()
150    {
151       rb_tree_init(&by_dst);
152       rb_tree_init(&by_src);
153    }
154 
begin__anon652d27ac0111::acp155    acp_forward_iterator begin()
156    {
157       return acp_forward_iterator(rb_tree_first(&by_src),
158                                   rb_tree_offsetof(struct acp_entry, by_src, 0));
159    }
160 
end__anon652d27ac0111::acp161    const acp_forward_iterator end() const
162    {
163       return acp_forward_iterator(nullptr, 0);
164    }
165 
length__anon652d27ac0111::acp166    unsigned length()
167    {
168       unsigned l = 0;
169 
170       for (rb_node *iter = rb_tree_first(&by_src);
171            iter != NULL; iter = rb_node_next(iter))
172          l++;
173 
174       return l;
175    }
176 
add__anon652d27ac0111::acp177    void add(acp_entry *entry)
178    {
179       rb_tree_insert(&by_dst, &entry->by_dst, cmp_entry_dst_entry_dst);
180       rb_tree_insert(&by_src, &entry->by_src, cmp_entry_src_entry_src);
181    }
182 
remove__anon652d27ac0111::acp183    void remove(acp_entry *entry)
184    {
185       rb_tree_remove(&by_dst, &entry->by_dst);
186       rb_tree_remove(&by_src, &entry->by_src);
187    }
188 
find_by_src__anon652d27ac0111::acp189    acp_forward_iterator find_by_src(unsigned nr)
190    {
191       struct rb_node *rbn = rb_tree_search(&by_src,
192                                            (void *)(uintptr_t) nr,
193                                            cmp_entry_src_nr);
194 
195       return acp_forward_iterator(rbn, rb_tree_offsetof(struct acp_entry,
196                                                         by_src, rbn));
197    }
198 
find_by_dst__anon652d27ac0111::acp199    acp_forward_iterator find_by_dst(unsigned nr)
200    {
201       struct rb_node *rbn = rb_tree_search(&by_dst,
202                                            (void *)(uintptr_t) nr,
203                                            cmp_entry_dst_nr);
204 
205       return acp_forward_iterator(rbn, rb_tree_offsetof(struct acp_entry,
206                                                         by_dst, rbn));
207    }
208 };
209 
210 struct block_data {
211    /**
212     * Which entries in the fs_copy_prop_dataflow acp table are live at the
213     * start of this block.  This is the useful output of the analysis, since
214     * it lets us plug those into the local copy propagation on the second
215     * pass.
216     */
217    BITSET_WORD *livein;
218 
219    /**
220     * Which entries in the fs_copy_prop_dataflow acp table are live at the end
221     * of this block.  This is done in initial setup from the per-block acps
222     * returned by the first local copy prop pass.
223     */
224    BITSET_WORD *liveout;
225 
226    /**
227     * Which entries in the fs_copy_prop_dataflow acp table are generated by
228     * instructions in this block which reach the end of the block without
229     * being killed.
230     */
231    BITSET_WORD *copy;
232 
233    /**
234     * Which entries in the fs_copy_prop_dataflow acp table are killed over the
235     * course of this block.
236     */
237    BITSET_WORD *kill;
238 
239    /**
240     * Which entries in the fs_copy_prop_dataflow acp table are guaranteed to
241     * have a fully uninitialized destination at the end of this block.
242     */
243    BITSET_WORD *undef;
244 
245    /**
246     * Which entries in the fs_copy_prop_dataflow acp table can the
247     * start of this block be reached from.  Note that this is a weaker
248     * condition than livein.
249     */
250    BITSET_WORD *reachin;
251 
252    /**
253     * Which entries in the fs_copy_prop_dataflow acp table are
254     * overwritten by an instruction with channel masks inconsistent
255     * with the copy instruction (e.g. due to force_writemask_all).
256     * Such an overwrite can cause the copy entry to become invalid
257     * even if the copy instruction is subsequently re-executed for any
258     * given channel i, since the execution of the overwrite for
259     * channel i may corrupt other channels j!=i inactive for the
260     * subsequent copy.
261     */
262    BITSET_WORD *exec_mismatch;
263 };
264 
265 class fs_copy_prop_dataflow
266 {
267 public:
268    fs_copy_prop_dataflow(linear_ctx *lin_ctx, elk_cfg_t *cfg,
269                          const fs_live_variables &live,
270                          struct acp *out_acp);
271 
272    void setup_initial_values();
273    void run();
274 
275    void dump_block_data() const UNUSED;
276 
277    elk_cfg_t *cfg;
278    const fs_live_variables &live;
279 
280    acp_entry **acp;
281    int num_acp;
282    int bitset_words;
283 
284   struct block_data *bd;
285 };
286 } /* anonymous namespace */
287 
fs_copy_prop_dataflow(linear_ctx * lin_ctx,elk_cfg_t * cfg,const fs_live_variables & live,struct acp * out_acp)288 fs_copy_prop_dataflow::fs_copy_prop_dataflow(linear_ctx *lin_ctx, elk_cfg_t *cfg,
289                                              const fs_live_variables &live,
290                                              struct acp *out_acp)
291    : cfg(cfg), live(live)
292 {
293    bd = linear_zalloc_array(lin_ctx, struct block_data, cfg->num_blocks);
294 
295    num_acp = 0;
296    foreach_block (block, cfg)
297       num_acp += out_acp[block->num].length();
298 
299    bitset_words = BITSET_WORDS(num_acp);
300 
301    foreach_block (block, cfg) {
302       bd[block->num].livein = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
303       bd[block->num].liveout = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
304       bd[block->num].copy = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
305       bd[block->num].kill = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
306       bd[block->num].undef = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
307       bd[block->num].reachin = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
308       bd[block->num].exec_mismatch = linear_zalloc_array(lin_ctx, BITSET_WORD, bitset_words);
309    }
310 
311    acp = linear_zalloc_array(lin_ctx, struct acp_entry *, num_acp);
312 
313    int next_acp = 0;
314    foreach_block (block, cfg) {
315       for (auto iter = out_acp[block->num].begin();
316            iter != out_acp[block->num].end(); ++iter) {
317          acp[next_acp] = *iter;
318 
319          (*iter)->global_idx = next_acp;
320 
321          /* opt_copy_propagation_local populates out_acp with copies created
322           * in a block which are still live at the end of the block.  This
323           * is exactly what we want in the COPY set.
324           */
325          BITSET_SET(bd[block->num].copy, next_acp);
326 
327          next_acp++;
328       }
329    }
330 
331    assert(next_acp == num_acp);
332 
333    setup_initial_values();
334    run();
335 }
336 
337 /**
338  * Like reg_offset, but register must be VGRF or FIXED_GRF.
339  */
340 static inline unsigned
grf_reg_offset(const elk_fs_reg & r)341 grf_reg_offset(const elk_fs_reg &r)
342 {
343    return (r.file == VGRF ? 0 : r.nr) * REG_SIZE +
344           r.offset +
345           (r.file == FIXED_GRF ? r.subnr : 0);
346 }
347 
348 /**
349  * Like regions_overlap, but register must be VGRF or FIXED_GRF.
350  */
351 static inline bool
grf_regions_overlap(const elk_fs_reg & r,unsigned dr,const elk_fs_reg & s,unsigned ds)352 grf_regions_overlap(const elk_fs_reg &r, unsigned dr, const elk_fs_reg &s, unsigned ds)
353 {
354    return reg_space(r) == reg_space(s) &&
355           !(grf_reg_offset(r) + dr <= grf_reg_offset(s) ||
356             grf_reg_offset(s) + ds <= grf_reg_offset(r));
357 }
358 
359 /**
360  * Set up initial values for each of the data flow sets, prior to running
361  * the fixed-point algorithm.
362  */
363 void
setup_initial_values()364 fs_copy_prop_dataflow::setup_initial_values()
365 {
366    /* Initialize the COPY and KILL sets. */
367    {
368       struct acp acp_table;
369 
370       /* First, get all the KILLs for instructions which overwrite ACP
371        * destinations.
372        */
373       for (int i = 0; i < num_acp; i++)
374          acp_table.add(acp[i]);
375 
376       foreach_block (block, cfg) {
377          foreach_inst_in_block(elk_fs_inst, inst, block) {
378             if (inst->dst.file != VGRF &&
379                 inst->dst.file != FIXED_GRF)
380                continue;
381 
382             for (auto iter = acp_table.find_by_src(inst->dst.nr);
383               iter != acp_table.end() && (*iter)->src.nr == inst->dst.nr;
384               ++iter) {
385                if (grf_regions_overlap(inst->dst, inst->size_written,
386                                        (*iter)->src, (*iter)->size_read)) {
387                   BITSET_SET(bd[block->num].kill, (*iter)->global_idx);
388                   if (inst->force_writemask_all && !(*iter)->force_writemask_all)
389                      BITSET_SET(bd[block->num].exec_mismatch, (*iter)->global_idx);
390                }
391             }
392 
393             if (inst->dst.file != VGRF)
394                continue;
395 
396             for (auto iter = acp_table.find_by_dst(inst->dst.nr);
397               iter != acp_table.end() && (*iter)->dst.nr == inst->dst.nr;
398               ++iter) {
399                if (grf_regions_overlap(inst->dst, inst->size_written,
400                                        (*iter)->dst, (*iter)->size_written)) {
401                   BITSET_SET(bd[block->num].kill, (*iter)->global_idx);
402                   if (inst->force_writemask_all && !(*iter)->force_writemask_all)
403                      BITSET_SET(bd[block->num].exec_mismatch, (*iter)->global_idx);
404                }
405             }
406          }
407       }
408    }
409 
410    /* Populate the initial values for the livein and liveout sets.  For the
411     * block at the start of the program, livein = 0 and liveout = copy.
412     * For the others, set liveout and livein to ~0 (the universal set).
413     */
414    foreach_block (block, cfg) {
415       if (block->parents.is_empty()) {
416          for (int i = 0; i < bitset_words; i++) {
417             bd[block->num].livein[i] = 0u;
418             bd[block->num].liveout[i] = bd[block->num].copy[i];
419          }
420       } else {
421          for (int i = 0; i < bitset_words; i++) {
422             bd[block->num].liveout[i] = ~0u;
423             bd[block->num].livein[i] = ~0u;
424          }
425       }
426    }
427 
428    /* Initialize the undef set. */
429    foreach_block (block, cfg) {
430       for (int i = 0; i < num_acp; i++) {
431          BITSET_SET(bd[block->num].undef, i);
432          for (unsigned off = 0; off < acp[i]->size_written; off += REG_SIZE) {
433             if (BITSET_TEST(live.block_data[block->num].defout,
434                             live.var_from_reg(byte_offset(acp[i]->dst, off))))
435                BITSET_CLEAR(bd[block->num].undef, i);
436          }
437       }
438    }
439 }
440 
441 /**
442  * Walk the set of instructions in the block, marking which entries in the acp
443  * are killed by the block.
444  */
445 void
run()446 fs_copy_prop_dataflow::run()
447 {
448    bool progress;
449 
450    do {
451       progress = false;
452 
453       foreach_block (block, cfg) {
454          if (block->parents.is_empty())
455             continue;
456 
457          for (int i = 0; i < bitset_words; i++) {
458             const BITSET_WORD old_liveout = bd[block->num].liveout[i];
459             const BITSET_WORD old_reachin = bd[block->num].reachin[i];
460             BITSET_WORD livein_from_any_block = 0;
461 
462             /* Update livein for this block.  If a copy is live out of all
463              * parent blocks, it's live coming in to this block.
464              */
465             bd[block->num].livein[i] = ~0u;
466             foreach_list_typed(elk_bblock_link, parent_link, link, &block->parents) {
467                elk_bblock_t *parent = parent_link->block;
468                /* Consider ACP entries with a known-undefined destination to
469                 * be available from the parent.  This is valid because we're
470                 * free to set the undefined variable equal to the source of
471                 * the ACP entry without breaking the application's
472                 * expectations, since the variable is undefined.
473                 */
474                bd[block->num].livein[i] &= (bd[parent->num].liveout[i] |
475                                             bd[parent->num].undef[i]);
476                livein_from_any_block |= bd[parent->num].liveout[i];
477 
478                /* Update reachin for this block.  If the end of any
479                 * parent block is reachable from the copy, the start
480                 * of this block is reachable from it as well.
481                 */
482                bd[block->num].reachin[i] |= (bd[parent->num].reachin[i] |
483                                              bd[parent->num].copy[i]);
484             }
485 
486             /* Limit to the set of ACP entries that can possibly be available
487              * at the start of the block, since propagating from a variable
488              * which is guaranteed to be undefined (rather than potentially
489              * undefined for some dynamic control-flow paths) doesn't seem
490              * particularly useful.
491              */
492             bd[block->num].livein[i] &= livein_from_any_block;
493 
494             /* Update liveout for this block. */
495             bd[block->num].liveout[i] =
496                bd[block->num].copy[i] | (bd[block->num].livein[i] &
497                                          ~bd[block->num].kill[i]);
498 
499             if (old_liveout != bd[block->num].liveout[i] ||
500                 old_reachin != bd[block->num].reachin[i])
501                progress = true;
502          }
503       }
504    } while (progress);
505 
506    /* Perform a second fixed-point pass in order to propagate the
507     * exec_mismatch bitsets.  Note that this requires an accurate
508     * value of the reachin bitsets as input, which isn't available
509     * until the end of the first propagation pass, so this loop cannot
510     * be folded into the previous one.
511     */
512    do {
513       progress = false;
514 
515       foreach_block (block, cfg) {
516          for (int i = 0; i < bitset_words; i++) {
517             const BITSET_WORD old_exec_mismatch = bd[block->num].exec_mismatch[i];
518 
519             /* Update exec_mismatch for this block.  If the end of a
520              * parent block is reachable by an overwrite with
521              * inconsistent execution masking, the start of this block
522              * is reachable by such an overwrite as well.
523              */
524             foreach_list_typed(elk_bblock_link, parent_link, link, &block->parents) {
525                elk_bblock_t *parent = parent_link->block;
526                bd[block->num].exec_mismatch[i] |= (bd[parent->num].exec_mismatch[i] &
527                                                    bd[parent->num].reachin[i]);
528             }
529 
530             /* Only consider overwrites with inconsistent execution
531              * masking if they are reachable from the copy, since
532              * overwrites unreachable from a copy are harmless to that
533              * copy.
534              */
535             bd[block->num].exec_mismatch[i] &= bd[block->num].reachin[i];
536             if (old_exec_mismatch != bd[block->num].exec_mismatch[i])
537                progress = true;
538          }
539       }
540    } while (progress);
541 }
542 
543 void
dump_block_data() const544 fs_copy_prop_dataflow::dump_block_data() const
545 {
546    foreach_block (block, cfg) {
547       fprintf(stderr, "Block %d [%d, %d] (parents ", block->num,
548              block->start_ip, block->end_ip);
549       foreach_list_typed(elk_bblock_link, link, link, &block->parents) {
550          elk_bblock_t *parent = link->block;
551          fprintf(stderr, "%d ", parent->num);
552       }
553       fprintf(stderr, "):\n");
554       fprintf(stderr, "       livein = 0x");
555       for (int i = 0; i < bitset_words; i++)
556          fprintf(stderr, "%08x", bd[block->num].livein[i]);
557       fprintf(stderr, ", liveout = 0x");
558       for (int i = 0; i < bitset_words; i++)
559          fprintf(stderr, "%08x", bd[block->num].liveout[i]);
560       fprintf(stderr, ",\n       copy   = 0x");
561       for (int i = 0; i < bitset_words; i++)
562          fprintf(stderr, "%08x", bd[block->num].copy[i]);
563       fprintf(stderr, ", kill    = 0x");
564       for (int i = 0; i < bitset_words; i++)
565          fprintf(stderr, "%08x", bd[block->num].kill[i]);
566       fprintf(stderr, "\n");
567    }
568 }
569 
570 static bool
is_logic_op(enum elk_opcode opcode)571 is_logic_op(enum elk_opcode opcode)
572 {
573    return (opcode == ELK_OPCODE_AND ||
574            opcode == ELK_OPCODE_OR  ||
575            opcode == ELK_OPCODE_XOR ||
576            opcode == ELK_OPCODE_NOT);
577 }
578 
579 static bool
can_take_stride(elk_fs_inst * inst,elk_reg_type dst_type,unsigned arg,unsigned stride,const struct elk_compiler * compiler)580 can_take_stride(elk_fs_inst *inst, elk_reg_type dst_type,
581                 unsigned arg, unsigned stride,
582                 const struct elk_compiler *compiler)
583 {
584    const struct intel_device_info *devinfo = compiler->devinfo;
585 
586    if (stride > 4)
587       return false;
588 
589    /* Bail if the channels of the source need to be aligned to the byte offset
590     * of the corresponding channel of the destination, and the provided stride
591     * would break this restriction.
592     */
593    if (has_dst_aligned_region_restriction(devinfo, inst, dst_type) &&
594        !(type_sz(inst->src[arg].type) * stride ==
595            type_sz(dst_type) * inst->dst.stride ||
596          stride == 0))
597       return false;
598 
599    /* 3-source instructions can only be Align16, which restricts what strides
600     * they can take. They can only take a stride of 1 (the usual case), or 0
601     * with a special "repctrl" bit. But the repctrl bit doesn't work for
602     * 64-bit datatypes, so if the source type is 64-bit then only a stride of
603     * 1 is allowed. From the Broadwell PRM, Volume 7 "3D Media GPGPU", page
604     * 944:
605     *
606     *    This is applicable to 32b datatypes and 16b datatype. 64b datatypes
607     *    cannot use the replicate control.
608     */
609    if (inst->elk_is_3src(compiler)) {
610       if (type_sz(inst->src[arg].type) > 4)
611          return stride == 1;
612       else
613          return stride == 1 || stride == 0;
614    }
615 
616    /* From the Broadwell PRM, Volume 2a "Command Reference - Instructions",
617     * page 391 ("Extended Math Function"):
618     *
619     *     The following restrictions apply for align1 mode: Scalar source is
620     *     supported. Source and destination horizontal stride must be the
621     *     same.
622     *
623     * From the Haswell PRM Volume 2b "Command Reference - Instructions", page
624     * 134 ("Extended Math Function"):
625     *
626     *    Scalar source is supported. Source and destination horizontal stride
627     *    must be 1.
628     *
629     * and similar language exists for IVB and SNB. Pre-SNB, math instructions
630     * are sends, so the sources are moved to MRF's and there are no
631     * restrictions.
632     */
633    if (inst->is_math()) {
634       if (devinfo->ver == 6 || devinfo->ver == 7) {
635          assert(inst->dst.stride == 1);
636          return stride == 1 || stride == 0;
637       } else if (devinfo->ver >= 8) {
638          return stride == inst->dst.stride || stride == 0;
639       }
640    }
641 
642    return true;
643 }
644 
645 static bool
instruction_requires_packed_data(elk_fs_inst * inst)646 instruction_requires_packed_data(elk_fs_inst *inst)
647 {
648    switch (inst->opcode) {
649    case ELK_FS_OPCODE_DDX_FINE:
650    case ELK_FS_OPCODE_DDX_COARSE:
651    case ELK_FS_OPCODE_DDY_FINE:
652    case ELK_FS_OPCODE_DDY_COARSE:
653    case ELK_SHADER_OPCODE_QUAD_SWIZZLE:
654       return true;
655    default:
656       return false;
657    }
658 }
659 
660 static bool
try_copy_propagate(const elk_compiler * compiler,elk_fs_inst * inst,acp_entry * entry,int arg,const elk::simple_allocator & alloc)661 try_copy_propagate(const elk_compiler *compiler, elk_fs_inst *inst,
662                    acp_entry *entry, int arg,
663                    const elk::simple_allocator &alloc)
664 {
665    if (inst->src[arg].file != VGRF)
666       return false;
667 
668    const struct intel_device_info *devinfo = compiler->devinfo;
669 
670    assert(entry->src.file == VGRF || entry->src.file == UNIFORM ||
671           entry->src.file == ATTR || entry->src.file == FIXED_GRF);
672 
673    /* Avoid propagating a LOAD_PAYLOAD instruction into another if there is a
674     * good chance that we'll be able to eliminate the latter through register
675     * coalescing.  If only part of the sources of the second LOAD_PAYLOAD can
676     * be simplified through copy propagation we would be making register
677     * coalescing impossible, ending up with unnecessary copies in the program.
678     * This is also the case for is_multi_copy_payload() copies that can only
679     * be coalesced when the instruction is lowered into a sequence of MOVs.
680     *
681     * Worse -- In cases where the ACP entry was the result of CSE combining
682     * multiple LOAD_PAYLOAD subexpressions, propagating the first LOAD_PAYLOAD
683     * into the second would undo the work of CSE, leading to an infinite
684     * optimization loop.  Avoid this by detecting LOAD_PAYLOAD copies from CSE
685     * temporaries which should match is_coalescing_payload().
686     */
687    if (entry->opcode == ELK_SHADER_OPCODE_LOAD_PAYLOAD &&
688        (is_coalescing_payload(alloc, inst) || is_multi_copy_payload(inst)))
689       return false;
690 
691    assert(entry->dst.file == VGRF);
692    if (inst->src[arg].nr != entry->dst.nr)
693       return false;
694 
695    /* Bail if inst is reading a range that isn't contained in the range
696     * that entry is writing.
697     */
698    if (!region_contained_in(inst->src[arg], inst->size_read(arg),
699                             entry->dst, entry->size_written))
700       return false;
701 
702    /* Send messages with EOT set are restricted to use g112-g127 (and we
703     * sometimes need g127 for other purposes), so avoid copy propagating
704     * anything that would make it impossible to satisfy that restriction.
705     */
706    if (inst->eot) {
707       /* Avoid propagating a FIXED_GRF register, as that's already pinned. */
708       if (entry->src.file == FIXED_GRF)
709          return false;
710 
711       /* We might be propagating from a large register, while the SEND only
712        * is reading a portion of it (say the .A channel in an RGBA value).
713        * We need to pin both split SEND sources in g112-g126/127, so only
714        * allow this if the registers aren't too large.
715        */
716       if (inst->opcode == ELK_SHADER_OPCODE_SEND && entry->src.file == VGRF) {
717          unsigned prop_src_size = alloc.sizes[entry->src.nr];
718          if (prop_src_size > 15)
719             return false;
720       }
721    }
722 
723    /* Avoid propagating odd-numbered FIXED_GRF registers into the first source
724     * of a LINTERP instruction on platforms where the PLN instruction has
725     * register alignment restrictions.
726     */
727    if (devinfo->has_pln && devinfo->ver <= 6 &&
728        entry->src.file == FIXED_GRF && (entry->src.nr & 1) &&
729        inst->opcode == ELK_FS_OPCODE_LINTERP && arg == 0)
730       return false;
731 
732    /* we can't generally copy-propagate UD negations because we
733     * can end up accessing the resulting values as signed integers
734     * instead. See also resolve_ud_negate() and comment in
735     * elk_fs_generator::generate_code.
736     */
737    if (entry->src.type == ELK_REGISTER_TYPE_UD &&
738        entry->src.negate)
739       return false;
740 
741    bool has_source_modifiers = entry->src.abs || entry->src.negate;
742 
743    if (has_source_modifiers && !inst->can_do_source_mods(devinfo))
744       return false;
745 
746    /* Reject cases that would violate register regioning restrictions. */
747    if ((entry->src.file == UNIFORM || !entry->src.is_contiguous()) &&
748        ((devinfo->ver == 6 && inst->is_math()) ||
749         inst->is_send_from_grf() ||
750         inst->uses_indirect_addressing())) {
751       return false;
752    }
753 
754    if (has_source_modifiers &&
755        inst->opcode == ELK_SHADER_OPCODE_GFX4_SCRATCH_WRITE)
756       return false;
757 
758    /* Some instructions implemented in the generator backend, such as
759     * derivatives, assume that their operands are packed so we can't
760     * generally propagate strided regions to them.
761     */
762    const unsigned entry_stride = (entry->src.file == FIXED_GRF ? 1 :
763                                   entry->src.stride);
764    if (instruction_requires_packed_data(inst) && entry_stride != 1)
765       return false;
766 
767    const elk_reg_type dst_type = (has_source_modifiers &&
768                                   entry->dst.type != inst->src[arg].type) ?
769       entry->dst.type : inst->dst.type;
770 
771    /* Bail if the result of composing both strides would exceed the
772     * hardware limit.
773     */
774    if (!can_take_stride(inst, dst_type, arg,
775                         entry_stride * inst->src[arg].stride,
776                         compiler))
777       return false;
778 
779    /* From the Cherry Trail/Braswell PRMs, Volume 7: 3D Media GPGPU:
780     *    EU Overview
781     *       Register Region Restrictions
782     *          Special Requirements for Handling Double Precision Data Types :
783     *
784     *   "When source or destination datatype is 64b or operation is integer
785     *    DWord multiply, regioning in Align1 must follow these rules:
786     *
787     *      1. Source and Destination horizontal stride must be aligned to the
788     *         same qword.
789     *      2. Regioning must ensure Src.Vstride = Src.Width * Src.Hstride.
790     *      3. Source and Destination offset must be the same, except the case
791     *         of scalar source."
792     *
793     * Most of this is already checked in can_take_stride(), we're only left
794     * with checking 3.
795     */
796    if (has_dst_aligned_region_restriction(devinfo, inst, dst_type) &&
797        entry_stride != 0 &&
798        (reg_offset(inst->dst) % REG_SIZE) != (reg_offset(entry->src) % REG_SIZE))
799       return false;
800 
801    /* Bail if the source FIXED_GRF region of the copy cannot be trivially
802     * composed with the source region of the instruction -- E.g. because the
803     * copy uses some extended stride greater than 4 not supported natively by
804     * the hardware as a horizontal stride, or because instruction compression
805     * could require us to use a vertical stride shorter than a GRF.
806     */
807    if (entry->src.file == FIXED_GRF &&
808        (inst->src[arg].stride > 4 ||
809         inst->dst.component_size(inst->exec_size) >
810         inst->src[arg].component_size(inst->exec_size)))
811       return false;
812 
813    /* Bail if the instruction type is larger than the execution type of the
814     * copy, what implies that each channel is reading multiple channels of the
815     * destination of the copy, and simply replacing the sources would give a
816     * program with different semantics.
817     */
818    if ((type_sz(entry->dst.type) < type_sz(inst->src[arg].type) ||
819         entry->is_partial_write) &&
820        inst->opcode != ELK_OPCODE_MOV) {
821       return false;
822    }
823 
824    /* Bail if the result of composing both strides cannot be expressed
825     * as another stride. This avoids, for example, trying to transform
826     * this:
827     *
828     *     MOV (8) rX<1>UD rY<0;1,0>UD
829     *     FOO (8) ...     rX<8;8,1>UW
830     *
831     * into this:
832     *
833     *     FOO (8) ...     rY<0;1,0>UW
834     *
835     * Which would have different semantics.
836     */
837    if (entry_stride != 1 &&
838        (inst->src[arg].stride *
839         type_sz(inst->src[arg].type)) % type_sz(entry->src.type) != 0)
840       return false;
841 
842    /* Since semantics of source modifiers are type-dependent we need to
843     * ensure that the meaning of the instruction remains the same if we
844     * change the type. If the sizes of the types are different the new
845     * instruction will read a different amount of data than the original
846     * and the semantics will always be different.
847     */
848    if (has_source_modifiers &&
849        entry->dst.type != inst->src[arg].type &&
850        (!inst->can_change_types() ||
851         type_sz(entry->dst.type) != type_sz(inst->src[arg].type)))
852       return false;
853 
854    if (devinfo->ver >= 8 && (entry->src.negate || entry->src.abs) &&
855        is_logic_op(inst->opcode)) {
856       return false;
857    }
858 
859    /* Save the offset of inst->src[arg] relative to entry->dst for it to be
860     * applied later.
861     */
862    const unsigned rel_offset = inst->src[arg].offset - entry->dst.offset;
863 
864    /* Fold the copy into the instruction consuming it. */
865    inst->src[arg].file = entry->src.file;
866    inst->src[arg].nr = entry->src.nr;
867    inst->src[arg].subnr = entry->src.subnr;
868    inst->src[arg].offset = entry->src.offset;
869 
870    /* Compose the strides of both regions. */
871    if (entry->src.file == FIXED_GRF) {
872       if (inst->src[arg].stride) {
873          const unsigned orig_width = 1 << entry->src.width;
874          const unsigned reg_width = REG_SIZE / (type_sz(inst->src[arg].type) *
875                                                 inst->src[arg].stride);
876          inst->src[arg].width = cvt(MIN2(orig_width, reg_width)) - 1;
877          inst->src[arg].hstride = cvt(inst->src[arg].stride);
878          inst->src[arg].vstride = inst->src[arg].hstride + inst->src[arg].width;
879       } else {
880          inst->src[arg].vstride = inst->src[arg].hstride =
881             inst->src[arg].width = 0;
882       }
883 
884       inst->src[arg].stride = 1;
885 
886       /* Hopefully no Align16 around here... */
887       assert(entry->src.swizzle == ELK_SWIZZLE_XYZW);
888       inst->src[arg].swizzle = entry->src.swizzle;
889    } else {
890       inst->src[arg].stride *= entry->src.stride;
891    }
892 
893    /* Compute the first component of the copy that the instruction is
894     * reading, and the base byte offset within that component.
895     */
896    assert((entry->dst.offset % REG_SIZE == 0 || inst->opcode == ELK_OPCODE_MOV) &&
897            entry->dst.stride == 1);
898    const unsigned component = rel_offset / type_sz(entry->dst.type);
899    const unsigned suboffset = rel_offset % type_sz(entry->dst.type);
900 
901    /* Calculate the byte offset at the origin of the copy of the given
902     * component and suboffset.
903     */
904    inst->src[arg] = byte_offset(inst->src[arg],
905       component * entry_stride * type_sz(entry->src.type) + suboffset);
906 
907    if (has_source_modifiers) {
908       if (entry->dst.type != inst->src[arg].type) {
909          /* We are propagating source modifiers from a MOV with a different
910           * type.  If we got here, then we can just change the source and
911           * destination types of the instruction and keep going.
912           */
913          for (int i = 0; i < inst->sources; i++) {
914             inst->src[i].type = entry->dst.type;
915          }
916          inst->dst.type = entry->dst.type;
917       }
918 
919       if (!inst->src[arg].abs) {
920          inst->src[arg].abs = entry->src.abs;
921          inst->src[arg].negate ^= entry->src.negate;
922       }
923    }
924 
925    return true;
926 }
927 
928 
929 static bool
try_constant_propagate(const elk_compiler * compiler,elk_fs_inst * inst,acp_entry * entry,int arg)930 try_constant_propagate(const elk_compiler *compiler, elk_fs_inst *inst,
931                        acp_entry *entry, int arg)
932 {
933    const struct intel_device_info *devinfo = compiler->devinfo;
934    bool progress = false;
935 
936    if (type_sz(entry->src.type) > 4)
937       return false;
938 
939    if (inst->src[arg].file != VGRF)
940       return false;
941 
942    assert(entry->dst.file == VGRF);
943    if (inst->src[arg].nr != entry->dst.nr)
944       return false;
945 
946    /* Bail if inst is reading a range that isn't contained in the range
947     * that entry is writing.
948     */
949    if (!region_contained_in(inst->src[arg], inst->size_read(arg),
950                             entry->dst, entry->size_written))
951       return false;
952 
953    /* If the size of the use type is larger than the size of the entry
954     * type, the entry doesn't contain all of the data that the user is
955     * trying to use.
956     */
957    if (type_sz(inst->src[arg].type) > type_sz(entry->dst.type))
958       return false;
959 
960    elk_fs_reg val = entry->src;
961 
962    /* If the size of the use type is smaller than the size of the entry,
963     * clamp the value to the range of the use type.  This enables constant
964     * copy propagation in cases like
965     *
966     *
967     *    mov(8)          g12<1>UD        0x0000000cUD
968     *    ...
969     *    mul(8)          g47<1>D         g86<8,8,1>D     g12<16,8,2>W
970     */
971    if (type_sz(inst->src[arg].type) < type_sz(entry->dst.type)) {
972       if (type_sz(inst->src[arg].type) != 2 || type_sz(entry->dst.type) != 4)
973          return false;
974 
975       assert(inst->src[arg].subnr == 0 || inst->src[arg].subnr == 2);
976 
977       /* When subnr is 0, we want the lower 16-bits, and when it's 2, we
978        * want the upper 16-bits. No other values of subnr are valid for a
979        * UD source.
980        */
981       const uint16_t v = inst->src[arg].subnr == 2 ? val.ud >> 16 : val.ud;
982 
983       val.ud = v | (uint32_t(v) << 16);
984    }
985 
986    val.type = inst->src[arg].type;
987 
988    if (inst->src[arg].abs) {
989       if ((devinfo->ver >= 8 && is_logic_op(inst->opcode)) ||
990           !elk_abs_immediate(val.type, &val.as_elk_reg())) {
991          return false;
992       }
993    }
994 
995    if (inst->src[arg].negate) {
996       if ((devinfo->ver >= 8 && is_logic_op(inst->opcode)) ||
997           !elk_negate_immediate(val.type, &val.as_elk_reg())) {
998          return false;
999       }
1000    }
1001 
1002    switch (inst->opcode) {
1003    case ELK_OPCODE_MOV:
1004    case ELK_SHADER_OPCODE_LOAD_PAYLOAD:
1005    case ELK_FS_OPCODE_PACK:
1006       inst->src[arg] = val;
1007       progress = true;
1008       break;
1009 
1010    case ELK_SHADER_OPCODE_POW:
1011       /* Allow constant propagation into src1 (except on Gen 6 which
1012        * doesn't support scalar source math), and let constant combining
1013        * promote the constant on Gen < 8.
1014        */
1015       if (devinfo->ver == 6)
1016          break;
1017 
1018       if (arg == 1) {
1019          inst->src[arg] = val;
1020          progress = true;
1021       }
1022       break;
1023 
1024    case ELK_OPCODE_SUBB:
1025       if (arg == 1) {
1026          inst->src[arg] = val;
1027          progress = true;
1028       }
1029       break;
1030 
1031    case ELK_OPCODE_MACH:
1032    case ELK_OPCODE_MUL:
1033    case ELK_SHADER_OPCODE_MULH:
1034    case ELK_OPCODE_ADD:
1035    case ELK_OPCODE_XOR:
1036    case ELK_OPCODE_ADDC:
1037       if (arg == 1) {
1038          inst->src[arg] = val;
1039          progress = true;
1040       } else if (arg == 0 && inst->src[1].file != IMM) {
1041          /* Don't copy propagate the constant in situations like
1042           *
1043           *    mov(8)          g8<1>D          0x7fffffffD
1044           *    mul(8)          g16<1>D         g8<8,8,1>D      g15<16,8,2>W
1045           *
1046           * On platforms that only have a 32x16 multiplier, this will
1047           * result in lowering the multiply to
1048           *
1049           *    mul(8)          g15<1>D         g14<8,8,1>D     0xffffUW
1050           *    mul(8)          g16<1>D         g14<8,8,1>D     0x7fffUW
1051           *    add(8)          g15.1<2>UW      g15.1<16,8,2>UW g16<16,8,2>UW
1052           *
1053           * On Gfx8 and Gfx9, which have the full 32x32 multiplier, it
1054           * results in
1055           *
1056           *    mul(8)          g16<1>D         g15<16,8,2>W    0x7fffffffD
1057           *
1058           * Volume 2a of the Skylake PRM says:
1059           *
1060           *    When multiplying a DW and any lower precision integer, the
1061           *    DW operand must on src0.
1062           */
1063          if (inst->opcode == ELK_OPCODE_MUL &&
1064              type_sz(inst->src[1].type) < 4 &&
1065              type_sz(val.type) == 4)
1066             break;
1067 
1068          /* Fit this constant in by commuting the operands.
1069           * Exception: we can't do this for 32-bit integer MUL/MACH
1070           * because it's asymmetric.
1071           *
1072           * The BSpec says for Broadwell that
1073           *
1074           *    "When multiplying DW x DW, the dst cannot be accumulator."
1075           *
1076           * Integer MUL with a non-accumulator destination will be lowered
1077           * by lower_integer_multiplication(), so don't restrict it.
1078           */
1079          if (((inst->opcode == ELK_OPCODE_MUL &&
1080                inst->dst.is_accumulator()) ||
1081               inst->opcode == ELK_OPCODE_MACH) &&
1082              (inst->src[1].type == ELK_REGISTER_TYPE_D ||
1083               inst->src[1].type == ELK_REGISTER_TYPE_UD))
1084             break;
1085          inst->src[0] = inst->src[1];
1086          inst->src[1] = val;
1087          progress = true;
1088       }
1089       break;
1090 
1091    case ELK_OPCODE_CMP:
1092    case ELK_OPCODE_IF:
1093       if (arg == 1) {
1094          inst->src[arg] = val;
1095          progress = true;
1096       } else if (arg == 0 && inst->src[1].file != IMM) {
1097          enum elk_conditional_mod new_cmod;
1098 
1099          new_cmod = elk_swap_cmod(inst->conditional_mod);
1100          if (new_cmod != ELK_CONDITIONAL_NONE) {
1101             /* Fit this constant in by swapping the operands and
1102              * flipping the test
1103              */
1104             inst->src[0] = inst->src[1];
1105             inst->src[1] = val;
1106             inst->conditional_mod = new_cmod;
1107             progress = true;
1108          }
1109       }
1110       break;
1111 
1112    case ELK_OPCODE_SEL:
1113       if (arg == 1) {
1114          inst->src[arg] = val;
1115          progress = true;
1116       } else if (arg == 0) {
1117          if (inst->src[1].file != IMM &&
1118              (inst->conditional_mod == ELK_CONDITIONAL_NONE ||
1119               /* Only GE and L are commutative. */
1120               inst->conditional_mod == ELK_CONDITIONAL_GE ||
1121               inst->conditional_mod == ELK_CONDITIONAL_L)) {
1122             inst->src[0] = inst->src[1];
1123             inst->src[1] = val;
1124 
1125             /* If this was predicated, flipping operands means
1126              * we also need to flip the predicate.
1127              */
1128             if (inst->conditional_mod == ELK_CONDITIONAL_NONE) {
1129                inst->predicate_inverse =
1130                   !inst->predicate_inverse;
1131             }
1132          } else {
1133             inst->src[0] = val;
1134          }
1135 
1136          progress = true;
1137       }
1138       break;
1139 
1140    case ELK_FS_OPCODE_FB_WRITE_LOGICAL:
1141       /* The omask source of ELK_FS_OPCODE_FB_WRITE_LOGICAL is
1142        * bit-cast using a strided region so they cannot be immediates.
1143        */
1144       if (arg != FB_WRITE_LOGICAL_SRC_OMASK) {
1145          inst->src[arg] = val;
1146          progress = true;
1147       }
1148       break;
1149 
1150    case ELK_SHADER_OPCODE_INT_QUOTIENT:
1151    case ELK_SHADER_OPCODE_INT_REMAINDER:
1152       /* Allow constant propagation into either source (except on Gen 6
1153        * which doesn't support scalar source math). Constant combining
1154        * promote the src1 constant on Gen < 8, and it will promote the src0
1155        * constant on all platforms.
1156        */
1157       if (devinfo->ver == 6)
1158          break;
1159 
1160       FALLTHROUGH;
1161    case ELK_OPCODE_AND:
1162    case ELK_OPCODE_ASR:
1163    case ELK_OPCODE_BFE:
1164    case ELK_OPCODE_BFI1:
1165    case ELK_OPCODE_BFI2:
1166    case ELK_OPCODE_SHL:
1167    case ELK_OPCODE_SHR:
1168    case ELK_OPCODE_OR:
1169    case ELK_SHADER_OPCODE_TEX_LOGICAL:
1170    case ELK_SHADER_OPCODE_TXD_LOGICAL:
1171    case ELK_SHADER_OPCODE_TXF_LOGICAL:
1172    case ELK_SHADER_OPCODE_TXL_LOGICAL:
1173    case ELK_SHADER_OPCODE_TXS_LOGICAL:
1174    case ELK_FS_OPCODE_TXB_LOGICAL:
1175    case ELK_SHADER_OPCODE_TXF_CMS_LOGICAL:
1176    case ELK_SHADER_OPCODE_TXF_CMS_W_LOGICAL:
1177    case ELK_SHADER_OPCODE_TXF_CMS_W_GFX12_LOGICAL:
1178    case ELK_SHADER_OPCODE_TXF_UMS_LOGICAL:
1179    case ELK_SHADER_OPCODE_TXF_MCS_LOGICAL:
1180    case ELK_SHADER_OPCODE_LOD_LOGICAL:
1181    case ELK_SHADER_OPCODE_TG4_LOGICAL:
1182    case ELK_SHADER_OPCODE_TG4_OFFSET_LOGICAL:
1183    case ELK_SHADER_OPCODE_SAMPLEINFO_LOGICAL:
1184    case ELK_SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
1185    case ELK_SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
1186    case ELK_SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
1187    case ELK_SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
1188    case ELK_SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
1189    case ELK_SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
1190    case ELK_SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
1191    case ELK_SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
1192    case ELK_SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
1193    case ELK_FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
1194    case ELK_SHADER_OPCODE_BROADCAST:
1195    case ELK_OPCODE_MAD:
1196    case ELK_OPCODE_LRP:
1197    case ELK_FS_OPCODE_PACK_HALF_2x16_SPLIT:
1198    case ELK_SHADER_OPCODE_SHUFFLE:
1199       inst->src[arg] = val;
1200       progress = true;
1201       break;
1202 
1203    default:
1204       break;
1205    }
1206 
1207    return progress;
1208 }
1209 
1210 static bool
can_propagate_from(elk_fs_inst * inst)1211 can_propagate_from(elk_fs_inst *inst)
1212 {
1213    return (inst->opcode == ELK_OPCODE_MOV &&
1214            inst->dst.file == VGRF &&
1215            ((inst->src[0].file == VGRF &&
1216              !grf_regions_overlap(inst->dst, inst->size_written,
1217                                   inst->src[0], inst->size_read(0))) ||
1218             inst->src[0].file == ATTR ||
1219             inst->src[0].file == UNIFORM ||
1220             inst->src[0].file == IMM ||
1221             (inst->src[0].file == FIXED_GRF &&
1222              inst->src[0].is_contiguous())) &&
1223            inst->src[0].type == inst->dst.type &&
1224            !inst->saturate &&
1225            /* Subset of !is_partial_write() conditions. */
1226            !inst->predicate && inst->dst.is_contiguous()) ||
1227           is_identity_payload(FIXED_GRF, inst);
1228 }
1229 
1230 /* Walks a basic block and does copy propagation on it using the acp
1231  * list.
1232  */
1233 static bool
opt_copy_propagation_local(const elk_compiler * compiler,linear_ctx * lin_ctx,elk_bblock_t * block,struct acp & acp,const elk::simple_allocator & alloc)1234 opt_copy_propagation_local(const elk_compiler *compiler, linear_ctx *lin_ctx,
1235                            elk_bblock_t *block, struct acp &acp,
1236                            const elk::simple_allocator &alloc)
1237 {
1238    bool progress = false;
1239 
1240    foreach_inst_in_block(elk_fs_inst, inst, block) {
1241       /* Try propagating into this instruction. */
1242       bool instruction_progress = false;
1243       for (int i = inst->sources - 1; i >= 0; i--) {
1244          if (inst->src[i].file != VGRF)
1245             continue;
1246 
1247          for (auto iter = acp.find_by_dst(inst->src[i].nr);
1248               iter != acp.end() && (*iter)->dst.nr == inst->src[i].nr;
1249               ++iter) {
1250             if ((*iter)->src.file == IMM) {
1251                if (try_constant_propagate(compiler, inst, *iter, i)) {
1252                   instruction_progress = true;
1253                   break;
1254                }
1255             } else {
1256                if (try_copy_propagate(compiler, inst, *iter, i, alloc)) {
1257                   instruction_progress = true;
1258                   break;
1259                }
1260             }
1261          }
1262       }
1263 
1264       if (instruction_progress) {
1265          progress = true;
1266 
1267          /* If only one of the sources of a 2-source, commutative instruction (e.g.,
1268           * AND) is immediate, it must be src1. If both are immediate, opt_algebraic
1269           * should fold it away.
1270           */
1271          if (inst->sources == 2 && inst->is_commutative() &&
1272              inst->src[0].file == IMM && inst->src[1].file != IMM) {
1273             const auto src1 = inst->src[1];
1274             inst->src[1] = inst->src[0];
1275             inst->src[0] = src1;
1276          }
1277       }
1278 
1279       /* kill the destination from the ACP */
1280       if (inst->dst.file == VGRF || inst->dst.file == FIXED_GRF) {
1281          for (auto iter = acp.find_by_dst(inst->dst.nr);
1282               iter != acp.end() && (*iter)->dst.nr == inst->dst.nr;
1283               ++iter) {
1284             if (grf_regions_overlap((*iter)->dst, (*iter)->size_written,
1285                                     inst->dst, inst->size_written))
1286                acp.remove(*iter);
1287          }
1288 
1289          for (auto iter = acp.find_by_src(inst->dst.nr);
1290               iter != acp.end() && (*iter)->src.nr == inst->dst.nr;
1291               ++iter) {
1292             /* Make sure we kill the entry if this instruction overwrites
1293              * _any_ of the registers that it reads
1294              */
1295             if (grf_regions_overlap((*iter)->src, (*iter)->size_read,
1296                                     inst->dst, inst->size_written))
1297                acp.remove(*iter);
1298          }
1299       }
1300 
1301       /* If this instruction's source could potentially be folded into the
1302        * operand of another instruction, add it to the ACP.
1303        */
1304       if (can_propagate_from(inst)) {
1305          acp_entry *entry = linear_zalloc(lin_ctx, acp_entry);
1306          entry->dst = inst->dst;
1307          entry->src = inst->src[0];
1308          entry->size_written = inst->size_written;
1309          for (unsigned i = 0; i < inst->sources; i++)
1310             entry->size_read += inst->size_read(i);
1311          entry->opcode = inst->opcode;
1312          entry->is_partial_write = inst->is_partial_write();
1313          entry->force_writemask_all = inst->force_writemask_all;
1314          acp.add(entry);
1315       } else if (inst->opcode == ELK_SHADER_OPCODE_LOAD_PAYLOAD &&
1316                  inst->dst.file == VGRF) {
1317          int offset = 0;
1318          for (int i = 0; i < inst->sources; i++) {
1319             int effective_width = i < inst->header_size ? 8 : inst->exec_size;
1320             const unsigned size_written = effective_width *
1321                                           type_sz(inst->src[i].type);
1322             if (inst->src[i].file == VGRF ||
1323                 (inst->src[i].file == FIXED_GRF &&
1324                  inst->src[i].is_contiguous())) {
1325                const elk_reg_type t = i < inst->header_size ?
1326                   ELK_REGISTER_TYPE_UD : inst->src[i].type;
1327                elk_fs_reg dst = byte_offset(retype(inst->dst, t), offset);
1328                if (!dst.equals(inst->src[i])) {
1329                   acp_entry *entry = linear_zalloc(lin_ctx, acp_entry);
1330                   entry->dst = dst;
1331                   entry->src = retype(inst->src[i], t);
1332                   entry->size_written = size_written;
1333                   entry->size_read = inst->size_read(i);
1334                   entry->opcode = inst->opcode;
1335                   entry->force_writemask_all = inst->force_writemask_all;
1336                   acp.add(entry);
1337                }
1338             }
1339             offset += size_written;
1340          }
1341       }
1342    }
1343 
1344    return progress;
1345 }
1346 
1347 bool
opt_copy_propagation()1348 elk_fs_visitor::opt_copy_propagation()
1349 {
1350    bool progress = false;
1351    void *copy_prop_ctx = ralloc_context(NULL);
1352    linear_ctx *lin_ctx = linear_context(copy_prop_ctx);
1353    struct acp out_acp[cfg->num_blocks];
1354 
1355    const fs_live_variables &live = live_analysis.require();
1356 
1357    /* First, walk through each block doing local copy propagation and getting
1358     * the set of copies available at the end of the block.
1359     */
1360    foreach_block (block, cfg) {
1361       progress = opt_copy_propagation_local(compiler, lin_ctx, block,
1362                                             out_acp[block->num], alloc) || progress;
1363 
1364       /* If the destination of an ACP entry exists only within this block,
1365        * then there's no need to keep it for dataflow analysis.  We can delete
1366        * it from the out_acp table and avoid growing the bitsets any bigger
1367        * than we absolutely have to.
1368        *
1369        * Because nothing in opt_copy_propagation_local touches the block
1370        * start/end IPs and opt_copy_propagation_local is incapable of
1371        * extending the live range of an ACP destination beyond the block,
1372        * it's safe to use the liveness information in this way.
1373        */
1374       for (auto iter = out_acp[block->num].begin();
1375            iter != out_acp[block->num].end(); ++iter) {
1376          assert((*iter)->dst.file == VGRF);
1377          if (block->start_ip <= live.vgrf_start[(*iter)->dst.nr] &&
1378              live.vgrf_end[(*iter)->dst.nr] <= block->end_ip) {
1379             out_acp[block->num].remove(*iter);
1380          }
1381       }
1382    }
1383 
1384    /* Do dataflow analysis for those available copies. */
1385    fs_copy_prop_dataflow dataflow(lin_ctx, cfg, live, out_acp);
1386 
1387    /* Next, re-run local copy propagation, this time with the set of copies
1388     * provided by the dataflow analysis available at the start of a block.
1389     */
1390    foreach_block (block, cfg) {
1391       struct acp in_acp;
1392 
1393       for (int i = 0; i < dataflow.num_acp; i++) {
1394          if (BITSET_TEST(dataflow.bd[block->num].livein, i) &&
1395              !BITSET_TEST(dataflow.bd[block->num].exec_mismatch, i)) {
1396             struct acp_entry *entry = dataflow.acp[i];
1397             in_acp.add(entry);
1398          }
1399       }
1400 
1401       progress = opt_copy_propagation_local(compiler, lin_ctx, block,
1402                                             in_acp, alloc) ||
1403                  progress;
1404    }
1405 
1406    ralloc_free(copy_prop_ctx);
1407 
1408    if (progress)
1409       invalidate_analysis(DEPENDENCY_INSTRUCTION_DATA_FLOW |
1410                           DEPENDENCY_INSTRUCTION_DETAIL);
1411 
1412    return progress;
1413 }
1414