LCOV - code coverage report
Current view: top level - gcc - tree-predcom.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 98.1 % 1445 1418
Test Date: 2026-12-05 16:10:02 Functions: 100.0 % 80 80
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Predictive commoning.
       2              :    Copyright (C) 2005-2026 Free Software Foundation, Inc.
       3              : 
       4              : This file is part of GCC.
       5              : 
       6              : GCC is free software; you can redistribute it and/or modify it
       7              : under the terms of the GNU General Public License as published by the
       8              : Free Software Foundation; either version 3, or (at your option) any
       9              : later version.
      10              : 
      11              : GCC is distributed in the hope that it will be useful, but WITHOUT
      12              : ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
      13              : FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      14              : for more details.
      15              : 
      16              : You should have received a copy of the GNU General Public License
      17              : along with GCC; see the file COPYING3.  If not see
      18              : <http://www.gnu.org/licenses/>.  */
      19              : 
      20              : /* This file implements the predictive commoning optimization.  Predictive
      21              :    commoning can be viewed as CSE around a loop, and with some improvements,
      22              :    as generalized strength reduction-- i.e., reusing values computed in
      23              :    earlier iterations of a loop in the later ones.  So far, the pass only
      24              :    handles the most useful case, that is, reusing values of memory references.
      25              :    If you think this is all just a special case of PRE, you are sort of right;
      26              :    however, concentrating on loops is simpler, and makes it possible to
      27              :    incorporate data dependence analysis to detect the opportunities, perform
      28              :    loop unrolling to avoid copies together with renaming immediately,
      29              :    and if needed, we could also take register pressure into account.
      30              : 
      31              :    Let us demonstrate what is done on an example:
      32              : 
      33              :    for (i = 0; i < 100; i++)
      34              :      {
      35              :        a[i+2] = a[i] + a[i+1];
      36              :        b[10] = b[10] + i;
      37              :        c[i] = c[99 - i];
      38              :        d[i] = d[i + 1];
      39              :      }
      40              : 
      41              :    1) We find data references in the loop, and split them to mutually
      42              :       independent groups (i.e., we find components of a data dependence
      43              :       graph).  We ignore read-read dependences whose distance is not constant.
      44              :       (TODO -- we could also ignore antidependences).  In this example, we
      45              :       find the following groups:
      46              : 
      47              :       a[i]{read}, a[i+1]{read}, a[i+2]{write}
      48              :       b[10]{read}, b[10]{write}
      49              :       c[99 - i]{read}, c[i]{write}
      50              :       d[i + 1]{read}, d[i]{write}
      51              : 
      52              :    2) Inside each of the group, we verify several conditions:
      53              :       a) all the references must differ in indices only, and the indices
      54              :          must all have the same step
      55              :       b) the references must dominate loop latch (and thus, they must be
      56              :          ordered by dominance relation).
      57              :       c) the distance of the indices must be a small multiple of the step
      58              :       We are then able to compute the difference of the references (# of
      59              :       iterations before they point to the same place as the first of them).
      60              :       Also, in case there are writes in the loop, we split the groups into
      61              :       chains whose head is the write whose values are used by the reads in
      62              :       the same chain.  The chains are then processed independently,
      63              :       making the further transformations simpler.  Also, the shorter chains
      64              :       need the same number of registers, but may require lower unrolling
      65              :       factor in order to get rid of the copies on the loop latch.
      66              : 
      67              :       In our example, we get the following chains (the chain for c is invalid).
      68              : 
      69              :       a[i]{read,+0}, a[i+1]{read,-1}, a[i+2]{write,-2}
      70              :       b[10]{read,+0}, b[10]{write,+0}
      71              :       d[i + 1]{read,+0}, d[i]{write,+1}
      72              : 
      73              :    3) For each read, we determine the read or write whose value it reuses,
      74              :       together with the distance of this reuse.  I.e. we take the last
      75              :       reference before it with distance 0, or the last of the references
      76              :       with the smallest positive distance to the read.  Then, we remove
      77              :       the references that are not used in any of these chains, discard the
      78              :       empty groups, and propagate all the links so that they point to the
      79              :       single root reference of the chain (adjusting their distance
      80              :       appropriately).  Some extra care needs to be taken for references with
      81              :       step 0.  In our example (the numbers indicate the distance of the
      82              :       reuse),
      83              : 
      84              :       a[i] --> (*) 2, a[i+1] --> (*) 1, a[i+2] (*)
      85              :       b[10] --> (*) 1, b[10] (*)
      86              : 
      87              :    4) The chains are combined together if possible.  If the corresponding
      88              :       elements of two chains are always combined together with the same
      89              :       operator, we remember just the result of this combination, instead
      90              :       of remembering the values separately.  We may need to perform
      91              :       reassociation to enable combining, for example
      92              : 
      93              :       e[i] + f[i+1] + e[i+1] + f[i]
      94              : 
      95              :       can be reassociated as
      96              : 
      97              :       (e[i] + f[i]) + (e[i+1] + f[i+1])
      98              : 
      99              :       and we can combine the chains for e and f into one chain.
     100              : 
     101              :    5) For each root reference (end of the chain) R, let N be maximum distance
     102              :       of a reference reusing its value.  Variables R0 up to RN are created,
     103              :       together with phi nodes that transfer values from R1 .. RN to
     104              :       R0 .. R(N-1).
     105              :       Initial values are loaded to R0..R(N-1) (in case not all references
     106              :       must necessarily be accessed and they may trap, we may fail here;
     107              :       TODO sometimes, the loads could be guarded by a check for the number
     108              :       of iterations).  Values loaded/stored in roots are also copied to
     109              :       RN.  Other reads are replaced with the appropriate variable Ri.
     110              :       Everything is put to SSA form.
     111              : 
     112              :       As a small improvement, if R0 is dead after the root (i.e., all uses of
     113              :       the value with the maximum distance dominate the root), we can avoid
     114              :       creating RN and use R0 instead of it.
     115              : 
     116              :       In our example, we get (only the parts concerning a and b are shown):
     117              :       for (i = 0; i < 100; i++)
     118              :         {
     119              :           f = phi (a[0], s);
     120              :           s = phi (a[1], f);
     121              :           x = phi (b[10], x);
     122              : 
     123              :           f = f + s;
     124              :           a[i+2] = f;
     125              :           x = x + i;
     126              :           b[10] = x;
     127              :         }
     128              : 
     129              :    6) Factor F for unrolling is determined as the smallest common multiple of
     130              :       (N + 1) for each root reference (N for references for that we avoided
     131              :       creating RN).  If F and the loop is small enough, loop is unrolled F
     132              :       times.  The stores to RN (R0) in the copies of the loop body are
     133              :       periodically replaced with R0, R1, ... (R1, R2, ...), so that they can
     134              :       be coalesced and the copies can be eliminated.
     135              : 
     136              :       TODO -- copy propagation and other optimizations may change the live
     137              :       ranges of the temporary registers and prevent them from being coalesced;
     138              :       this may increase the register pressure.
     139              : 
     140              :       In our case, F = 2 and the (main loop of the) result is
     141              : 
     142              :       for (i = 0; i < ...; i += 2)
     143              :         {
     144              :           f = phi (a[0], f);
     145              :           s = phi (a[1], s);
     146              :           x = phi (b[10], x);
     147              : 
     148              :           f = f + s;
     149              :           a[i+2] = f;
     150              :           x = x + i;
     151              :           b[10] = x;
     152              : 
     153              :           s = s + f;
     154              :           a[i+3] = s;
     155              :           x = x + i;
     156              :           b[10] = x;
     157              :        }
     158              : 
     159              :    Apart from predictive commoning on Load-Load and Store-Load chains, we
     160              :    also support Store-Store chains -- stores killed by other store can be
     161              :    eliminated.  Given below example:
     162              : 
     163              :      for (i = 0; i < n; i++)
     164              :        {
     165              :          a[i] = 1;
     166              :          a[i+2] = 2;
     167              :        }
     168              : 
     169              :    It can be replaced with:
     170              : 
     171              :      t0 = a[0];
     172              :      t1 = a[1];
     173              :      for (i = 0; i < n; i++)
     174              :        {
     175              :          a[i] = 1;
     176              :          t2 = 2;
     177              :          t0 = t1;
     178              :          t1 = t2;
     179              :        }
     180              :      a[n] = t0;
     181              :      a[n+1] = t1;
     182              : 
     183              :    If the loop runs more than 1 iterations, it can be further simplified into:
     184              : 
     185              :      for (i = 0; i < n; i++)
     186              :        {
     187              :          a[i] = 1;
     188              :        }
     189              :      a[n] = 2;
     190              :      a[n+1] = 2;
     191              : 
     192              :    The interesting part is this can be viewed either as general store motion
     193              :    or general dead store elimination in either intra/inter-iterations way.
     194              : 
     195              :    With trivial effort, we also support load inside Store-Store chains if the
     196              :    load is dominated by a store statement in the same iteration of loop.  You
     197              :    can see this as a restricted Store-Mixed-Load-Store chain.
     198              : 
     199              :    TODO: For now, we don't support store-store chains in multi-exit loops.  We
     200              :    force to not unroll in case of store-store chain even if other chains might
     201              :    ask for unroll.
     202              : 
     203              :    Predictive commoning can be generalized for arbitrary computations (not
     204              :    just memory loads), and also nontrivial transfer functions (e.g., replacing
     205              :    i * i with ii_last + 2 * i + 1), to generalize strength reduction.  */
     206              : 
     207              : #include "config.h"
     208              : #include "system.h"
     209              : #include "coretypes.h"
     210              : #include "backend.h"
     211              : #include "rtl.h"
     212              : #include "tree.h"
     213              : #include "gimple.h"
     214              : #include "predict.h"
     215              : #include "tree-pass.h"
     216              : #include "ssa.h"
     217              : #include "gimple-pretty-print.h"
     218              : #include "alias.h"
     219              : #include "fold-const.h"
     220              : #include "cfgloop.h"
     221              : #include "tree-eh.h"
     222              : #include "gimplify.h"
     223              : #include "gimple-iterator.h"
     224              : #include "gimplify-me.h"
     225              : #include "tree-ssa-loop-ivopts.h"
     226              : #include "tree-ssa-loop-manip.h"
     227              : #include "tree-ssa-loop-niter.h"
     228              : #include "tree-ssa-loop.h"
     229              : #include "tree-into-ssa.h"
     230              : #include "tree-dfa.h"
     231              : #include "tree-ssa.h"
     232              : #include "tree-data-ref.h"
     233              : #include "tree-scalar-evolution.h"
     234              : #include "tree-affine.h"
     235              : #include "builtins.h"
     236              : #include "opts.h"
     237              : #include "tree-ssa-address.h"
     238              : 
     239              : /* The maximum number of iterations between the considered memory
     240              :    references.  */
     241              : 
     242              : #define MAX_DISTANCE (target_avail_regs < 16 ? 4 : 8)
     243              : 
     244              : /* Data references (or phi nodes that carry data reference values across
     245              :    loop iterations).  */
     246              : 
     247              : typedef class dref_d
     248              : {
     249              : public:
     250              :   /* The reference itself.  */
     251              :   struct data_reference *ref;
     252              : 
     253              :   /* The statement in that the reference appears.  */
     254              :   gimple *stmt;
     255              : 
     256              :   /* In case that STMT is a phi node, this field is set to the SSA name
     257              :      defined by it in replace_phis_by_defined_names (in order to avoid
     258              :      pointing to phi node that got reallocated in the meantime).  */
     259              :   tree name_defined_by_phi;
     260              : 
     261              :   /* Distance of the reference from the root of the chain (in number of
     262              :      iterations of the loop).  */
     263              :   unsigned distance;
     264              : 
     265              :   /* Number of iterations offset from the first reference in the component.  */
     266              :   widest_int offset;
     267              : 
     268              :   /* Number of the reference in a component, in dominance ordering.  */
     269              :   unsigned pos;
     270              : 
     271              :   /* True if the memory reference is always accessed when the loop is
     272              :      entered.  */
     273              :   unsigned always_accessed : 1;
     274              : } *dref;
     275              : 
     276              : 
     277              : /* Type of the chain of the references.  */
     278              : 
     279              : enum chain_type
     280              : {
     281              :   /* The addresses of the references in the chain are constant.  */
     282              :   CT_INVARIANT,
     283              : 
     284              :   /* There are only loads in the chain.  */
     285              :   CT_LOAD,
     286              : 
     287              :   /* Root of the chain is store, the rest are loads.  */
     288              :   CT_STORE_LOAD,
     289              : 
     290              :   /* There are only stores in the chain.  */
     291              :   CT_STORE_STORE,
     292              : 
     293              :   /* A combination of two chains.  */
     294              :   CT_COMBINATION
     295              : };
     296              : 
     297              : /* Chains of data references.  */
     298              : 
     299              : typedef struct chain
     300              : {
     301        76149 :   chain (chain_type t) : type (t), op (ERROR_MARK), rslt_type (NULL_TREE),
     302        76149 :     ch1 (NULL), ch2 (NULL), length (0), init_seq (NULL), fini_seq (NULL),
     303        76149 :     has_max_use_after (false), all_always_accessed (false), combined (false),
     304        76149 :     inv_store_elimination (false) {}
     305              : 
     306              :   /* Type of the chain.  */
     307              :   enum chain_type type;
     308              : 
     309              :   /* For combination chains, the operator and the two chains that are
     310              :      combined, and the type of the result.  */
     311              :   enum tree_code op;
     312              :   tree rslt_type;
     313              :   struct chain *ch1, *ch2;
     314              : 
     315              :   /* The references in the chain.  */
     316              :   auto_vec<dref> refs;
     317              : 
     318              :   /* The maximum distance of the reference in the chain from the root.  */
     319              :   unsigned length;
     320              : 
     321              :   /* The variables used to copy the value throughout iterations.  */
     322              :   auto_vec<tree> vars;
     323              : 
     324              :   /* Initializers for the variables.  */
     325              :   auto_vec<tree> inits;
     326              : 
     327              :   /* Finalizers for the eliminated stores.  */
     328              :   auto_vec<tree> finis;
     329              : 
     330              :   /* gimple stmts initializing the initial variables of the chain.  */
     331              :   gimple_seq init_seq;
     332              : 
     333              :   /* gimple stmts finalizing the eliminated stores of the chain.  */
     334              :   gimple_seq fini_seq;
     335              : 
     336              :   /* True if there is a use of a variable with the maximal distance
     337              :      that comes after the root in the loop.  */
     338              :   unsigned has_max_use_after : 1;
     339              : 
     340              :   /* True if all the memory references in the chain are always accessed.  */
     341              :   unsigned all_always_accessed : 1;
     342              : 
     343              :   /* True if this chain was combined together with some other chain.  */
     344              :   unsigned combined : 1;
     345              : 
     346              :   /* True if this is store elimination chain and eliminated stores store
     347              :      loop invariant value into memory.  */
     348              :   unsigned inv_store_elimination : 1;
     349              : } *chain_p;
     350              : 
     351              : 
     352              : /* Describes the knowledge about the step of the memory references in
     353              :    the component.  */
     354              : 
     355              : enum ref_step_type
     356              : {
     357              :   /* The step is zero.  */
     358              :   RS_INVARIANT,
     359              : 
     360              :   /* The step is nonzero.  */
     361              :   RS_NONZERO,
     362              : 
     363              :   /* The step may or may not be nonzero.  */
     364              :   RS_ANY
     365              : };
     366              : 
     367              : /* Components of the data dependence graph.  */
     368              : 
     369       814468 : struct component
     370              : {
     371       407234 :   component (bool es) : comp_step (RS_ANY), eliminate_store_p (es),
     372       407234 :     next (NULL) {}
     373              : 
     374              :   /* The references in the component.  */
     375              :   auto_vec<dref> refs;
     376              : 
     377              :   /* What we know about the step of the references in the component.  */
     378              :   enum ref_step_type comp_step;
     379              : 
     380              :   /* True if all references in component are stores and we try to do
     381              :      intra/inter loop iteration dead store elimination.  */
     382              :   bool eliminate_store_p;
     383              : 
     384              :   /* Next component in the list.  */
     385              :   struct component *next;
     386              : };
     387              : 
     388              : /* A class to encapsulate the global states used for predictive
     389              :    commoning work on top of one given LOOP.  */
     390              : 
     391              : class pcom_worker
     392              : {
     393              : public:
     394       444999 :   pcom_worker (loop_p l) : m_loop (l), m_cache (NULL) {}
     395              : 
     396       444999 :   ~pcom_worker ()
     397              :   {
     398       444999 :     free_data_refs (m_datarefs);
     399       444999 :     free_dependence_relations (m_dependences);
     400       444999 :     free_affine_expand_cache (&m_cache);
     401       444999 :     release_chains ();
     402       444999 :   }
     403              : 
     404              :   pcom_worker (const pcom_worker &) = delete;
     405              :   pcom_worker &operator= (const pcom_worker &) = delete;
     406              : 
     407              :   /* Performs predictive commoning.  */
     408              :   unsigned tree_predictive_commoning_loop (bool allow_unroll_p);
     409              : 
     410              :   /* Perform the predictive commoning optimization for chains, make this
     411              :      public for being called in callback execute_pred_commoning_cbck.  */
     412              :   void execute_pred_commoning (bitmap tmp_vars);
     413              : 
     414              : private:
     415              :   /* The pointer to the given loop.  */
     416              :   loop_p m_loop;
     417              : 
     418              :   /* All data references.  */
     419              :   auto_vec<data_reference_p, 10> m_datarefs;
     420              : 
     421              :   /* All data dependences.  */
     422              :   auto_vec<ddr_p, 10> m_dependences;
     423              : 
     424              :   /* All chains.  */
     425              :   auto_vec<chain_p> m_chains;
     426              : 
     427              :   /* Bitmap of ssa names defined by looparound phi nodes covered by chains.  */
     428              :   auto_bitmap m_looparound_phis;
     429              : 
     430              :   typedef hash_map<tree, name_expansion *> tree_expand_map_t;
     431              :   /* Cache used by tree_to_aff_combination_expand.  */
     432              :   tree_expand_map_t *m_cache;
     433              : 
     434              :   /* Splits dependence graph to components.  */
     435              :   struct component *split_data_refs_to_components ();
     436              : 
     437              :   /* Check the conditions on references inside each of components COMPS,
     438              :      and remove the unsuitable components from the list.  */
     439              :   struct component *filter_suitable_components (struct component *comps);
     440              : 
     441              :   /* Find roots of the values and determine distances in components COMPS,
     442              :      and separates the references to chains.  */
     443              :   void determine_roots (struct component *comps);
     444              : 
     445              :   /* Prepare initializers for chains, and free chains that cannot
     446              :      be used because the initializers might trap.  */
     447              :   void prepare_initializers ();
     448              : 
     449              :   /* Generates finalizer memory reference for chains.  Returns true if
     450              :      finalizer code generation for chains breaks loop closed ssa form.  */
     451              :   bool prepare_finalizers ();
     452              : 
     453              :   /* Try to combine the chains.  */
     454              :   void try_combine_chains ();
     455              : 
     456              :   /* Frees CHAINS.  */
     457              :   void release_chains ();
     458              : 
     459              :   /* Frees a chain CHAIN.  */
     460              :   void release_chain (chain_p chain);
     461              : 
     462              :   /* Prepare initializers for CHAIN.  Returns false if this is impossible
     463              :      because one of these initializers may trap, true otherwise.  */
     464              :   bool prepare_initializers_chain (chain_p chain);
     465              : 
     466              :   /* Generates finalizer memory references for CHAIN.  Returns true
     467              :      if finalizer code for CHAIN can be generated, otherwise false.  */
     468              :   bool prepare_finalizers_chain (chain_p chain);
     469              : 
     470              :   /* Stores DR_OFFSET (DR) + DR_INIT (DR) to OFFSET.  */
     471              :   void aff_combination_dr_offset (struct data_reference *dr, aff_tree *offset);
     472              : 
     473              :   /* Determines number of iterations of the innermost enclosing loop before
     474              :      B refers to exactly the same location as A and stores it to OFF.  */
     475              :   bool determine_offset (struct data_reference *a, struct data_reference *b,
     476              :                          poly_widest_int *off);
     477              : 
     478              :   /* Returns true if the component COMP satisfies the conditions
     479              :      described in 2) at the beginning of this file.  */
     480              :   bool suitable_component_p (struct component *comp);
     481              : 
     482              :   /* Returns true if REF is a valid initializer for ROOT with given
     483              :      DISTANCE (in iterations of the innermost enclosing loop).  */
     484              :   bool valid_initializer_p (struct data_reference *ref, unsigned distance,
     485              :                             struct data_reference *root);
     486              : 
     487              :   /* Finds looparound phi node of loop that copies the value of REF.  */
     488              :   gphi *find_looparound_phi (dref ref, dref root);
     489              : 
     490              :   /* Find roots of the values and determine distances in the component
     491              :      COMP.  The references are redistributed into chains.  */
     492              :   void determine_roots_comp (struct component *comp);
     493              : 
     494              :   /* For references in CHAIN that are copied around the loop, add the
     495              :      results of such copies to the chain.  */
     496              :   void add_looparound_copies (chain_p chain);
     497              : 
     498              :   /* Returns the single statement in that NAME is used, excepting
     499              :      the looparound phi nodes contained in one of the chains.  */
     500              :   gimple *single_nonlooparound_use (tree name);
     501              : 
     502              :   /* Remove statement STMT, as well as the chain of assignments in that
     503              :      it is used.  */
     504              :   void remove_stmt (gimple *stmt);
     505              : 
     506              :   /* Perform the predictive commoning optimization for a chain CHAIN.  */
     507              :   void execute_pred_commoning_chain (chain_p chain, bitmap tmp_vars);
     508              : 
     509              :   /* Returns the modify statement that uses NAME.  */
     510              :   gassign *find_use_stmt (tree *name);
     511              : 
     512              :   /* If the operation used in STMT is associative and commutative, go
     513              :      through the tree of the same operations and returns its root.  */
     514              :   gassign *find_associative_operation_root (gassign *stmt, unsigned *distance);
     515              : 
     516              :   /* Returns the common statement in that NAME1 and NAME2 have a use.  */
     517              :   gassign *find_common_use_stmt (tree *name1, tree *name2);
     518              : 
     519              :   /* Checks whether R1 and R2 are combined together using CODE, with the
     520              :      result in RSLT_TYPE, in order R1 CODE R2 if SWAP is false and in order
     521              :      R2 CODE R1 if it is true.  */
     522              :   bool combinable_refs_p (dref r1, dref r2, enum tree_code *code, bool *swap,
     523              :                           tree *rslt_type);
     524              : 
     525              :   /* Reassociates the expression in that NAME1 and NAME2 are used so that
     526              :      they are combined in a single statement, and returns this statement.  */
     527              :   gimple *reassociate_to_the_same_stmt (tree name1, tree name2);
     528              : 
     529              :   /* Returns the statement that combines references R1 and R2.  */
     530              :   gimple *stmt_combining_refs (dref r1, dref r2);
     531              : 
     532              :   /* Tries to combine chains CH1 and CH2 together.  */
     533              :   chain_p combine_chains (chain_p ch1, chain_p ch2);
     534              : };
     535              : 
     536              : /* Dumps data reference REF to FILE.  */
     537              : 
     538              : extern void dump_dref (FILE *, dref);
     539              : void
     540          308 : dump_dref (FILE *file, dref ref)
     541              : {
     542          308 :   if (ref->ref)
     543              :     {
     544          289 :       fprintf (file, "    ");
     545          289 :       print_generic_expr (file, DR_REF (ref->ref), TDF_SLIM);
     546          289 :       fprintf (file, " (id %u%s)\n", ref->pos,
     547          289 :                DR_IS_READ (ref->ref) ? "" : ", write");
     548              : 
     549          289 :       fprintf (file, "      offset ");
     550          289 :       print_decs (ref->offset, file);
     551          289 :       fprintf (file, "\n");
     552              : 
     553          289 :       fprintf (file, "      distance %u\n", ref->distance);
     554              :     }
     555              :   else
     556              :     {
     557           19 :       if (gimple_code (ref->stmt) == GIMPLE_PHI)
     558            1 :         fprintf (file, "    looparound ref\n");
     559              :       else
     560           18 :         fprintf (file, "    combination ref\n");
     561           19 :       fprintf (file, "      in statement ");
     562           19 :       print_gimple_stmt (file, ref->stmt, 0, TDF_SLIM);
     563           19 :       fprintf (file, "\n");
     564           19 :       fprintf (file, "      distance %u\n", ref->distance);
     565              :     }
     566              : 
     567          308 : }
     568              : 
     569              : /* Dumps CHAIN to FILE.  */
     570              : 
     571              : extern void dump_chain (FILE *, chain_p);
     572              : void
     573           58 : dump_chain (FILE *file, chain_p chain)
     574              : {
     575           58 :   dref a;
     576           58 :   const char *chain_type;
     577           58 :   unsigned i;
     578           58 :   tree var;
     579              : 
     580           58 :   switch (chain->type)
     581              :     {
     582              :     case CT_INVARIANT:
     583              :       chain_type = "Load motion";
     584              :       break;
     585              : 
     586           24 :     case CT_LOAD:
     587           24 :       chain_type = "Loads-only";
     588           24 :       break;
     589              : 
     590            5 :     case CT_STORE_LOAD:
     591            5 :       chain_type = "Store-loads";
     592            5 :       break;
     593              : 
     594           19 :     case CT_STORE_STORE:
     595           19 :       chain_type = "Store-stores";
     596           19 :       break;
     597              : 
     598            9 :     case CT_COMBINATION:
     599            9 :       chain_type = "Combination";
     600            9 :       break;
     601              : 
     602            0 :     default:
     603            0 :       gcc_unreachable ();
     604              :     }
     605              : 
     606           58 :   fprintf (file, "%s chain %p%s\n", chain_type, (void *) chain,
     607           58 :            chain->combined ? " (combined)" : "");
     608           58 :   if (chain->type != CT_INVARIANT)
     609           57 :     fprintf (file, "  max distance %u%s\n", chain->length,
     610           57 :              chain->has_max_use_after ? "" : ", may reuse first");
     611              : 
     612           58 :   if (chain->type == CT_COMBINATION)
     613              :     {
     614           18 :       fprintf (file, "  equal to %p %s %p in type ",
     615            9 :                (void *) chain->ch1, op_symbol_code (chain->op),
     616            9 :                (void *) chain->ch2);
     617            9 :       print_generic_expr (file, chain->rslt_type, TDF_SLIM);
     618            9 :       fprintf (file, "\n");
     619              :     }
     620              : 
     621           58 :   if (chain->vars.exists ())
     622              :     {
     623            0 :       fprintf (file, "  vars");
     624            0 :       FOR_EACH_VEC_ELT (chain->vars, i, var)
     625              :         {
     626            0 :           fprintf (file, " ");
     627            0 :           print_generic_expr (file, var, TDF_SLIM);
     628              :         }
     629            0 :       fprintf (file, "\n");
     630              :     }
     631              : 
     632           58 :   if (chain->inits.exists ())
     633              :     {
     634           41 :       fprintf (file, "  inits");
     635          149 :       FOR_EACH_VEC_ELT (chain->inits, i, var)
     636              :         {
     637           67 :           fprintf (file, " ");
     638           67 :           print_generic_expr (file, var, TDF_SLIM);
     639              :         }
     640           41 :       fprintf (file, "\n");
     641              :     }
     642              : 
     643           58 :   fprintf (file, "  references:\n");
     644          251 :   FOR_EACH_VEC_ELT (chain->refs, i, a)
     645          135 :     dump_dref (file, a);
     646              : 
     647           58 :   fprintf (file, "\n");
     648           58 : }
     649              : 
     650              : /* Dumps CHAINS to FILE.  */
     651              : 
     652              : void
     653           34 : dump_chains (FILE *file, const vec<chain_p> &chains)
     654              : {
     655           34 :   chain_p chain;
     656           34 :   unsigned i;
     657              : 
     658           92 :   FOR_EACH_VEC_ELT (chains, i, chain)
     659           58 :     dump_chain (file, chain);
     660           34 : }
     661              : 
     662              : /* Dumps COMP to FILE.  */
     663              : 
     664              : extern void dump_component (FILE *, struct component *);
     665              : void
     666          103 : dump_component (FILE *file, struct component *comp)
     667              : {
     668          103 :   dref a;
     669          103 :   unsigned i;
     670              : 
     671          206 :   fprintf (file, "Component%s:\n",
     672          103 :            comp->comp_step == RS_INVARIANT ? " (invariant)" : "");
     673          379 :   FOR_EACH_VEC_ELT (comp->refs, i, a)
     674          173 :     dump_dref (file, a);
     675          103 :   fprintf (file, "\n");
     676          103 : }
     677              : 
     678              : /* Dumps COMPS to FILE.  */
     679              : 
     680              : extern void dump_components (FILE *, struct component *);
     681              : void
     682           54 : dump_components (FILE *file, struct component *comps)
     683              : {
     684           54 :   struct component *comp;
     685              : 
     686          157 :   for (comp = comps; comp; comp = comp->next)
     687          103 :     dump_component (file, comp);
     688           54 : }
     689              : 
     690              : /* Frees a chain CHAIN.  */
     691              : 
     692              : void
     693       112969 : pcom_worker::release_chain (chain_p chain)
     694              : {
     695       112969 :   dref ref;
     696       112969 :   unsigned i;
     697              : 
     698       112969 :   if (chain == NULL)
     699       112969 :     return;
     700              : 
     701       173813 :   FOR_EACH_VEC_ELT (chain->refs, i, ref)
     702        97664 :     free (ref);
     703              : 
     704        76149 :   if (chain->init_seq)
     705            0 :     gimple_seq_discard (chain->init_seq);
     706              : 
     707        76149 :   if (chain->fini_seq)
     708            0 :     gimple_seq_discard (chain->fini_seq);
     709              : 
     710        76149 :   delete chain;
     711              : }
     712              : 
     713              : /* Frees CHAINS.  */
     714              : 
     715              : void
     716       444999 : pcom_worker::release_chains ()
     717              : {
     718       444999 :   unsigned i;
     719       444999 :   chain_p chain;
     720              : 
     721       475414 :   FOR_EACH_VEC_ELT (m_chains, i, chain)
     722        30415 :     release_chain (chain);
     723       444999 : }
     724              : 
     725              : /* Frees list of components COMPS.  */
     726              : 
     727              : static void
     728       183538 : release_components (struct component *comps)
     729              : {
     730       183538 :   struct component *act, *next;
     731              : 
     732       562925 :   for (act = comps; act; act = next)
     733              :     {
     734       379387 :       next = act->next;
     735       379387 :       delete act;
     736              :     }
     737       183538 : }
     738              : 
     739              : /* Finds a root of tree given by FATHERS containing A, and performs path
     740              :    shortening.  */
     741              : 
     742              : static unsigned
     743      7322935 : component_of (vec<unsigned> &fathers, unsigned a)
     744              : {
     745      7322935 :   unsigned root, n;
     746              : 
     747     11404119 :   for (root = a; root != fathers[root]; root = fathers[root])
     748      4081184 :     continue;
     749              : 
     750     11404119 :   for (; a != root; a = n)
     751              :     {
     752      4081184 :       n = fathers[a];
     753      4081184 :       fathers[a] = root;
     754              :     }
     755              : 
     756      7322935 :   return root;
     757      4081184 : }
     758              : 
     759              : /* Join operation for DFU.  FATHERS gives the tree, SIZES are sizes of the
     760              :    components, A and B are components to merge.  */
     761              : 
     762              : static void
     763       368754 : merge_comps (vec<unsigned> &fathers, vec<unsigned> &sizes,
     764              :              unsigned a, unsigned b)
     765              : {
     766       368754 :   unsigned ca = component_of (fathers, a);
     767       368754 :   unsigned cb = component_of (fathers, b);
     768              : 
     769       368754 :   if (ca == cb)
     770              :     return;
     771              : 
     772       368754 :   if (sizes[ca] < sizes[cb])
     773              :     {
     774        16627 :       sizes[cb] += sizes[ca];
     775        16627 :       fathers[ca] = cb;
     776              :     }
     777              :   else
     778              :     {
     779       352127 :       sizes[ca] += sizes[cb];
     780       352127 :       fathers[cb] = ca;
     781              :     }
     782              : }
     783              : 
     784              : /* Returns true if A is a reference that is suitable for predictive commoning
     785              :    in the innermost loop that contains it.  REF_STEP is set according to the
     786              :    step of the reference A.  */
     787              : 
     788              : static bool
     789      1208591 : suitable_reference_p (struct data_reference *a, enum ref_step_type *ref_step)
     790              : {
     791      1208591 :   tree ref = DR_REF (a), step = DR_STEP (a);
     792              : 
     793      1208591 :   if (!step
     794      1073852 :       || TREE_THIS_VOLATILE (ref)
     795      1058547 :       || !is_gimple_reg_type (TREE_TYPE (ref))
     796      2245286 :       || tree_could_throw_p (ref))
     797              :     return false;
     798              : 
     799       997674 :   if (integer_zerop (step))
     800        61790 :     *ref_step = RS_INVARIANT;
     801       935884 :   else if (integer_nonzerop (step))
     802       881802 :     *ref_step = RS_NONZERO;
     803              :   else
     804        54082 :     *ref_step = RS_ANY;
     805              : 
     806              :   return true;
     807              : }
     808              : 
     809              : /* Stores DR_OFFSET (DR) + DR_INIT (DR) to OFFSET.  */
     810              : 
     811              : void
     812       228716 : pcom_worker::aff_combination_dr_offset (struct data_reference *dr,
     813              :                                         aff_tree *offset)
     814              : {
     815       228716 :   tree type = TREE_TYPE (DR_OFFSET (dr));
     816       228716 :   aff_tree delta;
     817              : 
     818       228716 :   tree_to_aff_combination_expand (DR_OFFSET (dr), type, offset, &m_cache);
     819       228716 :   aff_combination_const (&delta, type, wi::to_poly_widest (DR_INIT (dr)));
     820       228716 :   aff_combination_add (offset, &delta);
     821       228716 : }
     822              : 
     823              : /* Returns true if the references A and B behave the same for TBAA.  The
     824              :    references created for a chain reuse the alias info of the chain root,
     825              :    which can be either of A and B, so check both directions.  */
     826              : 
     827              : static bool
     828       253469 : refs_tbaa_equivalent_p (tree a, tree b)
     829              : {
     830       253469 :   return refs_same_for_tbaa_p (a, b) && refs_same_for_tbaa_p (b, a);
     831              : }
     832              : 
     833              : /* Determines number of iterations of the innermost enclosing loop before B
     834              :    refers to exactly the same location as A and stores it to OFF.  If A and
     835              :    B do not have the same step, they never meet, or anything else fails,
     836              :    returns false, otherwise returns true.  Both A and B are assumed to
     837              :    satisfy suitable_reference_p.  */
     838              : 
     839              : bool
     840       279356 : pcom_worker::determine_offset (struct data_reference *a,
     841              :                                struct data_reference *b, poly_widest_int *off)
     842              : {
     843       838068 :   aff_tree diff, baseb, step;
     844       279356 :   tree typea, typeb;
     845              : 
     846              :   /* Check that both the references access the location in the same type
     847              :      and behave the same for TBAA.  */
     848       279356 :   typea = TREE_TYPE (DR_REF (a));
     849       279356 :   typeb = TREE_TYPE (DR_REF (b));
     850       279356 :   if (!useless_type_conversion_p (typeb, typea)
     851       279356 :       || !refs_tbaa_equivalent_p (DR_REF (a), DR_REF (b)))
     852              :     return false;
     853              : 
     854              :   /* Check whether the base address and the step of both references is the
     855              :      same.  */
     856       251230 :   if (!operand_equal_p (DR_STEP (a), DR_STEP (b), 0)
     857       251230 :       || !operand_equal_p (DR_BASE_ADDRESS (a), DR_BASE_ADDRESS (b), 0))
     858              :     return false;
     859              : 
     860       123150 :   if (integer_zerop (DR_STEP (a)))
     861              :     {
     862              :       /* If the references have loop invariant address, check that they access
     863              :          exactly the same location.  */
     864         8815 :       *off = 0;
     865         8815 :       return (operand_equal_p (DR_OFFSET (a), DR_OFFSET (b), 0)
     866         8815 :               && operand_equal_p (DR_INIT (a), DR_INIT (b), 0));
     867              :     }
     868              : 
     869              :   /* Compare the offsets of the addresses, and check whether the difference
     870              :      is a multiple of step.  */
     871       114335 :   aff_combination_dr_offset (a, &diff);
     872       114335 :   aff_combination_dr_offset (b, &baseb);
     873       114335 :   aff_combination_scale (&baseb, -1);
     874       114335 :   aff_combination_add (&diff, &baseb);
     875              : 
     876       114335 :   tree_to_aff_combination_expand (DR_STEP (a), TREE_TYPE (DR_STEP (a)),
     877              :                                   &step, &m_cache);
     878       114335 :   return aff_combination_constant_multiple_p (&diff, &step, off);
     879       279356 : }
     880              : 
     881              : /* Returns the last basic block in LOOP for that we are sure that
     882              :    it is executed whenever the loop is entered.  */
     883              : 
     884              : static basic_block
     885       271739 : last_always_executed_block (class loop *loop)
     886              : {
     887       271739 :   unsigned i;
     888       271739 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
     889       271739 :   edge ex;
     890       271739 :   basic_block last = loop->latch;
     891              : 
     892       691604 :   FOR_EACH_VEC_ELT (exits, i, ex)
     893       419865 :     last = nearest_common_dominator (CDI_DOMINATORS, last, ex->src);
     894              : 
     895       271739 :   return last;
     896       271739 : }
     897              : 
     898              : /* Splits dependence graph on DATAREFS described by DEPENDENCES to
     899              :    components.  */
     900              : 
     901              : struct component *
     902       271739 : pcom_worker::split_data_refs_to_components ()
     903              : {
     904       271739 :   unsigned i, n = m_datarefs.length ();
     905       271739 :   unsigned ca, ia, ib, bad;
     906       271739 :   struct data_reference *dr, *dra, *drb;
     907       271739 :   struct data_dependence_relation *ddr;
     908       271739 :   struct component *comp_list = NULL, *comp;
     909       271739 :   dref dataref;
     910              :   /* Don't do store elimination if loop has multiple exit edges.  */
     911       271739 :   bool eliminate_store_p = single_exit (m_loop) != NULL;
     912       271739 :   basic_block last_always_executed = last_always_executed_block (m_loop);
     913       271739 :   auto_bitmap no_store_store_comps;
     914       271739 :   auto_vec<unsigned> comp_father (n + 1);
     915       271739 :   auto_vec<unsigned> comp_size (n + 1);
     916       271739 :   comp_father.quick_grow (n + 1);
     917       271739 :   comp_size.quick_grow (n + 1);
     918              : 
     919      1320086 :   FOR_EACH_VEC_ELT (m_datarefs, i, dr)
     920              :     {
     921       776841 :       if (!DR_REF (dr))
     922              :           /* A fake reference for call or asm_expr that may clobber memory;
     923              :              just fail.  */
     924              :           return NULL;
     925              :       /* predcom pass isn't prepared to handle calls with data references.  */
     926       776841 :       if (is_gimple_call (DR_STMT (dr)))
     927              :         return NULL;
     928       776608 :       dr->aux = (void *) (size_t) i;
     929       776608 :       comp_father[i] = i;
     930       776608 :       comp_size[i] = 1;
     931              :     }
     932              : 
     933              :   /* A component reserved for the "bad" data references.  */
     934       271506 :   comp_father[n] = n;
     935       271506 :   comp_size[n] = 1;
     936              : 
     937      1047494 :   FOR_EACH_VEC_ELT (m_datarefs, i, dr)
     938              :     {
     939       775988 :       enum ref_step_type dummy;
     940              : 
     941       775988 :       if (!suitable_reference_p (dr, &dummy))
     942              :         {
     943       210917 :           ia = (unsigned) (size_t) dr->aux;
     944       210917 :           merge_comps (comp_father, comp_size, n, ia);
     945              :         }
     946              :     }
     947              : 
     948      4852454 :   FOR_EACH_VEC_ELT (m_dependences, i, ddr)
     949              :     {
     950      4580948 :       poly_widest_int dummy_off;
     951              : 
     952      4580948 :       if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
     953      2024508 :         continue;
     954              : 
     955      2556440 :       dra = DDR_A (ddr);
     956      2556440 :       drb = DDR_B (ddr);
     957              : 
     958              :       /* Don't do store elimination if there is any unknown dependence for
     959              :          any store data reference.  */
     960      1523735 :       if ((DR_IS_WRITE (dra) || DR_IS_WRITE (drb))
     961      2934963 :           && (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know
     962       343607 :               || DDR_NUM_DIST_VECTS (ddr) == 0))
     963              :         eliminate_store_p = false;
     964              : 
     965      2556440 :       ia = component_of (comp_father, (unsigned) (size_t) dra->aux);
     966      2556440 :       ib = component_of (comp_father, (unsigned) (size_t) drb->aux);
     967      2556440 :       if (ia == ib)
     968      2132546 :         continue;
     969              : 
     970       423894 :       bad = component_of (comp_father, n);
     971              : 
     972              :       /* If both A and B are reads, we may ignore unsuitable dependences.  */
     973       423894 :       if (DR_IS_READ (dra) && DR_IS_READ (drb))
     974              :         {
     975       170715 :           if (ia == bad || ib == bad
     976       354646 :               || !determine_offset (dra, drb, &dummy_off))
     977       176471 :             continue;
     978              :         }
     979              :       /* If A is read and B write or vice versa and there is unsuitable
     980              :          dependence, instead of merging both components into a component
     981              :          that will certainly not pass suitable_component_p, just put the
     982              :          read into bad component, perhaps at least the write together with
     983              :          all the other data refs in it's component will be optimizable.  */
     984       223426 :       else if (DR_IS_READ (dra) && ib != bad)
     985              :         {
     986       138498 :           if (ia == bad)
     987              :             {
     988        78378 :               bitmap_set_bit (no_store_store_comps, ib);
     989        78378 :               continue;
     990              :             }
     991        60120 :           else if (!determine_offset (dra, drb, &dummy_off))
     992              :             {
     993        29293 :               bitmap_set_bit (no_store_store_comps, ib);
     994        29293 :               merge_comps (comp_father, comp_size, bad, ia);
     995        29293 :               continue;
     996              :             }
     997              :         }
     998        84928 :       else if (DR_IS_READ (drb) && ia != bad)
     999              :         {
    1000        25309 :           if (ib == bad)
    1001              :             {
    1002        16108 :               bitmap_set_bit (no_store_store_comps, ia);
    1003        16108 :               continue;
    1004              :             }
    1005         9201 :           else if (!determine_offset (dra, drb, &dummy_off))
    1006              :             {
    1007         5305 :               bitmap_set_bit (no_store_store_comps, ia);
    1008         5305 :               merge_comps (comp_father, comp_size, bad, ib);
    1009         5305 :               continue;
    1010              :             }
    1011              :         }
    1012        49029 :       else if (DR_IS_WRITE (dra) && DR_IS_WRITE (drb)
    1013        40540 :                && ia != bad && ib != bad
    1014        69271 :                && !determine_offset (dra, drb, &dummy_off))
    1015              :         {
    1016         4900 :           merge_comps (comp_father, comp_size, bad, ia);
    1017         4900 :           merge_comps (comp_father, comp_size, bad, ib);
    1018         4900 :           continue;
    1019              :         }
    1020              : 
    1021       113439 :       merge_comps (comp_father, comp_size, ia, ib);
    1022      4580948 :     }
    1023              : 
    1024       271506 :   if (eliminate_store_p)
    1025              :     {
    1026       126698 :       tree niters = number_of_latch_executions (m_loop);
    1027              : 
    1028              :       /* Don't do store elimination if niters info is unknown because stores
    1029              :          in the last iteration can't be eliminated and we need to recover it
    1030              :          after loop.  */
    1031       126698 :       eliminate_store_p = (niters != NULL_TREE && niters != chrec_dont_know);
    1032              :     }
    1033              : 
    1034       271506 :   auto_vec<struct component *> comps;
    1035       271506 :   comps.safe_grow_cleared (n, true);
    1036       271506 :   bad = component_of (comp_father, n);
    1037      1319000 :   FOR_EACH_VEC_ELT (m_datarefs, i, dr)
    1038              :     {
    1039       775988 :       ia = (unsigned) (size_t) dr->aux;
    1040       775988 :       ca = component_of (comp_father, ia);
    1041       775988 :       if (ca == bad)
    1042       311622 :         continue;
    1043              : 
    1044       464366 :       comp = comps[ca];
    1045       464366 :       if (!comp)
    1046              :         {
    1047       407234 :           comp = new component (eliminate_store_p);
    1048       407234 :           comp->refs.reserve_exact (comp_size[ca]);
    1049       407234 :           comps[ca] = comp;
    1050              :         }
    1051              : 
    1052       464366 :       dataref = XCNEW (class dref_d);
    1053       464366 :       dataref->ref = dr;
    1054       464366 :       dataref->stmt = DR_STMT (dr);
    1055       464366 :       dataref->offset = 0;
    1056       464366 :       dataref->distance = 0;
    1057              : 
    1058       464366 :       dataref->always_accessed
    1059       464366 :               = dominated_by_p (CDI_DOMINATORS, last_always_executed,
    1060       464366 :                                 gimple_bb (dataref->stmt));
    1061       464366 :       dataref->pos = comp->refs.length ();
    1062       464366 :       comp->refs.quick_push (dataref);
    1063              :     }
    1064              : 
    1065       271506 :   if (eliminate_store_p)
    1066              :     {
    1067       106111 :       bitmap_iterator bi;
    1068       107270 :       EXECUTE_IF_SET_IN_BITMAP (no_store_store_comps, 0, ia, bi)
    1069              :         {
    1070         1159 :           ca = component_of (comp_father, ia);
    1071         1159 :           if (ca != bad)
    1072         1008 :             comps[ca]->eliminate_store_p = false;
    1073              :         }
    1074              :     }
    1075              : 
    1076      1047494 :   for (i = 0; i < n; i++)
    1077              :     {
    1078       775988 :       comp = comps[i];
    1079       775988 :       if (comp)
    1080              :         {
    1081       407234 :           comp->next = comp_list;
    1082       407234 :           comp_list = comp;
    1083              :         }
    1084              :     }
    1085       271506 :   return comp_list;
    1086       543245 : }
    1087              : 
    1088              : /* Returns true if the component COMP satisfies the conditions
    1089              :    described in 2) at the beginning of this file.  */
    1090              : 
    1091              : bool
    1092       407234 : pcom_worker::suitable_component_p (struct component *comp)
    1093              : {
    1094       407234 :   unsigned i;
    1095       407234 :   dref a, first;
    1096       407234 :   basic_block ba, bp = m_loop->header;
    1097       407234 :   bool ok, has_write = false;
    1098              : 
    1099       841029 :   FOR_EACH_VEC_ELT (comp->refs, i, a)
    1100              :     {
    1101       454631 :       ba = gimple_bb (a->stmt);
    1102              : 
    1103       454631 :       if (!just_once_each_iteration_p (m_loop, ba))
    1104              :         return false;
    1105              : 
    1106       433795 :       gcc_assert (dominated_by_p (CDI_DOMINATORS, ba, bp));
    1107       433795 :       bp = ba;
    1108              : 
    1109       433795 :       if (DR_IS_WRITE (a->ref))
    1110       150777 :         has_write = true;
    1111              :     }
    1112              : 
    1113       386398 :   first = comp->refs[0];
    1114       386398 :   ok = suitable_reference_p (first->ref, &comp->comp_step);
    1115       386398 :   gcc_assert (ok);
    1116       386398 :   first->offset = 0;
    1117              : 
    1118       818911 :   FOR_EACH_VEC_ELT (comp->refs, i, a)
    1119              :     {
    1120       432603 :       if (has_write && comp->comp_step == RS_NONZERO)
    1121              :         {
    1122              :           /* Punt for non-invariant references where step isn't a multiple
    1123              :              of reference size.  If step is smaller than reference size,
    1124              :              it overlaps the access in next iteration, if step is larger,
    1125              :              but not multiple of the access size, there could be overlap
    1126              :              in some later iteration.  There might be more latent issues
    1127              :              about this in predcom or data reference analysis.  If the
    1128              :              reference is a COMPONENT_REF, also check if step isn't a
    1129              :              multiple of the containing aggregate size.  See PR111683.  */
    1130       152674 :           tree ref = DR_REF (a->ref);
    1131       152674 :           tree step = DR_STEP (a->ref);
    1132       152674 :           if (TREE_CODE (ref) == COMPONENT_REF
    1133       152674 :               && DECL_BIT_FIELD (TREE_OPERAND (ref, 1)))
    1134           55 :             ref = TREE_OPERAND (ref, 0);
    1135       152746 :           do
    1136              :             {
    1137       152710 :               tree sz = TYPE_SIZE_UNIT (TREE_TYPE (ref));
    1138       152710 :               if (TREE_CODE (sz) != INTEGER_CST)
    1139           90 :                 return false;
    1140       305420 :               if (wi::multiple_of_p (wi::to_offset (step),
    1141       305420 :                                      wi::to_offset (sz), SIGNED))
    1142              :                 break;
    1143          126 :               if (TREE_CODE (ref) != COMPONENT_REF)
    1144              :                 return false;
    1145           36 :               ref = TREE_OPERAND (ref, 0);
    1146           36 :             }
    1147              :           while (1);
    1148              :         }
    1149       432513 :       if (i == 0)
    1150       386308 :         continue;
    1151              :       /* Polynomial offsets are no use, since we need to know the
    1152              :          gap between iteration numbers at compile time.  */
    1153        46205 :       poly_widest_int offset;
    1154        46205 :       if (!determine_offset (first->ref, a->ref, &offset)
    1155        46205 :           || !offset.is_constant (&a->offset))
    1156            0 :         return false;
    1157              : 
    1158        46205 :       enum ref_step_type a_step;
    1159        46205 :       gcc_checking_assert (suitable_reference_p (a->ref, &a_step)
    1160              :                            && a_step == comp->comp_step);
    1161        46205 :     }
    1162              : 
    1163              :   /* If there is a write inside the component, we must know whether the
    1164              :      step is nonzero or not -- we would not otherwise be able to recognize
    1165              :      whether the value accessed by reads comes from the OFFSET-th iteration
    1166              :      or the previous one.  */
    1167       386308 :   if (has_write && comp->comp_step == RS_ANY)
    1168         6921 :     return false;
    1169              : 
    1170              :   return true;
    1171              : }
    1172              : 
    1173              : /* Check the conditions on references inside each of components COMPS,
    1174              :    and remove the unsuitable components from the list.  The new list
    1175              :    of components is returned.  The conditions are described in 2) at
    1176              :    the beginning of this file.  */
    1177              : 
    1178              : struct component *
    1179       183538 : pcom_worker::filter_suitable_components (struct component *comps)
    1180              : {
    1181       183538 :   struct component **comp, *act;
    1182              : 
    1183       590772 :   for (comp = &comps; *comp; )
    1184              :     {
    1185       407234 :       act = *comp;
    1186       407234 :       if (suitable_component_p (act))
    1187       379387 :         comp = &act->next;
    1188              :       else
    1189              :         {
    1190        27847 :           dref ref;
    1191        27847 :           unsigned i;
    1192              : 
    1193        27847 :           *comp = act->next;
    1194        67829 :           FOR_EACH_VEC_ELT (act->refs, i, ref)
    1195        39982 :             free (ref);
    1196        27847 :           delete act;
    1197              :         }
    1198              :     }
    1199              : 
    1200       183538 :   return comps;
    1201              : }
    1202              : 
    1203              : /* Compares two drefs A and B by their offset and position.  Callback for
    1204              :    qsort.  */
    1205              : 
    1206              : static int
    1207       199206 : order_drefs (const void *a, const void *b)
    1208              : {
    1209       199206 :   const dref *const da = (const dref *) a;
    1210       199206 :   const dref *const db = (const dref *) b;
    1211       199206 :   int offcmp = wi::cmps ((*da)->offset, (*db)->offset);
    1212              : 
    1213       199206 :   if (offcmp != 0)
    1214              :     return offcmp;
    1215              : 
    1216       110342 :   return (*da)->pos - (*db)->pos;
    1217              : }
    1218              : 
    1219              : /* Compares two drefs A and B by their position.  Callback for qsort.  */
    1220              : 
    1221              : static int
    1222           48 : order_drefs_by_pos (const void *a, const void *b)
    1223              : {
    1224           48 :   const dref *const da = (const dref *) a;
    1225           48 :   const dref *const db = (const dref *) b;
    1226              : 
    1227           48 :   return (*da)->pos - (*db)->pos;
    1228              : }
    1229              : 
    1230              : /* Returns root of the CHAIN.  */
    1231              : 
    1232              : static inline dref
    1233       108735 : get_chain_root (chain_p chain)
    1234              : {
    1235       217470 :   return chain->refs[0];
    1236              : }
    1237              : 
    1238              : /* Given CHAIN, returns the last write ref at DISTANCE, or NULL if it doesn't
    1239              :    exist.  */
    1240              : 
    1241              : static inline dref
    1242          106 : get_chain_last_write_at (chain_p chain, unsigned distance)
    1243              : {
    1244          358 :   for (unsigned i = chain->refs.length (); i > 0; i--)
    1245          242 :     if (DR_IS_WRITE (chain->refs[i - 1]->ref)
    1246          242 :         && distance == chain->refs[i - 1]->distance)
    1247              :       return chain->refs[i - 1];
    1248              : 
    1249              :   return NULL;
    1250              : }
    1251              : 
    1252              : /* Given CHAIN, returns the last write ref with the same distance before load
    1253              :    at index LOAD_IDX, or NULL if it doesn't exist.  */
    1254              : 
    1255              : static inline dref
    1256            5 : get_chain_last_write_before_load (chain_p chain, unsigned load_idx)
    1257              : {
    1258            5 :   gcc_assert (load_idx < chain->refs.length ());
    1259              : 
    1260            5 :   unsigned distance = chain->refs[load_idx]->distance;
    1261              : 
    1262            5 :   for (unsigned i = load_idx; i > 0; i--)
    1263            5 :     if (DR_IS_WRITE (chain->refs[i - 1]->ref)
    1264            5 :         && distance == chain->refs[i - 1]->distance)
    1265              :       return chain->refs[i - 1];
    1266              : 
    1267              :   return NULL;
    1268              : }
    1269              : 
    1270              : /* Adds REF to the chain CHAIN.  */
    1271              : 
    1272              : static void
    1273        18849 : add_ref_to_chain (chain_p chain, dref ref)
    1274              : {
    1275        18849 :   dref root = get_chain_root (chain);
    1276              : 
    1277        18849 :   gcc_assert (wi::les_p (root->offset, ref->offset));
    1278        18849 :   widest_int dist = ref->offset - root->offset;
    1279        18849 :   gcc_assert (wi::fits_uhwi_p (dist));
    1280              : 
    1281        18849 :   chain->refs.safe_push (ref);
    1282              : 
    1283        18849 :   ref->distance = dist.to_uhwi ();
    1284              : 
    1285        18849 :   if (ref->distance >= chain->length)
    1286              :     {
    1287        18849 :       chain->length = ref->distance;
    1288        18849 :       chain->has_max_use_after = false;
    1289              :     }
    1290              : 
    1291              :   /* Promote this chain to CT_STORE_STORE if it has multiple stores.  */
    1292        18849 :   if (DR_IS_WRITE (ref->ref))
    1293           69 :     chain->type = CT_STORE_STORE;
    1294              : 
    1295              :   /* Don't set the flag for store-store chain since there is no use.  */
    1296        18849 :   if (chain->type != CT_STORE_STORE
    1297        18778 :       && ref->distance == chain->length
    1298        18778 :       && ref->pos > root->pos)
    1299         7659 :     chain->has_max_use_after = true;
    1300              : 
    1301        18849 :   chain->all_always_accessed &= ref->always_accessed;
    1302        18849 : }
    1303              : 
    1304              : /* Returns the chain for invariant component COMP.  */
    1305              : 
    1306              : static chain_p
    1307        15725 : make_invariant_chain (struct component *comp)
    1308              : {
    1309        15725 :   chain_p chain = new struct chain (CT_INVARIANT);
    1310        15725 :   unsigned i;
    1311        15725 :   dref ref;
    1312              : 
    1313        15725 :   chain->all_always_accessed = true;
    1314              : 
    1315        49757 :   FOR_EACH_VEC_ELT (comp->refs, i, ref)
    1316              :     {
    1317        18307 :       chain->refs.safe_push (ref);
    1318        18307 :       chain->all_always_accessed &= ref->always_accessed;
    1319              :     }
    1320              : 
    1321        15725 :   chain->inits = vNULL;
    1322        15725 :   chain->finis = vNULL;
    1323              : 
    1324        15725 :   return chain;
    1325              : }
    1326              : 
    1327              : /* Make a new chain of type TYPE rooted at REF.  */
    1328              : 
    1329              : static chain_p
    1330        60386 : make_rooted_chain (dref ref, enum chain_type type)
    1331              : {
    1332        60386 :   chain_p chain = new struct chain (type);
    1333              : 
    1334        60386 :   chain->refs.safe_push (ref);
    1335        60386 :   chain->all_always_accessed = ref->always_accessed;
    1336        60386 :   ref->distance = 0;
    1337              : 
    1338        60386 :   chain->inits = vNULL;
    1339        60386 :   chain->finis = vNULL;
    1340              : 
    1341        60386 :   return chain;
    1342              : }
    1343              : 
    1344              : /* Returns true if CHAIN is not trivial.  */
    1345              : 
    1346              : static bool
    1347        97206 : nontrivial_chain_p (chain_p chain)
    1348              : {
    1349        60386 :   return chain != NULL && chain->refs.length () > 1;
    1350              : }
    1351              : 
    1352              : /* Returns the ssa name that contains the value of REF, or NULL_TREE if there
    1353              :    is no such name.  */
    1354              : 
    1355              : static tree
    1356        97662 : name_for_ref (dref ref)
    1357              : {
    1358        97662 :   tree name;
    1359              : 
    1360        97662 :   if (is_gimple_assign (ref->stmt))
    1361              :     {
    1362        97638 :       if (!ref->ref || DR_IS_READ (ref->ref))
    1363        97638 :         name = gimple_assign_lhs (ref->stmt);
    1364              :       else
    1365            0 :         name = gimple_assign_rhs1 (ref->stmt);
    1366              :     }
    1367              :   else
    1368           24 :     name = PHI_RESULT (ref->stmt);
    1369              : 
    1370        97662 :   return (TREE_CODE (name) == SSA_NAME ? name : NULL_TREE);
    1371              : }
    1372              : 
    1373              : /* Returns true if REF is a valid initializer for ROOT with given DISTANCE (in
    1374              :    iterations of the innermost enclosing loop).  */
    1375              : 
    1376              : bool
    1377           35 : pcom_worker::valid_initializer_p (struct data_reference *ref, unsigned distance,
    1378              :                                   struct data_reference *root)
    1379              : {
    1380          105 :   aff_tree diff, base, step;
    1381           35 :   poly_widest_int off;
    1382              : 
    1383              :   /* Both REF and ROOT must be accessing the same object and behave the
    1384              :      same for TBAA, since the initializer stands in for a reference with
    1385              :      the alias info of ROOT.  */
    1386           35 :   if (!operand_equal_p (DR_BASE_ADDRESS (ref), DR_BASE_ADDRESS (root), 0)
    1387           35 :       || !refs_tbaa_equivalent_p (DR_REF (ref), DR_REF (root)))
    1388              :     return false;
    1389              : 
    1390              :   /* The initializer is defined outside of loop, hence its address must be
    1391              :      invariant inside the loop.  */
    1392           23 :   gcc_assert (integer_zerop (DR_STEP (ref)));
    1393              : 
    1394              :   /* If the address of the reference is invariant, initializer must access
    1395              :      exactly the same location.  */
    1396           23 :   if (integer_zerop (DR_STEP (root)))
    1397            0 :     return (operand_equal_p (DR_OFFSET (ref), DR_OFFSET (root), 0)
    1398            0 :             && operand_equal_p (DR_INIT (ref), DR_INIT (root), 0));
    1399              : 
    1400              :   /* Verify that this index of REF is equal to the root's index at
    1401              :      -DISTANCE-th iteration.  */
    1402           23 :   aff_combination_dr_offset (root, &diff);
    1403           23 :   aff_combination_dr_offset (ref, &base);
    1404           23 :   aff_combination_scale (&base, -1);
    1405           23 :   aff_combination_add (&diff, &base);
    1406              : 
    1407           23 :   tree_to_aff_combination_expand (DR_STEP (root), TREE_TYPE (DR_STEP (root)),
    1408              :                                   &step, &m_cache);
    1409           23 :   if (!aff_combination_constant_multiple_p (&diff, &step, &off))
    1410              :     return false;
    1411              : 
    1412           23 :   if (maybe_ne (off, distance))
    1413              :     return false;
    1414              : 
    1415              :   return true;
    1416           35 : }
    1417              : 
    1418              : /* Finds looparound phi node of loop that copies the value of REF, and if its
    1419              :    initial value is correct (equal to initial value of REF shifted by one
    1420              :    iteration), returns the phi node.  Otherwise, NULL_TREE is returned.  ROOT
    1421              :    is the root of the current chain.  */
    1422              : 
    1423              : gphi *
    1424        37210 : pcom_worker::find_looparound_phi (dref ref, dref root)
    1425              : {
    1426        37210 :   tree name, init, init_ref;
    1427        37210 :   edge latch = loop_latch_edge (m_loop);
    1428        37210 :   struct data_reference init_dr;
    1429        37210 :   gphi_iterator psi;
    1430              : 
    1431        37210 :   if (is_gimple_assign (ref->stmt))
    1432              :     {
    1433        37197 :       if (DR_IS_READ (ref->ref))
    1434        34257 :         name = gimple_assign_lhs (ref->stmt);
    1435              :       else
    1436         2940 :         name = gimple_assign_rhs1 (ref->stmt);
    1437              :     }
    1438              :   else
    1439           13 :     name = PHI_RESULT (ref->stmt);
    1440        37210 :   if (!name)
    1441              :     return NULL;
    1442              : 
    1443        37210 :   tree entry_vuse = NULL_TREE;
    1444        37210 :   gphi *phi = NULL;
    1445       319681 :   for (psi = gsi_start_phis (m_loop->header); !gsi_end_p (psi); gsi_next (&psi))
    1446              :     {
    1447       282508 :       gphi *p = psi.phi ();
    1448       282508 :       if (PHI_ARG_DEF_FROM_EDGE (p, latch) == name)
    1449              :         phi = p;
    1450       564930 :       else if (virtual_operand_p (gimple_phi_result (p)))
    1451        25320 :         entry_vuse = PHI_ARG_DEF_FROM_EDGE (p, loop_preheader_edge (m_loop));
    1452       282508 :       if (phi && entry_vuse)
    1453              :         break;
    1454              :     }
    1455        37210 :   if (!phi || !entry_vuse)
    1456              :     return NULL;
    1457              : 
    1458           37 :   init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (m_loop));
    1459           37 :   if (TREE_CODE (init) != SSA_NAME)
    1460              :     return NULL;
    1461           35 :   gassign *init_stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (init));
    1462           35 :   if (!init_stmt)
    1463              :     return NULL;
    1464           35 :   gcc_assert (gimple_assign_lhs (init_stmt) == init);
    1465              : 
    1466           35 :   init_ref = gimple_assign_rhs1 (init_stmt);
    1467           35 :   if (!REFERENCE_CLASS_P (init_ref)
    1468           35 :       && !DECL_P (init_ref))
    1469              :     return NULL;
    1470              : 
    1471              :   /* Analyze the behavior of INIT_REF with respect to LOOP (innermost
    1472              :      loop enclosing PHI).  */
    1473           35 :   memset (&init_dr, 0, sizeof (struct data_reference));
    1474           35 :   DR_REF (&init_dr) = init_ref;
    1475           35 :   DR_STMT (&init_dr) = phi;
    1476           35 :   if (!dr_analyze_innermost (&DR_INNERMOST (&init_dr), init_ref, m_loop,
    1477              :                              init_stmt))
    1478              :     return NULL;
    1479              : 
    1480           35 :   if (!valid_initializer_p (&init_dr, ref->distance + 1, root->ref))
    1481              :     return NULL;
    1482              : 
    1483              :   /* Make sure nothing clobbers the location we re-use the initial value
    1484              :      from.  */
    1485           46 :   if (entry_vuse != gimple_vuse (init_stmt))
    1486              :     {
    1487           10 :       ao_ref ref;
    1488           10 :       ao_ref_init (&ref, init_ref);
    1489           10 :       unsigned limit = param_sccvn_max_alias_queries_per_access;
    1490           10 :       tree vdef = entry_vuse;
    1491           10 :       do
    1492              :         {
    1493           10 :           gimple *def = SSA_NAME_DEF_STMT (vdef);
    1494           10 :           if (limit-- == 0 || gimple_code (def) == GIMPLE_PHI)
    1495           10 :             return NULL;
    1496           10 :           if (stmt_may_clobber_ref_p_1 (def, &ref))
    1497              :             /* When the stmt is an assign to init_ref we could in theory
    1498              :                use its RHS for the initial value of the looparound PHI
    1499              :                we replace in prepare_initializers_chain, but we have
    1500              :                no convenient place to store this info at the moment.  */
    1501              :             return NULL;
    1502            0 :           vdef = gimple_vuse (def);
    1503              :         }
    1504            0 :       while (vdef != gimple_vuse (init_stmt));
    1505              :     }
    1506              : 
    1507              :   return phi;
    1508              : }
    1509              : 
    1510              : /* Adds a reference for the looparound copy of REF in PHI to CHAIN.  */
    1511              : 
    1512              : static void
    1513           13 : insert_looparound_copy (chain_p chain, dref ref, gphi *phi)
    1514              : {
    1515           13 :   dref nw = XCNEW (class dref_d), aref;
    1516           13 :   unsigned i;
    1517              : 
    1518           13 :   nw->stmt = phi;
    1519           13 :   nw->distance = ref->distance + 1;
    1520           13 :   nw->always_accessed = 1;
    1521              : 
    1522           50 :   FOR_EACH_VEC_ELT (chain->refs, i, aref)
    1523           38 :     if (aref->distance >= nw->distance)
    1524              :       break;
    1525           13 :   chain->refs.safe_insert (i, nw);
    1526              : 
    1527           13 :   if (nw->distance > chain->length)
    1528              :     {
    1529           12 :       chain->length = nw->distance;
    1530           12 :       chain->has_max_use_after = false;
    1531              :     }
    1532           13 : }
    1533              : 
    1534              : /* For references in CHAIN that are copied around the loop (created previously
    1535              :    by PRE, or by user), add the results of such copies to the chain.  This
    1536              :    enables us to remove the copies by unrolling, and may need less registers
    1537              :    (also, it may allow us to combine chains together).  */
    1538              : 
    1539              : void
    1540        18478 : pcom_worker::add_looparound_copies (chain_p chain)
    1541              : {
    1542        18478 :   unsigned i;
    1543        18478 :   dref ref, root = get_chain_root (chain);
    1544        18478 :   gphi *phi;
    1545              : 
    1546        18478 :   if (chain->type == CT_STORE_STORE)
    1547        18478 :     return;
    1548              : 
    1549        55632 :   FOR_EACH_VEC_ELT (chain->refs, i, ref)
    1550              :     {
    1551        37210 :       phi = find_looparound_phi (ref, root);
    1552        37210 :       if (!phi)
    1553        37197 :         continue;
    1554              : 
    1555           13 :       bitmap_set_bit (m_looparound_phis, SSA_NAME_VERSION (PHI_RESULT (phi)));
    1556           13 :       insert_looparound_copy (chain, ref, phi);
    1557              :     }
    1558              : }
    1559              : 
    1560              : /* Find roots of the values and determine distances in the component COMP.
    1561              :    The references are redistributed into chains.  */
    1562              : 
    1563              : void
    1564       379387 : pcom_worker::determine_roots_comp (struct component *comp)
    1565              : {
    1566       379387 :   unsigned i;
    1567       379387 :   dref a;
    1568       379387 :   chain_p chain = NULL;
    1569       379387 :   widest_int last_ofs = 0;
    1570       379387 :   enum chain_type type;
    1571              : 
    1572              :   /* Invariants are handled specially.  */
    1573       379387 :   if (comp->comp_step == RS_INVARIANT)
    1574              :     {
    1575        15725 :       chain = make_invariant_chain (comp);
    1576        15725 :       m_chains.safe_push (chain);
    1577        15725 :       return;
    1578              :     }
    1579              : 
    1580              :   /* Trivial component.  */
    1581       363662 :   if (comp->refs.length () <= 1)
    1582              :     {
    1583       669409 :       if (comp->refs.length () == 1)
    1584              :         {
    1585       326842 :           free (comp->refs[0]);
    1586       326842 :           comp->refs.truncate (0);
    1587              :         }
    1588              :       return;
    1589              :     }
    1590              : 
    1591        36820 :   comp->refs.qsort (order_drefs);
    1592              : 
    1593              :   /* For Store-Store chain, we only support load if it is dominated by a
    1594              :      store statement in the same iteration of loop.  */
    1595        36820 :   if (comp->eliminate_store_p)
    1596        21829 :     for (a = NULL, i = 0; i < comp->refs.length (); i++)
    1597              :       {
    1598        21766 :         if (DR_IS_WRITE (comp->refs[i]->ref))
    1599              :           a = comp->refs[i];
    1600        19425 :         else if (a == NULL || a->offset != comp->refs[i]->offset)
    1601              :           {
    1602              :             /* If there is load that is not dominated by a store in the
    1603              :                same iteration of loop, clear the flag so no Store-Store
    1604              :                chain is generated for this component.  */
    1605        19412 :             comp->eliminate_store_p = false;
    1606        19412 :             break;
    1607              :           }
    1608              :       }
    1609              : 
    1610              :   /* Determine roots and create chains for components.  */
    1611       116055 :   FOR_EACH_VEC_ELT (comp->refs, i, a)
    1612              :     {
    1613       218856 :       if (!chain
    1614        42415 :           || (chain->type == CT_LOAD && DR_IS_WRITE (a->ref))
    1615        23345 :           || (!comp->eliminate_store_p && DR_IS_WRITE (a->ref))
    1616       140816 :           || wi::leu_p (MAX_DISTANCE, a->offset - last_ofs))
    1617              :         {
    1618        60386 :           if (nontrivial_chain_p (chain))
    1619              :             {
    1620          610 :               add_looparound_copies (chain);
    1621          610 :               m_chains.safe_push (chain);
    1622              :             }
    1623              :           else
    1624        59776 :             release_chain (chain);
    1625              : 
    1626              :           /* Determine type of the chain.  If the root reference is a load,
    1627              :              this can only be a CT_LOAD chain; other chains are initialized
    1628              :              to CT_STORE_LOAD and might be promoted to CT_STORE_STORE when
    1629              :              new reference is added.  */
    1630        60386 :           type = DR_IS_READ (a->ref) ? CT_LOAD : CT_STORE_LOAD;
    1631        60386 :           chain = make_rooted_chain (a, type);
    1632        60386 :           last_ofs = a->offset;
    1633        60386 :           continue;
    1634              :         }
    1635              : 
    1636        18849 :       add_ref_to_chain (chain, a);
    1637              :     }
    1638              : 
    1639        36820 :   if (nontrivial_chain_p (chain))
    1640              :     {
    1641        17868 :       add_looparound_copies (chain);
    1642        17868 :       m_chains.safe_push (chain);
    1643              :     }
    1644              :   else
    1645        18952 :     release_chain (chain);
    1646       379387 : }
    1647              : 
    1648              : /* Find roots of the values and determine distances in components COMPS, and
    1649              :    separates the references to chains.  */
    1650              : 
    1651              : void
    1652       183538 : pcom_worker::determine_roots (struct component *comps)
    1653              : {
    1654       183538 :   struct component *comp;
    1655              : 
    1656       562925 :   for (comp = comps; comp; comp = comp->next)
    1657       379387 :     determine_roots_comp (comp);
    1658       183538 : }
    1659              : 
    1660              : /* Replace the reference in statement STMT with temporary variable
    1661              :    NEW_TREE.  If SET is true, NEW_TREE is instead initialized to the value of
    1662              :    the reference in the statement.  IN_LHS is true if the reference
    1663              :    is in the lhs of STMT, false if it is in rhs.  */
    1664              : 
    1665              : static void
    1666        39421 : replace_ref_with (gimple *stmt, tree new_tree, bool set, bool in_lhs)
    1667              : {
    1668        39421 :   tree val;
    1669        39421 :   gassign *new_stmt;
    1670        39421 :   gimple_stmt_iterator bsi, psi;
    1671              : 
    1672        39421 :   if (gimple_code (stmt) == GIMPLE_PHI)
    1673              :     {
    1674            1 :       gcc_assert (!in_lhs && !set);
    1675              : 
    1676            1 :       val = PHI_RESULT (stmt);
    1677            1 :       bsi = gsi_after_labels (gimple_bb (stmt));
    1678            1 :       psi = gsi_for_stmt (stmt);
    1679            1 :       remove_phi_node (&psi, false);
    1680              : 
    1681              :       /* Turn the phi node into GIMPLE_ASSIGN.  */
    1682            1 :       new_stmt = gimple_build_assign (val, new_tree);
    1683            1 :       gsi_insert_before (&bsi, new_stmt, GSI_NEW_STMT);
    1684        20068 :       return;
    1685              :     }
    1686              : 
    1687              :   /* Since the reference is of gimple_reg type, it should only
    1688              :      appear as lhs or rhs of modify statement.  */
    1689        39420 :   gcc_assert (is_gimple_assign (stmt));
    1690              : 
    1691        39420 :   bsi = gsi_for_stmt (stmt);
    1692              : 
    1693              :   /* If we do not need to initialize NEW_TREE, just replace the use of OLD.  */
    1694        39420 :   if (!set)
    1695              :     {
    1696        20066 :       gcc_assert (!in_lhs);
    1697        20066 :       gimple_assign_set_rhs_from_tree (&bsi, new_tree);
    1698        20066 :       stmt = gsi_stmt (bsi);
    1699        20066 :       update_stmt (stmt);
    1700        20066 :       return;
    1701              :     }
    1702              : 
    1703        19354 :   if (in_lhs)
    1704              :     {
    1705              :       /* We have statement
    1706              : 
    1707              :          OLD = VAL
    1708              : 
    1709              :          If OLD is a memory reference, then VAL is gimple_val, and we transform
    1710              :          this to
    1711              : 
    1712              :          OLD = VAL
    1713              :          NEW = VAL
    1714              : 
    1715              :          Otherwise, we are replacing a combination chain,
    1716              :          VAL is the expression that performs the combination, and OLD is an
    1717              :          SSA name.  In this case, we transform the assignment to
    1718              : 
    1719              :          OLD = VAL
    1720              :          NEW = OLD
    1721              : 
    1722              :          */
    1723              : 
    1724         4876 :       val = gimple_assign_lhs (stmt);
    1725         4876 :       if (TREE_CODE (val) != SSA_NAME)
    1726              :         {
    1727         4857 :           val = gimple_assign_rhs1 (stmt);
    1728         4857 :           gcc_assert (gimple_assign_single_p (stmt));
    1729         4857 :           if (TREE_CLOBBER_P (val))
    1730            0 :             val = get_or_create_ssa_default_def (cfun, SSA_NAME_VAR (new_tree));
    1731              :           else
    1732         4857 :             gcc_assert (gimple_assign_copy_p (stmt));
    1733              :         }
    1734              :     }
    1735              :   else
    1736              :     {
    1737              :       /* VAL = OLD
    1738              : 
    1739              :          is transformed to
    1740              : 
    1741              :          VAL = OLD
    1742              :          NEW = VAL  */
    1743              : 
    1744        14478 :       val = gimple_assign_lhs (stmt);
    1745              :     }
    1746              : 
    1747        19354 :   new_stmt = gimple_build_assign (new_tree, unshare_expr (val));
    1748        19354 :   gsi_insert_after (&bsi, new_stmt, GSI_NEW_STMT);
    1749              : }
    1750              : 
    1751              : /* Returns a memory reference to DR in the (NITERS + ITER)-th iteration
    1752              :    of the loop it was analyzed in.  Append init stmts to STMTS.  */
    1753              : 
    1754              : static tree
    1755        28619 : ref_at_iteration (data_reference_p dr, int iter,
    1756              :                   gimple_seq *stmts, tree niters = NULL_TREE)
    1757              : {
    1758        28619 :   tree off = DR_OFFSET (dr);
    1759        28619 :   tree coff = DR_INIT (dr);
    1760        28619 :   tree ref = DR_REF (dr);
    1761        28619 :   enum tree_code ref_code = ERROR_MARK;
    1762        28619 :   tree ref_type = NULL_TREE;
    1763        28619 :   tree ref_op1 = NULL_TREE;
    1764        28619 :   tree ref_op2 = NULL_TREE;
    1765        28619 :   tree new_offset;
    1766              : 
    1767        28619 :   if (iter != 0)
    1768              :     {
    1769        28573 :       new_offset = size_binop (MULT_EXPR, DR_STEP (dr), ssize_int (iter));
    1770        28573 :       if (TREE_CODE (new_offset) == INTEGER_CST)
    1771        28567 :         coff = size_binop (PLUS_EXPR, coff, new_offset);
    1772              :       else
    1773            6 :         off = size_binop (PLUS_EXPR, off, new_offset);
    1774              :     }
    1775              : 
    1776        28619 :   if (niters != NULL_TREE)
    1777              :     {
    1778           73 :       niters = fold_convert (ssizetype, niters);
    1779           73 :       new_offset = size_binop (MULT_EXPR, DR_STEP (dr), niters);
    1780           73 :       if (TREE_CODE (niters) == INTEGER_CST)
    1781           44 :         coff = size_binop (PLUS_EXPR, coff, new_offset);
    1782              :       else
    1783           29 :         off = size_binop (PLUS_EXPR, off, new_offset);
    1784              :     }
    1785              : 
    1786              :   /* While data-ref analysis punts on bit offsets it still handles
    1787              :      bitfield accesses at byte boundaries.  Cope with that.  Note that
    1788              :      if the bitfield object also starts at a byte-boundary we can simply
    1789              :      replicate the COMPONENT_REF, but we have to subtract the component's
    1790              :      byte-offset from the MEM_REF address first.
    1791              :      Otherwise we simply build a BIT_FIELD_REF knowing that the bits
    1792              :      start at offset zero.  */
    1793        28619 :   if (TREE_CODE (ref) == COMPONENT_REF
    1794        28619 :       && DECL_BIT_FIELD (TREE_OPERAND (ref, 1)))
    1795              :     {
    1796          111 :       unsigned HOST_WIDE_INT boff;
    1797          111 :       tree field = TREE_OPERAND (ref, 1);
    1798          111 :       tree offset = component_ref_field_offset (ref);
    1799          111 :       ref_type = TREE_TYPE (ref);
    1800          111 :       boff = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field));
    1801              :       /* This can occur in Ada.  See the comment in get_bit_range.  */
    1802          111 :       if (boff % BITS_PER_UNIT != 0
    1803          111 :           || !tree_fits_uhwi_p (offset))
    1804              :         {
    1805            0 :           ref_code = BIT_FIELD_REF;
    1806            0 :           ref_op1 = DECL_SIZE (field);
    1807            0 :           ref_op2 = bitsize_zero_node;
    1808              :         }
    1809              :       else
    1810              :         {
    1811          111 :           boff >>= LOG2_BITS_PER_UNIT;
    1812          111 :           boff += tree_to_uhwi (offset);
    1813          111 :           coff = size_binop (MINUS_EXPR, coff, ssize_int (boff));
    1814          111 :           ref_code = COMPONENT_REF;
    1815          111 :           ref_op1 = field;
    1816          111 :           ref_op2 = TREE_OPERAND (ref, 2);
    1817          111 :           ref = TREE_OPERAND (ref, 0);
    1818              :         }
    1819              :     }
    1820              :   /* We may not associate the constant offset across the pointer plus
    1821              :      expression because that might form a pointer to before the object
    1822              :      then.  But for some cases we can retain that to allow tree_could_trap_p
    1823              :      to return false - see gcc.dg/tree-ssa/predcom-1.c  */
    1824        28619 :   tree addr, alias_ptr;
    1825        28619 :   if (integer_zerop  (off)
    1826        28619 :       && TREE_CODE (DR_BASE_ADDRESS (dr)) != POINTER_PLUS_EXPR)
    1827              :     {
    1828        27507 :       alias_ptr = fold_convert (reference_alias_ptr_type (ref), coff);
    1829        27507 :       addr = DR_BASE_ADDRESS (dr);
    1830              :     }
    1831              :   else
    1832              :     {
    1833         1112 :       alias_ptr = build_zero_cst (reference_alias_ptr_type (ref));
    1834         1112 :       off = size_binop (PLUS_EXPR, off, coff);
    1835         1112 :       addr = fold_build_pointer_plus (DR_BASE_ADDRESS (dr), off);
    1836              :     }
    1837        28619 :   addr = force_gimple_operand_1 (unshare_expr (addr), stmts,
    1838              :                                  is_gimple_mem_ref_addr, NULL_TREE);
    1839        28619 :   tree type = build_aligned_type (TREE_TYPE (ref),
    1840              :                                   get_object_alignment (ref));
    1841        28619 :   ref = build2 (MEM_REF, type, addr, alias_ptr);
    1842        28619 :   copy_ref_info (ref, DR_REF (dr));
    1843        28619 :   if (ref_type)
    1844          111 :     ref = build3 (ref_code, ref_type, ref, ref_op1, ref_op2);
    1845        28619 :   return ref;
    1846              : }
    1847              : 
    1848              : /* Get the initialization expression for the INDEX-th temporary variable
    1849              :    of CHAIN.  */
    1850              : 
    1851              : static tree
    1852        11951 : get_init_expr (chain_p chain, unsigned index)
    1853              : {
    1854        11951 :   if (chain->type == CT_COMBINATION)
    1855              :     {
    1856           70 :       tree e1 = get_init_expr (chain->ch1, index);
    1857           70 :       tree e2 = get_init_expr (chain->ch2, index);
    1858              : 
    1859           70 :       return fold_build2 (chain->op, chain->rslt_type, e1, e2);
    1860              :     }
    1861              :   else
    1862        11881 :     return chain->inits[index];
    1863              : }
    1864              : 
    1865              : /* Returns a new temporary variable used for the I-th variable carrying
    1866              :    value of REF.  The variable's uid is marked in TMP_VARS.  */
    1867              : 
    1868              : static tree
    1869        21421 : predcom_tmp_var (tree ref, unsigned i, bitmap tmp_vars)
    1870              : {
    1871        21421 :   tree type = TREE_TYPE (ref);
    1872              :   /* We never access the components of the temporary variable in predictive
    1873              :      commoning.  */
    1874        21421 :   tree var = create_tmp_reg (type, get_lsm_tmp_name (ref, i));
    1875        21421 :   bitmap_set_bit (tmp_vars, DECL_UID (var));
    1876        21421 :   return var;
    1877              : }
    1878              : 
    1879              : /* Creates the variables for CHAIN, as well as phi nodes for them and
    1880              :    initialization on entry to LOOP.  Uids of the newly created
    1881              :    temporary variables are marked in TMP_VARS.  */
    1882              : 
    1883              : static void
    1884        17393 : initialize_root_vars (class loop *loop, chain_p chain, bitmap tmp_vars)
    1885              : {
    1886        17393 :   unsigned i;
    1887        17393 :   unsigned n = chain->length;
    1888        17393 :   dref root = get_chain_root (chain);
    1889        17393 :   bool reuse_first = !chain->has_max_use_after;
    1890        17393 :   tree ref, init, var, next;
    1891        17393 :   gphi *phi;
    1892        17393 :   gimple_seq stmts;
    1893        17393 :   edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
    1894              : 
    1895              :   /* If N == 0, then all the references are within the single iteration.  And
    1896              :      since this is an nonempty chain, reuse_first cannot be true.  */
    1897        17393 :   gcc_assert (n > 0 || !reuse_first);
    1898              : 
    1899        17393 :   chain->vars.create (n + 1);
    1900              : 
    1901        17393 :   if (chain->type == CT_COMBINATION)
    1902           19 :     ref = gimple_assign_lhs (root->stmt);
    1903              :   else
    1904        17374 :     ref = DR_REF (root->ref);
    1905              : 
    1906        52832 :   for (i = 0; i < n + (reuse_first ? 0 : 1); i++)
    1907              :     {
    1908        19111 :       var = predcom_tmp_var (ref, i, tmp_vars);
    1909        19111 :       chain->vars.quick_push (var);
    1910              :     }
    1911        17393 :   if (reuse_first)
    1912        10045 :     chain->vars.quick_push (chain->vars[0]);
    1913              : 
    1914        46549 :   FOR_EACH_VEC_ELT (chain->vars, i, var)
    1915        29156 :     chain->vars[i] = make_ssa_name (var);
    1916              : 
    1917        29156 :   for (i = 0; i < n; i++)
    1918              :     {
    1919        11763 :       var = chain->vars[i];
    1920        11763 :       next = chain->vars[i + 1];
    1921        11763 :       init = get_init_expr (chain, i);
    1922              : 
    1923        11763 :       init = force_gimple_operand (init, &stmts, true, NULL_TREE);
    1924        11763 :       if (stmts)
    1925        11762 :         gsi_insert_seq_on_edge_immediate (entry, stmts);
    1926              : 
    1927        11763 :       phi = create_phi_node (var, loop->header);
    1928        11763 :       add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
    1929        11763 :       add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
    1930              :     }
    1931        17393 : }
    1932              : 
    1933              : /* For inter-iteration store elimination CHAIN in LOOP, returns true if
    1934              :    all stores to be eliminated store loop invariant values into memory.
    1935              :    In this case, we can use these invariant values directly after LOOP.  */
    1936              : 
    1937              : static bool
    1938           46 : is_inv_store_elimination_chain (class loop *loop, chain_p chain)
    1939              : {
    1940           46 :   if (chain->length == 0 || chain->type != CT_STORE_STORE)
    1941              :     return false;
    1942              : 
    1943           46 :   gcc_assert (!chain->has_max_use_after);
    1944              : 
    1945              :   /* If loop iterates for unknown times or fewer times than chain->length,
    1946              :      we still need to setup root variable and propagate it with PHI node.  */
    1947           46 :   tree niters = number_of_latch_executions (loop);
    1948           46 :   if (TREE_CODE (niters) != INTEGER_CST
    1949           46 :       || wi::leu_p (wi::to_wide (niters), chain->length))
    1950              :     return false;
    1951              : 
    1952              :   /* Check stores in chain for elimination if they only store loop invariant
    1953              :      values.  */
    1954           57 :   for (unsigned i = 0; i < chain->length; i++)
    1955              :     {
    1956           43 :       dref a = get_chain_last_write_at (chain, i);
    1957           43 :       if (a == NULL)
    1958            5 :         continue;
    1959              : 
    1960           38 :       gimple *def_stmt, *stmt = a->stmt;
    1961           38 :       if (!gimple_assign_single_p (stmt))
    1962              :         return false;
    1963              : 
    1964           38 :       tree val = gimple_assign_rhs1 (stmt);
    1965           38 :       if (TREE_CLOBBER_P (val))
    1966              :         return false;
    1967              : 
    1968           38 :       if (CONSTANT_CLASS_P (val))
    1969           20 :         continue;
    1970              : 
    1971           18 :       if (TREE_CODE (val) != SSA_NAME)
    1972              :         return false;
    1973              : 
    1974           18 :       def_stmt = SSA_NAME_DEF_STMT (val);
    1975           18 :       if (gimple_nop_p (def_stmt))
    1976            0 :         continue;
    1977              : 
    1978           18 :       if (flow_bb_inside_loop_p (loop, gimple_bb (def_stmt)))
    1979              :         return false;
    1980              :     }
    1981              :   return true;
    1982              : }
    1983              : 
    1984              : /* Creates root variables for store elimination CHAIN in which stores for
    1985              :    elimination only store loop invariant values.  In this case, we neither
    1986              :    need to load root variables before loop nor propagate it with PHI nodes.  */
    1987              : 
    1988              : static void
    1989           14 : initialize_root_vars_store_elim_1 (chain_p chain)
    1990              : {
    1991           14 :   tree var;
    1992           14 :   unsigned i, n = chain->length;
    1993              : 
    1994           14 :   chain->vars.create (n);
    1995           14 :   chain->vars.safe_grow_cleared (n, true);
    1996              : 
    1997              :   /* Initialize root value for eliminated stores at each distance.  */
    1998           53 :   for (i = 0; i < n; i++)
    1999              :     {
    2000           25 :       dref a = get_chain_last_write_at (chain, i);
    2001           25 :       if (a == NULL)
    2002            5 :         continue;
    2003              : 
    2004           20 :       var = gimple_assign_rhs1 (a->stmt);
    2005           20 :       chain->vars[a->distance] = var;
    2006              :     }
    2007              : 
    2008              :   /* We don't propagate values with PHI nodes, so manually propagate value
    2009              :      to bubble positions.  */
    2010           14 :   var = chain->vars[0];
    2011           25 :   for (i = 1; i < n; i++)
    2012              :     {
    2013           11 :       if (chain->vars[i] != NULL_TREE)
    2014              :         {
    2015            6 :           var = chain->vars[i];
    2016            6 :           continue;
    2017              :         }
    2018            5 :       chain->vars[i] = var;
    2019              :     }
    2020              : 
    2021              :   /* Revert the vector.  */
    2022           20 :   for (i = 0; i < n / 2; i++)
    2023            6 :     std::swap (chain->vars[i], chain->vars[n - i - 1]);
    2024           14 : }
    2025              : 
    2026              : /* Creates root variables for store elimination CHAIN in which stores for
    2027              :    elimination store loop variant values.  In this case, we may need to
    2028              :    load root variables before LOOP and propagate it with PHI nodes.  Uids
    2029              :    of the newly created root variables are marked in TMP_VARS.  */
    2030              : 
    2031              : static void
    2032           32 : initialize_root_vars_store_elim_2 (class loop *loop,
    2033              :                                    chain_p chain, bitmap tmp_vars)
    2034              : {
    2035           32 :   unsigned i, n = chain->length;
    2036           32 :   tree ref, init, var, next, val, phi_result;
    2037           32 :   gimple *stmt;
    2038           32 :   gimple_seq stmts;
    2039              : 
    2040           32 :   chain->vars.create (n);
    2041              : 
    2042           32 :   ref = DR_REF (get_chain_root (chain)->ref);
    2043           80 :   for (i = 0; i < n; i++)
    2044              :     {
    2045           48 :       var = predcom_tmp_var (ref, i, tmp_vars);
    2046           48 :       chain->vars.quick_push (var);
    2047              :     }
    2048              : 
    2049          112 :   FOR_EACH_VEC_ELT (chain->vars, i, var)
    2050           48 :     chain->vars[i] = make_ssa_name (var);
    2051              : 
    2052              :   /* Root values are either rhs operand of stores to be eliminated, or
    2053              :      loaded from memory before loop.  */
    2054           32 :   auto_vec<tree> vtemps;
    2055           32 :   vtemps.safe_grow_cleared (n, true);
    2056          112 :   for (i = 0; i < n; i++)
    2057              :     {
    2058           48 :       init = get_init_expr (chain, i);
    2059           48 :       if (init == NULL_TREE)
    2060              :         {
    2061              :           /* Root value is rhs operand of the store to be eliminated if
    2062              :              it isn't loaded from memory before loop.  */
    2063           38 :           dref a = get_chain_last_write_at (chain, i);
    2064           38 :           val = gimple_assign_rhs1 (a->stmt);
    2065           38 :           if (TREE_CLOBBER_P (val))
    2066              :             {
    2067            0 :               val = get_or_create_ssa_default_def (cfun, SSA_NAME_VAR (var));
    2068            0 :               gimple_assign_set_rhs1 (a->stmt, val);
    2069              :             }
    2070              : 
    2071           38 :           vtemps[n - i - 1] = val;
    2072              :         }
    2073              :       else
    2074              :         {
    2075           10 :           edge latch = loop_latch_edge (loop);
    2076           10 :           edge entry = loop_preheader_edge (loop);
    2077              : 
    2078              :           /* Root value is loaded from memory before loop, we also need
    2079              :              to add PHI nodes to propagate the value across iterations.  */
    2080           10 :           init = force_gimple_operand (init, &stmts, true, NULL_TREE);
    2081           10 :           if (stmts)
    2082           10 :             gsi_insert_seq_on_edge_immediate (entry, stmts);
    2083              : 
    2084           10 :           next = chain->vars[n - i];
    2085           10 :           phi_result = copy_ssa_name (next);
    2086           10 :           gphi *phi = create_phi_node (phi_result, loop->header);
    2087           10 :           add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
    2088           10 :           add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
    2089           10 :           vtemps[n - i - 1] = phi_result;
    2090              :         }
    2091              :     }
    2092              : 
    2093              :   /* Find the insertion position.  */
    2094           32 :   dref last = get_chain_root (chain);
    2095          104 :   for (i = 0; i < chain->refs.length (); i++)
    2096              :     {
    2097           72 :       if (chain->refs[i]->pos > last->pos)
    2098           10 :         last = chain->refs[i];
    2099              :     }
    2100              : 
    2101           32 :   gimple_stmt_iterator gsi = gsi_for_stmt (last->stmt);
    2102              : 
    2103              :   /* Insert statements copying root value to root variable.  */
    2104          112 :   for (i = 0; i < n; i++)
    2105              :     {
    2106           48 :       var = chain->vars[i];
    2107           48 :       val = vtemps[i];
    2108           48 :       stmt = gimple_build_assign (var, val);
    2109           48 :       gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
    2110              :     }
    2111           32 : }
    2112              : 
    2113              : /* Generates stores for CHAIN's eliminated stores in LOOP's last
    2114              :    (CHAIN->length - 1) iterations.  */
    2115              : 
    2116              : static void
    2117           46 : finalize_eliminated_stores (class loop *loop, chain_p chain)
    2118              : {
    2119           46 :   unsigned i, n = chain->length;
    2120              : 
    2121          119 :   for (i = 0; i < n; i++)
    2122              :     {
    2123           73 :       tree var = chain->vars[i];
    2124           73 :       tree fini = chain->finis[n - i - 1];
    2125           73 :       gimple *stmt = gimple_build_assign (fini, var);
    2126              : 
    2127           73 :       gimple_seq_add_stmt_without_update (&chain->fini_seq, stmt);
    2128              :     }
    2129              : 
    2130           46 :   if (chain->fini_seq)
    2131              :     {
    2132           46 :       gsi_insert_seq_on_edge_immediate (single_exit (loop), chain->fini_seq);
    2133           46 :       chain->fini_seq = NULL;
    2134              :     }
    2135           46 : }
    2136              : 
    2137              : /* Initializes a variable for load motion for ROOT and prepares phi nodes and
    2138              :    initialization on entry to LOOP if necessary.  The ssa name for the variable
    2139              :    is stored in VARS.  If WRITTEN is true, also a phi node to copy its value
    2140              :    around the loop is created.  Uid of the newly created temporary variable
    2141              :    is marked in TMP_VARS.  INITS is the list containing the (single)
    2142              :    initializer.  */
    2143              : 
    2144              : static void
    2145         2262 : initialize_root_vars_lm (class loop *loop, dref root, bool written,
    2146              :                          vec<tree> *vars, const vec<tree> &inits,
    2147              :                          bitmap tmp_vars)
    2148              : {
    2149         2262 :   unsigned i;
    2150         2262 :   tree ref = DR_REF (root->ref), init, var, next;
    2151         2262 :   gimple_seq stmts;
    2152         2262 :   gphi *phi;
    2153         2262 :   edge entry = loop_preheader_edge (loop), latch = loop_latch_edge (loop);
    2154              : 
    2155              :   /* Find the initializer for the variable, and check that it cannot
    2156              :      trap.  */
    2157         2262 :   init = inits[0];
    2158              : 
    2159         2643 :   vars->create (written ? 2 : 1);
    2160         2262 :   var = predcom_tmp_var (ref, 0, tmp_vars);
    2161         2262 :   vars->quick_push (var);
    2162         2262 :   if (written)
    2163         1881 :     vars->quick_push ((*vars)[0]);
    2164              : 
    2165         8667 :   FOR_EACH_VEC_ELT (*vars, i, var)
    2166         4143 :     (*vars)[i] = make_ssa_name (var);
    2167              : 
    2168         2262 :   var = (*vars)[0];
    2169              : 
    2170         2262 :   init = force_gimple_operand (init, &stmts, written, NULL_TREE);
    2171         2262 :   if (stmts)
    2172         1881 :     gsi_insert_seq_on_edge_immediate (entry, stmts);
    2173              : 
    2174         2262 :   if (written)
    2175              :     {
    2176         1881 :       next = (*vars)[1];
    2177         1881 :       phi = create_phi_node (var, loop->header);
    2178         1881 :       add_phi_arg (phi, init, entry, UNKNOWN_LOCATION);
    2179         1881 :       add_phi_arg (phi, next, latch, UNKNOWN_LOCATION);
    2180              :     }
    2181              :   else
    2182              :     {
    2183          381 :       gassign *init_stmt = gimple_build_assign (var, init);
    2184          381 :       gsi_insert_on_edge_immediate (entry, init_stmt);
    2185              :     }
    2186         2262 : }
    2187              : 
    2188              : 
    2189              : /* Execute load motion for references in chain CHAIN.  Uids of the newly
    2190              :    created temporary variables are marked in TMP_VARS.  */
    2191              : 
    2192              : static void
    2193        12890 : execute_load_motion (class loop *loop, chain_p chain, bitmap tmp_vars)
    2194              : {
    2195        12890 :   auto_vec<tree> vars;
    2196        12890 :   dref a;
    2197        12890 :   unsigned n_writes = 0, ridx, i;
    2198        12890 :   tree var;
    2199              : 
    2200        12890 :   gcc_assert (chain->type == CT_INVARIANT);
    2201        12890 :   gcc_assert (!chain->combined);
    2202        28021 :   FOR_EACH_VEC_ELT (chain->refs, i, a)
    2203        15131 :     if (DR_IS_WRITE (a->ref))
    2204        12791 :       n_writes++;
    2205              : 
    2206              :   /* If there are no reads in the loop, there is nothing to do.  */
    2207        25780 :   if (n_writes == chain->refs.length ())
    2208        10628 :     return;
    2209              : 
    2210         2262 :   initialize_root_vars_lm (loop, get_chain_root (chain), n_writes > 0,
    2211              :                            &vars, chain->inits, tmp_vars);
    2212              : 
    2213         2262 :   ridx = 0;
    2214        11087 :   FOR_EACH_VEC_ELT (chain->refs, i, a)
    2215              :     {
    2216         4301 :       bool is_read = DR_IS_READ (a->ref);
    2217              : 
    2218         4301 :       if (DR_IS_WRITE (a->ref))
    2219              :         {
    2220         1961 :           n_writes--;
    2221         1961 :           if (n_writes)
    2222              :             {
    2223           80 :               var = vars[0];
    2224           80 :               var = make_ssa_name (SSA_NAME_VAR (var));
    2225           80 :               vars[0] = var;
    2226              :             }
    2227              :           else
    2228              :             ridx = 1;
    2229              :         }
    2230              : 
    2231         4301 :       replace_ref_with (a->stmt, vars[ridx],
    2232              :                         !is_read, !is_read);
    2233              :     }
    2234        12890 : }
    2235              : 
    2236              : /* Returns the single statement in that NAME is used, excepting
    2237              :    the looparound phi nodes contained in one of the chains.  If there is no
    2238              :    such statement, or more statements, NULL is returned.  */
    2239              : 
    2240              : gimple *
    2241        54708 : pcom_worker::single_nonlooparound_use (tree name)
    2242              : {
    2243        54708 :   use_operand_p use;
    2244        54708 :   imm_use_iterator it;
    2245        54708 :   gimple *stmt, *ret = NULL;
    2246              : 
    2247       109991 :   FOR_EACH_IMM_USE_FAST (use, it, name)
    2248              :     {
    2249        57531 :       stmt = USE_STMT (use);
    2250              : 
    2251        57531 :       if (gimple_code (stmt) == GIMPLE_PHI)
    2252              :         {
    2253              :           /* Ignore uses in looparound phi nodes.  Uses in other phi nodes
    2254              :              could not be processed anyway, so just fail for them.  */
    2255          408 :           if (bitmap_bit_p (m_looparound_phis,
    2256          204 :                             SSA_NAME_VERSION (PHI_RESULT (stmt))))
    2257           60 :             continue;
    2258              : 
    2259              :           return NULL;
    2260              :         }
    2261        57327 :       else if (is_gimple_debug (stmt))
    2262          723 :         continue;
    2263        56604 :       else if (ret != NULL)
    2264              :         return NULL;
    2265              :       else
    2266              :         ret = stmt;
    2267         2248 :     }
    2268              : 
    2269        52460 :   return ret;
    2270              : }
    2271              : 
    2272              : /* Remove statement STMT, as well as the chain of assignments in that it is
    2273              :    used.  */
    2274              : 
    2275              : void
    2276          211 : pcom_worker::remove_stmt (gimple *stmt)
    2277              : {
    2278          211 :   tree name;
    2279          211 :   gimple *next;
    2280          211 :   gimple_stmt_iterator psi;
    2281              : 
    2282          211 :   if (gimple_code (stmt) == GIMPLE_PHI)
    2283              :     {
    2284           12 :       name = PHI_RESULT (stmt);
    2285           12 :       next = single_nonlooparound_use (name);
    2286           12 :       reset_debug_uses (stmt);
    2287           12 :       psi = gsi_for_stmt (stmt);
    2288           12 :       remove_phi_node (&psi, true);
    2289              : 
    2290           12 :       if (!next
    2291           11 :           || !gimple_assign_ssa_name_copy_p (next)
    2292           16 :           || gimple_assign_rhs1 (next) != name)
    2293              :         return;
    2294              : 
    2295          203 :       stmt = next;
    2296              :     }
    2297              : 
    2298          291 :   while (1)
    2299              :     {
    2300          247 :       gimple_stmt_iterator bsi;
    2301              : 
    2302          247 :       bsi = gsi_for_stmt (stmt);
    2303              : 
    2304          247 :       name = gimple_assign_lhs (stmt);
    2305          247 :       if (TREE_CODE (name) == SSA_NAME)
    2306              :         {
    2307          178 :           next = single_nonlooparound_use (name);
    2308          178 :           reset_debug_uses (stmt);
    2309              :         }
    2310              :       else
    2311              :         {
    2312              :           /* This is a store to be eliminated.  */
    2313          138 :           gcc_assert (gimple_vdef (stmt) != NULL);
    2314              :           next = NULL;
    2315              :         }
    2316              : 
    2317          247 :       unlink_stmt_vdef (stmt);
    2318          247 :       gsi_remove (&bsi, true);
    2319          247 :       release_defs (stmt);
    2320              : 
    2321          247 :       if (!next
    2322          115 :           || !gimple_assign_ssa_name_copy_p (next)
    2323          291 :           || gimple_assign_rhs1 (next) != name)
    2324          203 :         return;
    2325              : 
    2326           44 :       stmt = next;
    2327           44 :     }
    2328              : }
    2329              : 
    2330              : /* Perform the predictive commoning optimization for a chain CHAIN.
    2331              :    Uids of the newly created temporary variables are marked in TMP_VARS.*/
    2332              : 
    2333              : void
    2334        17525 : pcom_worker::execute_pred_commoning_chain (chain_p chain,
    2335              :                               bitmap tmp_vars)
    2336              : {
    2337        17525 :   unsigned i;
    2338        17525 :   dref a;
    2339        17525 :   tree var;
    2340        17525 :   bool in_lhs;
    2341              : 
    2342        17525 :   if (chain->combined)
    2343              :     {
    2344              :       /* For combined chains, just remove the statements that are used to
    2345              :          compute the values of the expression (except for the root one).
    2346              :          We delay this until after all chains are processed.  */
    2347              :     }
    2348        17449 :   else if (chain->type == CT_STORE_STORE)
    2349              :     {
    2350           56 :       if (chain->length > 0)
    2351              :         {
    2352           46 :           if (chain->inv_store_elimination)
    2353              :             {
    2354              :               /* If dead stores in this chain only store loop invariant
    2355              :                  values, we can simply record the invariant value and use
    2356              :                  it directly after loop.  */
    2357           14 :               initialize_root_vars_store_elim_1 (chain);
    2358              :             }
    2359              :           else
    2360              :             {
    2361              :               /* If dead stores in this chain store loop variant values,
    2362              :                  we need to set up the variables by loading from memory
    2363              :                  before loop and propagating it with PHI nodes.  */
    2364           32 :               initialize_root_vars_store_elim_2 (m_loop, chain, tmp_vars);
    2365              :             }
    2366              : 
    2367              :           /* For inter-iteration store elimination chain, stores at each
    2368              :              distance in loop's last (chain->length - 1) iterations can't
    2369              :              be eliminated, because there is no following killing store.
    2370              :              We need to generate these stores after loop.  */
    2371           46 :           finalize_eliminated_stores (m_loop, chain);
    2372              :         }
    2373              : 
    2374           56 :       bool last_store_p = true;
    2375          242 :       for (i = chain->refs.length (); i > 0; i--)
    2376              :         {
    2377          130 :           a = chain->refs[i - 1];
    2378              :           /* Preserve the last store of the chain.  Eliminate other stores
    2379              :              which are killed by the last one.  */
    2380          130 :           if (DR_IS_WRITE (a->ref))
    2381              :             {
    2382          125 :               if (last_store_p)
    2383              :                 last_store_p = false;
    2384              :               else
    2385           69 :                 remove_stmt (a->stmt);
    2386              : 
    2387          125 :               continue;
    2388              :             }
    2389              : 
    2390              :           /* Any load in Store-Store chain must be dominated by a previous
    2391              :              store, we replace the load reference with rhs of the store.  */
    2392            5 :           dref b = get_chain_last_write_before_load (chain, i - 1);
    2393            5 :           gcc_assert (b != NULL);
    2394            5 :           var = gimple_assign_rhs1 (b->stmt);
    2395            5 :           replace_ref_with (a->stmt, var, false, false);
    2396              :         }
    2397              :     }
    2398              :   else
    2399              :     {
    2400              :       /* For non-combined chains, set up the variables that hold its value.  */
    2401        17393 :       initialize_root_vars (m_loop, chain, tmp_vars);
    2402        17393 :       a = get_chain_root (chain);
    2403        17393 :       in_lhs = (chain->type == CT_STORE_LOAD
    2404        17393 :                 || chain->type == CT_COMBINATION);
    2405        17393 :       replace_ref_with (a->stmt, chain->vars[chain->length], true, in_lhs);
    2406              : 
    2407              :       /* Replace the uses of the original references by these variables.  */
    2408        52508 :       for (i = 1; chain->refs.iterate (i, &a); i++)
    2409              :         {
    2410        17722 :           var = chain->vars[chain->length - a->distance];
    2411        17722 :           replace_ref_with (a->stmt, var, false, false);
    2412              :         }
    2413              :     }
    2414        17525 : }
    2415              : 
    2416              : /* Determines the unroll factor necessary to remove as many temporary variable
    2417              :    copies as possible.  CHAINS is the list of chains that will be
    2418              :    optimized.  */
    2419              : 
    2420              : static unsigned
    2421         3772 : determine_unroll_factor (const vec<chain_p> &chains)
    2422              : {
    2423         3772 :   chain_p chain;
    2424         3772 :   unsigned factor = 1, af, nfactor, i;
    2425         3772 :   unsigned max = param_max_unroll_times;
    2426              : 
    2427         8428 :   FOR_EACH_VEC_ELT (chains, i, chain)
    2428              :     {
    2429         4682 :       if (chain->type == CT_INVARIANT)
    2430         1792 :         continue;
    2431              :       /* For now we can't handle unrolling when eliminating stores.  */
    2432         2890 :       else if (chain->type == CT_STORE_STORE)
    2433              :         return 1;
    2434              : 
    2435         2867 :       if (chain->combined)
    2436              :         {
    2437              :           /* For combined chains, we can't handle unrolling if we replace
    2438              :              looparound PHIs.  */
    2439              :           dref a;
    2440              :           unsigned j;
    2441          155 :           for (j = 1; chain->refs.iterate (j, &a); j++)
    2442           97 :             if (gimple_code (a->stmt) == GIMPLE_PHI)
    2443         3772 :               return 1;
    2444           58 :           continue;
    2445           58 :         }
    2446              : 
    2447              :       /* The best unroll factor for this chain is equal to the number of
    2448              :          temporary variables that we create for it.  */
    2449         2806 :       af = chain->length;
    2450         2806 :       if (chain->has_max_use_after)
    2451         1585 :         af++;
    2452              : 
    2453         2806 :       nfactor = factor * af / gcd (factor, af);
    2454         2806 :       if (nfactor <= max)
    2455         4656 :         factor = nfactor;
    2456              :     }
    2457              : 
    2458              :   return factor;
    2459              : }
    2460              : 
    2461              : /* Perform the predictive commoning optimization for chains.
    2462              :    Uids of the newly created temporary variables are marked in TMP_VARS.  */
    2463              : 
    2464              : void
    2465        19089 : pcom_worker::execute_pred_commoning (bitmap tmp_vars)
    2466              : {
    2467        19089 :   chain_p chain;
    2468        19089 :   unsigned i;
    2469              : 
    2470        49504 :   FOR_EACH_VEC_ELT (m_chains, i, chain)
    2471              :     {
    2472        30415 :       if (chain->type == CT_INVARIANT)
    2473        12890 :         execute_load_motion (m_loop, chain, tmp_vars);
    2474              :       else
    2475        17525 :         execute_pred_commoning_chain (chain, tmp_vars);
    2476              :     }
    2477              : 
    2478        49504 :   FOR_EACH_VEC_ELT (m_chains, i, chain)
    2479              :     {
    2480        30415 :       if (chain->type == CT_INVARIANT)
    2481              :         ;
    2482        17525 :       else if (chain->combined)
    2483              :         {
    2484              :           /* For combined chains, just remove the statements that are used to
    2485              :              compute the values of the expression (except for the root one).  */
    2486              :           dref a;
    2487              :           unsigned j;
    2488        30633 :           for (j = 1; chain->refs.iterate (j, &a); j++)
    2489          142 :             remove_stmt (a->stmt);
    2490              :         }
    2491              :     }
    2492        19089 : }
    2493              : 
    2494              : /* For each reference in CHAINS, if its defining statement is
    2495              :    phi node, record the ssa name that is defined by it.  */
    2496              : 
    2497              : static void
    2498          887 : replace_phis_by_defined_names (vec<chain_p> &chains)
    2499              : {
    2500          887 :   chain_p chain;
    2501          887 :   dref a;
    2502          887 :   unsigned i, j;
    2503              : 
    2504         2757 :   FOR_EACH_VEC_ELT (chains, i, chain)
    2505         3804 :     FOR_EACH_VEC_ELT (chain->refs, j, a)
    2506              :       {
    2507         1934 :         if (gimple_code (a->stmt) == GIMPLE_PHI)
    2508              :           {
    2509            1 :             a->name_defined_by_phi = PHI_RESULT (a->stmt);
    2510            1 :             a->stmt = NULL;
    2511              :           }
    2512              :       }
    2513          887 : }
    2514              : 
    2515              : /* For each reference in CHAINS, if name_defined_by_phi is not
    2516              :    NULL, use it to set the stmt field.  */
    2517              : 
    2518              : static void
    2519          887 : replace_names_by_phis (vec<chain_p> chains)
    2520              : {
    2521          887 :   chain_p chain;
    2522          887 :   dref a;
    2523          887 :   unsigned i, j;
    2524              : 
    2525         2757 :   FOR_EACH_VEC_ELT (chains, i, chain)
    2526         3804 :     FOR_EACH_VEC_ELT (chain->refs, j, a)
    2527         1934 :       if (a->stmt == NULL)
    2528              :         {
    2529            1 :           a->stmt = SSA_NAME_DEF_STMT (a->name_defined_by_phi);
    2530            1 :           gcc_assert (gimple_code (a->stmt) == GIMPLE_PHI);
    2531            1 :           a->name_defined_by_phi = NULL_TREE;
    2532              :         }
    2533          887 : }
    2534              : 
    2535              : /* Wrapper over execute_pred_commoning, to pass it as a callback
    2536              :    to tree_transform_and_unroll_loop.  */
    2537              : 
    2538              : struct epcc_data
    2539              : {
    2540              :   vec<chain_p> chains;
    2541              :   bitmap tmp_vars;
    2542              :   pcom_worker *worker;
    2543              : };
    2544              : 
    2545              : static void
    2546          887 : execute_pred_commoning_cbck (class loop *loop ATTRIBUTE_UNUSED, void *data)
    2547              : {
    2548          887 :   struct epcc_data *const dta = (struct epcc_data *) data;
    2549          887 :   pcom_worker *worker = dta->worker;
    2550              : 
    2551              :   /* Restore phi nodes that were replaced by ssa names before
    2552              :      tree_transform_and_unroll_loop (see detailed description in
    2553              :      tree_predictive_commoning_loop).  */
    2554          887 :   replace_names_by_phis (dta->chains);
    2555          887 :   worker->execute_pred_commoning (dta->tmp_vars);
    2556          887 : }
    2557              : 
    2558              : /* Base NAME and all the names in the chain of phi nodes that use it
    2559              :    on variable VAR.  The phi nodes are recognized by being in the copies of
    2560              :    the header of the LOOP.  */
    2561              : 
    2562              : static void
    2563          940 : base_names_in_chain_on (class loop *loop, tree name, tree var)
    2564              : {
    2565          940 :   gimple *stmt, *phi;
    2566          940 :   imm_use_iterator iter;
    2567              : 
    2568          940 :   replace_ssa_name_symbol (name, var);
    2569              : 
    2570         2984 :   while (1)
    2571              :     {
    2572         1962 :       phi = NULL;
    2573         2909 :       FOR_EACH_IMM_USE_STMT (stmt, iter, name)
    2574              :         {
    2575         1969 :           if (gimple_code (stmt) == GIMPLE_PHI
    2576         1969 :               && flow_bb_inside_loop_p (loop, gimple_bb (stmt)))
    2577              :             {
    2578              :               phi = stmt;
    2579              :               break;
    2580              :             }
    2581         1962 :         }
    2582         1962 :       if (!phi)
    2583          940 :         return;
    2584              : 
    2585         1022 :       name = PHI_RESULT (phi);
    2586         1022 :       replace_ssa_name_symbol (name, var);
    2587         1022 :     }
    2588              : }
    2589              : 
    2590              : /* Given an unrolled LOOP after predictive commoning, remove the
    2591              :    register copies arising from phi nodes by changing the base
    2592              :    variables of SSA names.  TMP_VARS is the set of the temporary variables
    2593              :    for those we want to perform this.  */
    2594              : 
    2595              : static void
    2596          887 : eliminate_temp_copies (class loop *loop, bitmap tmp_vars)
    2597              : {
    2598          887 :   edge e;
    2599          887 :   gphi *phi;
    2600          887 :   gimple *stmt;
    2601          887 :   tree name, use, var;
    2602          887 :   gphi_iterator psi;
    2603              : 
    2604          887 :   e = loop_latch_edge (loop);
    2605         4582 :   for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
    2606              :     {
    2607         3695 :       phi = psi.phi ();
    2608         3695 :       name = PHI_RESULT (phi);
    2609         3695 :       var = SSA_NAME_VAR (name);
    2610         2511 :       if (!var || !bitmap_bit_p (tmp_vars, DECL_UID (var)))
    2611         2755 :         continue;
    2612          940 :       use = PHI_ARG_DEF_FROM_EDGE (phi, e);
    2613          940 :       gcc_assert (TREE_CODE (use) == SSA_NAME);
    2614              : 
    2615              :       /* Base all the ssa names in the ud and du chain of NAME on VAR.  */
    2616          940 :       stmt = SSA_NAME_DEF_STMT (use);
    2617          981 :       while (gimple_code (stmt) == GIMPLE_PHI
    2618              :              /* In case we could not unroll the loop enough to eliminate
    2619              :                 all copies, we may reach the loop header before the defining
    2620              :                 statement (in that case, some register copies will be present
    2621              :                 in loop latch in the final code, corresponding to the newly
    2622              :                 created looparound phi nodes).  */
    2623          981 :              && gimple_bb (stmt) != loop->header)
    2624              :         {
    2625           41 :           gcc_assert (single_pred_p (gimple_bb (stmt)));
    2626           41 :           use = PHI_ARG_DEF (stmt, 0);
    2627           41 :           stmt = SSA_NAME_DEF_STMT (use);
    2628              :         }
    2629              : 
    2630          940 :       base_names_in_chain_on (loop, use, var);
    2631              :     }
    2632          887 : }
    2633              : 
    2634              : /* Returns true if CHAIN is suitable to be combined.  */
    2635              : 
    2636              : static bool
    2637       108934 : chain_can_be_combined_p (chain_p chain)
    2638              : {
    2639       108934 :   return (!chain->combined
    2640       108768 :           && (chain->type == CT_LOAD || chain->type == CT_COMBINATION));
    2641              : }
    2642              : 
    2643              : /* Returns the modify statement that uses NAME.  Skips over assignment
    2644              :    statements, NAME is replaced with the actual name used in the returned
    2645              :    statement.  */
    2646              : 
    2647              : gassign *
    2648        52871 : pcom_worker::find_use_stmt (tree *name)
    2649              : {
    2650        54518 :   tree rhs, lhs;
    2651              : 
    2652              :   /* Skip over assignments.  */
    2653        56165 :   while (1)
    2654              :     {
    2655        54518 :       auto stmt = safe_dyn_cast<gassign *> (single_nonlooparound_use (*name));
    2656        50944 :       if (!stmt)
    2657              :         return NULL;
    2658              : 
    2659        50944 :       lhs = gimple_assign_lhs (stmt);
    2660        50944 :       if (TREE_CODE (lhs) != SSA_NAME)
    2661              :         return NULL;
    2662              : 
    2663        50830 :       if (gimple_assign_copy_p (stmt))
    2664              :         {
    2665         1647 :           rhs = gimple_assign_rhs1 (stmt);
    2666         1647 :           if (rhs != *name)
    2667              :             return NULL;
    2668              : 
    2669         1647 :           *name = lhs;
    2670              :         }
    2671        54815 :       else if (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
    2672              :                == GIMPLE_BINARY_RHS)
    2673              :         return stmt;
    2674              :       else
    2675        44736 :         return NULL;
    2676         1647 :     }
    2677              : }
    2678              : 
    2679              : /* Returns true if we may perform reassociation for operation CODE in TYPE.  */
    2680              : 
    2681              : static bool
    2682         1065 : may_reassociate_p (tree type, enum tree_code code)
    2683              : {
    2684          670 :   if (FLOAT_TYPE_P (type)
    2685         1361 :       && !flag_unsafe_math_optimizations)
    2686              :     return false;
    2687              : 
    2688          737 :   return (commutative_tree_code (code)
    2689          737 :           && associative_tree_code (code));
    2690              : }
    2691              : 
    2692              : /* If the operation used in STMT is associative and commutative, go through the
    2693              :    tree of the same operations and returns its root.  Distance to the root
    2694              :    is stored in DISTANCE.  */
    2695              : 
    2696              : gassign *
    2697         1065 : pcom_worker::find_associative_operation_root (gassign *stmt, unsigned *distance)
    2698              : {
    2699         1065 :   tree lhs;
    2700         1065 :   enum tree_code code = gimple_assign_rhs_code (stmt);
    2701         1065 :   tree type = TREE_TYPE (gimple_assign_lhs (stmt));
    2702         1065 :   unsigned dist = 0;
    2703              : 
    2704         1065 :   if (!may_reassociate_p (type, code))
    2705              :     return NULL;
    2706              : 
    2707         4023 :   while (1)
    2708              :     {
    2709         2337 :       lhs = gimple_assign_lhs (stmt);
    2710         2337 :       gcc_assert (TREE_CODE (lhs) == SSA_NAME);
    2711              : 
    2712         2337 :       gassign *next = find_use_stmt (&lhs);
    2713         2337 :       if (!next
    2714         4304 :           || gimple_assign_rhs_code (next) != code)
    2715              :         break;
    2716              : 
    2717         1686 :       stmt = next;
    2718         1686 :       dist++;
    2719         1686 :     }
    2720              : 
    2721          651 :   if (distance)
    2722          198 :     *distance = dist;
    2723              :   return stmt;
    2724              : }
    2725              : 
    2726              : /* Returns the common statement in that NAME1 and NAME2 have a use.  If there
    2727              :    is no such statement, returns NULL_TREE.  In case the operation used on
    2728              :    NAME1 and NAME2 is associative and commutative, returns the root of the
    2729              :    tree formed by this operation instead of the statement that uses NAME1 or
    2730              :    NAME2.  */
    2731              : 
    2732              : gassign *
    2733        48722 : pcom_worker::find_common_use_stmt (tree *name1, tree *name2)
    2734              : {
    2735        48722 :   gassign *stmt1, *stmt2;
    2736              : 
    2737        48722 :   stmt1 = find_use_stmt (name1);
    2738        48722 :   if (!stmt1)
    2739              :     return NULL;
    2740              : 
    2741          781 :   stmt2 = find_use_stmt (name2);
    2742          781 :   if (!stmt2)
    2743              :     return NULL;
    2744              : 
    2745          668 :   if (stmt1 == stmt2)
    2746              :     return stmt1;
    2747              : 
    2748          638 :   stmt1 = find_associative_operation_root (stmt1, NULL);
    2749          638 :   if (!stmt1)
    2750              :     return NULL;
    2751          229 :   stmt2 = find_associative_operation_root (stmt2, NULL);
    2752          229 :   if (!stmt2)
    2753              :     return NULL;
    2754              : 
    2755          224 :   return (stmt1 == stmt2 ? stmt1 : NULL);
    2756              : }
    2757              : 
    2758              : /* Checks whether R1 and R2 are combined together using CODE, with the result
    2759              :    in RSLT_TYPE, in order R1 CODE R2 if SWAP is false and in order R2 CODE R1
    2760              :    if it is true.  If CODE is ERROR_MARK, set these values instead.  */
    2761              : 
    2762              : bool
    2763        48722 : pcom_worker::combinable_refs_p (dref r1, dref r2,
    2764              :                    enum tree_code *code, bool *swap, tree *rslt_type)
    2765              : {
    2766        48722 :   enum tree_code acode;
    2767        48722 :   bool aswap;
    2768        48722 :   tree atype;
    2769        48722 :   tree name1, name2;
    2770              : 
    2771        48722 :   name1 = name_for_ref (r1);
    2772        48722 :   name2 = name_for_ref (r2);
    2773        48722 :   gcc_assert (name1 != NULL_TREE && name2 != NULL_TREE);
    2774              : 
    2775        48722 :   gassign *stmt = find_common_use_stmt (&name1, &name2);
    2776              : 
    2777        48722 :   if (!stmt
    2778              :       /* A simple post-dominance check - make sure the combination
    2779              :          is executed under the same condition as the references.  */
    2780        48722 :       || (gimple_bb (stmt) != gimple_bb (r1->stmt)
    2781           20 :           && gimple_bb (stmt) != gimple_bb (r2->stmt)))
    2782              :     return false;
    2783              : 
    2784          115 :   acode = gimple_assign_rhs_code (stmt);
    2785          115 :   aswap = (!commutative_tree_code (acode)
    2786          115 :            && gimple_assign_rhs1 (stmt) != name1);
    2787          115 :   atype = TREE_TYPE (gimple_assign_lhs (stmt));
    2788              : 
    2789          115 :   if (*code == ERROR_MARK)
    2790              :     {
    2791           44 :       *code = acode;
    2792           44 :       *swap = aswap;
    2793           44 :       *rslt_type = atype;
    2794           44 :       return true;
    2795              :     }
    2796              : 
    2797           71 :   return (*code == acode
    2798           71 :           && *swap == aswap
    2799          142 :           && *rslt_type == atype);
    2800              : }
    2801              : 
    2802              : /* Remove OP from the operation on rhs of STMT, and replace STMT with
    2803              :    an assignment of the remaining operand.  */
    2804              : 
    2805              : static void
    2806          198 : remove_name_from_operation (gassign *stmt, tree op)
    2807              : {
    2808          198 :   tree other_op;
    2809          198 :   gimple_stmt_iterator si;
    2810              : 
    2811          198 :   if (gimple_assign_rhs1 (stmt) == op)
    2812           83 :     other_op = gimple_assign_rhs2 (stmt);
    2813              :   else
    2814              :     other_op = gimple_assign_rhs1 (stmt);
    2815              : 
    2816          198 :   si = gsi_for_stmt (stmt);
    2817          198 :   gimple_assign_set_rhs_from_tree (&si, other_op);
    2818              : 
    2819              :   /* We should not have reallocated STMT.  */
    2820          198 :   gcc_assert (gsi_stmt (si) == stmt);
    2821              : 
    2822          198 :   update_stmt (stmt);
    2823          198 : }
    2824              : 
    2825              : /* Reassociates the expression in that NAME1 and NAME2 are used so that they
    2826              :    are combined in a single statement, and returns this statement.  */
    2827              : 
    2828              : gimple *
    2829           99 : pcom_worker::reassociate_to_the_same_stmt (tree name1, tree name2)
    2830              : {
    2831           99 :   gimple *root1, *root2;
    2832           99 :   gassign *s1, *s2, *stmt1, *stmt2;
    2833           99 :   gassign *new_stmt, *tmp_stmt;
    2834           99 :   tree new_name, tmp_name, var, r1, r2;
    2835           99 :   unsigned dist1, dist2;
    2836           99 :   enum tree_code code;
    2837           99 :   tree type = TREE_TYPE (name1);
    2838           99 :   gimple_stmt_iterator bsi;
    2839              : 
    2840           99 :   stmt1 = find_use_stmt (&name1);
    2841           99 :   stmt2 = find_use_stmt (&name2);
    2842           99 :   root1 = find_associative_operation_root (stmt1, &dist1);
    2843           99 :   root2 = find_associative_operation_root (stmt2, &dist2);
    2844           99 :   code = gimple_assign_rhs_code (stmt1);
    2845              : 
    2846          198 :   gcc_assert (root1 && root2 && root1 == root2
    2847              :               && code == gimple_assign_rhs_code (stmt2));
    2848              : 
    2849              :   /* Find the root of the nearest expression in that both NAME1 and NAME2
    2850              :      are used.  */
    2851           99 :   r1 = name1;
    2852           99 :   s1 = stmt1;
    2853           99 :   r2 = name2;
    2854           99 :   s2 = stmt2;
    2855              : 
    2856          389 :   while (dist1 > dist2)
    2857              :     {
    2858          290 :       s1 = find_use_stmt (&r1);
    2859          290 :       r1 = gimple_assign_lhs (s1);
    2860          290 :       dist1--;
    2861              :     }
    2862          218 :   while (dist2 > dist1)
    2863              :     {
    2864          119 :       s2 = find_use_stmt (&r2);
    2865          119 :       r2 = gimple_assign_lhs (s2);
    2866          119 :       dist2--;
    2867              :     }
    2868              : 
    2869          202 :   while (s1 != s2)
    2870              :     {
    2871          103 :       s1 = find_use_stmt (&r1);
    2872          103 :       r1 = gimple_assign_lhs (s1);
    2873          103 :       s2 = find_use_stmt (&r2);
    2874          103 :       r2 = gimple_assign_lhs (s2);
    2875              :     }
    2876              : 
    2877              :   /* Remove NAME1 and NAME2 from the statements in that they are used
    2878              :      currently.  */
    2879           99 :   remove_name_from_operation (stmt1, name1);
    2880           99 :   remove_name_from_operation (stmt2, name2);
    2881              : 
    2882              :   /* Insert the new statement combining NAME1 and NAME2 before S1, and
    2883              :      combine it with the rhs of S1.  */
    2884           99 :   var = create_tmp_reg (type, "predreastmp");
    2885           99 :   new_name = make_ssa_name (var);
    2886           99 :   new_stmt = gimple_build_assign (new_name, code, name1, name2);
    2887              : 
    2888           99 :   var = create_tmp_reg (type, "predreastmp");
    2889           99 :   tmp_name = make_ssa_name (var);
    2890              : 
    2891              :   /* Rhs of S1 may now be either a binary expression with operation
    2892              :      CODE, or gimple_val (in case that stmt1 == s1 or stmt2 == s1,
    2893              :      so that name1 or name2 was removed from it).  */
    2894          198 :   tmp_stmt = gimple_build_assign (tmp_name, gimple_assign_rhs_code (s1),
    2895              :                                   gimple_assign_rhs1 (s1),
    2896              :                                   gimple_assign_rhs2 (s1));
    2897              : 
    2898           99 :   bsi = gsi_for_stmt (s1);
    2899           99 :   gimple_assign_set_rhs_with_ops (&bsi, code, new_name, tmp_name);
    2900           99 :   gimple *g1 = gsi_stmt (bsi);
    2901           99 :   update_stmt (g1);
    2902              : 
    2903           99 :   gsi_insert_before (&bsi, new_stmt, GSI_SAME_STMT);
    2904           99 :   gsi_insert_before (&bsi, tmp_stmt, GSI_SAME_STMT);
    2905              : 
    2906           99 :   return new_stmt;
    2907              : }
    2908              : 
    2909              : /* Returns the statement that combines references R1 and R2.  In case R1
    2910              :    and R2 are not used in the same statement, but they are used with an
    2911              :    associative and commutative operation in the same expression, reassociate
    2912              :    the expression so that they are used in the same statement.  */
    2913              : 
    2914              : gimple *
    2915          109 : pcom_worker::stmt_combining_refs (dref r1, dref r2)
    2916              : {
    2917          109 :   gimple *stmt1, *stmt2;
    2918          109 :   tree name1 = name_for_ref (r1);
    2919          109 :   tree name2 = name_for_ref (r2);
    2920              : 
    2921          109 :   stmt1 = find_use_stmt (&name1);
    2922          109 :   stmt2 = find_use_stmt (&name2);
    2923          109 :   if (stmt1 == stmt2)
    2924              :     return stmt1;
    2925              : 
    2926           99 :   return reassociate_to_the_same_stmt (name1, name2);
    2927              : }
    2928              : 
    2929              : /* Tries to combine chains CH1 and CH2 together.  If this succeeds, the
    2930              :    description of the new chain is returned, otherwise we return NULL.  */
    2931              : 
    2932              : chain_p
    2933        63396 : pcom_worker::combine_chains (chain_p ch1, chain_p ch2)
    2934              : {
    2935        63396 :   dref r1, r2, nw;
    2936        63396 :   enum tree_code op = ERROR_MARK;
    2937        63396 :   bool swap = false;
    2938        63396 :   chain_p new_chain;
    2939        63396 :   unsigned i;
    2940        63396 :   tree rslt_type = NULL_TREE;
    2941              : 
    2942        63396 :   if (ch1 == ch2)
    2943              :     return NULL;
    2944        48899 :   if (ch1->length != ch2->length)
    2945              :     return NULL;
    2946              : 
    2947       146559 :   if (ch1->refs.length () != ch2->refs.length ())
    2948              :     return NULL;
    2949              : 
    2950        97520 :   for (i = 0; (ch1->refs.iterate (i, &r1)
    2951        97482 :                && ch2->refs.iterate (i, &r2)); i++)
    2952              :     {
    2953        48722 :       if (r1->distance != r2->distance)
    2954              :         return NULL;
    2955              : 
    2956        48722 :       if (!combinable_refs_p (r1, r2, &op, &swap, &rslt_type))
    2957              :         return NULL;
    2958              :     }
    2959              : 
    2960           38 :   if (swap)
    2961            0 :     std::swap (ch1, ch2);
    2962              : 
    2963           38 :   new_chain = new struct chain (CT_COMBINATION);
    2964           38 :   new_chain->op = op;
    2965           38 :   new_chain->ch1 = ch1;
    2966           38 :   new_chain->ch2 = ch2;
    2967           38 :   new_chain->rslt_type = rslt_type;
    2968           38 :   new_chain->length = ch1->length;
    2969              : 
    2970           38 :   for (i = 0; (ch1->refs.iterate (i, &r1)
    2971          256 :                && ch2->refs.iterate (i, &r2)); i++)
    2972              :     {
    2973          109 :       nw = XCNEW (class dref_d);
    2974          109 :       nw->stmt = stmt_combining_refs (r1, r2);
    2975          109 :       nw->distance = r1->distance;
    2976              : 
    2977          109 :       new_chain->refs.safe_push (nw);
    2978              :     }
    2979              : 
    2980           38 :   ch1->combined = true;
    2981           38 :   ch2->combined = true;
    2982           38 :   return new_chain;
    2983              : }
    2984              : 
    2985              : /* Recursively update position information of all offspring chains to ROOT
    2986              :    chain's position information.  */
    2987              : 
    2988              : static void
    2989           38 : update_pos_for_combined_chains (chain_p root)
    2990              : {
    2991           38 :   chain_p ch1 = root->ch1, ch2 = root->ch2;
    2992           38 :   dref ref, ref1, ref2;
    2993           38 :   for (unsigned j = 0; (root->refs.iterate (j, &ref)
    2994          109 :                         && ch1->refs.iterate (j, &ref1)
    2995          256 :                         && ch2->refs.iterate (j, &ref2)); ++j)
    2996          109 :     ref1->pos = ref2->pos = ref->pos;
    2997              : 
    2998           38 :   if (ch1->type == CT_COMBINATION)
    2999           19 :     update_pos_for_combined_chains (ch1);
    3000           38 :   if (ch2->type == CT_COMBINATION)
    3001              :     update_pos_for_combined_chains (ch2);
    3002           38 : }
    3003              : 
    3004              : /* Returns true if statement S1 dominates statement S2.  */
    3005              : 
    3006              : static bool
    3007           15 : pcom_stmt_dominates_stmt_p (gimple *s1, gimple *s2)
    3008              : {
    3009           15 :   basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
    3010              : 
    3011           15 :   if (!bb1 || s1 == s2)
    3012              :     return true;
    3013              : 
    3014           15 :   if (bb1 == bb2)
    3015           15 :     return gimple_uid (s1) < gimple_uid (s2);
    3016              : 
    3017            0 :   return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
    3018              : }
    3019              : 
    3020              : /* Try to combine the chains.  */
    3021              : 
    3022              : void
    3023        19089 : pcom_worker::try_combine_chains ()
    3024              : {
    3025        19089 :   unsigned i, j;
    3026        19089 :   chain_p ch1, ch2, cch;
    3027        19089 :   auto_vec<chain_p> worklist;
    3028        19089 :   bool combined_p = false;
    3029              : 
    3030        49466 :   FOR_EACH_VEC_ELT (m_chains, i, ch1)
    3031        60754 :     if (chain_can_be_combined_p (ch1))
    3032        14535 :       worklist.safe_push (ch1);
    3033              : 
    3034        67324 :   while (!worklist.is_empty ())
    3035              :     {
    3036        14573 :       ch1 = worklist.pop ();
    3037        14573 :       if (!chain_can_be_combined_p (ch1))
    3038           38 :         continue;
    3039              : 
    3040       112143 :       FOR_EACH_VEC_ELT (m_chains, j, ch2)
    3041              :         {
    3042        63984 :           if (!chain_can_be_combined_p (ch2))
    3043          588 :             continue;
    3044              : 
    3045        63396 :           cch = combine_chains (ch1, ch2);
    3046        63396 :           if (cch)
    3047              :             {
    3048           38 :               worklist.safe_push (cch);
    3049           38 :               m_chains.safe_push (cch);
    3050           38 :               combined_p = true;
    3051           38 :               break;
    3052              :             }
    3053              :         }
    3054              :     }
    3055        19089 :   if (!combined_p)
    3056        19075 :     return;
    3057              : 
    3058              :   /* Setup UID for all statements in dominance order.  */
    3059           14 :   basic_block *bbs = get_loop_body_in_dom_order (m_loop);
    3060           14 :   renumber_gimple_stmt_uids_in_blocks (bbs, m_loop->num_nodes);
    3061           14 :   free (bbs);
    3062              : 
    3063              :   /* Re-association in combined chains may generate statements different to
    3064              :      order of references of the original chain.  We need to keep references
    3065              :      of combined chain in dominance order so that all uses will be inserted
    3066              :      after definitions.  Note:
    3067              :        A) This is necessary for all combined chains.
    3068              :        B) This is only necessary for ZERO distance references because other
    3069              :           references inherit value from loop carried PHIs.
    3070              : 
    3071              :      We first update position information for all combined chains.  */
    3072           14 :   dref ref;
    3073          114 :   for (i = 0; m_chains.iterate (i, &ch1); ++i)
    3074              :     {
    3075          100 :       if (ch1->type != CT_COMBINATION || ch1->combined)
    3076           81 :         continue;
    3077              : 
    3078           70 :       for (j = 0; ch1->refs.iterate (j, &ref); ++j)
    3079           51 :         ref->pos = gimple_uid (ref->stmt);
    3080              : 
    3081           19 :       update_pos_for_combined_chains (ch1);
    3082              :     }
    3083              :   /* Then sort references according to newly updated position information.  */
    3084          128 :   for (i = 0; m_chains.iterate (i, &ch1); ++i)
    3085              :     {
    3086          100 :       if (ch1->type != CT_COMBINATION && !ch1->combined)
    3087            5 :         continue;
    3088              : 
    3089              :       /* Find the first reference with non-ZERO distance.  */
    3090           95 :       if (ch1->length == 0)
    3091           12 :         j = ch1->refs.length();
    3092              :       else
    3093              :         {
    3094          166 :           for (j = 0; ch1->refs.iterate (j, &ref); ++j)
    3095          166 :             if (ref->distance != 0)
    3096              :               break;
    3097              :         }
    3098              : 
    3099              :       /* Sort all ZERO distance references by position.  */
    3100           95 :       qsort (&ch1->refs[0], j, sizeof (ch1->refs[0]), order_drefs_by_pos);
    3101              : 
    3102           95 :       if (ch1->combined)
    3103           76 :         continue;
    3104              : 
    3105              :       /* For ZERO length chain, has_max_use_after must be true since root
    3106              :          combined stmt must dominates others.  */
    3107           19 :       if (ch1->length == 0)
    3108              :         {
    3109            4 :           ch1->has_max_use_after = true;
    3110            4 :           continue;
    3111              :         }
    3112              :       /* Check if there is use at max distance after root for combined chains
    3113              :          and set flag accordingly.  */
    3114           15 :       ch1->has_max_use_after = false;
    3115           15 :       gimple *root_stmt = get_chain_root (ch1)->stmt;
    3116          140 :       for (j = 1; ch1->refs.iterate (j, &ref); ++j)
    3117              :         {
    3118           28 :           if (ref->distance == ch1->length
    3119           28 :               && !pcom_stmt_dominates_stmt_p (ref->stmt, root_stmt))
    3120              :             {
    3121            3 :               ch1->has_max_use_after = true;
    3122            3 :               break;
    3123              :             }
    3124              :         }
    3125              :     }
    3126        19089 : }
    3127              : 
    3128              : /* Prepare initializers for store elimination CHAIN in LOOP.  Returns false
    3129              :    if this is impossible because one of these initializers may trap, true
    3130              :    otherwise.  */
    3131              : 
    3132              : static bool
    3133           56 : prepare_initializers_chain_store_elim (class loop *loop, chain_p chain)
    3134              : {
    3135           56 :   unsigned i, n = chain->length;
    3136              : 
    3137              :   /* For now we can't eliminate stores if some of them are conditional
    3138              :      executed.  */
    3139           56 :   if (!chain->all_always_accessed)
    3140              :     return false;
    3141              : 
    3142              :   /* Nothing to initialize for intra-iteration store elimination.  */
    3143           56 :   if (n == 0 && chain->type == CT_STORE_STORE)
    3144              :     return true;
    3145              : 
    3146              :   /* For store elimination chain, there is nothing to initialize if stores
    3147              :      to be eliminated only store loop invariant values into memory.  */
    3148           46 :   if (chain->type == CT_STORE_STORE
    3149           46 :       && is_inv_store_elimination_chain (loop, chain))
    3150              :     {
    3151           14 :       chain->inv_store_elimination = true;
    3152           14 :       return true;
    3153              :     }
    3154              : 
    3155           32 :   chain->inits.create (n);
    3156           32 :   chain->inits.safe_grow_cleared (n, true);
    3157              : 
    3158              :   /* For store eliminating chain like below:
    3159              : 
    3160              :      for (i = 0; i < len; i++)
    3161              :        {
    3162              :          a[i] = 1;
    3163              :          // a[i + 1] = ...
    3164              :          a[i + 2] = 3;
    3165              :        }
    3166              : 
    3167              :      store to a[i + 1] is missed in loop body, it acts like bubbles.  The
    3168              :      content of a[i + 1] remain the same if the loop iterates fewer times
    3169              :      than chain->length.  We need to set up root variables for such stores
    3170              :      by loading from memory before loop.  Note we only need to load bubble
    3171              :      elements because loop body is guaranteed to be executed at least once
    3172              :      after loop's preheader edge.  */
    3173           32 :   auto_vec<bool> bubbles;
    3174           32 :   bubbles.safe_grow_cleared (n + 1, true);
    3175          136 :   for (i = 0; i < chain->refs.length (); i++)
    3176           72 :     bubbles[chain->refs[i]->distance] = true;
    3177              : 
    3178           32 :   struct data_reference *dr = get_chain_root (chain)->ref;
    3179           80 :   for (i = 0; i < n; i++)
    3180              :     {
    3181           48 :       if (bubbles[i])
    3182           38 :         continue;
    3183              : 
    3184           10 :       gimple_seq stmts = NULL;
    3185              : 
    3186           10 :       tree init = ref_at_iteration (dr, (int) 0 - i, &stmts);
    3187           10 :       if (stmts)
    3188            2 :         gimple_seq_add_seq_without_update (&chain->init_seq, stmts);
    3189              : 
    3190           10 :       chain->inits[i] = init;
    3191              :     }
    3192              : 
    3193           32 :   return true;
    3194           32 : }
    3195              : 
    3196              : /* Prepare initializers for CHAIN.  Returns false if this is impossible
    3197              :    because one of these initializers may trap, true otherwise.  */
    3198              : 
    3199              : bool
    3200        34203 : pcom_worker::prepare_initializers_chain (chain_p chain)
    3201              : {
    3202        34203 :   unsigned i, n = (chain->type == CT_INVARIANT) ? 1 : chain->length;
    3203        34203 :   struct data_reference *dr = get_chain_root (chain)->ref;
    3204        34203 :   tree init;
    3205        34203 :   dref laref;
    3206        34203 :   edge entry = loop_preheader_edge (m_loop);
    3207              : 
    3208        34203 :   if (chain->type == CT_STORE_STORE)
    3209           56 :     return prepare_initializers_chain_store_elim (m_loop, chain);
    3210              : 
    3211              :   /* Find the initializers for the variables, and check that they cannot
    3212              :      trap.  */
    3213        34147 :   chain->inits.create (n);
    3214        96843 :   for (i = 0; i < n; i++)
    3215        28549 :     chain->inits.quick_push (NULL_TREE);
    3216              : 
    3217              :   /* If we have replaced some looparound phi nodes, use their initializers
    3218              :      instead of creating our own.  */
    3219        89664 :   FOR_EACH_VEC_ELT (chain->refs, i, laref)
    3220              :     {
    3221        55517 :       if (gimple_code (laref->stmt) != GIMPLE_PHI)
    3222        55504 :         continue;
    3223              : 
    3224           13 :       gcc_assert (laref->distance > 0);
    3225           13 :       chain->inits[n - laref->distance]
    3226           26 :         = PHI_ARG_DEF_FROM_EDGE (laref->stmt, entry);
    3227              :     }
    3228              : 
    3229        58870 :   for (i = 0; i < n; i++)
    3230              :     {
    3231        28549 :       gimple_seq stmts = NULL;
    3232              : 
    3233        28549 :       if (chain->inits[i] != NULL_TREE)
    3234           13 :         continue;
    3235              : 
    3236        28536 :       init = ref_at_iteration (dr, (int) i - n, &stmts);
    3237        28536 :       if (!chain->all_always_accessed && tree_could_trap_p (init))
    3238              :         {
    3239         3826 :           gimple_seq_discard (stmts);
    3240         3826 :           return false;
    3241              :         }
    3242              : 
    3243        24710 :       if (stmts)
    3244         1101 :         gimple_seq_add_seq_without_update (&chain->init_seq, stmts);
    3245              : 
    3246        24710 :       chain->inits[i] = init;
    3247              :     }
    3248              : 
    3249              :   return true;
    3250              : }
    3251              : 
    3252              : /* Prepare initializers for chains, and free chains that cannot
    3253              :    be used because the initializers might trap.  */
    3254              : 
    3255              : void
    3256        19089 : pcom_worker::prepare_initializers ()
    3257              : {
    3258        19089 :   chain_p chain;
    3259        19089 :   unsigned i;
    3260              : 
    3261        53292 :   for (i = 0; i < m_chains.length (); )
    3262              :     {
    3263        34203 :       chain = m_chains[i];
    3264        34203 :       if (prepare_initializers_chain (chain))
    3265        30377 :         i++;
    3266              :       else
    3267              :         {
    3268         3826 :           release_chain (chain);
    3269         3826 :           m_chains.unordered_remove (i);
    3270              :         }
    3271              :     }
    3272        19089 : }
    3273              : 
    3274              : /* Generates finalizer memory references for CHAIN.  Returns true
    3275              :    if finalizer code for CHAIN can be generated, otherwise false.  */
    3276              : 
    3277              : bool
    3278           46 : pcom_worker::prepare_finalizers_chain (chain_p chain)
    3279              : {
    3280           46 :   unsigned i, n = chain->length;
    3281           46 :   struct data_reference *dr = get_chain_root (chain)->ref;
    3282           46 :   tree fini, niters = number_of_latch_executions (m_loop);
    3283              : 
    3284              :   /* For now we can't eliminate stores if some of them are conditional
    3285              :      executed.  */
    3286           46 :   if (!chain->all_always_accessed)
    3287              :     return false;
    3288              : 
    3289           46 :   chain->finis.create (n);
    3290          165 :   for (i = 0; i < n; i++)
    3291           73 :     chain->finis.quick_push (NULL_TREE);
    3292              : 
    3293              :   /* We never use looparound phi node for store elimination chains.  */
    3294              : 
    3295              :   /* Find the finalizers for the variables, and check that they cannot
    3296              :      trap.  */
    3297          119 :   for (i = 0; i < n; i++)
    3298              :     {
    3299           73 :       gimple_seq stmts = NULL;
    3300           73 :       gcc_assert (chain->finis[i] == NULL_TREE);
    3301              : 
    3302           73 :       if (TREE_CODE (niters) != INTEGER_CST && TREE_CODE (niters) != SSA_NAME)
    3303              :         {
    3304           14 :           niters = unshare_expr (niters);
    3305           14 :           niters = force_gimple_operand (niters, &stmts, true, NULL);
    3306           14 :           if (stmts)
    3307              :             {
    3308           14 :               gimple_seq_add_seq_without_update (&chain->fini_seq, stmts);
    3309           14 :               stmts = NULL;
    3310              :             }
    3311              :         }
    3312           73 :       fini = ref_at_iteration (dr, (int) 0 - i, &stmts, niters);
    3313           73 :       if (stmts)
    3314           29 :         gimple_seq_add_seq_without_update (&chain->fini_seq, stmts);
    3315              : 
    3316           73 :       chain->finis[i] = fini;
    3317              :     }
    3318              : 
    3319              :   return true;
    3320              : }
    3321              : 
    3322              : /* Generates finalizer memory reference for chains.  Returns true if
    3323              :    finalizer code generation for chains breaks loop closed ssa form.  */
    3324              : 
    3325              : bool
    3326        19089 : pcom_worker::prepare_finalizers ()
    3327              : {
    3328        19089 :   chain_p chain;
    3329        19089 :   unsigned i;
    3330        19089 :   bool loop_closed_ssa = false;
    3331              : 
    3332        49466 :   for (i = 0; i < m_chains.length ();)
    3333              :     {
    3334        30377 :       chain = m_chains[i];
    3335              : 
    3336              :       /* Finalizer is only necessary for inter-iteration store elimination
    3337              :          chains.  */
    3338        30377 :       if (chain->length == 0 || chain->type != CT_STORE_STORE)
    3339              :         {
    3340        30331 :           i++;
    3341        30331 :           continue;
    3342              :         }
    3343              : 
    3344           46 :       if (prepare_finalizers_chain (chain))
    3345              :         {
    3346           46 :           i++;
    3347              :           /* Be conservative, assume loop closed ssa form is corrupted
    3348              :              by store-store chain.  Though it's not always the case if
    3349              :              eliminated stores only store loop invariant values into
    3350              :              memory.  */
    3351           46 :           loop_closed_ssa = true;
    3352              :         }
    3353              :       else
    3354              :         {
    3355            0 :           release_chain (chain);
    3356            0 :           m_chains.unordered_remove (i);
    3357              :         }
    3358              :     }
    3359        19089 :   return loop_closed_ssa;
    3360              : }
    3361              : 
    3362              : /* Insert all initializing gimple stmts into LOOP's entry edge.  */
    3363              : 
    3364              : static void
    3365        19089 : insert_init_seqs (class loop *loop, vec<chain_p> &chains)
    3366              : {
    3367        19089 :   unsigned i;
    3368        19089 :   edge entry = loop_preheader_edge (loop);
    3369              : 
    3370        68593 :   for (i = 0; i < chains.length (); ++i)
    3371        30415 :     if (chains[i]->init_seq)
    3372              :       {
    3373         1066 :         gsi_insert_seq_on_edge_immediate (entry, chains[i]->init_seq);
    3374         1066 :         chains[i]->init_seq = NULL;
    3375              :       }
    3376        19089 : }
    3377              : 
    3378              : /* Performs predictive commoning for LOOP.  Sets bit 1<<1 of return value
    3379              :    if LOOP was unrolled; Sets bit 1<<2 of return value if loop closed ssa
    3380              :    form was corrupted.  Non-zero return value indicates some changes were
    3381              :    applied to this loop.  */
    3382              : 
    3383              : unsigned
    3384       444999 : pcom_worker::tree_predictive_commoning_loop (bool allow_unroll_p)
    3385              : {
    3386       444999 :   struct component *components;
    3387       444999 :   unsigned unroll_factor = 0;
    3388       444999 :   class tree_niter_desc desc;
    3389       444999 :   bool unroll = false, loop_closed_ssa = false;
    3390              : 
    3391       444999 :   if (dump_file && (dump_flags & TDF_DETAILS))
    3392           56 :     fprintf (dump_file, "Processing loop %d\n", m_loop->num);
    3393              : 
    3394              :   /* Nothing for predictive commoning if loop only iterates 1 time.  */
    3395       444999 :   if (get_max_loop_iterations_int (m_loop) == 0)
    3396              :     {
    3397        27117 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3398            1 :         fprintf (dump_file, "Loop iterates only 1 time, nothing to do.\n");
    3399              : 
    3400              :       return 0;
    3401              :     }
    3402              : 
    3403              :   /* Find the data references and split them into components according to their
    3404              :      dependence relations.  */
    3405       417882 :   auto_vec<loop_p, 3> loop_nest;
    3406       417882 :   if (!compute_data_dependences_for_loop (m_loop, true, &loop_nest, &m_datarefs,
    3407              :                                           &m_dependences))
    3408              :     {
    3409       146143 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3410            0 :         fprintf (dump_file, "Cannot analyze data dependencies\n");
    3411              :       return 0;
    3412              :     }
    3413              : 
    3414       271739 :   if (dump_file && (dump_flags & TDF_DETAILS))
    3415           55 :     dump_data_dependence_relations (dump_file, m_dependences);
    3416              : 
    3417       271739 :   components = split_data_refs_to_components ();
    3418              : 
    3419       271739 :   loop_nest.release ();
    3420       271739 :   if (!components)
    3421              :     return 0;
    3422              : 
    3423       183538 :   if (dump_file && (dump_flags & TDF_DETAILS))
    3424              :     {
    3425           54 :       fprintf (dump_file, "Initial state:\n\n");
    3426           54 :       dump_components (dump_file, components);
    3427              :     }
    3428              : 
    3429              :   /* Find the suitable components and split them into chains.  */
    3430       183538 :   components = filter_suitable_components (components);
    3431              : 
    3432       183538 :   auto_bitmap tmp_vars;
    3433       183538 :   determine_roots (components);
    3434       183538 :   release_components (components);
    3435              : 
    3436       183538 :   if (!m_chains.exists ())
    3437              :     {
    3438       164449 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3439           20 :         fprintf (dump_file,
    3440              :                  "Predictive commoning failed: no suitable chains\n");
    3441              :       return 0;
    3442              :     }
    3443              : 
    3444        19089 :   prepare_initializers ();
    3445        19089 :   loop_closed_ssa = prepare_finalizers ();
    3446              : 
    3447              :   /* Try to combine the chains that are always worked with together.  */
    3448        19089 :   try_combine_chains ();
    3449              : 
    3450        19089 :   insert_init_seqs (m_loop, m_chains);
    3451              : 
    3452        19089 :   if (dump_file && (dump_flags & TDF_DETAILS))
    3453              :     {
    3454           34 :       fprintf (dump_file, "Before commoning:\n\n");
    3455           34 :       dump_chains (dump_file, m_chains);
    3456              :     }
    3457              : 
    3458        19089 :   if (allow_unroll_p)
    3459              :     /* Determine the unroll factor, and if the loop should be unrolled, ensure
    3460              :        that its number of iterations is divisible by the factor.  */
    3461         3772 :     unroll_factor = determine_unroll_factor (m_chains);
    3462              : 
    3463         3772 :   if (unroll_factor > 1)
    3464          902 :     unroll = can_unroll_loop_p (m_loop, unroll_factor, &desc);
    3465              : 
    3466              :   /* Execute the predictive commoning transformations, and possibly unroll the
    3467              :      loop.  */
    3468          902 :   if (unroll)
    3469              :     {
    3470          887 :       struct epcc_data dta;
    3471              : 
    3472          887 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3473            9 :         fprintf (dump_file, "Unrolling %u times.\n", unroll_factor);
    3474              : 
    3475          887 :       dta.tmp_vars = tmp_vars;
    3476          887 :       dta.chains = m_chains.to_vec_legacy ();
    3477          887 :       dta.worker = this;
    3478              : 
    3479              :       /* Cfg manipulations performed in tree_transform_and_unroll_loop before
    3480              :          execute_pred_commoning_cbck is called may cause phi nodes to be
    3481              :          reallocated, which is a problem since CHAINS may point to these
    3482              :          statements.  To fix this, we store the ssa names defined by the
    3483              :          phi nodes here instead of the phi nodes themselves, and restore
    3484              :          the phi nodes in execute_pred_commoning_cbck.  A bit hacky.  */
    3485          887 :       replace_phis_by_defined_names (m_chains);
    3486              : 
    3487          887 :       tree_transform_and_unroll_loop (m_loop, unroll_factor, &desc,
    3488              :                                       execute_pred_commoning_cbck, &dta);
    3489          887 :       eliminate_temp_copies (m_loop, tmp_vars);
    3490              :     }
    3491              :   else
    3492              :     {
    3493        18202 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3494           25 :         fprintf (dump_file,
    3495              :                  "Executing predictive commoning without unrolling.\n");
    3496        18202 :       execute_pred_commoning (tmp_vars);
    3497              :     }
    3498              : 
    3499        56335 :   return (unroll ? 2 : 1) | (loop_closed_ssa ? 4 : 1);
    3500       601420 : }
    3501              : 
    3502              : /* Runs predictive commoning.  */
    3503              : 
    3504              : unsigned
    3505       215177 : tree_predictive_commoning (bool allow_unroll_p)
    3506              : {
    3507       215177 :   unsigned ret = 0, changed = 0;
    3508              : 
    3509       215177 :   initialize_original_copy_tables ();
    3510      1113217 :   for (auto loop : loops_list (cfun, LI_ONLY_INNERMOST))
    3511       467686 :     if (optimize_loop_for_speed_p (loop))
    3512              :       {
    3513       444999 :         pcom_worker w(loop);
    3514       444999 :         changed |= w.tree_predictive_commoning_loop (allow_unroll_p);
    3515       444999 :       }
    3516       215177 :   free_original_copy_tables ();
    3517              : 
    3518       215177 :   if (changed > 0)
    3519              :     {
    3520        12226 :       ret = TODO_update_ssa_only_virtuals;
    3521              : 
    3522              :       /* Cached SCEV information is stale after any transformation, not
    3523              :          only after unrolling: the data-reference analysis above queried
    3524              :          SCEV before references were rewritten.  */
    3525        12226 :       scev_reset ();
    3526              : 
    3527              :       /* Some loop(s) got unrolled.  */
    3528        12226 :       if (changed > 1)
    3529              :         {
    3530              :           /* Need to fix up loop closed SSA.  */
    3531          844 :           if (changed >= 4)
    3532           45 :             rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
    3533              : 
    3534              :           ret |= TODO_cleanup_cfg;
    3535              :         }
    3536              :     }
    3537              : 
    3538           45 :   if (ret != 0)
    3539        12226 :     cfun->pending_TODOs |= PENDING_TODO_force_next_scalar_cleanup;
    3540              : 
    3541       215177 :   return ret;
    3542              : }
    3543              : 
    3544              : /* Predictive commoning Pass.  */
    3545              : 
    3546              : static unsigned
    3547       215177 : run_tree_predictive_commoning (struct function *fun, bool allow_unroll_p)
    3548              : {
    3549       430354 :   if (number_of_loops (fun) <= 1)
    3550              :     return 0;
    3551              : 
    3552       215177 :   return tree_predictive_commoning (allow_unroll_p);
    3553              : }
    3554              : 
    3555              : namespace {
    3556              : 
    3557              : const pass_data pass_data_predcom =
    3558              : {
    3559              :   GIMPLE_PASS, /* type */
    3560              :   "pcom", /* name */
    3561              :   OPTGROUP_LOOP, /* optinfo_flags */
    3562              :   TV_PREDCOM, /* tv_id */
    3563              :   PROP_cfg, /* properties_required */
    3564              :   0, /* properties_provided */
    3565              :   0, /* properties_destroyed */
    3566              :   0, /* todo_flags_start */
    3567              :   0, /* todo_flags_finish */
    3568              : };
    3569              : 
    3570              : class pass_predcom : public gimple_opt_pass
    3571              : {
    3572              : public:
    3573       302985 :   pass_predcom (gcc::context *ctxt)
    3574       605970 :     : gimple_opt_pass (pass_data_predcom, ctxt)
    3575              :   {}
    3576              : 
    3577              :   /* opt_pass methods: */
    3578              :   bool
    3579       251589 :   gate (function *) final override
    3580              :   {
    3581       251589 :     if (flag_predictive_commoning != 0)
    3582              :       return true;
    3583              :     /* Loop vectorization enables predictive commoning implicitly
    3584              :        only if predictive commoning isn't set explicitly, and it
    3585              :        doesn't allow unrolling.  */
    3586       221028 :     if (flag_tree_loop_vectorize
    3587       184617 :         && !OPTION_SET_P (flag_predictive_commoning))
    3588       184617 :       return true;
    3589              : 
    3590              :     return false;
    3591              :   }
    3592              : 
    3593              :   unsigned int
    3594       215177 :   execute (function *fun) final override
    3595              :   {
    3596       215177 :     bool allow_unroll_p = flag_predictive_commoning != 0;
    3597       215177 :     return run_tree_predictive_commoning (fun, allow_unroll_p);
    3598              :   }
    3599              : 
    3600              : }; // class pass_predcom
    3601              : 
    3602              : } // anon namespace
    3603              : 
    3604              : gimple_opt_pass *
    3605       302985 : make_pass_predcom (gcc::context *ctxt)
    3606              : {
    3607       302985 :   return new pass_predcom (ctxt);
    3608              : }
        

Generated by: LCOV version 2.6-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.