• 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 brw_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 #define ACP_HASH_SIZE 16
36 
37 #include "util/bitset.h"
38 #include "brw_fs.h"
39 #include "brw_fs_live_variables.h"
40 #include "brw_cfg.h"
41 #include "brw_eu.h"
42 
43 using namespace brw;
44 
45 namespace { /* avoid conflict with opt_copy_propagation_elements */
46 struct acp_entry : public exec_node {
47    fs_reg dst;
48    fs_reg src;
49    uint8_t size_written;
50    uint8_t size_read;
51    enum opcode opcode;
52    bool saturate;
53 };
54 
55 struct block_data {
56    /**
57     * Which entries in the fs_copy_prop_dataflow acp table are live at the
58     * start of this block.  This is the useful output of the analysis, since
59     * it lets us plug those into the local copy propagation on the second
60     * pass.
61     */
62    BITSET_WORD *livein;
63 
64    /**
65     * Which entries in the fs_copy_prop_dataflow acp table are live at the end
66     * of this block.  This is done in initial setup from the per-block acps
67     * returned by the first local copy prop pass.
68     */
69    BITSET_WORD *liveout;
70 
71    /**
72     * Which entries in the fs_copy_prop_dataflow acp table are generated by
73     * instructions in this block which reach the end of the block without
74     * being killed.
75     */
76    BITSET_WORD *copy;
77 
78    /**
79     * Which entries in the fs_copy_prop_dataflow acp table are killed over the
80     * course of this block.
81     */
82    BITSET_WORD *kill;
83 
84    /**
85     * Which entries in the fs_copy_prop_dataflow acp table are guaranteed to
86     * have a fully uninitialized destination at the end of this block.
87     */
88    BITSET_WORD *undef;
89 };
90 
91 class fs_copy_prop_dataflow
92 {
93 public:
94    fs_copy_prop_dataflow(void *mem_ctx, cfg_t *cfg,
95                          const fs_live_variables *live,
96                          exec_list *out_acp[ACP_HASH_SIZE]);
97 
98    void setup_initial_values();
99    void run();
100 
101    void dump_block_data() const UNUSED;
102 
103    void *mem_ctx;
104    cfg_t *cfg;
105    const fs_live_variables *live;
106 
107    acp_entry **acp;
108    int num_acp;
109    int bitset_words;
110 
111   struct block_data *bd;
112 };
113 } /* anonymous namespace */
114 
fs_copy_prop_dataflow(void * mem_ctx,cfg_t * cfg,const fs_live_variables * live,exec_list * out_acp[ACP_HASH_SIZE])115 fs_copy_prop_dataflow::fs_copy_prop_dataflow(void *mem_ctx, cfg_t *cfg,
116                                              const fs_live_variables *live,
117                                              exec_list *out_acp[ACP_HASH_SIZE])
118    : mem_ctx(mem_ctx), cfg(cfg), live(live)
119 {
120    bd = rzalloc_array(mem_ctx, struct block_data, cfg->num_blocks);
121 
122    num_acp = 0;
123    foreach_block (block, cfg) {
124       for (int i = 0; i < ACP_HASH_SIZE; i++) {
125          num_acp += out_acp[block->num][i].length();
126       }
127    }
128 
129    acp = rzalloc_array(mem_ctx, struct acp_entry *, num_acp);
130 
131    bitset_words = BITSET_WORDS(num_acp);
132 
133    int next_acp = 0;
134    foreach_block (block, cfg) {
135       bd[block->num].livein = rzalloc_array(bd, BITSET_WORD, bitset_words);
136       bd[block->num].liveout = rzalloc_array(bd, BITSET_WORD, bitset_words);
137       bd[block->num].copy = rzalloc_array(bd, BITSET_WORD, bitset_words);
138       bd[block->num].kill = rzalloc_array(bd, BITSET_WORD, bitset_words);
139       bd[block->num].undef = rzalloc_array(bd, BITSET_WORD, bitset_words);
140 
141       for (int i = 0; i < ACP_HASH_SIZE; i++) {
142          foreach_in_list(acp_entry, entry, &out_acp[block->num][i]) {
143             acp[next_acp] = entry;
144 
145             /* opt_copy_propagation_local populates out_acp with copies created
146              * in a block which are still live at the end of the block.  This
147              * is exactly what we want in the COPY set.
148              */
149             BITSET_SET(bd[block->num].copy, next_acp);
150 
151             next_acp++;
152          }
153       }
154    }
155 
156    assert(next_acp == num_acp);
157 
158    setup_initial_values();
159    run();
160 }
161 
162 /**
163  * Set up initial values for each of the data flow sets, prior to running
164  * the fixed-point algorithm.
165  */
166 void
setup_initial_values()167 fs_copy_prop_dataflow::setup_initial_values()
168 {
169    /* Initialize the COPY and KILL sets. */
170    foreach_block (block, cfg) {
171       foreach_inst_in_block(fs_inst, inst, block) {
172          if (inst->dst.file != VGRF)
173             continue;
174 
175          /* Mark ACP entries which are killed by this instruction. */
176          for (int i = 0; i < num_acp; i++) {
177             if (regions_overlap(inst->dst, inst->size_written,
178                                 acp[i]->dst, acp[i]->size_written) ||
179                 regions_overlap(inst->dst, inst->size_written,
180                                 acp[i]->src, acp[i]->size_read)) {
181                BITSET_SET(bd[block->num].kill, i);
182             }
183          }
184       }
185    }
186 
187    /* Populate the initial values for the livein and liveout sets.  For the
188     * block at the start of the program, livein = 0 and liveout = copy.
189     * For the others, set liveout and livein to ~0 (the universal set).
190     */
191    foreach_block (block, cfg) {
192       if (block->parents.is_empty()) {
193          for (int i = 0; i < bitset_words; i++) {
194             bd[block->num].livein[i] = 0u;
195             bd[block->num].liveout[i] = bd[block->num].copy[i];
196          }
197       } else {
198          for (int i = 0; i < bitset_words; i++) {
199             bd[block->num].liveout[i] = ~0u;
200             bd[block->num].livein[i] = ~0u;
201          }
202       }
203    }
204 
205    /* Initialize the undef set. */
206    foreach_block (block, cfg) {
207       for (int i = 0; i < num_acp; i++) {
208          BITSET_SET(bd[block->num].undef, i);
209          for (unsigned off = 0; off < acp[i]->size_written; off += REG_SIZE) {
210             if (BITSET_TEST(live->block_data[block->num].defout,
211                             live->var_from_reg(byte_offset(acp[i]->dst, off))))
212                BITSET_CLEAR(bd[block->num].undef, i);
213          }
214       }
215    }
216 }
217 
218 /**
219  * Walk the set of instructions in the block, marking which entries in the acp
220  * are killed by the block.
221  */
222 void
run()223 fs_copy_prop_dataflow::run()
224 {
225    bool progress;
226 
227    do {
228       progress = false;
229 
230       foreach_block (block, cfg) {
231          if (block->parents.is_empty())
232             continue;
233 
234          for (int i = 0; i < bitset_words; i++) {
235             const BITSET_WORD old_liveout = bd[block->num].liveout[i];
236             BITSET_WORD livein_from_any_block = 0;
237 
238             /* Update livein for this block.  If a copy is live out of all
239              * parent blocks, it's live coming in to this block.
240              */
241             bd[block->num].livein[i] = ~0u;
242             foreach_list_typed(bblock_link, parent_link, link, &block->parents) {
243                bblock_t *parent = parent_link->block;
244                /* Consider ACP entries with a known-undefined destination to
245                 * be available from the parent.  This is valid because we're
246                 * free to set the undefined variable equal to the source of
247                 * the ACP entry without breaking the application's
248                 * expectations, since the variable is undefined.
249                 */
250                bd[block->num].livein[i] &= (bd[parent->num].liveout[i] |
251                                             bd[parent->num].undef[i]);
252                livein_from_any_block |= bd[parent->num].liveout[i];
253             }
254 
255             /* Limit to the set of ACP entries that can possibly be available
256              * at the start of the block, since propagating from a variable
257              * which is guaranteed to be undefined (rather than potentially
258              * undefined for some dynamic control-flow paths) doesn't seem
259              * particularly useful.
260              */
261             bd[block->num].livein[i] &= livein_from_any_block;
262 
263             /* Update liveout for this block. */
264             bd[block->num].liveout[i] =
265                bd[block->num].copy[i] | (bd[block->num].livein[i] &
266                                          ~bd[block->num].kill[i]);
267 
268             if (old_liveout != bd[block->num].liveout[i])
269                progress = true;
270          }
271       }
272    } while (progress);
273 }
274 
275 void
dump_block_data() const276 fs_copy_prop_dataflow::dump_block_data() const
277 {
278    foreach_block (block, cfg) {
279       fprintf(stderr, "Block %d [%d, %d] (parents ", block->num,
280              block->start_ip, block->end_ip);
281       foreach_list_typed(bblock_link, link, link, &block->parents) {
282          bblock_t *parent = link->block;
283          fprintf(stderr, "%d ", parent->num);
284       }
285       fprintf(stderr, "):\n");
286       fprintf(stderr, "       livein = 0x");
287       for (int i = 0; i < bitset_words; i++)
288          fprintf(stderr, "%08x", bd[block->num].livein[i]);
289       fprintf(stderr, ", liveout = 0x");
290       for (int i = 0; i < bitset_words; i++)
291          fprintf(stderr, "%08x", bd[block->num].liveout[i]);
292       fprintf(stderr, ",\n       copy   = 0x");
293       for (int i = 0; i < bitset_words; i++)
294          fprintf(stderr, "%08x", bd[block->num].copy[i]);
295       fprintf(stderr, ", kill    = 0x");
296       for (int i = 0; i < bitset_words; i++)
297          fprintf(stderr, "%08x", bd[block->num].kill[i]);
298       fprintf(stderr, "\n");
299    }
300 }
301 
302 static bool
is_logic_op(enum opcode opcode)303 is_logic_op(enum opcode opcode)
304 {
305    return (opcode == BRW_OPCODE_AND ||
306            opcode == BRW_OPCODE_OR  ||
307            opcode == BRW_OPCODE_XOR ||
308            opcode == BRW_OPCODE_NOT);
309 }
310 
311 static bool
can_take_stride(fs_inst * inst,unsigned arg,unsigned stride,const gen_device_info * devinfo)312 can_take_stride(fs_inst *inst, unsigned arg, unsigned stride,
313                 const gen_device_info *devinfo)
314 {
315    if (stride > 4)
316       return false;
317 
318    /* 3-source instructions can only be Align16, which restricts what strides
319     * they can take. They can only take a stride of 1 (the usual case), or 0
320     * with a special "repctrl" bit. But the repctrl bit doesn't work for
321     * 64-bit datatypes, so if the source type is 64-bit then only a stride of
322     * 1 is allowed. From the Broadwell PRM, Volume 7 "3D Media GPGPU", page
323     * 944:
324     *
325     *    This is applicable to 32b datatypes and 16b datatype. 64b datatypes
326     *    cannot use the replicate control.
327     */
328    if (inst->is_3src(devinfo)) {
329       if (type_sz(inst->src[arg].type) > 4)
330          return stride == 1;
331       else
332          return stride == 1 || stride == 0;
333    }
334 
335    /* From the Broadwell PRM, Volume 2a "Command Reference - Instructions",
336     * page 391 ("Extended Math Function"):
337     *
338     *     The following restrictions apply for align1 mode: Scalar source is
339     *     supported. Source and destination horizontal stride must be the
340     *     same.
341     *
342     * From the Haswell PRM Volume 2b "Command Reference - Instructions", page
343     * 134 ("Extended Math Function"):
344     *
345     *    Scalar source is supported. Source and destination horizontal stride
346     *    must be 1.
347     *
348     * and similar language exists for IVB and SNB. Pre-SNB, math instructions
349     * are sends, so the sources are moved to MRF's and there are no
350     * restrictions.
351     */
352    if (inst->is_math()) {
353       if (devinfo->gen == 6 || devinfo->gen == 7) {
354          assert(inst->dst.stride == 1);
355          return stride == 1 || stride == 0;
356       } else if (devinfo->gen >= 8) {
357          return stride == inst->dst.stride || stride == 0;
358       }
359    }
360 
361    return true;
362 }
363 
364 bool
try_copy_propagate(fs_inst * inst,int arg,acp_entry * entry)365 fs_visitor::try_copy_propagate(fs_inst *inst, int arg, acp_entry *entry)
366 {
367    if (inst->src[arg].file != VGRF)
368       return false;
369 
370    if (entry->src.file == IMM)
371       return false;
372    assert(entry->src.file == VGRF || entry->src.file == UNIFORM ||
373           entry->src.file == ATTR);
374 
375    if (entry->opcode == SHADER_OPCODE_LOAD_PAYLOAD &&
376        inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD)
377       return false;
378 
379    assert(entry->dst.file == VGRF);
380    if (inst->src[arg].nr != entry->dst.nr)
381       return false;
382 
383    /* Bail if inst is reading a range that isn't contained in the range
384     * that entry is writing.
385     */
386    if (!region_contained_in(inst->src[arg], inst->size_read(arg),
387                             entry->dst, entry->size_written))
388       return false;
389 
390    /* we can't generally copy-propagate UD negations because we
391     * can end up accessing the resulting values as signed integers
392     * instead. See also resolve_ud_negate() and comment in
393     * fs_generator::generate_code.
394     */
395    if (entry->src.type == BRW_REGISTER_TYPE_UD &&
396        entry->src.negate)
397       return false;
398 
399    bool has_source_modifiers = entry->src.abs || entry->src.negate;
400 
401    if ((has_source_modifiers || entry->src.file == UNIFORM ||
402         !entry->src.is_contiguous()) &&
403        !inst->can_do_source_mods(devinfo))
404       return false;
405 
406    if (has_source_modifiers &&
407        inst->opcode == SHADER_OPCODE_GEN4_SCRATCH_WRITE)
408       return false;
409 
410    /* Bail if the result of composing both strides would exceed the
411     * hardware limit.
412     */
413    if (!can_take_stride(inst, arg, entry->src.stride * inst->src[arg].stride,
414                         devinfo))
415       return false;
416 
417    /* Bail if the instruction type is larger than the execution type of the
418     * copy, what implies that each channel is reading multiple channels of the
419     * destination of the copy, and simply replacing the sources would give a
420     * program with different semantics.
421     */
422    if (type_sz(entry->dst.type) < type_sz(inst->src[arg].type))
423       return false;
424 
425    /* Bail if the result of composing both strides cannot be expressed
426     * as another stride. This avoids, for example, trying to transform
427     * this:
428     *
429     *     MOV (8) rX<1>UD rY<0;1,0>UD
430     *     FOO (8) ...     rX<8;8,1>UW
431     *
432     * into this:
433     *
434     *     FOO (8) ...     rY<0;1,0>UW
435     *
436     * Which would have different semantics.
437     */
438    if (entry->src.stride != 1 &&
439        (inst->src[arg].stride *
440         type_sz(inst->src[arg].type)) % type_sz(entry->src.type) != 0)
441       return false;
442 
443    /* Since semantics of source modifiers are type-dependent we need to
444     * ensure that the meaning of the instruction remains the same if we
445     * change the type. If the sizes of the types are different the new
446     * instruction will read a different amount of data than the original
447     * and the semantics will always be different.
448     */
449    if (has_source_modifiers &&
450        entry->dst.type != inst->src[arg].type &&
451        (!inst->can_change_types() ||
452         type_sz(entry->dst.type) != type_sz(inst->src[arg].type)))
453       return false;
454 
455    if (devinfo->gen >= 8 && (entry->src.negate || entry->src.abs) &&
456        is_logic_op(inst->opcode)) {
457       return false;
458    }
459 
460    if (entry->saturate) {
461       switch(inst->opcode) {
462       case BRW_OPCODE_SEL:
463          if ((inst->conditional_mod != BRW_CONDITIONAL_GE &&
464               inst->conditional_mod != BRW_CONDITIONAL_L) ||
465              inst->src[1].file != IMM ||
466              inst->src[1].f < 0.0 ||
467              inst->src[1].f > 1.0) {
468             return false;
469          }
470          break;
471       default:
472          return false;
473       }
474    }
475 
476    inst->src[arg].file = entry->src.file;
477    inst->src[arg].nr = entry->src.nr;
478    inst->src[arg].stride *= entry->src.stride;
479    inst->saturate = inst->saturate || entry->saturate;
480 
481    /* Compute the offset of inst->src[arg] relative to entry->dst */
482    const unsigned rel_offset = inst->src[arg].offset - entry->dst.offset;
483 
484    /* Compute the first component of the copy that the instruction is
485     * reading, and the base byte offset within that component.
486     */
487    assert(entry->dst.offset % REG_SIZE == 0 && entry->dst.stride == 1);
488    const unsigned component = rel_offset / type_sz(entry->dst.type);
489    const unsigned suboffset = rel_offset % type_sz(entry->dst.type);
490 
491    /* Calculate the byte offset at the origin of the copy of the given
492     * component and suboffset.
493     */
494    inst->src[arg].offset = suboffset +
495       component * entry->src.stride * type_sz(entry->src.type) +
496       entry->src.offset;
497 
498    if (has_source_modifiers) {
499       if (entry->dst.type != inst->src[arg].type) {
500          /* We are propagating source modifiers from a MOV with a different
501           * type.  If we got here, then we can just change the source and
502           * destination types of the instruction and keep going.
503           */
504          assert(inst->can_change_types());
505          for (int i = 0; i < inst->sources; i++) {
506             inst->src[i].type = entry->dst.type;
507          }
508          inst->dst.type = entry->dst.type;
509       }
510 
511       if (!inst->src[arg].abs) {
512          inst->src[arg].abs = entry->src.abs;
513          inst->src[arg].negate ^= entry->src.negate;
514       }
515    }
516 
517    return true;
518 }
519 
520 
521 bool
try_constant_propagate(fs_inst * inst,acp_entry * entry)522 fs_visitor::try_constant_propagate(fs_inst *inst, acp_entry *entry)
523 {
524    bool progress = false;
525 
526    if (entry->src.file != IMM)
527       return false;
528    if (type_sz(entry->src.type) > 4)
529       return false;
530    if (entry->saturate)
531       return false;
532 
533    for (int i = inst->sources - 1; i >= 0; i--) {
534       if (inst->src[i].file != VGRF)
535          continue;
536 
537       assert(entry->dst.file == VGRF);
538       if (inst->src[i].nr != entry->dst.nr)
539          continue;
540 
541       /* Bail if inst is reading a range that isn't contained in the range
542        * that entry is writing.
543        */
544       if (!region_contained_in(inst->src[i], inst->size_read(i),
545                                entry->dst, entry->size_written))
546          continue;
547 
548       /* If the type sizes don't match each channel of the instruction is
549        * either extracting a portion of the constant (which could be handled
550        * with some effort but the code below doesn't) or reading multiple
551        * channels of the source at once.
552        */
553       if (type_sz(inst->src[i].type) != type_sz(entry->dst.type))
554          continue;
555 
556       fs_reg val = entry->src;
557       val.type = inst->src[i].type;
558 
559       if (inst->src[i].abs) {
560          if ((devinfo->gen >= 8 && is_logic_op(inst->opcode)) ||
561              !brw_abs_immediate(val.type, &val.as_brw_reg())) {
562             continue;
563          }
564       }
565 
566       if (inst->src[i].negate) {
567          if ((devinfo->gen >= 8 && is_logic_op(inst->opcode)) ||
568              !brw_negate_immediate(val.type, &val.as_brw_reg())) {
569             continue;
570          }
571       }
572 
573       switch (inst->opcode) {
574       case BRW_OPCODE_MOV:
575       case SHADER_OPCODE_LOAD_PAYLOAD:
576       case FS_OPCODE_PACK:
577          inst->src[i] = val;
578          progress = true;
579          break;
580 
581       case SHADER_OPCODE_INT_QUOTIENT:
582       case SHADER_OPCODE_INT_REMAINDER:
583          /* FINISHME: Promote non-float constants and remove this. */
584          if (devinfo->gen < 8)
585             break;
586          /* fallthrough */
587       case SHADER_OPCODE_POW:
588          /* Allow constant propagation into src1 (except on Gen 6 which
589           * doesn't support scalar source math), and let constant combining
590           * promote the constant on Gen < 8.
591           */
592          if (devinfo->gen == 6)
593             break;
594          /* fallthrough */
595       case BRW_OPCODE_BFI1:
596       case BRW_OPCODE_ASR:
597       case BRW_OPCODE_SHL:
598       case BRW_OPCODE_SHR:
599       case BRW_OPCODE_SUBB:
600          if (i == 1) {
601             inst->src[i] = val;
602             progress = true;
603          }
604          break;
605 
606       case BRW_OPCODE_MACH:
607       case BRW_OPCODE_MUL:
608       case SHADER_OPCODE_MULH:
609       case BRW_OPCODE_ADD:
610       case BRW_OPCODE_OR:
611       case BRW_OPCODE_AND:
612       case BRW_OPCODE_XOR:
613       case BRW_OPCODE_ADDC:
614          if (i == 1) {
615             inst->src[i] = val;
616             progress = true;
617          } else if (i == 0 && inst->src[1].file != IMM) {
618             /* Fit this constant in by commuting the operands.
619              * Exception: we can't do this for 32-bit integer MUL/MACH
620              * because it's asymmetric.
621              *
622              * The BSpec says for Broadwell that
623              *
624              *    "When multiplying DW x DW, the dst cannot be accumulator."
625              *
626              * Integer MUL with a non-accumulator destination will be lowered
627              * by lower_integer_multiplication(), so don't restrict it.
628              */
629             if (((inst->opcode == BRW_OPCODE_MUL &&
630                   inst->dst.is_accumulator()) ||
631                  inst->opcode == BRW_OPCODE_MACH) &&
632                 (inst->src[1].type == BRW_REGISTER_TYPE_D ||
633                  inst->src[1].type == BRW_REGISTER_TYPE_UD))
634                break;
635             inst->src[0] = inst->src[1];
636             inst->src[1] = val;
637             progress = true;
638          }
639          break;
640 
641       case BRW_OPCODE_CMP:
642       case BRW_OPCODE_IF:
643          if (i == 1) {
644             inst->src[i] = val;
645             progress = true;
646          } else if (i == 0 && inst->src[1].file != IMM) {
647             enum brw_conditional_mod new_cmod;
648 
649             new_cmod = brw_swap_cmod(inst->conditional_mod);
650             if (new_cmod != BRW_CONDITIONAL_NONE) {
651                /* Fit this constant in by swapping the operands and
652                 * flipping the test
653                 */
654                inst->src[0] = inst->src[1];
655                inst->src[1] = val;
656                inst->conditional_mod = new_cmod;
657                progress = true;
658             }
659          }
660          break;
661 
662       case BRW_OPCODE_SEL:
663          if (i == 1) {
664             inst->src[i] = val;
665             progress = true;
666          } else if (i == 0 && inst->src[1].file != IMM) {
667             inst->src[0] = inst->src[1];
668             inst->src[1] = val;
669 
670             /* If this was predicated, flipping operands means
671              * we also need to flip the predicate.
672              */
673             if (inst->conditional_mod == BRW_CONDITIONAL_NONE) {
674                inst->predicate_inverse =
675                   !inst->predicate_inverse;
676             }
677             progress = true;
678          }
679          break;
680 
681       case SHADER_OPCODE_UNTYPED_ATOMIC:
682       case SHADER_OPCODE_UNTYPED_SURFACE_READ:
683       case SHADER_OPCODE_UNTYPED_SURFACE_WRITE:
684       case SHADER_OPCODE_TYPED_ATOMIC:
685       case SHADER_OPCODE_TYPED_SURFACE_READ:
686       case SHADER_OPCODE_TYPED_SURFACE_WRITE:
687       case SHADER_OPCODE_BYTE_SCATTERED_WRITE:
688       case SHADER_OPCODE_BYTE_SCATTERED_READ:
689          /* We only propagate into the surface argument of the
690           * instruction. Everything else goes through LOAD_PAYLOAD.
691           */
692          if (i == 1) {
693             inst->src[i] = val;
694             progress = true;
695          }
696          break;
697 
698       case FS_OPCODE_FB_WRITE_LOGICAL:
699          /* The stencil and omask sources of FS_OPCODE_FB_WRITE_LOGICAL are
700           * bit-cast using a strided region so they cannot be immediates.
701           */
702          if (i != FB_WRITE_LOGICAL_SRC_SRC_STENCIL &&
703              i != FB_WRITE_LOGICAL_SRC_OMASK) {
704             inst->src[i] = val;
705             progress = true;
706          }
707          break;
708 
709       case SHADER_OPCODE_TEX_LOGICAL:
710       case SHADER_OPCODE_TXD_LOGICAL:
711       case SHADER_OPCODE_TXF_LOGICAL:
712       case SHADER_OPCODE_TXL_LOGICAL:
713       case SHADER_OPCODE_TXS_LOGICAL:
714       case FS_OPCODE_TXB_LOGICAL:
715       case SHADER_OPCODE_TXF_CMS_LOGICAL:
716       case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
717       case SHADER_OPCODE_TXF_UMS_LOGICAL:
718       case SHADER_OPCODE_TXF_MCS_LOGICAL:
719       case SHADER_OPCODE_LOD_LOGICAL:
720       case SHADER_OPCODE_TG4_LOGICAL:
721       case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
722       case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
723       case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
724       case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
725       case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
726       case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
727       case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
728       case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
729       case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
730          inst->src[i] = val;
731          progress = true;
732          break;
733 
734       case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
735       case SHADER_OPCODE_BROADCAST:
736          inst->src[i] = val;
737          progress = true;
738          break;
739 
740       case BRW_OPCODE_MAD:
741       case BRW_OPCODE_LRP:
742          inst->src[i] = val;
743          progress = true;
744          break;
745 
746       default:
747          break;
748       }
749    }
750 
751    return progress;
752 }
753 
754 static bool
can_propagate_from(fs_inst * inst)755 can_propagate_from(fs_inst *inst)
756 {
757    return (inst->opcode == BRW_OPCODE_MOV &&
758            inst->dst.file == VGRF &&
759            ((inst->src[0].file == VGRF &&
760              !regions_overlap(inst->dst, inst->size_written,
761                               inst->src[0], inst->size_read(0))) ||
762             inst->src[0].file == ATTR ||
763             inst->src[0].file == UNIFORM ||
764             inst->src[0].file == IMM) &&
765            inst->src[0].type == inst->dst.type &&
766            !inst->is_partial_write());
767 }
768 
769 /* Walks a basic block and does copy propagation on it using the acp
770  * list.
771  */
772 bool
opt_copy_propagation_local(void * copy_prop_ctx,bblock_t * block,exec_list * acp)773 fs_visitor::opt_copy_propagation_local(void *copy_prop_ctx, bblock_t *block,
774                                        exec_list *acp)
775 {
776    bool progress = false;
777 
778    foreach_inst_in_block(fs_inst, inst, block) {
779       /* Try propagating into this instruction. */
780       for (int i = 0; i < inst->sources; i++) {
781          if (inst->src[i].file != VGRF)
782             continue;
783 
784          foreach_in_list(acp_entry, entry, &acp[inst->src[i].nr % ACP_HASH_SIZE]) {
785             if (try_constant_propagate(inst, entry))
786                progress = true;
787             else if (try_copy_propagate(inst, i, entry))
788                progress = true;
789          }
790       }
791 
792       /* kill the destination from the ACP */
793       if (inst->dst.file == VGRF) {
794          foreach_in_list_safe(acp_entry, entry, &acp[inst->dst.nr % ACP_HASH_SIZE]) {
795             if (regions_overlap(entry->dst, entry->size_written,
796                                 inst->dst, inst->size_written))
797                entry->remove();
798          }
799 
800          /* Oops, we only have the chaining hash based on the destination, not
801           * the source, so walk across the entire table.
802           */
803          for (int i = 0; i < ACP_HASH_SIZE; i++) {
804             foreach_in_list_safe(acp_entry, entry, &acp[i]) {
805                /* Make sure we kill the entry if this instruction overwrites
806                 * _any_ of the registers that it reads
807                 */
808                if (regions_overlap(entry->src, entry->size_read,
809                                    inst->dst, inst->size_written))
810                   entry->remove();
811             }
812 	 }
813       }
814 
815       /* If this instruction's source could potentially be folded into the
816        * operand of another instruction, add it to the ACP.
817        */
818       if (can_propagate_from(inst)) {
819          acp_entry *entry = ralloc(copy_prop_ctx, acp_entry);
820          entry->dst = inst->dst;
821          entry->src = inst->src[0];
822          entry->size_written = inst->size_written;
823          entry->size_read = inst->size_read(0);
824          entry->opcode = inst->opcode;
825          entry->saturate = inst->saturate;
826          acp[entry->dst.nr % ACP_HASH_SIZE].push_tail(entry);
827       } else if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD &&
828                  inst->dst.file == VGRF) {
829          int offset = 0;
830          for (int i = 0; i < inst->sources; i++) {
831             int effective_width = i < inst->header_size ? 8 : inst->exec_size;
832             assert(effective_width * type_sz(inst->src[i].type) % REG_SIZE == 0);
833             const unsigned size_written = effective_width *
834                                           type_sz(inst->src[i].type);
835             if (inst->src[i].file == VGRF) {
836                acp_entry *entry = rzalloc(copy_prop_ctx, acp_entry);
837                entry->dst = byte_offset(inst->dst, offset);
838                entry->src = inst->src[i];
839                entry->size_written = size_written;
840                entry->size_read = inst->size_read(i);
841                entry->opcode = inst->opcode;
842                if (!entry->dst.equals(inst->src[i])) {
843                   acp[entry->dst.nr % ACP_HASH_SIZE].push_tail(entry);
844                } else {
845                   ralloc_free(entry);
846                }
847             }
848             offset += size_written;
849          }
850       }
851    }
852 
853    return progress;
854 }
855 
856 bool
opt_copy_propagation()857 fs_visitor::opt_copy_propagation()
858 {
859    bool progress = false;
860    void *copy_prop_ctx = ralloc_context(NULL);
861    exec_list *out_acp[cfg->num_blocks];
862 
863    for (int i = 0; i < cfg->num_blocks; i++)
864       out_acp[i] = new exec_list [ACP_HASH_SIZE];
865 
866    calculate_live_intervals();
867 
868    /* First, walk through each block doing local copy propagation and getting
869     * the set of copies available at the end of the block.
870     */
871    foreach_block (block, cfg) {
872       progress = opt_copy_propagation_local(copy_prop_ctx, block,
873                                             out_acp[block->num]) || progress;
874    }
875 
876    /* Do dataflow analysis for those available copies. */
877    fs_copy_prop_dataflow dataflow(copy_prop_ctx, cfg, live_intervals, out_acp);
878 
879    /* Next, re-run local copy propagation, this time with the set of copies
880     * provided by the dataflow analysis available at the start of a block.
881     */
882    foreach_block (block, cfg) {
883       exec_list in_acp[ACP_HASH_SIZE];
884 
885       for (int i = 0; i < dataflow.num_acp; i++) {
886          if (BITSET_TEST(dataflow.bd[block->num].livein, i)) {
887             struct acp_entry *entry = dataflow.acp[i];
888             in_acp[entry->dst.nr % ACP_HASH_SIZE].push_tail(entry);
889          }
890       }
891 
892       progress = opt_copy_propagation_local(copy_prop_ctx, block, in_acp) ||
893                  progress;
894    }
895 
896    for (int i = 0; i < cfg->num_blocks; i++)
897       delete [] out_acp[i];
898    ralloc_free(copy_prop_ctx);
899 
900    if (progress)
901       invalidate_live_intervals();
902 
903    return progress;
904 }
905