• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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__anoncae3908a0111::acp149    acp()
150    {
151       rb_tree_init(&by_dst);
152       rb_tree_init(&by_src);
153    }
154 
begin__anoncae3908a0111::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__anoncae3908a0111::acp161    const acp_forward_iterator end() const
162    {
163       return acp_forward_iterator(nullptr, 0);
164    }
165 
length__anoncae3908a0111::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__anoncae3908a0111::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__anoncae3908a0111::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__anoncae3908a0111::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__anoncae3908a0111::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,uint8_t max_polygons)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                    uint8_t max_polygons)
665 {
666    if (inst->src[arg].file != VGRF)
667       return false;
668 
669    const struct intel_device_info *devinfo = compiler->devinfo;
670 
671    assert(entry->src.file == VGRF || entry->src.file == UNIFORM ||
672           entry->src.file == ATTR || entry->src.file == FIXED_GRF);
673 
674    /* Avoid propagating a LOAD_PAYLOAD instruction into another if there is a
675     * good chance that we'll be able to eliminate the latter through register
676     * coalescing.  If only part of the sources of the second LOAD_PAYLOAD can
677     * be simplified through copy propagation we would be making register
678     * coalescing impossible, ending up with unnecessary copies in the program.
679     * This is also the case for is_multi_copy_payload() copies that can only
680     * be coalesced when the instruction is lowered into a sequence of MOVs.
681     *
682     * Worse -- In cases where the ACP entry was the result of CSE combining
683     * multiple LOAD_PAYLOAD subexpressions, propagating the first LOAD_PAYLOAD
684     * into the second would undo the work of CSE, leading to an infinite
685     * optimization loop.  Avoid this by detecting LOAD_PAYLOAD copies from CSE
686     * temporaries which should match is_coalescing_payload().
687     */
688    if (entry->opcode == ELK_SHADER_OPCODE_LOAD_PAYLOAD &&
689        (is_coalescing_payload(alloc, inst) || is_multi_copy_payload(inst)))
690       return false;
691 
692    assert(entry->dst.file == VGRF);
693    if (inst->src[arg].nr != entry->dst.nr)
694       return false;
695 
696    /* Bail if inst is reading a range that isn't contained in the range
697     * that entry is writing.
698     */
699    if (!region_contained_in(inst->src[arg], inst->size_read(arg),
700                             entry->dst, entry->size_written))
701       return false;
702 
703    /* Send messages with EOT set are restricted to use g112-g127 (and we
704     * sometimes need g127 for other purposes), so avoid copy propagating
705     * anything that would make it impossible to satisfy that restriction.
706     */
707    if (inst->eot) {
708       /* Avoid propagating a FIXED_GRF register, as that's already pinned. */
709       if (entry->src.file == FIXED_GRF)
710          return false;
711 
712       /* We might be propagating from a large register, while the SEND only
713        * is reading a portion of it (say the .A channel in an RGBA value).
714        * We need to pin both split SEND sources in g112-g126/127, so only
715        * allow this if the registers aren't too large.
716        */
717       if (inst->opcode == ELK_SHADER_OPCODE_SEND && entry->src.file == VGRF) {
718          int other_src = arg == 2 ? 3 : 2;
719          unsigned other_size = inst->src[other_src].file == VGRF ?
720                                alloc.sizes[inst->src[other_src].nr] :
721                                inst->size_read(other_src);
722          unsigned prop_src_size = alloc.sizes[entry->src.nr];
723          if (other_size + prop_src_size > 15)
724             return false;
725       }
726    }
727 
728    /* Avoid propagating odd-numbered FIXED_GRF registers into the first source
729     * of a LINTERP instruction on platforms where the PLN instruction has
730     * register alignment restrictions.
731     */
732    if (devinfo->has_pln && devinfo->ver <= 6 &&
733        entry->src.file == FIXED_GRF && (entry->src.nr & 1) &&
734        inst->opcode == ELK_FS_OPCODE_LINTERP && arg == 0)
735       return false;
736 
737    /* we can't generally copy-propagate UD negations because we
738     * can end up accessing the resulting values as signed integers
739     * instead. See also resolve_ud_negate() and comment in
740     * elk_fs_generator::generate_code.
741     */
742    if (entry->src.type == ELK_REGISTER_TYPE_UD &&
743        entry->src.negate)
744       return false;
745 
746    bool has_source_modifiers = entry->src.abs || entry->src.negate;
747 
748    if (has_source_modifiers && !inst->can_do_source_mods(devinfo))
749       return false;
750 
751    /* Reject cases that would violate register regioning restrictions. */
752    if ((entry->src.file == UNIFORM || !entry->src.is_contiguous()) &&
753        ((devinfo->ver == 6 && inst->is_math()) ||
754         inst->is_send_from_grf() ||
755         inst->uses_indirect_addressing())) {
756       return false;
757    }
758 
759    if (has_source_modifiers &&
760        inst->opcode == ELK_SHADER_OPCODE_GFX4_SCRATCH_WRITE)
761       return false;
762 
763    /* Some instructions implemented in the generator backend, such as
764     * derivatives, assume that their operands are packed so we can't
765     * generally propagate strided regions to them.
766     */
767    const unsigned entry_stride = (entry->src.file == FIXED_GRF ? 1 :
768                                   entry->src.stride);
769    if (instruction_requires_packed_data(inst) && entry_stride != 1)
770       return false;
771 
772    const elk_reg_type dst_type = (has_source_modifiers &&
773                                   entry->dst.type != inst->src[arg].type) ?
774       entry->dst.type : inst->dst.type;
775 
776    /* Bail if the result of composing both strides would exceed the
777     * hardware limit.
778     */
779    if (!can_take_stride(inst, dst_type, arg,
780                         entry_stride * inst->src[arg].stride,
781                         compiler))
782       return false;
783 
784    /* From the Cherry Trail/Braswell PRMs, Volume 7: 3D Media GPGPU:
785     *    EU Overview
786     *       Register Region Restrictions
787     *          Special Requirements for Handling Double Precision Data Types :
788     *
789     *   "When source or destination datatype is 64b or operation is integer
790     *    DWord multiply, regioning in Align1 must follow these rules:
791     *
792     *      1. Source and Destination horizontal stride must be aligned to the
793     *         same qword.
794     *      2. Regioning must ensure Src.Vstride = Src.Width * Src.Hstride.
795     *      3. Source and Destination offset must be the same, except the case
796     *         of scalar source."
797     *
798     * Most of this is already checked in can_take_stride(), we're only left
799     * with checking 3.
800     */
801    if (has_dst_aligned_region_restriction(devinfo, inst, dst_type) &&
802        entry_stride != 0 &&
803        (reg_offset(inst->dst) % REG_SIZE) != (reg_offset(entry->src) % REG_SIZE))
804       return false;
805 
806    /* The <8;8,0> regions used for FS attributes in multipolygon
807     * dispatch mode could violate regioning restrictions, don't copy
808     * propagate them in such cases.
809     */
810    if (entry->src.file == ATTR && max_polygons > 1 &&
811        (has_dst_aligned_region_restriction(devinfo, inst, dst_type) ||
812 	instruction_requires_packed_data(inst) ||
813 	(inst->elk_is_3src(compiler) && arg == 2) ||
814 	entry->dst.type != inst->src[arg].type))
815       return false;
816 
817    /* Bail if the source FIXED_GRF region of the copy cannot be trivially
818     * composed with the source region of the instruction -- E.g. because the
819     * copy uses some extended stride greater than 4 not supported natively by
820     * the hardware as a horizontal stride, or because instruction compression
821     * could require us to use a vertical stride shorter than a GRF.
822     */
823    if (entry->src.file == FIXED_GRF &&
824        (inst->src[arg].stride > 4 ||
825         inst->dst.component_size(inst->exec_size) >
826         inst->src[arg].component_size(inst->exec_size)))
827       return false;
828 
829    /* Bail if the instruction type is larger than the execution type of the
830     * copy, what implies that each channel is reading multiple channels of the
831     * destination of the copy, and simply replacing the sources would give a
832     * program with different semantics.
833     */
834    if ((type_sz(entry->dst.type) < type_sz(inst->src[arg].type) ||
835         entry->is_partial_write) &&
836        inst->opcode != ELK_OPCODE_MOV) {
837       return false;
838    }
839 
840    /* Bail if the result of composing both strides cannot be expressed
841     * as another stride. This avoids, for example, trying to transform
842     * this:
843     *
844     *     MOV (8) rX<1>UD rY<0;1,0>UD
845     *     FOO (8) ...     rX<8;8,1>UW
846     *
847     * into this:
848     *
849     *     FOO (8) ...     rY<0;1,0>UW
850     *
851     * Which would have different semantics.
852     */
853    if (entry_stride != 1 &&
854        (inst->src[arg].stride *
855         type_sz(inst->src[arg].type)) % type_sz(entry->src.type) != 0)
856       return false;
857 
858    /* Since semantics of source modifiers are type-dependent we need to
859     * ensure that the meaning of the instruction remains the same if we
860     * change the type. If the sizes of the types are different the new
861     * instruction will read a different amount of data than the original
862     * and the semantics will always be different.
863     */
864    if (has_source_modifiers &&
865        entry->dst.type != inst->src[arg].type &&
866        (!inst->can_change_types() ||
867         type_sz(entry->dst.type) != type_sz(inst->src[arg].type)))
868       return false;
869 
870    if (devinfo->ver >= 8 && (entry->src.negate || entry->src.abs) &&
871        is_logic_op(inst->opcode)) {
872       return false;
873    }
874 
875    /* Save the offset of inst->src[arg] relative to entry->dst for it to be
876     * applied later.
877     */
878    const unsigned rel_offset = inst->src[arg].offset - entry->dst.offset;
879 
880    /* Fold the copy into the instruction consuming it. */
881    inst->src[arg].file = entry->src.file;
882    inst->src[arg].nr = entry->src.nr;
883    inst->src[arg].subnr = entry->src.subnr;
884    inst->src[arg].offset = entry->src.offset;
885 
886    /* Compose the strides of both regions. */
887    if (entry->src.file == FIXED_GRF) {
888       if (inst->src[arg].stride) {
889          const unsigned orig_width = 1 << entry->src.width;
890          const unsigned reg_width = REG_SIZE / (type_sz(inst->src[arg].type) *
891                                                 inst->src[arg].stride);
892          inst->src[arg].width = cvt(MIN2(orig_width, reg_width)) - 1;
893          inst->src[arg].hstride = cvt(inst->src[arg].stride);
894          inst->src[arg].vstride = inst->src[arg].hstride + inst->src[arg].width;
895       } else {
896          inst->src[arg].vstride = inst->src[arg].hstride =
897             inst->src[arg].width = 0;
898       }
899 
900       inst->src[arg].stride = 1;
901 
902       /* Hopefully no Align16 around here... */
903       assert(entry->src.swizzle == ELK_SWIZZLE_XYZW);
904       inst->src[arg].swizzle = entry->src.swizzle;
905    } else {
906       inst->src[arg].stride *= entry->src.stride;
907    }
908 
909    /* Compute the first component of the copy that the instruction is
910     * reading, and the base byte offset within that component.
911     */
912    assert((entry->dst.offset % REG_SIZE == 0 || inst->opcode == ELK_OPCODE_MOV) &&
913            entry->dst.stride == 1);
914    const unsigned component = rel_offset / type_sz(entry->dst.type);
915    const unsigned suboffset = rel_offset % type_sz(entry->dst.type);
916 
917    /* Calculate the byte offset at the origin of the copy of the given
918     * component and suboffset.
919     */
920    inst->src[arg] = byte_offset(inst->src[arg],
921       component * entry_stride * type_sz(entry->src.type) + suboffset);
922 
923    if (has_source_modifiers) {
924       if (entry->dst.type != inst->src[arg].type) {
925          /* We are propagating source modifiers from a MOV with a different
926           * type.  If we got here, then we can just change the source and
927           * destination types of the instruction and keep going.
928           */
929          for (int i = 0; i < inst->sources; i++) {
930             inst->src[i].type = entry->dst.type;
931          }
932          inst->dst.type = entry->dst.type;
933       }
934 
935       if (!inst->src[arg].abs) {
936          inst->src[arg].abs = entry->src.abs;
937          inst->src[arg].negate ^= entry->src.negate;
938       }
939    }
940 
941    return true;
942 }
943 
944 
945 static bool
try_constant_propagate(const elk_compiler * compiler,elk_fs_inst * inst,acp_entry * entry,int arg)946 try_constant_propagate(const elk_compiler *compiler, elk_fs_inst *inst,
947                        acp_entry *entry, int arg)
948 {
949    const struct intel_device_info *devinfo = compiler->devinfo;
950    bool progress = false;
951 
952    if (type_sz(entry->src.type) > 4)
953       return false;
954 
955    if (inst->src[arg].file != VGRF)
956       return false;
957 
958    assert(entry->dst.file == VGRF);
959    if (inst->src[arg].nr != entry->dst.nr)
960       return false;
961 
962    /* Bail if inst is reading a range that isn't contained in the range
963     * that entry is writing.
964     */
965    if (!region_contained_in(inst->src[arg], inst->size_read(arg),
966                             entry->dst, entry->size_written))
967       return false;
968 
969    /* If the size of the use type is larger than the size of the entry
970     * type, the entry doesn't contain all of the data that the user is
971     * trying to use.
972     */
973    if (type_sz(inst->src[arg].type) > type_sz(entry->dst.type))
974       return false;
975 
976    elk_fs_reg val = entry->src;
977 
978    /* If the size of the use type is smaller than the size of the entry,
979     * clamp the value to the range of the use type.  This enables constant
980     * copy propagation in cases like
981     *
982     *
983     *    mov(8)          g12<1>UD        0x0000000cUD
984     *    ...
985     *    mul(8)          g47<1>D         g86<8,8,1>D     g12<16,8,2>W
986     */
987    if (type_sz(inst->src[arg].type) < type_sz(entry->dst.type)) {
988       if (type_sz(inst->src[arg].type) != 2 || type_sz(entry->dst.type) != 4)
989          return false;
990 
991       assert(inst->src[arg].subnr == 0 || inst->src[arg].subnr == 2);
992 
993       /* When subnr is 0, we want the lower 16-bits, and when it's 2, we
994        * want the upper 16-bits. No other values of subnr are valid for a
995        * UD source.
996        */
997       const uint16_t v = inst->src[arg].subnr == 2 ? val.ud >> 16 : val.ud;
998 
999       val.ud = v | (uint32_t(v) << 16);
1000    }
1001 
1002    val.type = inst->src[arg].type;
1003 
1004    if (inst->src[arg].abs) {
1005       if ((devinfo->ver >= 8 && is_logic_op(inst->opcode)) ||
1006           !elk_abs_immediate(val.type, &val.as_elk_reg())) {
1007          return false;
1008       }
1009    }
1010 
1011    if (inst->src[arg].negate) {
1012       if ((devinfo->ver >= 8 && is_logic_op(inst->opcode)) ||
1013           !elk_negate_immediate(val.type, &val.as_elk_reg())) {
1014          return false;
1015       }
1016    }
1017 
1018    switch (inst->opcode) {
1019    case ELK_OPCODE_MOV:
1020    case ELK_SHADER_OPCODE_LOAD_PAYLOAD:
1021    case ELK_FS_OPCODE_PACK:
1022       inst->src[arg] = val;
1023       progress = true;
1024       break;
1025 
1026    case ELK_SHADER_OPCODE_POW:
1027       /* Allow constant propagation into src1 (except on Gen 6 which
1028        * doesn't support scalar source math), and let constant combining
1029        * promote the constant on Gen < 8.
1030        */
1031       if (devinfo->ver == 6)
1032          break;
1033 
1034       if (arg == 1) {
1035          inst->src[arg] = val;
1036          progress = true;
1037       }
1038       break;
1039 
1040    case ELK_OPCODE_SUBB:
1041       if (arg == 1) {
1042          inst->src[arg] = val;
1043          progress = true;
1044       }
1045       break;
1046 
1047    case ELK_OPCODE_MACH:
1048    case ELK_OPCODE_MUL:
1049    case ELK_SHADER_OPCODE_MULH:
1050    case ELK_OPCODE_ADD:
1051    case ELK_OPCODE_XOR:
1052    case ELK_OPCODE_ADDC:
1053       if (arg == 1) {
1054          inst->src[arg] = val;
1055          progress = true;
1056       } else if (arg == 0 && inst->src[1].file != IMM) {
1057          /* Don't copy propagate the constant in situations like
1058           *
1059           *    mov(8)          g8<1>D          0x7fffffffD
1060           *    mul(8)          g16<1>D         g8<8,8,1>D      g15<16,8,2>W
1061           *
1062           * On platforms that only have a 32x16 multiplier, this will
1063           * result in lowering the multiply to
1064           *
1065           *    mul(8)          g15<1>D         g14<8,8,1>D     0xffffUW
1066           *    mul(8)          g16<1>D         g14<8,8,1>D     0x7fffUW
1067           *    add(8)          g15.1<2>UW      g15.1<16,8,2>UW g16<16,8,2>UW
1068           *
1069           * On Gfx8 and Gfx9, which have the full 32x32 multiplier, it
1070           * results in
1071           *
1072           *    mul(8)          g16<1>D         g15<16,8,2>W    0x7fffffffD
1073           *
1074           * Volume 2a of the Skylake PRM says:
1075           *
1076           *    When multiplying a DW and any lower precision integer, the
1077           *    DW operand must on src0.
1078           */
1079          if (inst->opcode == ELK_OPCODE_MUL &&
1080              type_sz(inst->src[1].type) < 4 &&
1081              type_sz(val.type) == 4)
1082             break;
1083 
1084          /* Fit this constant in by commuting the operands.
1085           * Exception: we can't do this for 32-bit integer MUL/MACH
1086           * because it's asymmetric.
1087           *
1088           * The BSpec says for Broadwell that
1089           *
1090           *    "When multiplying DW x DW, the dst cannot be accumulator."
1091           *
1092           * Integer MUL with a non-accumulator destination will be lowered
1093           * by lower_integer_multiplication(), so don't restrict it.
1094           */
1095          if (((inst->opcode == ELK_OPCODE_MUL &&
1096                inst->dst.is_accumulator()) ||
1097               inst->opcode == ELK_OPCODE_MACH) &&
1098              (inst->src[1].type == ELK_REGISTER_TYPE_D ||
1099               inst->src[1].type == ELK_REGISTER_TYPE_UD))
1100             break;
1101          inst->src[0] = inst->src[1];
1102          inst->src[1] = val;
1103          progress = true;
1104       }
1105       break;
1106 
1107    case ELK_OPCODE_ADD3:
1108       /* add3 can have a single imm16 source. Proceed if the source type is
1109        * already W or UW or the value can be coerced to one of those types.
1110        */
1111       if (val.type == ELK_REGISTER_TYPE_W || val.type == ELK_REGISTER_TYPE_UW)
1112          ; /* Nothing to do. */
1113       else if (val.ud <= 0xffff)
1114          val = elk_imm_uw(val.ud);
1115       else if (val.d >= -0x8000 && val.d <= 0x7fff)
1116          val = elk_imm_w(val.d);
1117       else
1118          break;
1119 
1120       if (arg == 2) {
1121          inst->src[arg] = val;
1122          progress = true;
1123       } else if (inst->src[2].file != IMM) {
1124          inst->src[arg] = inst->src[2];
1125          inst->src[2] = val;
1126          progress = true;
1127       }
1128 
1129       break;
1130 
1131    case ELK_OPCODE_CMP:
1132    case ELK_OPCODE_IF:
1133       if (arg == 1) {
1134          inst->src[arg] = val;
1135          progress = true;
1136       } else if (arg == 0 && inst->src[1].file != IMM) {
1137          enum elk_conditional_mod new_cmod;
1138 
1139          new_cmod = elk_swap_cmod(inst->conditional_mod);
1140          if (new_cmod != ELK_CONDITIONAL_NONE) {
1141             /* Fit this constant in by swapping the operands and
1142              * flipping the test
1143              */
1144             inst->src[0] = inst->src[1];
1145             inst->src[1] = val;
1146             inst->conditional_mod = new_cmod;
1147             progress = true;
1148          }
1149       }
1150       break;
1151 
1152    case ELK_OPCODE_SEL:
1153       if (arg == 1) {
1154          inst->src[arg] = val;
1155          progress = true;
1156       } else if (arg == 0) {
1157          if (inst->src[1].file != IMM &&
1158              (inst->conditional_mod == ELK_CONDITIONAL_NONE ||
1159               /* Only GE and L are commutative. */
1160               inst->conditional_mod == ELK_CONDITIONAL_GE ||
1161               inst->conditional_mod == ELK_CONDITIONAL_L)) {
1162             inst->src[0] = inst->src[1];
1163             inst->src[1] = val;
1164 
1165             /* If this was predicated, flipping operands means
1166              * we also need to flip the predicate.
1167              */
1168             if (inst->conditional_mod == ELK_CONDITIONAL_NONE) {
1169                inst->predicate_inverse =
1170                   !inst->predicate_inverse;
1171             }
1172          } else {
1173             inst->src[0] = val;
1174          }
1175 
1176          progress = true;
1177       }
1178       break;
1179 
1180    case ELK_FS_OPCODE_FB_WRITE_LOGICAL:
1181       /* The stencil and omask sources of ELK_FS_OPCODE_FB_WRITE_LOGICAL are
1182        * bit-cast using a strided region so they cannot be immediates.
1183        */
1184       if (arg != FB_WRITE_LOGICAL_SRC_SRC_STENCIL &&
1185           arg != FB_WRITE_LOGICAL_SRC_OMASK) {
1186          inst->src[arg] = val;
1187          progress = true;
1188       }
1189       break;
1190 
1191    case ELK_SHADER_OPCODE_INT_QUOTIENT:
1192    case ELK_SHADER_OPCODE_INT_REMAINDER:
1193       /* Allow constant propagation into either source (except on Gen 6
1194        * which doesn't support scalar source math). Constant combining
1195        * promote the src1 constant on Gen < 8, and it will promote the src0
1196        * constant on all platforms.
1197        */
1198       if (devinfo->ver == 6)
1199          break;
1200 
1201       FALLTHROUGH;
1202    case ELK_OPCODE_AND:
1203    case ELK_OPCODE_ASR:
1204    case ELK_OPCODE_BFE:
1205    case ELK_OPCODE_BFI1:
1206    case ELK_OPCODE_BFI2:
1207    case ELK_OPCODE_ROL:
1208    case ELK_OPCODE_ROR:
1209    case ELK_OPCODE_SHL:
1210    case ELK_OPCODE_SHR:
1211    case ELK_OPCODE_OR:
1212    case ELK_SHADER_OPCODE_TEX_LOGICAL:
1213    case ELK_SHADER_OPCODE_TXD_LOGICAL:
1214    case ELK_SHADER_OPCODE_TXF_LOGICAL:
1215    case ELK_SHADER_OPCODE_TXL_LOGICAL:
1216    case ELK_SHADER_OPCODE_TXS_LOGICAL:
1217    case ELK_FS_OPCODE_TXB_LOGICAL:
1218    case ELK_SHADER_OPCODE_TXF_CMS_LOGICAL:
1219    case ELK_SHADER_OPCODE_TXF_CMS_W_LOGICAL:
1220    case ELK_SHADER_OPCODE_TXF_CMS_W_GFX12_LOGICAL:
1221    case ELK_SHADER_OPCODE_TXF_UMS_LOGICAL:
1222    case ELK_SHADER_OPCODE_TXF_MCS_LOGICAL:
1223    case ELK_SHADER_OPCODE_LOD_LOGICAL:
1224    case ELK_SHADER_OPCODE_TG4_LOGICAL:
1225    case ELK_SHADER_OPCODE_TG4_OFFSET_LOGICAL:
1226    case ELK_SHADER_OPCODE_SAMPLEINFO_LOGICAL:
1227    case ELK_SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
1228    case ELK_SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
1229    case ELK_SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
1230    case ELK_SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
1231    case ELK_SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
1232    case ELK_SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
1233    case ELK_SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
1234    case ELK_SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
1235    case ELK_SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
1236    case ELK_FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
1237    case ELK_SHADER_OPCODE_BROADCAST:
1238    case ELK_OPCODE_MAD:
1239    case ELK_OPCODE_LRP:
1240    case ELK_FS_OPCODE_PACK_HALF_2x16_SPLIT:
1241    case ELK_SHADER_OPCODE_SHUFFLE:
1242       inst->src[arg] = val;
1243       progress = true;
1244       break;
1245 
1246    default:
1247       break;
1248    }
1249 
1250    return progress;
1251 }
1252 
1253 static bool
can_propagate_from(elk_fs_inst * inst)1254 can_propagate_from(elk_fs_inst *inst)
1255 {
1256    return (inst->opcode == ELK_OPCODE_MOV &&
1257            inst->dst.file == VGRF &&
1258            ((inst->src[0].file == VGRF &&
1259              !grf_regions_overlap(inst->dst, inst->size_written,
1260                                   inst->src[0], inst->size_read(0))) ||
1261             inst->src[0].file == ATTR ||
1262             inst->src[0].file == UNIFORM ||
1263             inst->src[0].file == IMM ||
1264             (inst->src[0].file == FIXED_GRF &&
1265              inst->src[0].is_contiguous())) &&
1266            inst->src[0].type == inst->dst.type &&
1267            !inst->saturate &&
1268            /* Subset of !is_partial_write() conditions. */
1269            !inst->predicate && inst->dst.is_contiguous()) ||
1270           is_identity_payload(FIXED_GRF, inst);
1271 }
1272 
1273 /* Walks a basic block and does copy propagation on it using the acp
1274  * list.
1275  */
1276 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,uint8_t max_polygons)1277 opt_copy_propagation_local(const elk_compiler *compiler, linear_ctx *lin_ctx,
1278                            elk_bblock_t *block, struct acp &acp,
1279                            const elk::simple_allocator &alloc,
1280                            uint8_t max_polygons)
1281 {
1282    bool progress = false;
1283 
1284    foreach_inst_in_block(elk_fs_inst, inst, block) {
1285       /* Try propagating into this instruction. */
1286       bool instruction_progress = false;
1287       for (int i = inst->sources - 1; i >= 0; i--) {
1288          if (inst->src[i].file != VGRF)
1289             continue;
1290 
1291          for (auto iter = acp.find_by_dst(inst->src[i].nr);
1292               iter != acp.end() && (*iter)->dst.nr == inst->src[i].nr;
1293               ++iter) {
1294             if ((*iter)->src.file == IMM) {
1295                if (try_constant_propagate(compiler, inst, *iter, i)) {
1296                   instruction_progress = true;
1297                   break;
1298                }
1299             } else {
1300                if (try_copy_propagate(compiler, inst, *iter, i, alloc,
1301                                       max_polygons)) {
1302                   instruction_progress = true;
1303                   break;
1304                }
1305             }
1306          }
1307       }
1308 
1309       if (instruction_progress) {
1310          progress = true;
1311 
1312          /* ADD3 can only have the immediate as src0. */
1313          if (inst->opcode == ELK_OPCODE_ADD3) {
1314             if (inst->src[2].file == IMM) {
1315                const auto src0 = inst->src[0];
1316                inst->src[0] = inst->src[2];
1317                inst->src[2] = src0;
1318             }
1319          }
1320 
1321          /* If only one of the sources of a 2-source, commutative instruction (e.g.,
1322           * AND) is immediate, it must be src1. If both are immediate, opt_algebraic
1323           * should fold it away.
1324           */
1325          if (inst->sources == 2 && inst->is_commutative() &&
1326              inst->src[0].file == IMM && inst->src[1].file != IMM) {
1327             const auto src1 = inst->src[1];
1328             inst->src[1] = inst->src[0];
1329             inst->src[0] = src1;
1330          }
1331       }
1332 
1333       /* kill the destination from the ACP */
1334       if (inst->dst.file == VGRF || inst->dst.file == FIXED_GRF) {
1335          for (auto iter = acp.find_by_dst(inst->dst.nr);
1336               iter != acp.end() && (*iter)->dst.nr == inst->dst.nr;
1337               ++iter) {
1338             if (grf_regions_overlap((*iter)->dst, (*iter)->size_written,
1339                                     inst->dst, inst->size_written))
1340                acp.remove(*iter);
1341          }
1342 
1343          for (auto iter = acp.find_by_src(inst->dst.nr);
1344               iter != acp.end() && (*iter)->src.nr == inst->dst.nr;
1345               ++iter) {
1346             /* Make sure we kill the entry if this instruction overwrites
1347              * _any_ of the registers that it reads
1348              */
1349             if (grf_regions_overlap((*iter)->src, (*iter)->size_read,
1350                                     inst->dst, inst->size_written))
1351                acp.remove(*iter);
1352          }
1353       }
1354 
1355       /* If this instruction's source could potentially be folded into the
1356        * operand of another instruction, add it to the ACP.
1357        */
1358       if (can_propagate_from(inst)) {
1359          acp_entry *entry = linear_zalloc(lin_ctx, acp_entry);
1360          entry->dst = inst->dst;
1361          entry->src = inst->src[0];
1362          entry->size_written = inst->size_written;
1363          for (unsigned i = 0; i < inst->sources; i++)
1364             entry->size_read += inst->size_read(i);
1365          entry->opcode = inst->opcode;
1366          entry->is_partial_write = inst->is_partial_write();
1367          entry->force_writemask_all = inst->force_writemask_all;
1368          acp.add(entry);
1369       } else if (inst->opcode == ELK_SHADER_OPCODE_LOAD_PAYLOAD &&
1370                  inst->dst.file == VGRF) {
1371          int offset = 0;
1372          for (int i = 0; i < inst->sources; i++) {
1373             int effective_width = i < inst->header_size ? 8 : inst->exec_size;
1374             const unsigned size_written = effective_width *
1375                                           type_sz(inst->src[i].type);
1376             if (inst->src[i].file == VGRF ||
1377                 (inst->src[i].file == FIXED_GRF &&
1378                  inst->src[i].is_contiguous())) {
1379                const elk_reg_type t = i < inst->header_size ?
1380                   ELK_REGISTER_TYPE_UD : inst->src[i].type;
1381                elk_fs_reg dst = byte_offset(retype(inst->dst, t), offset);
1382                if (!dst.equals(inst->src[i])) {
1383                   acp_entry *entry = linear_zalloc(lin_ctx, acp_entry);
1384                   entry->dst = dst;
1385                   entry->src = retype(inst->src[i], t);
1386                   entry->size_written = size_written;
1387                   entry->size_read = inst->size_read(i);
1388                   entry->opcode = inst->opcode;
1389                   entry->force_writemask_all = inst->force_writemask_all;
1390                   acp.add(entry);
1391                }
1392             }
1393             offset += size_written;
1394          }
1395       }
1396    }
1397 
1398    return progress;
1399 }
1400 
1401 bool
opt_copy_propagation()1402 elk_fs_visitor::opt_copy_propagation()
1403 {
1404    bool progress = false;
1405    void *copy_prop_ctx = ralloc_context(NULL);
1406    linear_ctx *lin_ctx = linear_context(copy_prop_ctx);
1407    struct acp out_acp[cfg->num_blocks];
1408 
1409    const fs_live_variables &live = live_analysis.require();
1410 
1411    /* First, walk through each block doing local copy propagation and getting
1412     * the set of copies available at the end of the block.
1413     */
1414    foreach_block (block, cfg) {
1415       progress = opt_copy_propagation_local(compiler, lin_ctx, block,
1416                                             out_acp[block->num], alloc,
1417                                             max_polygons) || progress;
1418 
1419       /* If the destination of an ACP entry exists only within this block,
1420        * then there's no need to keep it for dataflow analysis.  We can delete
1421        * it from the out_acp table and avoid growing the bitsets any bigger
1422        * than we absolutely have to.
1423        *
1424        * Because nothing in opt_copy_propagation_local touches the block
1425        * start/end IPs and opt_copy_propagation_local is incapable of
1426        * extending the live range of an ACP destination beyond the block,
1427        * it's safe to use the liveness information in this way.
1428        */
1429       for (auto iter = out_acp[block->num].begin();
1430            iter != out_acp[block->num].end(); ++iter) {
1431          assert((*iter)->dst.file == VGRF);
1432          if (block->start_ip <= live.vgrf_start[(*iter)->dst.nr] &&
1433              live.vgrf_end[(*iter)->dst.nr] <= block->end_ip) {
1434             out_acp[block->num].remove(*iter);
1435          }
1436       }
1437    }
1438 
1439    /* Do dataflow analysis for those available copies. */
1440    fs_copy_prop_dataflow dataflow(lin_ctx, cfg, live, out_acp);
1441 
1442    /* Next, re-run local copy propagation, this time with the set of copies
1443     * provided by the dataflow analysis available at the start of a block.
1444     */
1445    foreach_block (block, cfg) {
1446       struct acp in_acp;
1447 
1448       for (int i = 0; i < dataflow.num_acp; i++) {
1449          if (BITSET_TEST(dataflow.bd[block->num].livein, i) &&
1450              !BITSET_TEST(dataflow.bd[block->num].exec_mismatch, i)) {
1451             struct acp_entry *entry = dataflow.acp[i];
1452             in_acp.add(entry);
1453          }
1454       }
1455 
1456       progress = opt_copy_propagation_local(compiler, lin_ctx, block,
1457                                             in_acp, alloc, max_polygons) ||
1458                  progress;
1459    }
1460 
1461    ralloc_free(copy_prop_ctx);
1462 
1463    if (progress)
1464       invalidate_analysis(DEPENDENCY_INSTRUCTION_DATA_FLOW |
1465                           DEPENDENCY_INSTRUCTION_DETAIL);
1466 
1467    return progress;
1468 }
1469