• 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 64
36 
37 #include "util/bitset.h"
38 #include "util/u_math.h"
39 #include "brw_fs.h"
40 #include "brw_fs_live_variables.h"
41 #include "brw_cfg.h"
42 #include "brw_eu.h"
43 
44 using namespace brw;
45 
46 namespace { /* avoid conflict with opt_copy_propagation_elements */
47 struct acp_entry : public exec_node {
48    fs_reg dst;
49    fs_reg src;
50    unsigned global_idx;
51    unsigned size_written;
52    unsigned size_read;
53    enum opcode opcode;
54    bool saturate;
55 };
56 
57 struct block_data {
58    /**
59     * Which entries in the fs_copy_prop_dataflow acp table are live at the
60     * start of this block.  This is the useful output of the analysis, since
61     * it lets us plug those into the local copy propagation on the second
62     * pass.
63     */
64    BITSET_WORD *livein;
65 
66    /**
67     * Which entries in the fs_copy_prop_dataflow acp table are live at the end
68     * of this block.  This is done in initial setup from the per-block acps
69     * returned by the first local copy prop pass.
70     */
71    BITSET_WORD *liveout;
72 
73    /**
74     * Which entries in the fs_copy_prop_dataflow acp table are generated by
75     * instructions in this block which reach the end of the block without
76     * being killed.
77     */
78    BITSET_WORD *copy;
79 
80    /**
81     * Which entries in the fs_copy_prop_dataflow acp table are killed over the
82     * course of this block.
83     */
84    BITSET_WORD *kill;
85 
86    /**
87     * Which entries in the fs_copy_prop_dataflow acp table are guaranteed to
88     * have a fully uninitialized destination at the end of this block.
89     */
90    BITSET_WORD *undef;
91 };
92 
93 class fs_copy_prop_dataflow
94 {
95 public:
96    fs_copy_prop_dataflow(void *mem_ctx, cfg_t *cfg,
97                          const fs_live_variables &live,
98                          exec_list *out_acp[ACP_HASH_SIZE]);
99 
100    void setup_initial_values();
101    void run();
102 
103    void dump_block_data() const UNUSED;
104 
105    void *mem_ctx;
106    cfg_t *cfg;
107    const fs_live_variables &live;
108 
109    acp_entry **acp;
110    int num_acp;
111    int bitset_words;
112 
113   struct block_data *bd;
114 };
115 } /* anonymous namespace */
116 
fs_copy_prop_dataflow(void * mem_ctx,cfg_t * cfg,const fs_live_variables & live,exec_list * out_acp[ACP_HASH_SIZE])117 fs_copy_prop_dataflow::fs_copy_prop_dataflow(void *mem_ctx, cfg_t *cfg,
118                                              const fs_live_variables &live,
119                                              exec_list *out_acp[ACP_HASH_SIZE])
120    : mem_ctx(mem_ctx), cfg(cfg), live(live)
121 {
122    bd = rzalloc_array(mem_ctx, struct block_data, cfg->num_blocks);
123 
124    num_acp = 0;
125    foreach_block (block, cfg) {
126       for (int i = 0; i < ACP_HASH_SIZE; i++) {
127          num_acp += out_acp[block->num][i].length();
128       }
129    }
130 
131    acp = rzalloc_array(mem_ctx, struct acp_entry *, num_acp);
132 
133    bitset_words = BITSET_WORDS(num_acp);
134 
135    int next_acp = 0;
136    foreach_block (block, cfg) {
137       bd[block->num].livein = rzalloc_array(bd, BITSET_WORD, bitset_words);
138       bd[block->num].liveout = rzalloc_array(bd, BITSET_WORD, bitset_words);
139       bd[block->num].copy = rzalloc_array(bd, BITSET_WORD, bitset_words);
140       bd[block->num].kill = rzalloc_array(bd, BITSET_WORD, bitset_words);
141       bd[block->num].undef = rzalloc_array(bd, BITSET_WORD, bitset_words);
142 
143       for (int i = 0; i < ACP_HASH_SIZE; i++) {
144          foreach_in_list(acp_entry, entry, &out_acp[block->num][i]) {
145             acp[next_acp] = entry;
146 
147             entry->global_idx = next_acp;
148 
149             /* opt_copy_propagation_local populates out_acp with copies created
150              * in a block which are still live at the end of the block.  This
151              * is exactly what we want in the COPY set.
152              */
153             BITSET_SET(bd[block->num].copy, next_acp);
154 
155             next_acp++;
156          }
157       }
158    }
159 
160    assert(next_acp == num_acp);
161 
162    setup_initial_values();
163    run();
164 }
165 
166 /**
167  * Set up initial values for each of the data flow sets, prior to running
168  * the fixed-point algorithm.
169  */
170 void
setup_initial_values()171 fs_copy_prop_dataflow::setup_initial_values()
172 {
173    /* Initialize the COPY and KILL sets. */
174    {
175       /* Create a temporary table of ACP entries which we'll use for efficient
176        * look-up.  Unfortunately, we have to do this in two steps because we
177        * have to match both sources and destinations and an ACP entry can only
178        * be in one list at a time.
179        *
180        * We choose to make the table size between num_acp/2 and num_acp/4 to
181        * try and trade off between the time it takes to initialize the table
182        * via exec_list constructors or make_empty() and the cost of
183        * collisions.  In practice, it doesn't appear to matter too much what
184        * size we make the table as long as it's roughly the same order of
185        * magnitude as num_acp.  We get most of the benefit of the table
186        * approach even if we use a table of size ACP_HASH_SIZE though a
187        * full-sized table is 1-2% faster in practice.
188        */
189       unsigned acp_table_size = util_next_power_of_two(num_acp) / 4;
190       acp_table_size = MAX2(acp_table_size, ACP_HASH_SIZE);
191       exec_list *acp_table = new exec_list[acp_table_size];
192 
193       /* First, get all the KILLs for instructions which overwrite ACP
194        * destinations.
195        */
196       for (int i = 0; i < num_acp; i++) {
197          unsigned idx = reg_space(acp[i]->dst) & (acp_table_size - 1);
198          acp_table[idx].push_tail(acp[i]);
199       }
200 
201       foreach_block (block, cfg) {
202          foreach_inst_in_block(fs_inst, inst, block) {
203             if (inst->dst.file != VGRF)
204                continue;
205 
206             unsigned idx = reg_space(inst->dst) & (acp_table_size - 1);
207             foreach_in_list(acp_entry, entry, &acp_table[idx]) {
208                if (regions_overlap(inst->dst, inst->size_written,
209                                    entry->dst, entry->size_written))
210                   BITSET_SET(bd[block->num].kill, entry->global_idx);
211             }
212          }
213       }
214 
215       /* Clear the table for the second pass */
216       for (unsigned i = 0; i < acp_table_size; i++)
217          acp_table[i].make_empty();
218 
219       /* Next, get all the KILLs for instructions which overwrite ACP
220        * sources.
221        */
222       for (int i = 0; i < num_acp; i++) {
223          unsigned idx = reg_space(acp[i]->src) & (acp_table_size - 1);
224          acp_table[idx].push_tail(acp[i]);
225       }
226 
227       foreach_block (block, cfg) {
228          foreach_inst_in_block(fs_inst, inst, block) {
229             if (inst->dst.file != VGRF &&
230                 inst->dst.file != FIXED_GRF)
231                continue;
232 
233             unsigned idx = reg_space(inst->dst) & (acp_table_size - 1);
234             foreach_in_list(acp_entry, entry, &acp_table[idx]) {
235                if (regions_overlap(inst->dst, inst->size_written,
236                                    entry->src, entry->size_read))
237                   BITSET_SET(bd[block->num].kill, entry->global_idx);
238             }
239          }
240       }
241 
242       delete [] acp_table;
243    }
244 
245    /* Populate the initial values for the livein and liveout sets.  For the
246     * block at the start of the program, livein = 0 and liveout = copy.
247     * For the others, set liveout and livein to ~0 (the universal set).
248     */
249    foreach_block (block, cfg) {
250       if (block->parents.is_empty()) {
251          for (int i = 0; i < bitset_words; i++) {
252             bd[block->num].livein[i] = 0u;
253             bd[block->num].liveout[i] = bd[block->num].copy[i];
254          }
255       } else {
256          for (int i = 0; i < bitset_words; i++) {
257             bd[block->num].liveout[i] = ~0u;
258             bd[block->num].livein[i] = ~0u;
259          }
260       }
261    }
262 
263    /* Initialize the undef set. */
264    foreach_block (block, cfg) {
265       for (int i = 0; i < num_acp; i++) {
266          BITSET_SET(bd[block->num].undef, i);
267          for (unsigned off = 0; off < acp[i]->size_written; off += REG_SIZE) {
268             if (BITSET_TEST(live.block_data[block->num].defout,
269                             live.var_from_reg(byte_offset(acp[i]->dst, off))))
270                BITSET_CLEAR(bd[block->num].undef, i);
271          }
272       }
273    }
274 }
275 
276 /**
277  * Walk the set of instructions in the block, marking which entries in the acp
278  * are killed by the block.
279  */
280 void
run()281 fs_copy_prop_dataflow::run()
282 {
283    bool progress;
284 
285    do {
286       progress = false;
287 
288       foreach_block (block, cfg) {
289          if (block->parents.is_empty())
290             continue;
291 
292          for (int i = 0; i < bitset_words; i++) {
293             const BITSET_WORD old_liveout = bd[block->num].liveout[i];
294             BITSET_WORD livein_from_any_block = 0;
295 
296             /* Update livein for this block.  If a copy is live out of all
297              * parent blocks, it's live coming in to this block.
298              */
299             bd[block->num].livein[i] = ~0u;
300             foreach_list_typed(bblock_link, parent_link, link, &block->parents) {
301                bblock_t *parent = parent_link->block;
302                /* Consider ACP entries with a known-undefined destination to
303                 * be available from the parent.  This is valid because we're
304                 * free to set the undefined variable equal to the source of
305                 * the ACP entry without breaking the application's
306                 * expectations, since the variable is undefined.
307                 */
308                bd[block->num].livein[i] &= (bd[parent->num].liveout[i] |
309                                             bd[parent->num].undef[i]);
310                livein_from_any_block |= bd[parent->num].liveout[i];
311             }
312 
313             /* Limit to the set of ACP entries that can possibly be available
314              * at the start of the block, since propagating from a variable
315              * which is guaranteed to be undefined (rather than potentially
316              * undefined for some dynamic control-flow paths) doesn't seem
317              * particularly useful.
318              */
319             bd[block->num].livein[i] &= livein_from_any_block;
320 
321             /* Update liveout for this block. */
322             bd[block->num].liveout[i] =
323                bd[block->num].copy[i] | (bd[block->num].livein[i] &
324                                          ~bd[block->num].kill[i]);
325 
326             if (old_liveout != bd[block->num].liveout[i])
327                progress = true;
328          }
329       }
330    } while (progress);
331 }
332 
333 void
dump_block_data() const334 fs_copy_prop_dataflow::dump_block_data() const
335 {
336    foreach_block (block, cfg) {
337       fprintf(stderr, "Block %d [%d, %d] (parents ", block->num,
338              block->start_ip, block->end_ip);
339       foreach_list_typed(bblock_link, link, link, &block->parents) {
340          bblock_t *parent = link->block;
341          fprintf(stderr, "%d ", parent->num);
342       }
343       fprintf(stderr, "):\n");
344       fprintf(stderr, "       livein = 0x");
345       for (int i = 0; i < bitset_words; i++)
346          fprintf(stderr, "%08x", bd[block->num].livein[i]);
347       fprintf(stderr, ", liveout = 0x");
348       for (int i = 0; i < bitset_words; i++)
349          fprintf(stderr, "%08x", bd[block->num].liveout[i]);
350       fprintf(stderr, ",\n       copy   = 0x");
351       for (int i = 0; i < bitset_words; i++)
352          fprintf(stderr, "%08x", bd[block->num].copy[i]);
353       fprintf(stderr, ", kill    = 0x");
354       for (int i = 0; i < bitset_words; i++)
355          fprintf(stderr, "%08x", bd[block->num].kill[i]);
356       fprintf(stderr, "\n");
357    }
358 }
359 
360 static bool
is_logic_op(enum opcode opcode)361 is_logic_op(enum opcode opcode)
362 {
363    return (opcode == BRW_OPCODE_AND ||
364            opcode == BRW_OPCODE_OR  ||
365            opcode == BRW_OPCODE_XOR ||
366            opcode == BRW_OPCODE_NOT);
367 }
368 
369 static bool
can_take_stride(fs_inst * inst,unsigned arg,unsigned stride,const gen_device_info * devinfo)370 can_take_stride(fs_inst *inst, unsigned arg, unsigned stride,
371                 const gen_device_info *devinfo)
372 {
373    if (stride > 4)
374       return false;
375 
376    /* Bail if the channels of the source need to be aligned to the byte offset
377     * of the corresponding channel of the destination, and the provided stride
378     * would break this restriction.
379     */
380    if (has_dst_aligned_region_restriction(devinfo, inst) &&
381        !(type_sz(inst->src[arg].type) * stride ==
382            type_sz(inst->dst.type) * inst->dst.stride ||
383          stride == 0))
384       return false;
385 
386    /* 3-source instructions can only be Align16, which restricts what strides
387     * they can take. They can only take a stride of 1 (the usual case), or 0
388     * with a special "repctrl" bit. But the repctrl bit doesn't work for
389     * 64-bit datatypes, so if the source type is 64-bit then only a stride of
390     * 1 is allowed. From the Broadwell PRM, Volume 7 "3D Media GPGPU", page
391     * 944:
392     *
393     *    This is applicable to 32b datatypes and 16b datatype. 64b datatypes
394     *    cannot use the replicate control.
395     */
396    if (inst->is_3src(devinfo)) {
397       if (type_sz(inst->src[arg].type) > 4)
398          return stride == 1;
399       else
400          return stride == 1 || stride == 0;
401    }
402 
403    /* From the Broadwell PRM, Volume 2a "Command Reference - Instructions",
404     * page 391 ("Extended Math Function"):
405     *
406     *     The following restrictions apply for align1 mode: Scalar source is
407     *     supported. Source and destination horizontal stride must be the
408     *     same.
409     *
410     * From the Haswell PRM Volume 2b "Command Reference - Instructions", page
411     * 134 ("Extended Math Function"):
412     *
413     *    Scalar source is supported. Source and destination horizontal stride
414     *    must be 1.
415     *
416     * and similar language exists for IVB and SNB. Pre-SNB, math instructions
417     * are sends, so the sources are moved to MRF's and there are no
418     * restrictions.
419     */
420    if (inst->is_math()) {
421       if (devinfo->gen == 6 || devinfo->gen == 7) {
422          assert(inst->dst.stride == 1);
423          return stride == 1 || stride == 0;
424       } else if (devinfo->gen >= 8) {
425          return stride == inst->dst.stride || stride == 0;
426       }
427    }
428 
429    return true;
430 }
431 
432 static bool
instruction_requires_packed_data(fs_inst * inst)433 instruction_requires_packed_data(fs_inst *inst)
434 {
435    switch (inst->opcode) {
436    case FS_OPCODE_DDX_FINE:
437    case FS_OPCODE_DDX_COARSE:
438    case FS_OPCODE_DDY_FINE:
439    case FS_OPCODE_DDY_COARSE:
440    case SHADER_OPCODE_QUAD_SWIZZLE:
441       return true;
442    default:
443       return false;
444    }
445 }
446 
447 bool
try_copy_propagate(fs_inst * inst,int arg,acp_entry * entry)448 fs_visitor::try_copy_propagate(fs_inst *inst, int arg, acp_entry *entry)
449 {
450    if (inst->src[arg].file != VGRF)
451       return false;
452 
453    if (entry->src.file == IMM)
454       return false;
455    assert(entry->src.file == VGRF || entry->src.file == UNIFORM ||
456           entry->src.file == ATTR || entry->src.file == FIXED_GRF);
457 
458    /* Avoid propagating a LOAD_PAYLOAD instruction into another if there is a
459     * good chance that we'll be able to eliminate the latter through register
460     * coalescing.  If only part of the sources of the second LOAD_PAYLOAD can
461     * be simplified through copy propagation we would be making register
462     * coalescing impossible, ending up with unnecessary copies in the program.
463     * This is also the case for is_multi_copy_payload() copies that can only
464     * be coalesced when the instruction is lowered into a sequence of MOVs.
465     *
466     * Worse -- In cases where the ACP entry was the result of CSE combining
467     * multiple LOAD_PAYLOAD subexpressions, propagating the first LOAD_PAYLOAD
468     * into the second would undo the work of CSE, leading to an infinite
469     * optimization loop.  Avoid this by detecting LOAD_PAYLOAD copies from CSE
470     * temporaries which should match is_coalescing_payload().
471     */
472    if (entry->opcode == SHADER_OPCODE_LOAD_PAYLOAD &&
473        (is_coalescing_payload(alloc, inst) || is_multi_copy_payload(inst)))
474       return false;
475 
476    assert(entry->dst.file == VGRF);
477    if (inst->src[arg].nr != entry->dst.nr)
478       return false;
479 
480    /* Bail if inst is reading a range that isn't contained in the range
481     * that entry is writing.
482     */
483    if (!region_contained_in(inst->src[arg], inst->size_read(arg),
484                             entry->dst, entry->size_written))
485       return false;
486 
487    /* Avoid propagating a FIXED_GRF register into an EOT instruction in order
488     * for any register allocation restrictions to be applied.
489     */
490    if (entry->src.file == FIXED_GRF && inst->eot)
491       return false;
492 
493    /* Avoid propagating odd-numbered FIXED_GRF registers into the first source
494     * of a LINTERP instruction on platforms where the PLN instruction has
495     * register alignment restrictions.
496     */
497    if (devinfo->has_pln && devinfo->gen <= 6 &&
498        entry->src.file == FIXED_GRF && (entry->src.nr & 1) &&
499        inst->opcode == FS_OPCODE_LINTERP && arg == 0)
500       return false;
501 
502    /* we can't generally copy-propagate UD negations because we
503     * can end up accessing the resulting values as signed integers
504     * instead. See also resolve_ud_negate() and comment in
505     * fs_generator::generate_code.
506     */
507    if (entry->src.type == BRW_REGISTER_TYPE_UD &&
508        entry->src.negate)
509       return false;
510 
511    bool has_source_modifiers = entry->src.abs || entry->src.negate;
512 
513    if ((has_source_modifiers || entry->src.file == UNIFORM ||
514         !entry->src.is_contiguous()) &&
515        !inst->can_do_source_mods(devinfo))
516       return false;
517 
518    if (has_source_modifiers &&
519        inst->opcode == SHADER_OPCODE_GEN4_SCRATCH_WRITE)
520       return false;
521 
522    /* Some instructions implemented in the generator backend, such as
523     * derivatives, assume that their operands are packed so we can't
524     * generally propagate strided regions to them.
525     */
526    const unsigned entry_stride = (entry->src.file == FIXED_GRF ? 1 :
527                                   entry->src.stride);
528    if (instruction_requires_packed_data(inst) && entry_stride != 1)
529       return false;
530 
531    /* Bail if the result of composing both strides would exceed the
532     * hardware limit.
533     */
534    if (!can_take_stride(inst, arg, entry_stride * inst->src[arg].stride,
535                         devinfo))
536       return false;
537 
538    /* Bail if the source FIXED_GRF region of the copy cannot be trivially
539     * composed with the source region of the instruction -- E.g. because the
540     * copy uses some extended stride greater than 4 not supported natively by
541     * the hardware as a horizontal stride, or because instruction compression
542     * could require us to use a vertical stride shorter than a GRF.
543     */
544    if (entry->src.file == FIXED_GRF &&
545        (inst->src[arg].stride > 4 ||
546         inst->dst.component_size(inst->exec_size) >
547         inst->src[arg].component_size(inst->exec_size)))
548       return false;
549 
550    /* Bail if the instruction type is larger than the execution type of the
551     * copy, what implies that each channel is reading multiple channels of the
552     * destination of the copy, and simply replacing the sources would give a
553     * program with different semantics.
554     */
555    if (type_sz(entry->dst.type) < type_sz(inst->src[arg].type))
556       return false;
557 
558    /* Bail if the result of composing both strides cannot be expressed
559     * as another stride. This avoids, for example, trying to transform
560     * this:
561     *
562     *     MOV (8) rX<1>UD rY<0;1,0>UD
563     *     FOO (8) ...     rX<8;8,1>UW
564     *
565     * into this:
566     *
567     *     FOO (8) ...     rY<0;1,0>UW
568     *
569     * Which would have different semantics.
570     */
571    if (entry_stride != 1 &&
572        (inst->src[arg].stride *
573         type_sz(inst->src[arg].type)) % type_sz(entry->src.type) != 0)
574       return false;
575 
576    /* Since semantics of source modifiers are type-dependent we need to
577     * ensure that the meaning of the instruction remains the same if we
578     * change the type. If the sizes of the types are different the new
579     * instruction will read a different amount of data than the original
580     * and the semantics will always be different.
581     */
582    if (has_source_modifiers &&
583        entry->dst.type != inst->src[arg].type &&
584        (!inst->can_change_types() ||
585         type_sz(entry->dst.type) != type_sz(inst->src[arg].type)))
586       return false;
587 
588    if (devinfo->gen >= 8 && (entry->src.negate || entry->src.abs) &&
589        is_logic_op(inst->opcode)) {
590       return false;
591    }
592 
593    if (entry->saturate) {
594       switch(inst->opcode) {
595       case BRW_OPCODE_SEL:
596          if ((inst->conditional_mod != BRW_CONDITIONAL_GE &&
597               inst->conditional_mod != BRW_CONDITIONAL_L) ||
598              inst->src[1].file != IMM ||
599              inst->src[1].f < 0.0 ||
600              inst->src[1].f > 1.0) {
601             return false;
602          }
603          break;
604       default:
605          return false;
606       }
607    }
608 
609    /* Save the offset of inst->src[arg] relative to entry->dst for it to be
610     * applied later.
611     */
612    const unsigned rel_offset = inst->src[arg].offset - entry->dst.offset;
613 
614    /* Fold the copy into the instruction consuming it. */
615    inst->src[arg].file = entry->src.file;
616    inst->src[arg].nr = entry->src.nr;
617    inst->src[arg].subnr = entry->src.subnr;
618    inst->src[arg].offset = entry->src.offset;
619 
620    /* Compose the strides of both regions. */
621    if (entry->src.file == FIXED_GRF) {
622       if (inst->src[arg].stride) {
623          const unsigned orig_width = 1 << entry->src.width;
624          const unsigned reg_width = REG_SIZE / (type_sz(inst->src[arg].type) *
625                                                 inst->src[arg].stride);
626          inst->src[arg].width = cvt(MIN2(orig_width, reg_width)) - 1;
627          inst->src[arg].hstride = cvt(inst->src[arg].stride);
628          inst->src[arg].vstride = inst->src[arg].hstride + inst->src[arg].width;
629       } else {
630          inst->src[arg].vstride = inst->src[arg].hstride =
631             inst->src[arg].width = 0;
632       }
633 
634       inst->src[arg].stride = 1;
635 
636       /* Hopefully no Align16 around here... */
637       assert(entry->src.swizzle == BRW_SWIZZLE_XYZW);
638       inst->src[arg].swizzle = entry->src.swizzle;
639    } else {
640       inst->src[arg].stride *= entry->src.stride;
641    }
642 
643    /* Compose any saturate modifiers. */
644    inst->saturate = inst->saturate || entry->saturate;
645 
646    /* Compute the first component of the copy that the instruction is
647     * reading, and the base byte offset within that component.
648     */
649    assert(entry->dst.offset % REG_SIZE == 0 && entry->dst.stride == 1);
650    const unsigned component = rel_offset / type_sz(entry->dst.type);
651    const unsigned suboffset = rel_offset % type_sz(entry->dst.type);
652 
653    /* Calculate the byte offset at the origin of the copy of the given
654     * component and suboffset.
655     */
656    inst->src[arg] = byte_offset(inst->src[arg],
657       component * entry_stride * type_sz(entry->src.type) + suboffset);
658 
659    if (has_source_modifiers) {
660       if (entry->dst.type != inst->src[arg].type) {
661          /* We are propagating source modifiers from a MOV with a different
662           * type.  If we got here, then we can just change the source and
663           * destination types of the instruction and keep going.
664           */
665          assert(inst->can_change_types());
666          for (int i = 0; i < inst->sources; i++) {
667             inst->src[i].type = entry->dst.type;
668          }
669          inst->dst.type = entry->dst.type;
670       }
671 
672       if (!inst->src[arg].abs) {
673          inst->src[arg].abs = entry->src.abs;
674          inst->src[arg].negate ^= entry->src.negate;
675       }
676    }
677 
678    return true;
679 }
680 
681 
682 bool
try_constant_propagate(fs_inst * inst,acp_entry * entry)683 fs_visitor::try_constant_propagate(fs_inst *inst, acp_entry *entry)
684 {
685    bool progress = false;
686 
687    if (entry->src.file != IMM)
688       return false;
689    if (type_sz(entry->src.type) > 4)
690       return false;
691    if (entry->saturate)
692       return false;
693 
694    for (int i = inst->sources - 1; i >= 0; i--) {
695       if (inst->src[i].file != VGRF)
696          continue;
697 
698       assert(entry->dst.file == VGRF);
699       if (inst->src[i].nr != entry->dst.nr)
700          continue;
701 
702       /* Bail if inst is reading a range that isn't contained in the range
703        * that entry is writing.
704        */
705       if (!region_contained_in(inst->src[i], inst->size_read(i),
706                                entry->dst, entry->size_written))
707          continue;
708 
709       /* If the type sizes don't match each channel of the instruction is
710        * either extracting a portion of the constant (which could be handled
711        * with some effort but the code below doesn't) or reading multiple
712        * channels of the source at once.
713        */
714       if (type_sz(inst->src[i].type) != type_sz(entry->dst.type))
715          continue;
716 
717       fs_reg val = entry->src;
718       val.type = inst->src[i].type;
719 
720       if (inst->src[i].abs) {
721          if ((devinfo->gen >= 8 && is_logic_op(inst->opcode)) ||
722              !brw_abs_immediate(val.type, &val.as_brw_reg())) {
723             continue;
724          }
725       }
726 
727       if (inst->src[i].negate) {
728          if ((devinfo->gen >= 8 && is_logic_op(inst->opcode)) ||
729              !brw_negate_immediate(val.type, &val.as_brw_reg())) {
730             continue;
731          }
732       }
733 
734       switch (inst->opcode) {
735       case BRW_OPCODE_MOV:
736       case SHADER_OPCODE_LOAD_PAYLOAD:
737       case FS_OPCODE_PACK:
738          inst->src[i] = val;
739          progress = true;
740          break;
741 
742       case SHADER_OPCODE_INT_QUOTIENT:
743       case SHADER_OPCODE_INT_REMAINDER:
744          /* FINISHME: Promote non-float constants and remove this. */
745          if (devinfo->gen < 8)
746             break;
747          /* fallthrough */
748       case SHADER_OPCODE_POW:
749          /* Allow constant propagation into src1 (except on Gen 6 which
750           * doesn't support scalar source math), and let constant combining
751           * promote the constant on Gen < 8.
752           */
753          if (devinfo->gen == 6)
754             break;
755          /* fallthrough */
756       case BRW_OPCODE_BFI1:
757       case BRW_OPCODE_ASR:
758       case BRW_OPCODE_SHL:
759       case BRW_OPCODE_SHR:
760       case BRW_OPCODE_SUBB:
761          if (i == 1) {
762             inst->src[i] = val;
763             progress = true;
764          }
765          break;
766 
767       case BRW_OPCODE_MACH:
768       case BRW_OPCODE_MUL:
769       case SHADER_OPCODE_MULH:
770       case BRW_OPCODE_ADD:
771       case BRW_OPCODE_OR:
772       case BRW_OPCODE_AND:
773       case BRW_OPCODE_XOR:
774       case BRW_OPCODE_ADDC:
775          if (i == 1) {
776             inst->src[i] = val;
777             progress = true;
778          } else if (i == 0 && inst->src[1].file != IMM) {
779             /* Fit this constant in by commuting the operands.
780              * Exception: we can't do this for 32-bit integer MUL/MACH
781              * because it's asymmetric.
782              *
783              * The BSpec says for Broadwell that
784              *
785              *    "When multiplying DW x DW, the dst cannot be accumulator."
786              *
787              * Integer MUL with a non-accumulator destination will be lowered
788              * by lower_integer_multiplication(), so don't restrict it.
789              */
790             if (((inst->opcode == BRW_OPCODE_MUL &&
791                   inst->dst.is_accumulator()) ||
792                  inst->opcode == BRW_OPCODE_MACH) &&
793                 (inst->src[1].type == BRW_REGISTER_TYPE_D ||
794                  inst->src[1].type == BRW_REGISTER_TYPE_UD))
795                break;
796             inst->src[0] = inst->src[1];
797             inst->src[1] = val;
798             progress = true;
799          }
800          break;
801 
802       case BRW_OPCODE_CMP:
803       case BRW_OPCODE_IF:
804          if (i == 1) {
805             inst->src[i] = val;
806             progress = true;
807          } else if (i == 0 && inst->src[1].file != IMM) {
808             enum brw_conditional_mod new_cmod;
809 
810             new_cmod = brw_swap_cmod(inst->conditional_mod);
811             if (new_cmod != BRW_CONDITIONAL_NONE) {
812                /* Fit this constant in by swapping the operands and
813                 * flipping the test
814                 */
815                inst->src[0] = inst->src[1];
816                inst->src[1] = val;
817                inst->conditional_mod = new_cmod;
818                progress = true;
819             }
820          }
821          break;
822 
823       case BRW_OPCODE_SEL:
824          if (i == 1) {
825             inst->src[i] = val;
826             progress = true;
827          } else if (i == 0 && inst->src[1].file != IMM &&
828                     (inst->conditional_mod == BRW_CONDITIONAL_NONE ||
829                      /* Only GE and L are commutative. */
830                      inst->conditional_mod == BRW_CONDITIONAL_GE ||
831                      inst->conditional_mod == BRW_CONDITIONAL_L)) {
832             inst->src[0] = inst->src[1];
833             inst->src[1] = val;
834 
835             /* If this was predicated, flipping operands means
836              * we also need to flip the predicate.
837              */
838             if (inst->conditional_mod == BRW_CONDITIONAL_NONE) {
839                inst->predicate_inverse =
840                   !inst->predicate_inverse;
841             }
842             progress = true;
843          }
844          break;
845 
846       case FS_OPCODE_FB_WRITE_LOGICAL:
847          /* The stencil and omask sources of FS_OPCODE_FB_WRITE_LOGICAL are
848           * bit-cast using a strided region so they cannot be immediates.
849           */
850          if (i != FB_WRITE_LOGICAL_SRC_SRC_STENCIL &&
851              i != FB_WRITE_LOGICAL_SRC_OMASK) {
852             inst->src[i] = val;
853             progress = true;
854          }
855          break;
856 
857       case SHADER_OPCODE_TEX_LOGICAL:
858       case SHADER_OPCODE_TXD_LOGICAL:
859       case SHADER_OPCODE_TXF_LOGICAL:
860       case SHADER_OPCODE_TXL_LOGICAL:
861       case SHADER_OPCODE_TXS_LOGICAL:
862       case FS_OPCODE_TXB_LOGICAL:
863       case SHADER_OPCODE_TXF_CMS_LOGICAL:
864       case SHADER_OPCODE_TXF_CMS_W_LOGICAL:
865       case SHADER_OPCODE_TXF_UMS_LOGICAL:
866       case SHADER_OPCODE_TXF_MCS_LOGICAL:
867       case SHADER_OPCODE_LOD_LOGICAL:
868       case SHADER_OPCODE_TG4_LOGICAL:
869       case SHADER_OPCODE_TG4_OFFSET_LOGICAL:
870       case SHADER_OPCODE_SAMPLEINFO_LOGICAL:
871       case SHADER_OPCODE_IMAGE_SIZE_LOGICAL:
872       case SHADER_OPCODE_UNTYPED_ATOMIC_LOGICAL:
873       case SHADER_OPCODE_UNTYPED_ATOMIC_FLOAT_LOGICAL:
874       case SHADER_OPCODE_UNTYPED_SURFACE_READ_LOGICAL:
875       case SHADER_OPCODE_UNTYPED_SURFACE_WRITE_LOGICAL:
876       case SHADER_OPCODE_TYPED_ATOMIC_LOGICAL:
877       case SHADER_OPCODE_TYPED_SURFACE_READ_LOGICAL:
878       case SHADER_OPCODE_TYPED_SURFACE_WRITE_LOGICAL:
879       case SHADER_OPCODE_BYTE_SCATTERED_WRITE_LOGICAL:
880       case SHADER_OPCODE_BYTE_SCATTERED_READ_LOGICAL:
881          inst->src[i] = val;
882          progress = true;
883          break;
884 
885       case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD:
886       case SHADER_OPCODE_BROADCAST:
887          inst->src[i] = val;
888          progress = true;
889          break;
890 
891       case BRW_OPCODE_MAD:
892       case BRW_OPCODE_LRP:
893          inst->src[i] = val;
894          progress = true;
895          break;
896 
897       default:
898          break;
899       }
900    }
901 
902    return progress;
903 }
904 
905 static bool
can_propagate_from(fs_inst * inst)906 can_propagate_from(fs_inst *inst)
907 {
908    return (inst->opcode == BRW_OPCODE_MOV &&
909            inst->dst.file == VGRF &&
910            ((inst->src[0].file == VGRF &&
911              !regions_overlap(inst->dst, inst->size_written,
912                               inst->src[0], inst->size_read(0))) ||
913             inst->src[0].file == ATTR ||
914             inst->src[0].file == UNIFORM ||
915             inst->src[0].file == IMM ||
916             (inst->src[0].file == FIXED_GRF &&
917              inst->src[0].is_contiguous())) &&
918            inst->src[0].type == inst->dst.type &&
919            !inst->is_partial_write()) ||
920           is_identity_payload(FIXED_GRF, inst);
921 }
922 
923 /* Walks a basic block and does copy propagation on it using the acp
924  * list.
925  */
926 bool
opt_copy_propagation_local(void * copy_prop_ctx,bblock_t * block,exec_list * acp)927 fs_visitor::opt_copy_propagation_local(void *copy_prop_ctx, bblock_t *block,
928                                        exec_list *acp)
929 {
930    bool progress = false;
931 
932    foreach_inst_in_block(fs_inst, inst, block) {
933       /* Try propagating into this instruction. */
934       for (int i = 0; i < inst->sources; i++) {
935          if (inst->src[i].file != VGRF)
936             continue;
937 
938          foreach_in_list(acp_entry, entry, &acp[inst->src[i].nr % ACP_HASH_SIZE]) {
939             if (try_constant_propagate(inst, entry))
940                progress = true;
941             else if (try_copy_propagate(inst, i, entry))
942                progress = true;
943          }
944       }
945 
946       /* kill the destination from the ACP */
947       if (inst->dst.file == VGRF || inst->dst.file == FIXED_GRF) {
948          foreach_in_list_safe(acp_entry, entry, &acp[inst->dst.nr % ACP_HASH_SIZE]) {
949             if (regions_overlap(entry->dst, entry->size_written,
950                                 inst->dst, inst->size_written))
951                entry->remove();
952          }
953 
954          /* Oops, we only have the chaining hash based on the destination, not
955           * the source, so walk across the entire table.
956           */
957          for (int i = 0; i < ACP_HASH_SIZE; i++) {
958             foreach_in_list_safe(acp_entry, entry, &acp[i]) {
959                /* Make sure we kill the entry if this instruction overwrites
960                 * _any_ of the registers that it reads
961                 */
962                if (regions_overlap(entry->src, entry->size_read,
963                                    inst->dst, inst->size_written))
964                   entry->remove();
965             }
966 	 }
967       }
968 
969       /* If this instruction's source could potentially be folded into the
970        * operand of another instruction, add it to the ACP.
971        */
972       if (can_propagate_from(inst)) {
973          acp_entry *entry = rzalloc(copy_prop_ctx, acp_entry);
974          entry->dst = inst->dst;
975          entry->src = inst->src[0];
976          entry->size_written = inst->size_written;
977          for (unsigned i = 0; i < inst->sources; i++)
978             entry->size_read += inst->size_read(i);
979          entry->opcode = inst->opcode;
980          entry->saturate = inst->saturate;
981          acp[entry->dst.nr % ACP_HASH_SIZE].push_tail(entry);
982       } else if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD &&
983                  inst->dst.file == VGRF) {
984          int offset = 0;
985          for (int i = 0; i < inst->sources; i++) {
986             int effective_width = i < inst->header_size ? 8 : inst->exec_size;
987             assert(effective_width * type_sz(inst->src[i].type) % REG_SIZE == 0);
988             const unsigned size_written = effective_width *
989                                           type_sz(inst->src[i].type);
990             if (inst->src[i].file == VGRF ||
991                 (inst->src[i].file == FIXED_GRF &&
992                  inst->src[i].is_contiguous())) {
993                acp_entry *entry = rzalloc(copy_prop_ctx, acp_entry);
994                entry->dst = byte_offset(inst->dst, offset);
995                entry->src = inst->src[i];
996                entry->size_written = size_written;
997                entry->size_read = inst->size_read(i);
998                entry->opcode = inst->opcode;
999                if (!entry->dst.equals(inst->src[i])) {
1000                   acp[entry->dst.nr % ACP_HASH_SIZE].push_tail(entry);
1001                } else {
1002                   ralloc_free(entry);
1003                }
1004             }
1005             offset += size_written;
1006          }
1007       }
1008    }
1009 
1010    return progress;
1011 }
1012 
1013 bool
opt_copy_propagation()1014 fs_visitor::opt_copy_propagation()
1015 {
1016    bool progress = false;
1017    void *copy_prop_ctx = ralloc_context(NULL);
1018    exec_list *out_acp[cfg->num_blocks];
1019 
1020    for (int i = 0; i < cfg->num_blocks; i++)
1021       out_acp[i] = new exec_list [ACP_HASH_SIZE];
1022 
1023    const fs_live_variables &live = live_analysis.require();
1024 
1025    /* First, walk through each block doing local copy propagation and getting
1026     * the set of copies available at the end of the block.
1027     */
1028    foreach_block (block, cfg) {
1029       progress = opt_copy_propagation_local(copy_prop_ctx, block,
1030                                             out_acp[block->num]) || progress;
1031 
1032       /* If the destination of an ACP entry exists only within this block,
1033        * then there's no need to keep it for dataflow analysis.  We can delete
1034        * it from the out_acp table and avoid growing the bitsets any bigger
1035        * than we absolutely have to.
1036        *
1037        * Because nothing in opt_copy_propagation_local touches the block
1038        * start/end IPs and opt_copy_propagation_local is incapable of
1039        * extending the live range of an ACP destination beyond the block,
1040        * it's safe to use the liveness information in this way.
1041        */
1042       for (unsigned a = 0; a < ACP_HASH_SIZE; a++) {
1043          foreach_in_list_safe(acp_entry, entry, &out_acp[block->num][a]) {
1044             assert(entry->dst.file == VGRF);
1045             if (block->start_ip <= live.vgrf_start[entry->dst.nr] &&
1046                 live.vgrf_end[entry->dst.nr] <= block->end_ip)
1047                entry->remove();
1048          }
1049       }
1050    }
1051 
1052    /* Do dataflow analysis for those available copies. */
1053    fs_copy_prop_dataflow dataflow(copy_prop_ctx, cfg, live, out_acp);
1054 
1055    /* Next, re-run local copy propagation, this time with the set of copies
1056     * provided by the dataflow analysis available at the start of a block.
1057     */
1058    foreach_block (block, cfg) {
1059       exec_list in_acp[ACP_HASH_SIZE];
1060 
1061       for (int i = 0; i < dataflow.num_acp; i++) {
1062          if (BITSET_TEST(dataflow.bd[block->num].livein, i)) {
1063             struct acp_entry *entry = dataflow.acp[i];
1064             in_acp[entry->dst.nr % ACP_HASH_SIZE].push_tail(entry);
1065          }
1066       }
1067 
1068       progress = opt_copy_propagation_local(copy_prop_ctx, block, in_acp) ||
1069                  progress;
1070    }
1071 
1072    for (int i = 0; i < cfg->num_blocks; i++)
1073       delete [] out_acp[i];
1074    ralloc_free(copy_prop_ctx);
1075 
1076    if (progress)
1077       invalidate_analysis(DEPENDENCY_INSTRUCTION_DATA_FLOW |
1078                           DEPENDENCY_INSTRUCTION_DETAIL);
1079 
1080    return progress;
1081 }
1082