LCOV - code coverage report
Current view: top level - gcc - tree-ssa-loop-ivopts.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 91.5 % 3773 3451
Test Date: 2026-12-05 16:10:02 Functions: 96.8 % 185 179
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Induction variable optimizations.
       2              :    Copyright (C) 2003-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 pass tries to find the optimal set of induction variables for the loop.
      21              :    It optimizes just the basic linear induction variables (although adding
      22              :    support for other types should not be too hard).  It includes the
      23              :    optimizations commonly known as strength reduction, induction variable
      24              :    coalescing and induction variable elimination.  It does it in the
      25              :    following steps:
      26              : 
      27              :    1) The interesting uses of induction variables are found.  This includes
      28              : 
      29              :       -- uses of induction variables in non-linear expressions
      30              :       -- addresses of arrays
      31              :       -- comparisons of induction variables
      32              : 
      33              :       Note the interesting uses are categorized and handled in group.
      34              :       Generally, address type uses are grouped together if their iv bases
      35              :       are different in constant offset.
      36              : 
      37              :    2) Candidates for the induction variables are found.  This includes
      38              : 
      39              :       -- old induction variables
      40              :       -- the variables defined by expressions derived from the "interesting
      41              :          groups/uses" above
      42              : 
      43              :    3) The optimal (w.r. to a cost function) set of variables is chosen.  The
      44              :       cost function assigns a cost to sets of induction variables and consists
      45              :       of three parts:
      46              : 
      47              :       -- The group/use costs.  Each of the interesting groups/uses chooses
      48              :          the best induction variable in the set and adds its cost to the sum.
      49              :          The cost reflects the time spent on modifying the induction variables
      50              :          value to be usable for the given purpose (adding base and offset for
      51              :          arrays, etc.).
      52              :       -- The variable costs.  Each of the variables has a cost assigned that
      53              :          reflects the costs associated with incrementing the value of the
      54              :          variable.  The original variables are somewhat preferred.
      55              :       -- The set cost.  Depending on the size of the set, extra cost may be
      56              :          added to reflect register pressure.
      57              : 
      58              :       All the costs are defined in a machine-specific way, using the target
      59              :       hooks and machine descriptions to determine them.
      60              : 
      61              :    4) The trees are transformed to use the new variables, the dead code is
      62              :       removed.
      63              : 
      64              :    All of this is done loop by loop.  Doing it globally is theoretically
      65              :    possible, it might give a better performance and it might enable us
      66              :    to decide costs more precisely, but getting all the interactions right
      67              :    would be complicated.
      68              : 
      69              :    For the targets supporting low-overhead loops, IVOPTs has to take care of
      70              :    the loops which will probably be transformed in RTL doloop optimization,
      71              :    to try to make selected IV candidate set optimal.  The process of doloop
      72              :    support includes:
      73              : 
      74              :    1) Analyze the current loop will be transformed to doloop or not, find and
      75              :       mark its compare type IV use as doloop use (iv_group field doloop_p), and
      76              :       set flag doloop_use_p of ivopts_data to notify subsequent processings on
      77              :       doloop.  See analyze_and_mark_doloop_use and its callees for the details.
      78              :       The target hook predict_doloop_p can be used for target specific checks.
      79              : 
      80              :    2) Add one doloop dedicated IV cand {(may_be_zero ? 1 : (niter + 1)), +, -1},
      81              :       set flag doloop_p of iv_cand, step cost is set as zero and no extra cost
      82              :       like biv.  For cost determination between doloop IV cand and IV use, the
      83              :       target hooks doloop_cost_for_generic and doloop_cost_for_address are
      84              :       provided to add on extra costs for generic type and address type IV use.
      85              :       Zero cost is assigned to the pair between doloop IV cand and doloop IV
      86              :       use, and bound zero is set for IV elimination.
      87              : 
      88              :    3) With the cost setting in step 2), the current cost model based IV
      89              :       selection algorithm will process as usual, pick up doloop dedicated IV if
      90              :       profitable.  */
      91              : 
      92              : #include "config.h"
      93              : #include "system.h"
      94              : #include "coretypes.h"
      95              : #include "backend.h"
      96              : #include "rtl.h"
      97              : #include "tree.h"
      98              : #include "gimple.h"
      99              : #include "cfghooks.h"
     100              : #include "tree-pass.h"
     101              : #include "memmodel.h"
     102              : #include "tm_p.h"
     103              : #include "ssa.h"
     104              : #include "expmed.h"
     105              : #include "insn-config.h"
     106              : #include "emit-rtl.h"
     107              : #include "recog.h"
     108              : #include "cgraph.h"
     109              : #include "gimple-pretty-print.h"
     110              : #include "alias.h"
     111              : #include "fold-const.h"
     112              : #include "stor-layout.h"
     113              : #include "tree-eh.h"
     114              : #include "gimplify.h"
     115              : #include "gimple-iterator.h"
     116              : #include "gimplify-me.h"
     117              : #include "tree-cfg.h"
     118              : #include "tree-ssa-loop-ivopts.h"
     119              : #include "tree-ssa-loop-manip.h"
     120              : #include "tree-ssa-loop-niter.h"
     121              : #include "tree-ssa-loop.h"
     122              : #include "explow.h"
     123              : #include "expr.h"
     124              : #include "tree-dfa.h"
     125              : #include "tree-ssa.h"
     126              : #include "cfgloop.h"
     127              : #include "tree-scalar-evolution.h"
     128              : #include "tree-affine.h"
     129              : #include "tree-ssa-propagate.h"
     130              : #include "tree-ssa-address.h"
     131              : #include "builtins.h"
     132              : #include "tree-vectorizer.h"
     133              : #include "dbgcnt.h"
     134              : #include "cfganal.h"
     135              : #include "gimple-fold.h"
     136              : #include "gimple-range.h"
     137              : 
     138              : /* For lang_hooks.types.type_for_mode.  */
     139              : #include "langhooks.h"
     140              : 
     141              : /* FIXME: Expressions are expanded to RTL in this pass to determine the
     142              :    cost of different addressing modes.  This should be moved to a TBD
     143              :    interface between the GIMPLE and RTL worlds.  */
     144              : 
     145              : /* The infinite cost.  */
     146              : #define INFTY 1000000000
     147              : 
     148              : /* Returns the expected number of loop iterations for LOOP.
     149              :    The average trip count is computed from profile data if it
     150              :    exists. */
     151              : 
     152              : static inline unsigned HOST_WIDE_INT
     153      8971770 : avg_loop_niter (class loop *loop)
     154              : {
     155      8971770 :   HOST_WIDE_INT niter = estimated_stmt_executions_int (loop);
     156      8971770 :   if (niter == -1)
     157              :     {
     158      5041879 :       niter = likely_max_stmt_executions_int (loop);
     159              : 
     160      5041879 :       if (niter == -1 || niter > param_avg_loop_niter)
     161      4218916 :         return param_avg_loop_niter;
     162              :     }
     163              : 
     164      4752854 :   return niter;
     165              : }
     166              : 
     167              : struct iv_use;
     168              : 
     169              : /* Representation of the induction variable.  */
     170              : struct iv
     171              : {
     172              :   tree base;            /* Initial value of the iv.  */
     173              :   tree base_object;     /* A memory object to that the induction variable points.  */
     174              :   tree step;            /* Step of the iv (constant only).  */
     175              :   tree ssa_name;        /* The ssa name with the value.  */
     176              :   struct iv_use *nonlin_use;    /* The identifier in the use if it is the case.  */
     177              :   bool biv_p;           /* Is it a biv?  */
     178              :   bool no_overflow;     /* True if the iv doesn't overflow.  */
     179              :   bool have_address_use;/* For biv, indicate if it's used in any address
     180              :                            type use.  */
     181              : };
     182              : 
     183              : /* Per-ssa version information (induction variable descriptions, etc.).  */
     184              : struct version_info
     185              : {
     186              :   tree name;            /* The ssa name.  */
     187              :   struct iv *iv;        /* Induction variable description.  */
     188              :   bool has_nonlin_use;  /* For a loop-level invariant, whether it is used in
     189              :                            an expression that is not an induction variable.  */
     190              :   bool preserve_biv;    /* For the original biv, whether to preserve it.  */
     191              :   unsigned inv_id;      /* Id of an invariant.  */
     192              : };
     193              : 
     194              : /* Types of uses.  */
     195              : enum use_type
     196              : {
     197              :   USE_NONLINEAR_EXPR,   /* Use in a nonlinear expression.  */
     198              :   USE_REF_ADDRESS,      /* Use is an address for an explicit memory
     199              :                            reference.  */
     200              :   USE_PTR_ADDRESS,      /* Use is a pointer argument to a function in
     201              :                            cases where the expansion of the function
     202              :                            will turn the argument into a normal address.  */
     203              :   USE_COMPARE           /* Use is a compare.  */
     204              : };
     205              : 
     206              : /* Cost of a computation.  */
     207              : class comp_cost
     208              : {
     209              : public:
     210    134435886 :   comp_cost (): cost (0), complexity (0), scratch (0)
     211              :   {}
     212              : 
     213     25740883 :   comp_cost (int64_t cost, unsigned complexity, int64_t scratch = 0)
     214     15690736 :     : cost (cost), complexity (complexity), scratch (scratch)
     215              :   {}
     216              : 
     217              :   /* Returns true if COST is infinite.  */
     218              :   bool infinite_cost_p ();
     219              : 
     220              :   /* Adds costs COST1 and COST2.  */
     221              :   friend comp_cost operator+ (comp_cost cost1, comp_cost cost2);
     222              : 
     223              :   /* Adds COST to the comp_cost.  */
     224              :   comp_cost operator+= (comp_cost cost);
     225              : 
     226              :   /* Adds constant C to this comp_cost.  */
     227              :   comp_cost operator+= (HOST_WIDE_INT c);
     228              : 
     229              :   /* Subtracts constant C to this comp_cost.  */
     230              :   comp_cost operator-= (HOST_WIDE_INT c);
     231              : 
     232              :   /* Divide the comp_cost by constant C.  */
     233              :   comp_cost operator/= (HOST_WIDE_INT c);
     234              : 
     235              :   /* Multiply the comp_cost by constant C.  */
     236              :   comp_cost operator*= (HOST_WIDE_INT c);
     237              : 
     238              :   /* Subtracts costs COST1 and COST2.  */
     239              :   friend comp_cost operator- (comp_cost cost1, comp_cost cost2);
     240              : 
     241              :   /* Subtracts COST from this comp_cost.  */
     242              :   comp_cost operator-= (comp_cost cost);
     243              : 
     244              :   /* Returns true if COST1 is smaller than COST2.  */
     245              :   friend bool operator< (comp_cost cost1, comp_cost cost2);
     246              : 
     247              :   /* Returns true if COST1 and COST2 are equal.  */
     248              :   friend bool operator== (comp_cost cost1, comp_cost cost2);
     249              : 
     250              :   /* Returns true if COST1 is smaller or equal than COST2.  */
     251              :   friend bool operator<= (comp_cost cost1, comp_cost cost2);
     252              : 
     253              :   int64_t cost;         /* The runtime cost.  */
     254              :   unsigned complexity;  /* The estimate of the complexity of the code for
     255              :                            the computation (in no concrete units --
     256              :                            complexity field should be larger for more
     257              :                            complex expressions and addressing modes).  */
     258              :   int64_t scratch;      /* Scratch used during cost computation.  */
     259              : };
     260              : 
     261              : static const comp_cost no_cost;
     262              : static const comp_cost infinite_cost (INFTY, 0, INFTY);
     263              : 
     264              : bool
     265   1897912002 : comp_cost::infinite_cost_p ()
     266              : {
     267   1897912002 :   return cost == INFTY;
     268              : }
     269              : 
     270              : comp_cost
     271    253002588 : operator+ (comp_cost cost1, comp_cost cost2)
     272              : {
     273    253002588 :   if (cost1.infinite_cost_p () || cost2.infinite_cost_p ())
     274      1918980 :     return infinite_cost;
     275              : 
     276    251083608 :   gcc_assert (cost1.cost + cost2.cost < infinite_cost.cost);
     277    251083608 :   cost1.cost += cost2.cost;
     278    251083608 :   cost1.complexity += cost2.complexity;
     279              : 
     280    251083608 :   return cost1;
     281              : }
     282              : 
     283              : comp_cost
     284    217492086 : operator- (comp_cost cost1, comp_cost cost2)
     285              : {
     286    217492086 :   if (cost1.infinite_cost_p ())
     287            0 :     return infinite_cost;
     288              : 
     289    217492086 :   gcc_assert (!cost2.infinite_cost_p ());
     290    217492086 :   gcc_assert (cost1.cost - cost2.cost < infinite_cost.cost);
     291              : 
     292    217492086 :   cost1.cost -= cost2.cost;
     293    217492086 :   cost1.complexity -= cost2.complexity;
     294              : 
     295    217492086 :   return cost1;
     296              : }
     297              : 
     298              : comp_cost
     299    253002588 : comp_cost::operator+= (comp_cost cost)
     300              : {
     301    253002588 :   *this = *this + cost;
     302    253002588 :   return *this;
     303              : }
     304              : 
     305              : comp_cost
     306    897627277 : comp_cost::operator+= (HOST_WIDE_INT c)
     307              : {
     308    897627277 :   if (c >= INFTY)
     309            0 :     this->cost = INFTY;
     310              : 
     311    897627277 :   if (infinite_cost_p ())
     312            0 :     return *this;
     313              : 
     314    897627277 :   gcc_assert (this->cost + c < infinite_cost.cost);
     315    897627277 :   this->cost += c;
     316              : 
     317    897627277 :   return *this;
     318              : }
     319              : 
     320              : comp_cost
     321       539832 : comp_cost::operator-= (HOST_WIDE_INT c)
     322              : {
     323       539832 :   if (infinite_cost_p ())
     324            0 :     return *this;
     325              : 
     326       539832 :   gcc_assert (this->cost - c < infinite_cost.cost);
     327       539832 :   this->cost -= c;
     328              : 
     329       539832 :   return *this;
     330              : }
     331              : 
     332              : comp_cost
     333            0 : comp_cost::operator/= (HOST_WIDE_INT c)
     334              : {
     335            0 :   gcc_assert (c != 0);
     336            0 :   if (infinite_cost_p ())
     337            0 :     return *this;
     338              : 
     339            0 :   this->cost /= c;
     340              : 
     341            0 :   return *this;
     342              : }
     343              : 
     344              : comp_cost
     345            0 : comp_cost::operator*= (HOST_WIDE_INT c)
     346              : {
     347            0 :   if (infinite_cost_p ())
     348            0 :     return *this;
     349              : 
     350            0 :   gcc_assert (this->cost * c < infinite_cost.cost);
     351            0 :   this->cost *= c;
     352              : 
     353            0 :   return *this;
     354              : }
     355              : 
     356              : comp_cost
     357    217492086 : comp_cost::operator-= (comp_cost cost)
     358              : {
     359    217492086 :   *this = *this - cost;
     360    217492086 :   return *this;
     361              : }
     362              : 
     363              : bool
     364    193660647 : operator< (comp_cost cost1, comp_cost cost2)
     365              : {
     366    193660647 :   if (cost1.cost == cost2.cost)
     367     84376547 :     return cost1.complexity < cost2.complexity;
     368              : 
     369    109284100 :   return cost1.cost < cost2.cost;
     370              : }
     371              : 
     372              : bool
     373      3931551 : operator== (comp_cost cost1, comp_cost cost2)
     374              : {
     375      3931551 :   return cost1.cost == cost2.cost
     376      3931551 :     && cost1.complexity == cost2.complexity;
     377              : }
     378              : 
     379              : bool
     380      6539605 : operator<= (comp_cost cost1, comp_cost cost2)
     381              : {
     382      6539605 :   return cost1 < cost2 || cost1 == cost2;
     383              : }
     384              : 
     385              : struct iv_inv_expr_ent;
     386              : 
     387              : /* The candidate - cost pair.  */
     388              : class cost_pair
     389              : {
     390              : public:
     391              :   struct iv_cand *cand; /* The candidate.  */
     392              :   comp_cost cost;       /* The cost.  */
     393              :   enum tree_code comp;  /* For iv elimination, the comparison.  */
     394              :   bitmap inv_vars;      /* The list of invariant ssa_vars that have to be
     395              :                            preserved when representing iv_use with iv_cand.  */
     396              :   bitmap inv_exprs;     /* The list of newly created invariant expressions
     397              :                            when representing iv_use with iv_cand.  */
     398              :   tree value;           /* For final value elimination, the expression for
     399              :                            the final value of the iv.  For iv elimination,
     400              :                            the new bound to compare with.  */
     401              : };
     402              : 
     403              : /* Use.  */
     404              : struct iv_use
     405              : {
     406              :   unsigned id;          /* The id of the use.  */
     407              :   unsigned group_id;    /* The group id the use belongs to.  */
     408              :   enum use_type type;   /* Type of the use.  */
     409              :   tree mem_type;        /* The memory type to use when testing whether an
     410              :                            address is legitimate, and what the address's
     411              :                            cost is.  */
     412              :   struct iv *iv;        /* The induction variable it is based on.  */
     413              :   gimple *stmt;         /* Statement in that it occurs.  */
     414              :   tree *op_p;           /* The place where it occurs.  */
     415              : 
     416              :   tree addr_base;       /* Base address with const offset stripped.  */
     417              :   poly_uint64 addr_offset;
     418              :                         /* Const offset stripped from base address.  */
     419              : };
     420              : 
     421              : /* Group of uses.  */
     422              : struct iv_group
     423              : {
     424              :   /* The id of the group.  */
     425              :   unsigned id;
     426              :   /* Uses of the group are of the same type.  */
     427              :   enum use_type type;
     428              :   /* The set of "related" IV candidates, plus the important ones.  */
     429              :   bitmap related_cands;
     430              :   /* Number of IV candidates in the cost_map.  */
     431              :   unsigned n_map_members;
     432              :   /* The costs wrto the iv candidates.  */
     433              :   class cost_pair *cost_map;
     434              :   /* The selected candidate for the group.  */
     435              :   struct iv_cand *selected;
     436              :   /* To indicate this is a doloop use group.  */
     437              :   bool doloop_p;
     438              :   /* Uses in the group.  */
     439              :   vec<struct iv_use *> vuses;
     440              : };
     441              : 
     442              : /* The position where the iv is computed.  */
     443              : enum iv_position
     444              : {
     445              :   IP_NORMAL,            /* At the end, just before the exit condition.  */
     446              :   IP_END,               /* At the end of the latch block.  */
     447              :   IP_BEFORE_USE,        /* Immediately before a specific use.  */
     448              :   IP_AFTER_USE,         /* Immediately after a specific use.  */
     449              :   IP_ORIGINAL           /* The original biv.  */
     450              : };
     451              : 
     452              : /* The induction variable candidate.  */
     453              : struct iv_cand
     454              : {
     455              :   unsigned id;          /* The number of the candidate.  */
     456              :   bool important;       /* Whether this is an "important" candidate, i.e. such
     457              :                            that it should be considered by all uses.  */
     458              :   bool involves_undefs; /* Whether the IV involves undefined values.  */
     459              :   enum iv_position pos : 8;/* Where it is computed.  */
     460              :   gimple *incremented_at;/* For original biv, the statement where it is
     461              :                            incremented.  */
     462              :   tree var_before;      /* The variable used for it before increment.  */
     463              :   tree var_after;       /* The variable used for it after increment.  */
     464              :   struct iv *iv;        /* The value of the candidate.  NULL for
     465              :                            "pseudocandidate" used to indicate the possibility
     466              :                            to replace the final value of an iv by direct
     467              :                            computation of the value.  */
     468              :   unsigned cost;        /* Cost of the candidate.  */
     469              :   unsigned cost_step;   /* Cost of the candidate's increment operation.  */
     470              :   unsigned nregs;       /* Total number of registers used by the candidate.  */
     471              :   struct iv_use *ainc_use; /* For IP_{BEFORE,AFTER}_USE candidates, the place
     472              :                               where it is incremented.  */
     473              :   bitmap inv_vars;      /* The list of invariant ssa_vars used in step of the
     474              :                            iv_cand.  */
     475              :   bitmap inv_exprs;     /* If step is more complicated than a single ssa_var,
     476              :                            handle it as a new invariant expression which will
     477              :                            be hoisted out of loop.  */
     478              :   struct iv *orig_iv;   /* The original iv if this cand is added from biv with
     479              :                            smaller type.  */
     480              :   bool doloop_p;        /* Whether this is a doloop candidate.  */
     481              : };
     482              : 
     483              : /* Hashtable entry for common candidate derived from iv uses.  */
     484      2684003 : class iv_common_cand
     485              : {
     486              : public:
     487              :   tree base;
     488              :   tree step;
     489              :   /* IV uses from which this common candidate is derived.  */
     490              :   auto_vec<struct iv_use *> uses;
     491              :   hashval_t hash;
     492              : };
     493              : 
     494              : /* Hashtable helpers.  */
     495              : 
     496              : struct iv_common_cand_hasher : delete_ptr_hash <iv_common_cand>
     497              : {
     498              :   static inline hashval_t hash (const iv_common_cand *);
     499              :   static inline bool equal (const iv_common_cand *, const iv_common_cand *);
     500              : };
     501              : 
     502              : /* Hash function for possible common candidates.  */
     503              : 
     504              : inline hashval_t
     505      9864622 : iv_common_cand_hasher::hash (const iv_common_cand *ccand)
     506              : {
     507      9864622 :   return ccand->hash;
     508              : }
     509              : 
     510              : /* Hash table equality function for common candidates.  */
     511              : 
     512              : inline bool
     513     11139910 : iv_common_cand_hasher::equal (const iv_common_cand *ccand1,
     514              :                               const iv_common_cand *ccand2)
     515              : {
     516     11139910 :   return (ccand1->hash == ccand2->hash
     517      1650925 :           && operand_equal_p (ccand1->base, ccand2->base, 0)
     518      1631322 :           && operand_equal_p (ccand1->step, ccand2->step, 0)
     519     12766064 :           && (TYPE_PRECISION (TREE_TYPE (ccand1->base))
     520      1626154 :               == TYPE_PRECISION (TREE_TYPE (ccand2->base))));
     521              : }
     522              : 
     523              : /* Loop invariant expression hashtable entry.  */
     524              : 
     525              : struct iv_inv_expr_ent
     526              : {
     527              :   /* Tree expression of the entry.  */
     528              :   tree expr;
     529              :   /* Unique identifier.  */
     530              :   int id;
     531              :   /* Hash value.  */
     532              :   hashval_t hash;
     533              : };
     534              : 
     535              : /* Sort iv_inv_expr_ent pair A and B by id field.  */
     536              : 
     537              : static int
     538         5824 : sort_iv_inv_expr_ent (const void *a, const void *b)
     539              : {
     540         5824 :   const iv_inv_expr_ent * const *e1 = (const iv_inv_expr_ent * const *) (a);
     541         5824 :   const iv_inv_expr_ent * const *e2 = (const iv_inv_expr_ent * const *) (b);
     542              : 
     543         5824 :   unsigned id1 = (*e1)->id;
     544         5824 :   unsigned id2 = (*e2)->id;
     545              : 
     546         5824 :   if (id1 < id2)
     547              :     return -1;
     548         2704 :   else if (id1 > id2)
     549              :     return 1;
     550              :   else
     551            0 :     return 0;
     552              : }
     553              : 
     554              : /* Hashtable helpers.  */
     555              : 
     556              : struct iv_inv_expr_hasher : free_ptr_hash <iv_inv_expr_ent>
     557              : {
     558              :   static inline hashval_t hash (const iv_inv_expr_ent *);
     559              :   static inline bool equal (const iv_inv_expr_ent *, const iv_inv_expr_ent *);
     560              : };
     561              : 
     562              : /* Return true if uses of type TYPE represent some form of address.  */
     563              : 
     564              : inline bool
     565      9172618 : address_p (use_type type)
     566              : {
     567      9172618 :   return type == USE_REF_ADDRESS || type == USE_PTR_ADDRESS;
     568              : }
     569              : 
     570              : /* Hash function for loop invariant expressions.  */
     571              : 
     572              : inline hashval_t
     573      6592606 : iv_inv_expr_hasher::hash (const iv_inv_expr_ent *expr)
     574              : {
     575      6592606 :   return expr->hash;
     576              : }
     577              : 
     578              : /* Hash table equality function for expressions.  */
     579              : 
     580              : inline bool
     581      7913880 : iv_inv_expr_hasher::equal (const iv_inv_expr_ent *expr1,
     582              :                            const iv_inv_expr_ent *expr2)
     583              : {
     584      7913880 :   return expr1->hash == expr2->hash
     585      7913880 :          && operand_equal_p (expr1->expr, expr2->expr, 0);
     586              : }
     587              : 
     588              : struct ivopts_data
     589              : {
     590              :   /* The currently optimized loop.  */
     591              :   class loop *current_loop;
     592              :   location_t loop_loc;
     593              : 
     594              :   /* Numbers of iterations for all exits of the current loop.  */
     595              :   hash_map<edge, tree_niter_desc *> *niters;
     596              : 
     597              :   /* Number of registers used in it.  */
     598              :   unsigned regs_used;
     599              : 
     600              :   /* The size of version_info array allocated.  */
     601              :   unsigned version_info_size;
     602              : 
     603              :   /* The array of information for the ssa names.  */
     604              :   struct version_info *version_info;
     605              : 
     606              :   /* The hashtable of loop invariant expressions created
     607              :      by ivopt.  */
     608              :   hash_table<iv_inv_expr_hasher> *inv_expr_tab;
     609              : 
     610              :   /* The bitmap of indices in version_info whose value was changed.  */
     611              :   bitmap relevant;
     612              : 
     613              :   /* The uses of induction variables.  */
     614              :   vec<iv_group *> vgroups;
     615              : 
     616              :   /* The candidates.  */
     617              :   vec<iv_cand *> vcands;
     618              : 
     619              :   /* A bitmap of important candidates.  */
     620              :   bitmap important_candidates;
     621              : 
     622              :   /* Cache used by tree_to_aff_combination_expand.  */
     623              :   hash_map<tree, name_expansion *> *name_expansion_cache;
     624              : 
     625              :   /* The hashtable of common candidates derived from iv uses.  */
     626              :   hash_table<iv_common_cand_hasher> *iv_common_cand_tab;
     627              : 
     628              :   /* The common candidates.  */
     629              :   vec<iv_common_cand *> iv_common_cands;
     630              : 
     631              :   /* Hash map recording base object information of tree exp.  */
     632              :   hash_map<tree, tree> *base_object_map;
     633              : 
     634              :   /* The maximum invariant variable id.  */
     635              :   unsigned max_inv_var_id;
     636              : 
     637              :   /* The maximum invariant expression id.  */
     638              :   unsigned max_inv_expr_id;
     639              : 
     640              :   /* Number of registers used by each invariant variable and expression.  */
     641              :   vec<unsigned> inv_var_nregs;
     642              :   vec<unsigned> inv_expr_nregs;
     643              : 
     644              :   /* Number of no_overflow BIVs which are not used in memory address.  */
     645              :   unsigned bivs_not_used_in_addr;
     646              : 
     647              :   /* Obstack for iv structure.  */
     648              :   struct obstack iv_obstack;
     649              : 
     650              :   /* Whether to consider just related and important candidates when replacing a
     651              :      use.  */
     652              :   bool consider_all_candidates;
     653              : 
     654              :   /* Are we optimizing for speed?  */
     655              :   bool speed;
     656              : 
     657              :   /* Whether the loop body includes any function calls.  */
     658              :   bool body_includes_call;
     659              : 
     660              :   /* Whether the loop body can only be exited via single exit.  */
     661              :   bool loop_single_exit_p;
     662              : 
     663              :   /* Whether the loop has doloop comparison use.  */
     664              :   bool doloop_use_p;
     665              : };
     666              : 
     667              : /* An assignment of iv candidates to uses.  */
     668              : 
     669              : class iv_ca
     670              : {
     671              : public:
     672              :   /* The number of uses covered by the assignment.  */
     673              :   unsigned upto;
     674              : 
     675              :   /* Number of uses that cannot be expressed by the candidates in the set.  */
     676              :   unsigned bad_groups;
     677              : 
     678              :   /* Candidate assigned to a use, together with the related costs.  */
     679              :   class cost_pair **cand_for_group;
     680              : 
     681              :   /* Number of times each candidate is used.  */
     682              :   unsigned *n_cand_uses;
     683              : 
     684              :   /* The candidates used.  */
     685              :   bitmap cands;
     686              : 
     687              :   /* The number of candidates in the set.  */
     688              :   unsigned n_cands;
     689              : 
     690              :   /* The number of invariants needed, including both invariant variants and
     691              :      invariant expressions.  */
     692              :   unsigned n_invs;
     693              : 
     694              :   /* Total number of registers used by candidates.  */
     695              :   unsigned n_cand_regs;
     696              : 
     697              :   /* Total number of registers used by invariants.  */
     698              :   unsigned n_inv_regs;
     699              : 
     700              :   /* Total cost of expressing uses.  */
     701              :   comp_cost cand_use_cost;
     702              : 
     703              :   /* Total cost of candidates.  */
     704              :   int64_t cand_cost;
     705              : 
     706              :   /* Number of times each invariant variable is used.  */
     707              :   unsigned *n_inv_var_uses;
     708              : 
     709              :   /* Number of times each invariant expression is used.  */
     710              :   unsigned *n_inv_expr_uses;
     711              : 
     712              :   /* Total cost of the assignment.  */
     713              :   comp_cost cost;
     714              : };
     715              : 
     716              : /* Difference of two iv candidate assignments.  */
     717              : 
     718              : struct iv_ca_delta
     719              : {
     720              :   /* Changed group.  */
     721              :   struct iv_group *group;
     722              : 
     723              :   /* An old assignment (for rollback purposes).  */
     724              :   class cost_pair *old_cp;
     725              : 
     726              :   /* A new assignment.  */
     727              :   class cost_pair *new_cp;
     728              : 
     729              :   /* Next change in the list.  */
     730              :   struct iv_ca_delta *next;
     731              : };
     732              : 
     733              : /* Bound on number of candidates below that all candidates are considered.  */
     734              : 
     735              : #define CONSIDER_ALL_CANDIDATES_BOUND \
     736              :   ((unsigned) param_iv_consider_all_candidates_bound)
     737              : 
     738              : /* If there are more iv occurrences, we just give up (it is quite unlikely that
     739              :    optimizing such a loop would help, and it would take ages).  */
     740              : 
     741              : #define MAX_CONSIDERED_GROUPS \
     742              :   ((unsigned) param_iv_max_considered_uses)
     743              : 
     744              : /* If there are at most this number of ivs in the set, try removing unnecessary
     745              :    ivs from the set always.  */
     746              : 
     747              : #define ALWAYS_PRUNE_CAND_SET_BOUND \
     748              :   ((unsigned) param_iv_always_prune_cand_set_bound)
     749              : 
     750              : /* The list of trees for that the decl_rtl field must be reset is stored
     751              :    here.  */
     752              : 
     753              : static vec<tree> decl_rtl_to_reset;
     754              : 
     755              : static comp_cost force_expr_to_var_cost (tree, bool);
     756              : 
     757              : /* The single loop exit if it dominates the latch, NULL otherwise.  */
     758              : 
     759              : edge
     760       724833 : single_dom_exit (class loop *loop)
     761              : {
     762       724833 :   edge exit = single_exit (loop);
     763              : 
     764       724833 :   if (!exit)
     765              :     return NULL;
     766              : 
     767       481804 :   if (!just_once_each_iteration_p (loop, exit->src))
     768         5820 :     return NULL;
     769              : 
     770              :   return exit;
     771              : }
     772              : 
     773              : /* Dumps information about the induction variable IV to FILE.  Don't dump
     774              :    variable's name if DUMP_NAME is FALSE.  The information is dumped with
     775              :    preceding spaces indicated by INDENT_LEVEL.  */
     776              : 
     777              : void
     778         1690 : dump_iv (FILE *file, struct iv *iv, bool dump_name, unsigned indent_level)
     779              : {
     780         1690 :   const char *p;
     781         1690 :   const char spaces[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\0'};
     782              : 
     783         1690 :   if (indent_level > 4)
     784              :     indent_level = 4;
     785         1690 :   p = spaces + 8 - (indent_level << 1);
     786              : 
     787         1690 :   fprintf (file, "%sIV struct:\n", p);
     788         1690 :   if (iv->ssa_name && dump_name)
     789              :     {
     790          573 :       fprintf (file, "%s  SSA_NAME:\t", p);
     791          573 :       print_generic_expr (file, iv->ssa_name, TDF_SLIM);
     792          573 :       fprintf (file, "\n");
     793              :     }
     794              : 
     795         1690 :   fprintf (file, "%s  Type:\t", p);
     796         1690 :   print_generic_expr (file, TREE_TYPE (iv->base), TDF_SLIM);
     797         1690 :   fprintf (file, "\n");
     798              : 
     799         1690 :   fprintf (file, "%s  Base:\t", p);
     800         1690 :   print_generic_expr (file, iv->base, TDF_SLIM);
     801         1690 :   fprintf (file, "\n");
     802              : 
     803         1690 :   fprintf (file, "%s  Step:\t", p);
     804         1690 :   print_generic_expr (file, iv->step, TDF_SLIM);
     805         1690 :   fprintf (file, "\n");
     806              : 
     807         1690 :   if (iv->base_object)
     808              :     {
     809          527 :       fprintf (file, "%s  Object:\t", p);
     810          527 :       print_generic_expr (file, iv->base_object, TDF_SLIM);
     811          527 :       fprintf (file, "\n");
     812              :     }
     813              : 
     814         3056 :   fprintf (file, "%s  Biv:\t%c\n", p, iv->biv_p ? 'Y' : 'N');
     815              : 
     816         1690 :   fprintf (file, "%s  Overflowness wrto loop niter:\t%s\n",
     817         1690 :            p, iv->no_overflow ? "No-overflow" : "Overflow");
     818         1690 : }
     819              : 
     820              : /* Dumps information about the USE to FILE.  */
     821              : 
     822              : void
     823          264 : dump_use (FILE *file, struct iv_use *use)
     824              : {
     825          264 :   fprintf (file, "  Use %d.%d:\n", use->group_id, use->id);
     826          264 :   fprintf (file, "    At stmt:\t");
     827          264 :   print_gimple_stmt (file, use->stmt, 0);
     828          264 :   fprintf (file, "    At pos:\t");
     829          264 :   if (use->op_p)
     830          172 :     print_generic_expr (file, *use->op_p, TDF_SLIM);
     831          264 :   fprintf (file, "\n");
     832          264 :   dump_iv (file, use->iv, false, 2);
     833          264 : }
     834              : 
     835              : /* Dumps information about the uses to FILE.  */
     836              : 
     837              : void
     838           72 : dump_groups (FILE *file, struct ivopts_data *data)
     839              : {
     840           72 :   unsigned i, j;
     841           72 :   struct iv_group *group;
     842              : 
     843          305 :   for (i = 0; i < data->vgroups.length (); i++)
     844              :     {
     845          233 :       group = data->vgroups[i];
     846          233 :       fprintf (file, "Group %d:\n", group->id);
     847          233 :       if (group->type == USE_NONLINEAR_EXPR)
     848           92 :         fprintf (file, "  Type:\tGENERIC\n");
     849          141 :       else if (group->type == USE_REF_ADDRESS)
     850           62 :         fprintf (file, "  Type:\tREFERENCE ADDRESS\n");
     851           79 :       else if (group->type == USE_PTR_ADDRESS)
     852            0 :         fprintf (file, "  Type:\tPOINTER ARGUMENT ADDRESS\n");
     853              :       else
     854              :         {
     855           79 :           gcc_assert (group->type == USE_COMPARE);
     856           79 :           fprintf (file, "  Type:\tCOMPARE\n");
     857              :         }
     858          497 :       for (j = 0; j < group->vuses.length (); j++)
     859          264 :         dump_use (file, group->vuses[j]);
     860              :     }
     861           72 : }
     862              : 
     863              : /* Dumps information about induction variable candidate CAND to FILE.  */
     864              : 
     865              : void
     866          853 : dump_cand (FILE *file, struct iv_cand *cand)
     867              : {
     868          853 :   struct iv *iv = cand->iv;
     869              : 
     870          853 :   fprintf (file, "Candidate %d:\n", cand->id);
     871          853 :   if (cand->inv_vars)
     872              :     {
     873           28 :       fprintf (file, "  Depend on inv.vars: ");
     874           28 :       dump_bitmap (file, cand->inv_vars);
     875              :     }
     876          853 :   if (cand->inv_exprs)
     877              :     {
     878            4 :       fprintf (file, "  Depend on inv.exprs: ");
     879            4 :       dump_bitmap (file, cand->inv_exprs);
     880              :     }
     881              : 
     882          853 :   if (cand->var_before)
     883              :     {
     884          737 :       fprintf (file, "  Var before: ");
     885          737 :       print_generic_expr (file, cand->var_before, TDF_SLIM);
     886          737 :       fprintf (file, "\n");
     887              :     }
     888          853 :   if (cand->var_after)
     889              :     {
     890          737 :       fprintf (file, "  Var after: ");
     891          737 :       print_generic_expr (file, cand->var_after, TDF_SLIM);
     892          737 :       fprintf (file, "\n");
     893              :     }
     894              : 
     895          853 :   switch (cand->pos)
     896              :     {
     897          701 :     case IP_NORMAL:
     898          701 :       fprintf (file, "  Incr POS: before exit test\n");
     899          701 :       break;
     900              : 
     901            0 :     case IP_BEFORE_USE:
     902            0 :       fprintf (file, "  Incr POS: before use %d\n", cand->ainc_use->id);
     903            0 :       break;
     904              : 
     905            0 :     case IP_AFTER_USE:
     906            0 :       fprintf (file, "  Incr POS: after use %d\n", cand->ainc_use->id);
     907            0 :       break;
     908              : 
     909            0 :     case IP_END:
     910            0 :       fprintf (file, "  Incr POS: at end\n");
     911            0 :       break;
     912              : 
     913          152 :     case IP_ORIGINAL:
     914          152 :       fprintf (file, "  Incr POS: orig biv\n");
     915          152 :       break;
     916              :     }
     917              : 
     918          853 :   dump_iv (file, iv, false, 1);
     919          853 : }
     920              : 
     921              : /* Returns the info for ssa version VER.  */
     922              : 
     923              : static inline struct version_info *
     924    120483578 : ver_info (struct ivopts_data *data, unsigned ver)
     925              : {
     926    120483578 :   return data->version_info + ver;
     927              : }
     928              : 
     929              : /* Returns the info for ssa name NAME.  */
     930              : 
     931              : static inline struct version_info *
     932     97495041 : name_info (struct ivopts_data *data, tree name)
     933              : {
     934     97495041 :   return ver_info (data, SSA_NAME_VERSION (name));
     935              : }
     936              : 
     937              : /* Returns true if STMT is after the place where the IP_NORMAL ivs will be
     938              :    emitted in LOOP.  */
     939              : 
     940              : static bool
     941     33945100 : stmt_after_ip_normal_pos (class loop *loop, gimple *stmt)
     942              : {
     943     33945100 :   basic_block bb = ip_normal_pos (loop), sbb = gimple_bb (stmt);
     944              : 
     945     33945100 :   gcc_assert (bb);
     946              : 
     947     33945100 :   if (sbb == loop->latch)
     948              :     return true;
     949              : 
     950     33825327 :   if (sbb != bb)
     951              :     return false;
     952              : 
     953     20303931 :   return stmt == last_nondebug_stmt (bb);
     954              : }
     955              : 
     956              : /* Returns true if STMT if after the place where the original induction
     957              :    variable CAND is incremented.  If TRUE_IF_EQUAL is set, we return true
     958              :    if the positions are identical.  */
     959              : 
     960              : static bool
     961      8033688 : stmt_after_inc_pos (struct iv_cand *cand, gimple *stmt, bool true_if_equal)
     962              : {
     963      8033688 :   basic_block cand_bb = gimple_bb (cand->incremented_at);
     964      8033688 :   basic_block stmt_bb = gimple_bb (stmt);
     965              : 
     966      8033688 :   if (!dominated_by_p (CDI_DOMINATORS, stmt_bb, cand_bb))
     967              :     return false;
     968              : 
     969      5611513 :   if (stmt_bb != cand_bb)
     970              :     return true;
     971              : 
     972      5370246 :   if (true_if_equal
     973      5370246 :       && gimple_uid (stmt) == gimple_uid (cand->incremented_at))
     974              :     return true;
     975      5363694 :   return gimple_uid (stmt) > gimple_uid (cand->incremented_at);
     976              : }
     977              : 
     978              : /* Returns true if STMT if after the place where the induction variable
     979              :    CAND is incremented in LOOP.  */
     980              : 
     981              : static bool
     982     43207517 : stmt_after_increment (class loop *loop, struct iv_cand *cand, gimple *stmt)
     983              : {
     984     43207517 :   switch (cand->pos)
     985              :     {
     986              :     case IP_END:
     987              :       return false;
     988              : 
     989     33945100 :     case IP_NORMAL:
     990     33945100 :       return stmt_after_ip_normal_pos (loop, stmt);
     991              : 
     992      8023826 :     case IP_ORIGINAL:
     993      8023826 :     case IP_AFTER_USE:
     994      8023826 :       return stmt_after_inc_pos (cand, stmt, false);
     995              : 
     996         9862 :     case IP_BEFORE_USE:
     997         9862 :       return stmt_after_inc_pos (cand, stmt, true);
     998              : 
     999            0 :     default:
    1000            0 :       gcc_unreachable ();
    1001              :     }
    1002              : }
    1003              : 
    1004              : /* walk_tree callback for contains_abnormal_ssa_name_p.  */
    1005              : 
    1006              : static tree
    1007     15234753 : contains_abnormal_ssa_name_p_1 (tree *tp, int *walk_subtrees, void *)
    1008              : {
    1009     15234753 :   if (TREE_CODE (*tp) == SSA_NAME
    1010     15234753 :       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (*tp))
    1011              :     return *tp;
    1012              : 
    1013     15234737 :   if (!EXPR_P (*tp))
    1014     10417983 :     *walk_subtrees = 0;
    1015              : 
    1016              :   return NULL_TREE;
    1017              : }
    1018              : 
    1019              : /* Returns true if EXPR contains a ssa name that occurs in an
    1020              :    abnormal phi node.  */
    1021              : 
    1022              : bool
    1023      8181530 : contains_abnormal_ssa_name_p (tree expr)
    1024              : {
    1025      8181530 :   return walk_tree_without_duplicates
    1026      8181530 :            (&expr, contains_abnormal_ssa_name_p_1, NULL) != NULL_TREE;
    1027              : }
    1028              : 
    1029              : /*  Returns the structure describing number of iterations determined from
    1030              :     EXIT of DATA->current_loop, or NULL if something goes wrong.  */
    1031              : 
    1032              : static class tree_niter_desc *
    1033      4495612 : niter_for_exit (struct ivopts_data *data, edge exit)
    1034              : {
    1035      4495612 :   class tree_niter_desc *desc;
    1036      4495612 :   tree_niter_desc **slot;
    1037              : 
    1038      4495612 :   if (!data->niters)
    1039              :     {
    1040       487336 :       data->niters = new hash_map<edge, tree_niter_desc *>;
    1041       487336 :       slot = NULL;
    1042              :     }
    1043              :   else
    1044      4008276 :     slot = data->niters->get (exit);
    1045              : 
    1046      4495612 :   if (!slot)
    1047              :     {
    1048              :       /* Try to determine number of iterations.  We cannot safely work with ssa
    1049              :          names that appear in phi nodes on abnormal edges, so that we do not
    1050              :          create overlapping life ranges for them (PR 27283).  */
    1051       499615 :       desc = XNEW (class tree_niter_desc);
    1052       499615 :       ::new (static_cast<void*> (desc)) tree_niter_desc ();
    1053       499615 :       if (!number_of_iterations_exit (data->current_loop,
    1054              :                                       exit, desc, true)
    1055       499615 :           || contains_abnormal_ssa_name_p (desc->niter))
    1056              :         {
    1057        38954 :           desc->~tree_niter_desc ();
    1058        38954 :           XDELETE (desc);
    1059        38954 :           desc = NULL;
    1060              :         }
    1061       499615 :       data->niters->put (exit, desc);
    1062              :     }
    1063              :   else
    1064      3995997 :     desc = *slot;
    1065              : 
    1066      4495612 :   return desc;
    1067              : }
    1068              : 
    1069              : /* Returns the structure describing number of iterations determined from
    1070              :    single dominating exit of DATA->current_loop, or NULL if something
    1071              :    goes wrong.  */
    1072              : 
    1073              : static class tree_niter_desc *
    1074           72 : niter_for_single_dom_exit (struct ivopts_data *data)
    1075              : {
    1076           72 :   edge exit = single_dom_exit (data->current_loop);
    1077              : 
    1078           72 :   if (!exit)
    1079              :     return NULL;
    1080              : 
    1081           62 :   return niter_for_exit (data, exit);
    1082              : }
    1083              : 
    1084              : /* Initializes data structures used by the iv optimization pass, stored
    1085              :    in DATA.  */
    1086              : 
    1087              : static void
    1088       251559 : tree_ssa_iv_optimize_init (struct ivopts_data *data)
    1089              : {
    1090       251559 :   data->version_info_size = 2 * num_ssa_names;
    1091       251559 :   data->version_info = XCNEWVEC (struct version_info, data->version_info_size);
    1092       251559 :   data->relevant = BITMAP_ALLOC (NULL);
    1093       251559 :   data->important_candidates = BITMAP_ALLOC (NULL);
    1094       251559 :   data->max_inv_var_id = 0;
    1095       251559 :   data->max_inv_expr_id = 0;
    1096       251559 :   data->inv_var_nregs.create (0);
    1097       251559 :   data->inv_expr_nregs.create (0);
    1098       251559 :   data->niters = NULL;
    1099       251559 :   data->vgroups.create (20);
    1100       251559 :   data->vcands.create (20);
    1101       251559 :   data->inv_expr_tab = new hash_table<iv_inv_expr_hasher> (10);
    1102       251559 :   data->name_expansion_cache = NULL;
    1103       251559 :   data->base_object_map = NULL;
    1104       251559 :   data->iv_common_cand_tab = new hash_table<iv_common_cand_hasher> (10);
    1105       251559 :   data->iv_common_cands.create (20);
    1106       251559 :   decl_rtl_to_reset.create (20);
    1107       251559 :   gcc_obstack_init (&data->iv_obstack);
    1108       251559 : }
    1109              : 
    1110              : /* walk_tree callback for determine_base_object.  */
    1111              : 
    1112              : static tree
    1113     19839519 : determine_base_object_1 (tree *tp, int *walk_subtrees, void *wdata)
    1114              : {
    1115     19839519 :   tree_code code = TREE_CODE (*tp);
    1116     19839519 :   tree obj = NULL_TREE;
    1117     19839519 :   if (code == ADDR_EXPR)
    1118              :     {
    1119      1079419 :       tree base = get_base_address (TREE_OPERAND (*tp, 0));
    1120      1079419 :       if (!base)
    1121            0 :         obj = *tp;
    1122      1079419 :       else if (TREE_CODE (base) != MEM_REF)
    1123      1079395 :         obj = fold_convert (ptr_type_node, build_fold_addr_expr (base));
    1124              :     }
    1125     18760100 :   else if (code == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (*tp)))
    1126      1954408 :         obj = fold_convert (ptr_type_node, *tp);
    1127              : 
    1128      3033803 :   if (!obj)
    1129              :     {
    1130     16805716 :       if (!EXPR_P (*tp))
    1131      7379839 :         *walk_subtrees = 0;
    1132              : 
    1133              :       return NULL_TREE;
    1134              :     }
    1135              :   /* Record special node for multiple base objects and stop.  */
    1136      3033803 :   if (*static_cast<tree *> (wdata))
    1137              :     {
    1138         4393 :       *static_cast<tree *> (wdata) = integer_zero_node;
    1139         4393 :       return integer_zero_node;
    1140              :     }
    1141              :   /* Record the base object and continue looking.  */
    1142      3029410 :   *static_cast<tree *> (wdata) = obj;
    1143      3029410 :   return NULL_TREE;
    1144              : }
    1145              : 
    1146              : /* Returns a memory object to that EXPR points with caching.  Return NULL if we
    1147              :    are able to determine that it does not point to any such object; specially
    1148              :    return integer_zero_node if EXPR contains multiple base objects.  */
    1149              : 
    1150              : static tree
    1151     10708001 : determine_base_object (struct ivopts_data *data, tree expr)
    1152              : {
    1153     10708001 :   tree *slot, obj = NULL_TREE;
    1154     10708001 :   if (data->base_object_map)
    1155              :     {
    1156     10538084 :       if ((slot = data->base_object_map->get(expr)) != NULL)
    1157      4866839 :         return *slot;
    1158              :     }
    1159              :   else
    1160       169917 :     data->base_object_map = new hash_map<tree, tree>;
    1161              : 
    1162      5841162 :   (void) walk_tree_without_duplicates (&expr, determine_base_object_1, &obj);
    1163      5841162 :   data->base_object_map->put (expr, obj);
    1164      5841162 :   return obj;
    1165              : }
    1166              : 
    1167              : /* Allocates an induction variable with given initial value BASE and step STEP
    1168              :    for loop LOOP.  NO_OVERFLOW implies the iv doesn't overflow.  */
    1169              : 
    1170              : static struct iv *
    1171     10708001 : alloc_iv (struct ivopts_data *data, tree base, tree step,
    1172              :           bool no_overflow = false)
    1173              : {
    1174     10708001 :   tree expr = base;
    1175     10708001 :   struct iv *iv = (struct iv*) obstack_alloc (&data->iv_obstack,
    1176              :                                               sizeof (struct iv));
    1177     10708001 :   gcc_assert (step != NULL_TREE);
    1178              : 
    1179              :   /* Canonicalize the address expression in base if it were an unsigned
    1180              :       computation. That leads to more equalities being detected and results in:
    1181              : 
    1182              :        1) More accurate cost can be computed for address expressions;
    1183              :        2) Duplicate candidates won't be created for bases in different
    1184              :           forms, like &a[0] and &a.
    1185              :        3) Duplicate candidates won't be created for IV expressions that differ
    1186              :           only in their sign.  */
    1187     10708001 :   aff_tree comb;
    1188     10708001 :   STRIP_NOPS (expr);
    1189     10708001 :   expr = fold_convert (unsigned_type_for (TREE_TYPE (expr)), expr);
    1190     10708001 :   tree_to_aff_combination (expr, TREE_TYPE (expr), &comb);
    1191     10708001 :   base = fold_convert (TREE_TYPE (base), aff_combination_to_tree (&comb));
    1192              : 
    1193     10708001 :   iv->base = base;
    1194     10708001 :   iv->base_object = determine_base_object (data, base);
    1195     10708001 :   iv->step = step;
    1196     10708001 :   iv->biv_p = false;
    1197     10708001 :   iv->nonlin_use = NULL;
    1198     10708001 :   iv->ssa_name = NULL_TREE;
    1199     10708001 :   if (!no_overflow
    1200     10708001 :        && !iv_can_overflow_p (data->current_loop, TREE_TYPE (base),
    1201              :                               base, step))
    1202              :     no_overflow = true;
    1203     10708001 :   iv->no_overflow = no_overflow;
    1204     10708001 :   iv->have_address_use = false;
    1205              : 
    1206     21416002 :   return iv;
    1207     10708001 : }
    1208              : 
    1209              : /* Sets STEP and BASE for induction variable IV.  NO_OVERFLOW implies the IV
    1210              :    doesn't overflow.  */
    1211              : 
    1212              : static void
    1213      5071824 : set_iv (struct ivopts_data *data, tree iv, tree base, tree step,
    1214              :         bool no_overflow)
    1215              : {
    1216      5071824 :   struct version_info *info = name_info (data, iv);
    1217              : 
    1218      5071824 :   gcc_assert (!info->iv);
    1219              : 
    1220      5071824 :   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (iv));
    1221      5071824 :   info->iv = alloc_iv (data, base, step, no_overflow);
    1222      5071824 :   info->iv->ssa_name = iv;
    1223      5071824 : }
    1224              : 
    1225              : /* Finds induction variable declaration for VAR.  */
    1226              : 
    1227              : static struct iv *
    1228     45689202 : get_iv (struct ivopts_data *data, tree var)
    1229              : {
    1230     45689202 :   basic_block bb;
    1231     45689202 :   tree type = TREE_TYPE (var);
    1232              : 
    1233     45689202 :   if (!POINTER_TYPE_P (type)
    1234     36379246 :       && !INTEGRAL_TYPE_P (type))
    1235              :     return NULL;
    1236              : 
    1237     39853215 :   if (!name_info (data, var)->iv)
    1238              :     {
    1239     18490685 :       bb = gimple_bb (SSA_NAME_DEF_STMT (var));
    1240              : 
    1241     18490685 :       if (!bb
    1242     18490685 :           || !flow_bb_inside_loop_p (data->current_loop, bb))
    1243              :         {
    1244       834144 :           if (POINTER_TYPE_P (type))
    1245       331049 :             type = sizetype;
    1246       834144 :           set_iv (data, var, var, build_int_cst (type, 0), true);
    1247              :         }
    1248              :     }
    1249              : 
    1250     39853215 :   return name_info (data, var)->iv;
    1251              : }
    1252              : 
    1253              : /* Return the first non-invariant ssa var found in EXPR.  */
    1254              : 
    1255              : static tree
    1256      4207865 : extract_single_var_from_expr (tree expr)
    1257              : {
    1258      4207865 :   int i, n;
    1259      4207865 :   tree tmp;
    1260      4207865 :   enum tree_code code;
    1261              : 
    1262      4207865 :   if (!expr || is_gimple_min_invariant (expr))
    1263              :     return NULL;
    1264              : 
    1265       682114 :   code = TREE_CODE (expr);
    1266       682114 :   if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
    1267              :     {
    1268       368250 :       n = TREE_OPERAND_LENGTH (expr);
    1269       736547 :       for (i = 0; i < n; i++)
    1270              :         {
    1271       368297 :           tmp = extract_single_var_from_expr (TREE_OPERAND (expr, i));
    1272              : 
    1273       368297 :           if (tmp)
    1274              :             return tmp;
    1275              :         }
    1276              :     }
    1277       313864 :   return (TREE_CODE (expr) == SSA_NAME) ? expr : NULL;
    1278              : }
    1279              : 
    1280              : /* Finds basic ivs.  */
    1281              : 
    1282              : static bool
    1283       650697 : find_bivs (struct ivopts_data *data)
    1284              : {
    1285       650697 :   gphi *phi;
    1286       650697 :   affine_iv iv;
    1287       650697 :   tree step, type, base, stop;
    1288       650697 :   bool found = false;
    1289       650697 :   class loop *loop = data->current_loop;
    1290       650697 :   gphi_iterator psi;
    1291              : 
    1292      2431303 :   for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
    1293              :     {
    1294      1780606 :       phi = psi.phi ();
    1295              : 
    1296      1780606 :       if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
    1297          252 :         continue;
    1298              : 
    1299      1780354 :       if (virtual_operand_p (PHI_RESULT (phi)))
    1300       427548 :         continue;
    1301              : 
    1302      1352806 :       if (!simple_iv (loop, loop, PHI_RESULT (phi), &iv, true))
    1303       453214 :         continue;
    1304              : 
    1305       899592 :       if (integer_zerop (iv.step))
    1306            0 :         continue;
    1307              : 
    1308       899592 :       step = iv.step;
    1309       899592 :       base = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
    1310              :       /* Stop expanding iv base at the first ssa var referred by iv step.
    1311              :          Ideally we should stop at any ssa var, because that's expensive
    1312              :          and unusual to happen, we just do it on the first one.
    1313              : 
    1314              :          See PR64705 for the rationale.  */
    1315       899592 :       stop = extract_single_var_from_expr (step);
    1316       899592 :       base = expand_simple_operations (base, stop);
    1317       899592 :       if (contains_abnormal_ssa_name_p (base)
    1318       899592 :           || contains_abnormal_ssa_name_p (step))
    1319           11 :         continue;
    1320              : 
    1321       899581 :       type = TREE_TYPE (PHI_RESULT (phi));
    1322       899581 :       base = fold_convert (type, base);
    1323       899581 :       if (step)
    1324              :         {
    1325       899581 :           if (POINTER_TYPE_P (type))
    1326       170776 :             step = convert_to_ptrofftype (step);
    1327              :           else
    1328       728805 :             step = fold_convert (type, step);
    1329              :         }
    1330              : 
    1331       899581 :       set_iv (data, PHI_RESULT (phi), base, step, iv.no_overflow);
    1332       899581 :       found = true;
    1333              :     }
    1334              : 
    1335       650697 :   return found;
    1336              : }
    1337              : 
    1338              : /* Marks basic ivs.  */
    1339              : 
    1340              : static void
    1341       519404 : mark_bivs (struct ivopts_data *data)
    1342              : {
    1343       519404 :   gphi *phi;
    1344       519404 :   gimple *def;
    1345       519404 :   tree var;
    1346       519404 :   struct iv *iv, *incr_iv;
    1347       519404 :   class loop *loop = data->current_loop;
    1348       519404 :   basic_block incr_bb;
    1349       519404 :   gphi_iterator psi;
    1350              : 
    1351       519404 :   data->bivs_not_used_in_addr = 0;
    1352      2022944 :   for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
    1353              :     {
    1354      1503540 :       phi = psi.phi ();
    1355              : 
    1356      1503540 :       iv = get_iv (data, PHI_RESULT (phi));
    1357      1503540 :       if (!iv)
    1358       603959 :         continue;
    1359              : 
    1360       899581 :       var = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
    1361       899581 :       def = SSA_NAME_DEF_STMT (var);
    1362              :       /* Don't mark iv peeled from other one as biv.  */
    1363       899704 :       if (def
    1364       899581 :           && gimple_code (def) == GIMPLE_PHI
    1365       900938 :           && gimple_bb (def) == loop->header)
    1366          123 :         continue;
    1367              : 
    1368       899458 :       incr_iv = get_iv (data, var);
    1369       899458 :       if (!incr_iv)
    1370         1245 :         continue;
    1371              : 
    1372              :       /* If the increment is in the subloop, ignore it.  */
    1373       898213 :       incr_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
    1374       898213 :       if (incr_bb->loop_father != data->current_loop
    1375       898213 :           || (incr_bb->flags & BB_IRREDUCIBLE_LOOP))
    1376            0 :         continue;
    1377              : 
    1378       898213 :       iv->biv_p = true;
    1379       898213 :       incr_iv->biv_p = true;
    1380       898213 :       if (iv->no_overflow)
    1381       601531 :         data->bivs_not_used_in_addr++;
    1382       898213 :       if (incr_iv->no_overflow)
    1383       592837 :         data->bivs_not_used_in_addr++;
    1384              :     }
    1385       519404 : }
    1386              : 
    1387              : /* Checks whether STMT defines a linear induction variable and stores its
    1388              :    parameters to IV.  */
    1389              : 
    1390              : static bool
    1391     13013321 : find_givs_in_stmt_scev (struct ivopts_data *data, gimple *stmt, affine_iv *iv)
    1392              : {
    1393     13013321 :   tree lhs, stop;
    1394     13013321 :   class loop *loop = data->current_loop;
    1395              : 
    1396     13013321 :   iv->base = NULL_TREE;
    1397     13013321 :   iv->step = NULL_TREE;
    1398              : 
    1399     13013321 :   auto assign = dyn_cast<gassign *> (stmt);
    1400     10912154 :   if (!assign)
    1401              :     return false;
    1402              : 
    1403     10912154 :   lhs = gimple_assign_lhs (assign);
    1404     10912154 :   if (TREE_CODE (lhs) != SSA_NAME)
    1405              :     return false;
    1406              : 
    1407     19402056 :   if (!simple_iv (loop, loop_containing_stmt (stmt), lhs, iv, true))
    1408              :     return false;
    1409              : 
    1410              :   /* Stop expanding iv base at the first ssa var referred by iv step.
    1411              :      Ideally we should stop at any ssa var, because that's expensive
    1412              :      and unusual to happen, we just do it on the first one.
    1413              : 
    1414              :      See PR64705 for the rationale.  */
    1415      2939976 :   stop = extract_single_var_from_expr (iv->step);
    1416      2939976 :   iv->base = expand_simple_operations (iv->base, stop);
    1417      2939976 :   if (contains_abnormal_ssa_name_p (iv->base)
    1418      2939976 :       || contains_abnormal_ssa_name_p (iv->step))
    1419              :     return false;
    1420              : 
    1421              :   /* If STMT could throw, then do not consider STMT as defining a GIV.
    1422              :      While this will suppress optimizations, we cannot safely delete this
    1423              :      GIV and associated statements, even if it appears it is not used.  */
    1424      2939972 :   if (stmt_could_throw_p (cfun, stmt))
    1425            8 :     return false;
    1426              : 
    1427              :   return true;
    1428              : }
    1429              : 
    1430              : /* Finds general ivs in statement STMT.  */
    1431              : 
    1432              : static void
    1433     13013321 : find_givs_in_stmt (struct ivopts_data *data, gimple *stmt)
    1434              : {
    1435     13013321 :   affine_iv iv;
    1436              : 
    1437     13013321 :   if (!find_givs_in_stmt_scev (data, stmt, &iv))
    1438              :     return;
    1439              : 
    1440      2939964 :   set_iv (data, gimple_assign_lhs (stmt), iv.base, iv.step, iv.no_overflow);
    1441              : }
    1442              : 
    1443              : /* Finds general ivs in basic block BB.  */
    1444              : 
    1445              : static void
    1446      2892345 : find_givs_in_bb (struct ivopts_data *data, basic_block bb)
    1447              : {
    1448      2892345 :   gimple_stmt_iterator bsi;
    1449              : 
    1450     28523180 :   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
    1451     22738490 :     if (!is_gimple_debug (gsi_stmt (bsi)))
    1452     13013321 :       find_givs_in_stmt (data, gsi_stmt (bsi));
    1453      2892345 : }
    1454              : 
    1455              : /* Finds general ivs.  */
    1456              : 
    1457              : static void
    1458       519404 : find_givs (struct ivopts_data *data, basic_block *body)
    1459              : {
    1460       519404 :   class loop *loop = data->current_loop;
    1461       519404 :   unsigned i;
    1462              : 
    1463      3411749 :   for (i = 0; i < loop->num_nodes; i++)
    1464      2892345 :     find_givs_in_bb (data, body[i]);
    1465       519404 : }
    1466              : 
    1467              : /* For each ssa name defined in LOOP determines whether it is an induction
    1468              :    variable and if so, its initial value and step.  */
    1469              : 
    1470              : static bool
    1471       650697 : find_induction_variables (struct ivopts_data *data, basic_block *body)
    1472              : {
    1473       650697 :   unsigned i;
    1474       650697 :   bitmap_iterator bi;
    1475              : 
    1476       650697 :   if (!find_bivs (data))
    1477              :     return false;
    1478              : 
    1479       519404 :   find_givs (data, body);
    1480       519404 :   mark_bivs (data);
    1481              : 
    1482       519404 :   if (dump_file && (dump_flags & TDF_DETAILS))
    1483              :     {
    1484           72 :       class tree_niter_desc *niter = niter_for_single_dom_exit (data);
    1485              : 
    1486           72 :       if (niter)
    1487              :         {
    1488           56 :           fprintf (dump_file, "  number of iterations ");
    1489           56 :           print_generic_expr (dump_file, niter->niter, TDF_SLIM);
    1490           56 :           if (!integer_zerop (niter->may_be_zero))
    1491              :             {
    1492            2 :               fprintf (dump_file, "; zero if ");
    1493            2 :               print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
    1494              :             }
    1495           56 :           fprintf (dump_file, "\n");
    1496           72 :         };
    1497              : 
    1498           72 :       fprintf (dump_file, "\n<Induction Vars>:\n");
    1499          895 :       EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
    1500              :         {
    1501          823 :           struct version_info *info = ver_info (data, i);
    1502          823 :           if (info->iv && info->iv->step && !integer_zerop (info->iv->step))
    1503          573 :             dump_iv (dump_file, ver_info (data, i)->iv, true, 0);
    1504              :         }
    1505              :     }
    1506              : 
    1507              :   return true;
    1508              : }
    1509              : 
    1510              : /* Records a use of TYPE at *USE_P in STMT whose value is IV in GROUP.
    1511              :    For address type use, ADDR_BASE is the stripped IV base, ADDR_OFFSET
    1512              :    is the const offset stripped from IV base and MEM_TYPE is the type
    1513              :    of the memory being addressed.  For uses of other types, ADDR_BASE
    1514              :    and ADDR_OFFSET are zero by default and MEM_TYPE is NULL_TREE.  */
    1515              : 
    1516              : static struct iv_use *
    1517      2125007 : record_use (struct iv_group *group, tree *use_p, struct iv *iv,
    1518              :             gimple *stmt, enum use_type type, tree mem_type,
    1519              :             tree addr_base, poly_uint64 addr_offset)
    1520              : {
    1521      2125007 :   struct iv_use *use = XCNEW (struct iv_use);
    1522              : 
    1523      2125007 :   use->id = group->vuses.length ();
    1524      2125007 :   use->group_id = group->id;
    1525      2125007 :   use->type = type;
    1526      2125007 :   use->mem_type = mem_type;
    1527      2125007 :   use->iv = iv;
    1528      2125007 :   use->stmt = stmt;
    1529      2125007 :   use->op_p = use_p;
    1530      2125007 :   use->addr_base = addr_base;
    1531      2125007 :   use->addr_offset = addr_offset;
    1532              : 
    1533      2125007 :   group->vuses.safe_push (use);
    1534      2125007 :   return use;
    1535              : }
    1536              : 
    1537              : /* Checks whether OP is a loop-level invariant and if so, records it.
    1538              :    NONLINEAR_USE is true if the invariant is used in a way we do not
    1539              :    handle specially.  */
    1540              : 
    1541              : static void
    1542     23392563 : record_invariant (struct ivopts_data *data, tree op, bool nonlinear_use)
    1543              : {
    1544     23392563 :   basic_block bb;
    1545     23392563 :   struct version_info *info;
    1546              : 
    1547     23392563 :   if (TREE_CODE (op) != SSA_NAME
    1548     23392563 :       || virtual_operand_p (op))
    1549              :     return;
    1550              : 
    1551     22166989 :   bb = gimple_bb (SSA_NAME_DEF_STMT (op));
    1552     22166989 :   if (bb
    1553     22166989 :       && flow_bb_inside_loop_p (data->current_loop, bb))
    1554              :     return;
    1555              : 
    1556      4020145 :   info = name_info (data, op);
    1557      4020145 :   info->name = op;
    1558      4020145 :   info->has_nonlin_use |= nonlinear_use;
    1559      4020145 :   if (!info->inv_id)
    1560      1379947 :     info->inv_id = ++data->max_inv_var_id;
    1561      4020145 :   bitmap_set_bit (data->relevant, SSA_NAME_VERSION (op));
    1562              : }
    1563              : 
    1564              : /* Record a group of TYPE.  */
    1565              : 
    1566              : static struct iv_group *
    1567      1848949 : record_group (struct ivopts_data *data, enum use_type type)
    1568              : {
    1569      1848949 :   struct iv_group *group = XCNEW (struct iv_group);
    1570              : 
    1571      1848949 :   group->id = data->vgroups.length ();
    1572      1848949 :   group->type = type;
    1573      1848949 :   group->related_cands = BITMAP_ALLOC (NULL);
    1574      1848949 :   group->vuses.create (1);
    1575      1848949 :   group->doloop_p = false;
    1576              : 
    1577      1848949 :   data->vgroups.safe_push (group);
    1578      1848949 :   return group;
    1579              : }
    1580              : 
    1581              : /* Record a use of TYPE at *USE_P in STMT whose value is IV in a group.
    1582              :    New group will be created if there is no existing group for the use.
    1583              :    MEM_TYPE is the type of memory being addressed, or NULL if this
    1584              :    isn't an address reference.  */
    1585              : 
    1586              : static struct iv_use *
    1587      2125007 : record_group_use (struct ivopts_data *data, tree *use_p,
    1588              :                   struct iv *iv, gimple *stmt, enum use_type type,
    1589              :                   tree mem_type)
    1590              : {
    1591      2125007 :   tree addr_base = NULL;
    1592      2125007 :   struct iv_group *group = NULL;
    1593      2125007 :   poly_uint64 addr_offset = 0;
    1594              : 
    1595              :   /* Record non address type use in a new group.  */
    1596      2125007 :   if (address_p (type))
    1597              :     {
    1598       873258 :       unsigned int i;
    1599              : 
    1600       873258 :       gcc_assert (POINTER_TYPE_P (TREE_TYPE (iv->base)));
    1601       873258 :       tree addr_toffset;
    1602       873258 :       split_constant_offset (iv->base, &addr_base, &addr_toffset);
    1603       873258 :       addr_offset = int_cst_value (addr_toffset);
    1604      1640834 :       for (i = 0; i < data->vgroups.length (); i++)
    1605              :         {
    1606      1097197 :           struct iv_use *use;
    1607              : 
    1608      1097197 :           group = data->vgroups[i];
    1609      1097197 :           use = group->vuses[0];
    1610      1097197 :           if (!address_p (use->type))
    1611       338308 :             continue;
    1612              : 
    1613              :           /* Check if it has the same stripped base and step.  */
    1614       758889 :           if (operand_equal_p (iv->base_object, use->iv->base_object, 0)
    1615       395843 :               && operand_equal_p (iv->step, use->iv->step, OEP_ASSUME_WRAPV)
    1616      1151561 :               && operand_equal_p (addr_base, use->addr_base, OEP_ASSUME_WRAPV))
    1617              :             break;
    1618              :         }
    1619      1746516 :       if (i == data->vgroups.length ())
    1620       543637 :         group = NULL;
    1621              :     }
    1622              : 
    1623       873258 :   if (!group)
    1624      1795386 :     group = record_group (data, type);
    1625              : 
    1626      2125007 :   return record_use (group, use_p, iv, stmt, type, mem_type,
    1627      2125007 :                      addr_base, addr_offset);
    1628              : }
    1629              : 
    1630              : /* Checks whether the use OP is interesting and if so, records it.  */
    1631              : 
    1632              : static struct iv_use *
    1633      7623276 : find_interesting_uses_op (struct ivopts_data *data, tree op)
    1634              : {
    1635      7623276 :   struct iv *iv;
    1636      7623276 :   gimple *stmt;
    1637      7623276 :   struct iv_use *use;
    1638              : 
    1639      7623276 :   if (TREE_CODE (op) != SSA_NAME)
    1640              :     return NULL;
    1641              : 
    1642      6037191 :   iv = get_iv (data, op);
    1643      6037191 :   if (!iv)
    1644              :     return NULL;
    1645              : 
    1646      2671374 :   if (iv->nonlin_use)
    1647              :     {
    1648       219573 :       gcc_assert (iv->nonlin_use->type == USE_NONLINEAR_EXPR);
    1649              :       return iv->nonlin_use;
    1650              :     }
    1651              : 
    1652      2451801 :   if (integer_zerop (iv->step))
    1653              :     {
    1654      1813272 :       record_invariant (data, op, true);
    1655      1813272 :       return NULL;
    1656              :     }
    1657              : 
    1658       638529 :   stmt = SSA_NAME_DEF_STMT (op);
    1659       638529 :   gcc_assert (gimple_code (stmt) == GIMPLE_PHI || is_gimple_assign (stmt));
    1660              : 
    1661       638529 :   use = record_group_use (data, NULL, iv, stmt, USE_NONLINEAR_EXPR, NULL_TREE);
    1662       638529 :   iv->nonlin_use = use;
    1663       638529 :   return use;
    1664              : }
    1665              : 
    1666              : /* Indicate how compare type iv_use can be handled.  */
    1667              : enum comp_iv_rewrite
    1668              : {
    1669              :   COMP_IV_NA,
    1670              :   /* We may rewrite compare type iv_use by expressing value of the iv_use.  */
    1671              :   COMP_IV_EXPR,
    1672              :   /* We may rewrite compare type iv_uses on both sides of comparison by
    1673              :      expressing value of each iv_use.  */
    1674              :   COMP_IV_EXPR_2,
    1675              :   /* We may rewrite compare type iv_use by expressing value of the iv_use
    1676              :      or by eliminating it with other iv_cand.  */
    1677              :   COMP_IV_ELIM
    1678              : };
    1679              : 
    1680              : /* Given a condition in statement STMT, checks whether it is a compare
    1681              :    of an induction variable and an invariant.  If this is the case,
    1682              :    CONTROL_VAR is set to location of the iv, BOUND to the location of
    1683              :    the invariant, IV_VAR and IV_BOUND are set to the corresponding
    1684              :    induction variable descriptions, and true is returned.  If this is not
    1685              :    the case, CONTROL_VAR and BOUND are set to the arguments of the
    1686              :    condition and false is returned.  */
    1687              : 
    1688              : static enum comp_iv_rewrite
    1689      7608114 : extract_cond_operands (struct ivopts_data *data, gimple *stmt,
    1690              :                        tree **control_var, tree **bound,
    1691              :                        struct iv **iv_var, struct iv **iv_bound)
    1692              : {
    1693              :   /* The objects returned when COND has constant operands.  */
    1694      7608114 :   static struct iv const_iv;
    1695      7608114 :   static tree zero;
    1696      7608114 :   tree *op0 = &zero, *op1 = &zero;
    1697      7608114 :   struct iv *iv0 = &const_iv, *iv1 = &const_iv;
    1698      7608114 :   enum comp_iv_rewrite rewrite_type = COMP_IV_NA;
    1699              : 
    1700      7608114 :   if (gimple_code (stmt) == GIMPLE_COND)
    1701              :     {
    1702      7330462 :       gcond *cond_stmt = as_a <gcond *> (stmt);
    1703      7330462 :       op0 = gimple_cond_lhs_ptr (cond_stmt);
    1704      7330462 :       op1 = gimple_cond_rhs_ptr (cond_stmt);
    1705              :     }
    1706              :   else
    1707              :     {
    1708       277652 :       op0 = gimple_assign_rhs1_ptr (stmt);
    1709       277652 :       op1 = gimple_assign_rhs2_ptr (stmt);
    1710              :     }
    1711              : 
    1712      7608114 :   zero = integer_zero_node;
    1713      7608114 :   const_iv.step = integer_zero_node;
    1714              : 
    1715      7608114 :   if (TREE_CODE (*op0) == SSA_NAME)
    1716      7607954 :     iv0 = get_iv (data, *op0);
    1717      7608114 :   if (TREE_CODE (*op1) == SSA_NAME)
    1718      3377083 :     iv1 = get_iv (data, *op1);
    1719              : 
    1720              :   /* If both sides of comparison are IVs.  We can express ivs on both end.  */
    1721      7608114 :   if (iv0 && iv1 && !integer_zerop (iv0->step) && !integer_zerop (iv1->step))
    1722              :     {
    1723        90419 :       rewrite_type = COMP_IV_EXPR_2;
    1724        90419 :       goto end;
    1725              :     }
    1726              : 
    1727              :   /* If none side of comparison is IV.  */
    1728      5904137 :   if ((!iv0 || integer_zerop (iv0->step))
    1729      8887352 :       && (!iv1 || integer_zerop (iv1->step)))
    1730       976261 :     goto end;
    1731              : 
    1732              :   /* Control variable may be on the other side.  */
    1733      6541434 :   if (!iv0 || integer_zerop (iv0->step))
    1734              :     {
    1735              :       std::swap (op0, op1);
    1736              :       std::swap (iv0, iv1);
    1737              :     }
    1738              :   /* If one side is IV and the other side isn't loop invariant.  */
    1739      6541434 :   if (!iv1)
    1740              :     rewrite_type = COMP_IV_EXPR;
    1741              :   /* If one side is IV and the other side is loop invariant.  */
    1742      5579883 :   else if (!integer_zerop (iv0->step) && integer_zerop (iv1->step))
    1743              :     rewrite_type = COMP_IV_ELIM;
    1744              : 
    1745      7608114 : end:
    1746      7608114 :   if (control_var)
    1747      7608114 :     *control_var = op0;
    1748      7608114 :   if (iv_var)
    1749      1587458 :     *iv_var = iv0;
    1750      7608114 :   if (bound)
    1751      7608114 :     *bound = op1;
    1752      7608114 :   if (iv_bound)
    1753      7608114 :     *iv_bound = iv1;
    1754              : 
    1755      7608114 :   return rewrite_type;
    1756              : }
    1757              : 
    1758              : /* Checks whether the condition in STMT is interesting and if so,
    1759              :    records it.  */
    1760              : 
    1761              : static void
    1762      1587458 : find_interesting_uses_cond (struct ivopts_data *data, gimple *stmt)
    1763              : {
    1764      1587458 :   tree *var_p, *bound_p;
    1765      1587458 :   struct iv *var_iv, *bound_iv;
    1766      1587458 :   enum comp_iv_rewrite ret;
    1767              : 
    1768      1587458 :   ret = extract_cond_operands (data, stmt,
    1769              :                                &var_p, &bound_p, &var_iv, &bound_iv);
    1770      1587458 :   if (ret == COMP_IV_NA)
    1771              :     {
    1772       976261 :       find_interesting_uses_op (data, *var_p);
    1773       976261 :       find_interesting_uses_op (data, *bound_p);
    1774       976261 :       return;
    1775              :     }
    1776              : 
    1777       611197 :   record_group_use (data, var_p, var_iv, stmt, USE_COMPARE, NULL_TREE);
    1778              :   /* Record compare type iv_use for iv on the other side of comparison.  */
    1779       611197 :   if (ret == COMP_IV_EXPR_2)
    1780         2023 :     record_group_use (data, bound_p, bound_iv, stmt, USE_COMPARE, NULL_TREE);
    1781              : }
    1782              : 
    1783              : /* Returns the outermost loop EXPR is obviously invariant in
    1784              :    relative to the loop LOOP, i.e. if all its operands are defined
    1785              :    outside of the returned loop.  Returns NULL if EXPR is not
    1786              :    even obviously invariant in LOOP.  */
    1787              : 
    1788              : class loop *
    1789       383872 : outermost_invariant_loop_for_expr (class loop *loop, tree expr)
    1790              : {
    1791       383872 :   basic_block def_bb;
    1792       383872 :   unsigned i, len;
    1793              : 
    1794       383872 :   if (is_gimple_min_invariant (expr))
    1795        51467 :     return current_loops->tree_root;
    1796              : 
    1797       332405 :   if (TREE_CODE (expr) == SSA_NAME)
    1798              :     {
    1799       197728 :       def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
    1800       197728 :       if (def_bb)
    1801              :         {
    1802       118119 :           if (flow_bb_inside_loop_p (loop, def_bb))
    1803              :             return NULL;
    1804       236222 :           return superloop_at_depth (loop,
    1805       161401 :                                      loop_depth (def_bb->loop_father) + 1);
    1806              :         }
    1807              : 
    1808        79609 :       return current_loops->tree_root;
    1809              :     }
    1810              : 
    1811       134677 :   if (!EXPR_P (expr))
    1812              :     return NULL;
    1813              : 
    1814       134677 :   unsigned maxdepth = 0;
    1815       134677 :   len = TREE_OPERAND_LENGTH (expr);
    1816       350355 :   for (i = 0; i < len; i++)
    1817              :     {
    1818       215702 :       class loop *ivloop;
    1819       215702 :       if (!TREE_OPERAND (expr, i))
    1820            0 :         continue;
    1821              : 
    1822       215702 :       ivloop = outermost_invariant_loop_for_expr (loop, TREE_OPERAND (expr, i));
    1823       215702 :       if (!ivloop)
    1824              :         return NULL;
    1825       559331 :       maxdepth = MAX (maxdepth, loop_depth (ivloop));
    1826              :     }
    1827              : 
    1828       134653 :   return superloop_at_depth (loop, maxdepth);
    1829              : }
    1830              : 
    1831              : /* Returns true if expression EXPR is obviously invariant in LOOP,
    1832              :    i.e. if all its operands are defined outside of the LOOP.  LOOP
    1833              :    should not be the function body.  */
    1834              : 
    1835              : bool
    1836     12595707 : expr_invariant_in_loop_p (class loop *loop, tree expr)
    1837              : {
    1838     12595707 :   basic_block def_bb;
    1839     12595707 :   unsigned i, len;
    1840              : 
    1841     12595707 :   gcc_assert (loop_depth (loop) > 0);
    1842              : 
    1843     12595707 :   if (is_gimple_min_invariant (expr))
    1844              :     return true;
    1845              : 
    1846      8688590 :   if (TREE_CODE (expr) == SSA_NAME)
    1847              :     {
    1848      8271556 :       def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
    1849      8271556 :       if (def_bb
    1850      8271556 :           && flow_bb_inside_loop_p (loop, def_bb))
    1851      4024326 :         return false;
    1852              : 
    1853              :       return true;
    1854              :     }
    1855              : 
    1856       417034 :   if (!EXPR_P (expr))
    1857              :     return false;
    1858              : 
    1859       417031 :   len = TREE_OPERAND_LENGTH (expr);
    1860       924913 :   for (i = 0; i < len; i++)
    1861       544086 :     if (TREE_OPERAND (expr, i)
    1862       544086 :         && !expr_invariant_in_loop_p (loop, TREE_OPERAND (expr, i)))
    1863              :       return false;
    1864              : 
    1865              :   return true;
    1866              : }
    1867              : 
    1868              : /* Given expression EXPR which computes inductive values with respect
    1869              :    to loop recorded in DATA, this function returns biv from which EXPR
    1870              :    is derived by tracing definition chains of ssa variables in EXPR.  */
    1871              : 
    1872              : static struct iv*
    1873       883107 : find_deriving_biv_for_expr (struct ivopts_data *data, tree expr)
    1874              : {
    1875      1428858 :   struct iv *iv;
    1876      1428858 :   unsigned i, n;
    1877      1428858 :   tree e2, e1;
    1878      1428858 :   enum tree_code code;
    1879      1428858 :   gimple *stmt;
    1880              : 
    1881      1428858 :   if (expr == NULL_TREE)
    1882              :     return NULL;
    1883              : 
    1884      1428610 :   if (is_gimple_min_invariant (expr))
    1885              :     return NULL;
    1886              : 
    1887      1140632 :   code = TREE_CODE (expr);
    1888      1140632 :   if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
    1889              :     {
    1890        23096 :       n = TREE_OPERAND_LENGTH (expr);
    1891        24808 :       for (i = 0; i < n; i++)
    1892              :         {
    1893        24407 :           iv = find_deriving_biv_for_expr (data, TREE_OPERAND (expr, i));
    1894        24407 :           if (iv)
    1895              :             return iv;
    1896              :         }
    1897              :     }
    1898              : 
    1899              :   /* Stop if it's not ssa name.  */
    1900      1117937 :   if (code != SSA_NAME)
    1901              :     return NULL;
    1902              : 
    1903      1117009 :   iv = get_iv (data, expr);
    1904      1117009 :   if (!iv || integer_zerop (iv->step))
    1905              :     return NULL;
    1906      1069209 :   else if (iv->biv_p)
    1907              :     return iv;
    1908              : 
    1909       795217 :   stmt = SSA_NAME_DEF_STMT (expr);
    1910       795217 :   if (gphi *phi = dyn_cast <gphi *> (stmt))
    1911              :     {
    1912           59 :       ssa_op_iter iter;
    1913           59 :       use_operand_p use_p;
    1914           59 :       basic_block phi_bb = gimple_bb (phi);
    1915              : 
    1916              :       /* Skip loop header PHI that doesn't define biv.  */
    1917           59 :       if (phi_bb->loop_father == data->current_loop)
    1918              :         return NULL;
    1919              : 
    1920            0 :       if (virtual_operand_p (gimple_phi_result (phi)))
    1921              :         return NULL;
    1922              : 
    1923            0 :       FOR_EACH_PHI_ARG (use_p, phi, iter, SSA_OP_USE)
    1924              :         {
    1925            0 :           tree use = USE_FROM_PTR (use_p);
    1926            0 :           iv = find_deriving_biv_for_expr (data, use);
    1927            0 :           if (iv)
    1928              :             return iv;
    1929              :         }
    1930              :       return NULL;
    1931              :     }
    1932       795158 :   auto assign = dyn_cast<gassign *> (stmt);
    1933       795158 :   if (!assign)
    1934              :     return NULL;
    1935              : 
    1936       795158 :   e1 = gimple_assign_rhs1 (assign);
    1937       795158 :   code = gimple_assign_rhs_code (assign);
    1938       795158 :   if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
    1939              :     return find_deriving_biv_for_expr (data, e1);
    1940              : 
    1941       786277 :   switch (code)
    1942              :     {
    1943       583534 :     case MULT_EXPR:
    1944       583534 :     case PLUS_EXPR:
    1945       583534 :     case MINUS_EXPR:
    1946       583534 :     case POINTER_PLUS_EXPR:
    1947              :       /* Increments, decrements and multiplications by a constant
    1948              :          are simple.  */
    1949       583534 :       e2 = gimple_assign_rhs2 (stmt);
    1950       583534 :       iv = find_deriving_biv_for_expr (data, e2);
    1951       583534 :       if (iv)
    1952              :         return iv;
    1953              :       gcc_fallthrough ();
    1954              : 
    1955              :     CASE_CONVERT:
    1956              :       /* Casts are simple.  */
    1957              :       return find_deriving_biv_for_expr (data, e1);
    1958              : 
    1959              :     default:
    1960              :       break;
    1961              :     }
    1962              : 
    1963              :   return NULL;
    1964              : }
    1965              : 
    1966              : /* Record BIV, its predecessor and successor that they are used in
    1967              :    address type uses.  */
    1968              : 
    1969              : static void
    1970       602082 : record_biv_for_address_use (struct ivopts_data *data, struct iv *biv)
    1971              : {
    1972       602082 :   unsigned i;
    1973       602082 :   tree type, base_1, base_2;
    1974       602082 :   bitmap_iterator bi;
    1975              : 
    1976       600908 :   if (!biv || !biv->biv_p || integer_zerop (biv->step)
    1977      1202990 :       || biv->have_address_use || !biv->no_overflow)
    1978       331695 :     return;
    1979              : 
    1980       537218 :   type = TREE_TYPE (biv->base);
    1981       537218 :   if (!INTEGRAL_TYPE_P (type))
    1982              :     return;
    1983              : 
    1984       270387 :   biv->have_address_use = true;
    1985       270387 :   data->bivs_not_used_in_addr--;
    1986       270387 :   base_1 = fold_build2 (PLUS_EXPR, type, biv->base, biv->step);
    1987      2478022 :   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
    1988              :     {
    1989      2207635 :       struct iv *iv = ver_info (data, i)->iv;
    1990              : 
    1991      1992307 :       if (!iv || !iv->biv_p || integer_zerop (iv->step)
    1992      3128275 :           || iv->have_address_use || !iv->no_overflow)
    1993      1909929 :         continue;
    1994              : 
    1995       297706 :       if (type != TREE_TYPE (iv->base)
    1996       297706 :           || !INTEGRAL_TYPE_P (TREE_TYPE (iv->base)))
    1997        30507 :         continue;
    1998              : 
    1999       267199 :       if (!operand_equal_p (biv->step, iv->step, 0))
    2000         5997 :         continue;
    2001              : 
    2002       261202 :       base_2 = fold_build2 (PLUS_EXPR, type, iv->base, iv->step);
    2003       261202 :       if (operand_equal_p (base_1, iv->base, 0)
    2004       261202 :           || operand_equal_p (base_2, biv->base, 0))
    2005              :         {
    2006       235235 :           iv->have_address_use = true;
    2007       235235 :           data->bivs_not_used_in_addr--;
    2008              :         }
    2009              :     }
    2010              : }
    2011              : 
    2012              : /* Cumulates the steps of indices into DATA and replaces their values with the
    2013              :    initial ones.  Returns false when the value of the index cannot be determined.
    2014              :    Callback for for_each_index.  */
    2015              : 
    2016              : struct ifs_ivopts_data
    2017              : {
    2018              :   struct ivopts_data *ivopts_data;
    2019              :   gimple *stmt;
    2020              :   tree step;
    2021              : };
    2022              : 
    2023              : static bool
    2024      2309285 : idx_find_step (tree base, tree *idx, void *data)
    2025              : {
    2026      2309285 :   struct ifs_ivopts_data *dta = (struct ifs_ivopts_data *) data;
    2027      2309285 :   struct iv *iv;
    2028      2309285 :   bool use_overflow_semantics = false;
    2029      2309285 :   tree step, iv_base, iv_step, lbound, off;
    2030      2309285 :   class loop *loop = dta->ivopts_data->current_loop;
    2031              : 
    2032              :   /* If base is a component ref, require that the offset of the reference
    2033              :      be invariant.  */
    2034      2309285 :   if (TREE_CODE (base) == COMPONENT_REF)
    2035              :     {
    2036           78 :       off = component_ref_field_offset (base);
    2037           78 :       return expr_invariant_in_loop_p (loop, off);
    2038              :     }
    2039              : 
    2040              :   /* If base is array, first check whether we will be able to move the
    2041              :      reference out of the loop (in order to take its address in strength
    2042              :      reduction).  In order for this to work we need both lower bound
    2043              :      and step to be loop invariants.  */
    2044      2309207 :   if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
    2045              :     {
    2046              :       /* Moreover, for a range, the size needs to be invariant as well.  */
    2047       563022 :       if (TREE_CODE (base) == ARRAY_RANGE_REF
    2048       563022 :           && !expr_invariant_in_loop_p (loop, TYPE_SIZE (TREE_TYPE (base))))
    2049              :         return false;
    2050              : 
    2051       563022 :       step = array_ref_element_size (base);
    2052       563022 :       lbound = array_ref_low_bound (base);
    2053              : 
    2054       563022 :       if (!expr_invariant_in_loop_p (loop, step)
    2055       563022 :           || !expr_invariant_in_loop_p (loop, lbound))
    2056              :         return false;
    2057              :     }
    2058              : 
    2059      2309201 :   if (TREE_CODE (*idx) != SSA_NAME)
    2060              :     return true;
    2061              : 
    2062      1865331 :   iv = get_iv (dta->ivopts_data, *idx);
    2063      1865331 :   if (!iv)
    2064              :     return false;
    2065              : 
    2066              :   /* XXX  We produce for a base of *D42 with iv->base being &x[0]
    2067              :           *&x[0], which is not folded and does not trigger the
    2068              :           ARRAY_REF path below.  */
    2069      1214118 :   *idx = iv->base;
    2070              : 
    2071      1214118 :   if (integer_zerop (iv->step))
    2072              :     return true;
    2073              : 
    2074       889536 :   if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
    2075              :     {
    2076       314064 :       step = array_ref_element_size (base);
    2077              : 
    2078              :       /* We only handle addresses whose step is an integer constant.  */
    2079       314064 :       if (TREE_CODE (step) != INTEGER_CST)
    2080              :         return false;
    2081              :     }
    2082              :   else
    2083              :     /* The step for pointer arithmetics already is 1 byte.  */
    2084       575472 :     step = size_one_node;
    2085              : 
    2086       889279 :   iv_base = iv->base;
    2087       889279 :   iv_step = iv->step;
    2088       889279 :   if (iv->no_overflow && nowrap_type_p (TREE_TYPE (iv_step)))
    2089              :     use_overflow_semantics = true;
    2090              : 
    2091       889279 :   if (!convert_affine_scev (dta->ivopts_data->current_loop,
    2092              :                             sizetype, &iv_base, &iv_step, dta->stmt,
    2093              :                             use_overflow_semantics))
    2094              :     {
    2095              :       /* The index might wrap.  */
    2096              :       return false;
    2097              :     }
    2098              : 
    2099       886009 :   step = fold_build2 (MULT_EXPR, sizetype, step, iv_step);
    2100       886009 :   dta->step = fold_build2 (PLUS_EXPR, sizetype, dta->step, step);
    2101              : 
    2102       886009 :   if (dta->ivopts_data->bivs_not_used_in_addr)
    2103              :     {
    2104       602082 :       if (!iv->biv_p)
    2105       275166 :         iv = find_deriving_biv_for_expr (dta->ivopts_data, iv->ssa_name);
    2106              : 
    2107       602082 :       record_biv_for_address_use (dta->ivopts_data, iv);
    2108              :     }
    2109              :   return true;
    2110              : }
    2111              : 
    2112              : /* Records use in index IDX.  Callback for for_each_index.  Ivopts data
    2113              :    object is passed to it in DATA.  */
    2114              : 
    2115              : static bool
    2116      1939229 : idx_record_use (tree base, tree *idx,
    2117              :                 void *vdata)
    2118              : {
    2119      1939229 :   struct ivopts_data *data = (struct ivopts_data *) vdata;
    2120      1939229 :   find_interesting_uses_op (data, *idx);
    2121      1939229 :   if (TREE_CODE (base) == ARRAY_REF || TREE_CODE (base) == ARRAY_RANGE_REF)
    2122              :     {
    2123       312281 :       if (TREE_OPERAND (base, 2))
    2124         5470 :         find_interesting_uses_op (data, TREE_OPERAND (base, 2));
    2125       312281 :       if (TREE_OPERAND (base, 3))
    2126        11482 :         find_interesting_uses_op (data, TREE_OPERAND (base, 3));
    2127              :     }
    2128      1939229 :   return true;
    2129              : }
    2130              : 
    2131              : /* If we can prove that TOP = cst * BOT for some constant cst,
    2132              :    store cst to MUL and return true.  Otherwise return false.
    2133              :    The returned value is always sign-extended, regardless of the
    2134              :    signedness of TOP and BOT.  */
    2135              : 
    2136              : static bool
    2137     17467830 : constant_multiple_of (tree top, tree bot, widest_int *mul,
    2138              :                       struct ivopts_data *data)
    2139              : {
    2140     34935660 :   aff_tree aff_top, aff_bot;
    2141     17467830 :   tree_to_aff_combination_expand (top, TREE_TYPE (top), &aff_top,
    2142              :                                   &data->name_expansion_cache);
    2143     17467830 :   tree_to_aff_combination_expand (bot, TREE_TYPE (bot), &aff_bot,
    2144              :                                   &data->name_expansion_cache);
    2145              : 
    2146     17467830 :   poly_widest_int poly_mul;
    2147     17467830 :   if (aff_combination_constant_multiple_p (&aff_top, &aff_bot, &poly_mul)
    2148     17467830 :       && poly_mul.is_constant (mul))
    2149     14435156 :     return true;
    2150              : 
    2151              :   return false;
    2152     17467830 : }
    2153              : 
    2154              : /* Return true if memory reference REF with step STEP may be unaligned.  */
    2155              : 
    2156              : static bool
    2157            0 : may_be_unaligned_p (tree ref, tree step)
    2158              : {
    2159              :   /* TARGET_MEM_REFs are translated directly to valid MEMs on the target,
    2160              :      thus they are not misaligned.  */
    2161            0 :   if (TREE_CODE (ref) == TARGET_MEM_REF)
    2162              :     return false;
    2163              : 
    2164            0 :   unsigned int align = TYPE_ALIGN (TREE_TYPE (ref));
    2165            0 :   if (GET_MODE_ALIGNMENT (TYPE_MODE (TREE_TYPE (ref))) > align)
    2166            0 :     align = GET_MODE_ALIGNMENT (TYPE_MODE (TREE_TYPE (ref)));
    2167              : 
    2168            0 :   unsigned HOST_WIDE_INT bitpos;
    2169            0 :   unsigned int ref_align;
    2170            0 :   get_object_alignment_1 (ref, &ref_align, &bitpos);
    2171            0 :   if (ref_align < align
    2172            0 :       || (bitpos % align) != 0
    2173            0 :       || (bitpos % BITS_PER_UNIT) != 0)
    2174              :     return true;
    2175              : 
    2176            0 :   unsigned int trailing_zeros = tree_ctz (step);
    2177            0 :   if (trailing_zeros < HOST_BITS_PER_INT
    2178            0 :       && (1U << trailing_zeros) * BITS_PER_UNIT < align)
    2179            0 :     return true;
    2180              : 
    2181              :   return false;
    2182              : }
    2183              : 
    2184              : /* Return true if EXPR may be non-addressable.   */
    2185              : 
    2186              : bool
    2187     13481224 : may_be_nonaddressable_p (tree expr)
    2188              : {
    2189     14545621 :   switch (TREE_CODE (expr))
    2190              :     {
    2191      9649296 :     case VAR_DECL:
    2192              :       /* Check if it's a register variable.  */
    2193      9649296 :       return DECL_HARD_REGISTER (expr);
    2194              : 
    2195              :     case TARGET_MEM_REF:
    2196              :       /* TARGET_MEM_REFs are translated directly to valid MEMs on the
    2197              :          target, thus they are always addressable.  */
    2198              :       return false;
    2199              : 
    2200      2090890 :     case MEM_REF:
    2201              :       /* Likewise for MEM_REFs, modulo the storage order.  */
    2202      2090890 :       return REF_REVERSE_STORAGE_ORDER (expr);
    2203              : 
    2204           89 :     case BIT_FIELD_REF:
    2205           89 :       if (REF_REVERSE_STORAGE_ORDER (expr))
    2206              :         return true;
    2207           89 :       return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
    2208              : 
    2209      1274136 :     case COMPONENT_REF:
    2210      1274136 :       if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (expr, 0))))
    2211              :         return true;
    2212      1274123 :       return DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1))
    2213      1274123 :              || may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
    2214              : 
    2215       927081 :     case ARRAY_REF:
    2216       927081 :     case ARRAY_RANGE_REF:
    2217       927081 :       if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (expr, 0))))
    2218              :         return true;
    2219       927081 :       return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
    2220              : 
    2221        25673 :     case VIEW_CONVERT_EXPR:
    2222              :       /* This kind of view-conversions may wrap non-addressable objects
    2223              :          and make them look addressable.  After some processing the
    2224              :          non-addressability may be uncovered again, causing ADDR_EXPRs
    2225              :          of inappropriate objects to be built.  */
    2226        25673 :       if (is_gimple_reg (TREE_OPERAND (expr, 0))
    2227        25673 :           || !is_gimple_addressable (TREE_OPERAND (expr, 0)))
    2228              :         return true;
    2229        25663 :       return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
    2230              : 
    2231       111564 :     case REALPART_EXPR:
    2232       111564 :     case IMAGPART_EXPR:
    2233       111564 :       return may_be_nonaddressable_p (TREE_OPERAND (expr, 0));
    2234              : 
    2235              :     CASE_CONVERT:
    2236              :       return true;
    2237              : 
    2238              :     default:
    2239              :       break;
    2240              :     }
    2241              : 
    2242              :   return false;
    2243              : }
    2244              : 
    2245              : /* Finds addresses in *OP_P inside STMT.  */
    2246              : 
    2247              : static void
    2248      2830551 : find_interesting_uses_address (struct ivopts_data *data, gimple *stmt,
    2249              :                                tree *op_p)
    2250              : {
    2251      2830551 :   tree base = *op_p, step = size_zero_node;
    2252      2830551 :   struct iv *civ;
    2253      2830551 :   struct ifs_ivopts_data ifs_ivopts_data;
    2254              : 
    2255              :   /* Do not play with volatile memory references.  A bit too conservative,
    2256              :      perhaps, but safe.  */
    2257      5661102 :   if (gimple_has_volatile_ops (stmt))
    2258        66258 :     goto fail;
    2259              : 
    2260              :   /* Ignore bitfields for now.  Not really something terribly complicated
    2261              :      to handle.  TODO.  */
    2262      2764293 :   if (TREE_CODE (base) == BIT_FIELD_REF)
    2263        95029 :     goto fail;
    2264              : 
    2265      2669264 :   base = unshare_expr (base);
    2266              : 
    2267      2669264 :   if (TREE_CODE (base) == TARGET_MEM_REF)
    2268              :     {
    2269       316114 :       tree type = build_pointer_type (TREE_TYPE (base));
    2270       316114 :       tree astep;
    2271              : 
    2272       316114 :       if (TMR_BASE (base)
    2273       316114 :           && TREE_CODE (TMR_BASE (base)) == SSA_NAME)
    2274              :         {
    2275       293884 :           civ = get_iv (data, TMR_BASE (base));
    2276       293884 :           if (!civ)
    2277       259103 :             goto fail;
    2278              : 
    2279        34781 :           TMR_BASE (base) = civ->base;
    2280        34781 :           step = civ->step;
    2281              :         }
    2282        57011 :       if (TMR_INDEX2 (base)
    2283        57011 :           && TREE_CODE (TMR_INDEX2 (base)) == SSA_NAME)
    2284              :         {
    2285        14006 :           civ = get_iv (data, TMR_INDEX2 (base));
    2286        14006 :           if (!civ)
    2287         5132 :             goto fail;
    2288              : 
    2289         8874 :           TMR_INDEX2 (base) = civ->base;
    2290         8874 :           step = civ->step;
    2291              :         }
    2292        51879 :       if (TMR_INDEX (base)
    2293        51879 :           && TREE_CODE (TMR_INDEX (base)) == SSA_NAME)
    2294              :         {
    2295        51879 :           civ = get_iv (data, TMR_INDEX (base));
    2296        51879 :           if (!civ)
    2297        51879 :             goto fail;
    2298              : 
    2299            0 :           TMR_INDEX (base) = civ->base;
    2300            0 :           astep = civ->step;
    2301              : 
    2302            0 :           if (astep)
    2303              :             {
    2304            0 :               if (TMR_STEP (base))
    2305            0 :                 astep = fold_build2 (MULT_EXPR, type, TMR_STEP (base), astep);
    2306              : 
    2307            0 :               step = fold_build2 (PLUS_EXPR, type, step, astep);
    2308              :             }
    2309              :         }
    2310              : 
    2311            0 :       if (integer_zerop (step))
    2312            0 :         goto fail;
    2313            0 :       base = tree_mem_ref_addr (type, base);
    2314              :     }
    2315              :   else
    2316              :     {
    2317      2353150 :       ifs_ivopts_data.ivopts_data = data;
    2318      2353150 :       ifs_ivopts_data.stmt = stmt;
    2319      2353150 :       ifs_ivopts_data.step = size_zero_node;
    2320      2353150 :       if (!for_each_index (&base, idx_find_step, &ifs_ivopts_data)
    2321      2353150 :           || integer_zerop (ifs_ivopts_data.step))
    2322      1468940 :         goto fail;
    2323       884210 :       step = ifs_ivopts_data.step;
    2324              : 
    2325              :       /* Check that the base expression is addressable.  This needs
    2326              :          to be done after substituting bases of IVs into it.  */
    2327       884210 :       if (may_be_nonaddressable_p (base))
    2328          791 :         goto fail;
    2329              : 
    2330              :       /* Moreover, on strict alignment platforms, check that it is
    2331              :          sufficiently aligned.  */
    2332       883419 :       if (STRICT_ALIGNMENT && may_be_unaligned_p (base, step))
    2333              :         goto fail;
    2334              : 
    2335       883419 :       base = build_fold_addr_expr (base);
    2336              : 
    2337              :       /* Substituting bases of IVs into the base expression might
    2338              :          have caused folding opportunities.  */
    2339       883419 :       if (TREE_CODE (base) == ADDR_EXPR)
    2340              :         {
    2341       468181 :           tree *ref = &TREE_OPERAND (base, 0);
    2342      1601444 :           while (handled_component_p (*ref))
    2343       665082 :             ref = &TREE_OPERAND (*ref, 0);
    2344       468181 :           if (TREE_CODE (*ref) == MEM_REF)
    2345              :             {
    2346       298363 :               tree tem = fold_binary (MEM_REF, TREE_TYPE (*ref),
    2347              :                                       TREE_OPERAND (*ref, 0),
    2348              :                                       TREE_OPERAND (*ref, 1));
    2349       298363 :               if (tem)
    2350            0 :                 *ref = tem;
    2351              :             }
    2352              :         }
    2353              :     }
    2354              : 
    2355       883419 :   civ = alloc_iv (data, base, step);
    2356              :   /* Fail if base object of this memory reference is unknown.  */
    2357       883419 :   if (civ->base_object == NULL_TREE)
    2358        10891 :     goto fail;
    2359              : 
    2360       872528 :   record_group_use (data, op_p, civ, stmt, USE_REF_ADDRESS, TREE_TYPE (*op_p));
    2361       872528 :   return;
    2362              : 
    2363      1958023 : fail:
    2364      1958023 :   for_each_index (op_p, idx_record_use, data);
    2365              : }
    2366              : 
    2367              : /* Finds and records invariants used in STMT.  */
    2368              : 
    2369              : static void
    2370     15973686 : find_invariants_stmt (struct ivopts_data *data, gimple *stmt)
    2371              : {
    2372     15973686 :   ssa_op_iter iter;
    2373     15973686 :   use_operand_p use_p;
    2374     15973686 :   tree op;
    2375              : 
    2376     53128528 :   FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
    2377              :     {
    2378     21181156 :       op = USE_FROM_PTR (use_p);
    2379     21181156 :       record_invariant (data, op, false);
    2380              :     }
    2381     15973686 : }
    2382              : 
    2383              : /* CALL calls an internal function.  If operand *OP_P will become an
    2384              :    address when the call is expanded, return the type of the memory
    2385              :    being addressed, otherwise return null.  */
    2386              : 
    2387              : static tree
    2388         4902 : get_mem_type_for_internal_fn (gcall *call, tree *op_p)
    2389              : {
    2390         4902 :   switch (gimple_call_internal_fn (call))
    2391              :     {
    2392          319 :     case IFN_MASK_LOAD:
    2393          319 :     case IFN_MASK_LOAD_LANES:
    2394          319 :     case IFN_MASK_LEN_LOAD_LANES:
    2395          319 :     case IFN_LEN_LOAD:
    2396          319 :     case IFN_MASK_LEN_LOAD:
    2397          319 :       if (op_p == gimple_call_arg_ptr (call, 0))
    2398          319 :         return TREE_TYPE (gimple_call_lhs (call));
    2399              :       return NULL_TREE;
    2400              : 
    2401          411 :     case IFN_MASK_STORE:
    2402          411 :     case IFN_MASK_STORE_LANES:
    2403          411 :     case IFN_MASK_LEN_STORE_LANES:
    2404          411 :     case IFN_LEN_STORE:
    2405          411 :     case IFN_MASK_LEN_STORE:
    2406          411 :       {
    2407          411 :         if (op_p == gimple_call_arg_ptr (call, 0))
    2408              :           {
    2409          411 :             internal_fn ifn = gimple_call_internal_fn (call);
    2410          411 :             int index = internal_fn_stored_value_index (ifn);
    2411          411 :             return TREE_TYPE (gimple_call_arg (call, index));
    2412              :           }
    2413              :         return NULL_TREE;
    2414              :       }
    2415              : 
    2416              :     default:
    2417              :       return NULL_TREE;
    2418              :     }
    2419              : }
    2420              : 
    2421              : /* IV is a (non-address) iv that describes operand *OP_P of STMT.
    2422              :    Return true if the operand will become an address when STMT
    2423              :    is expanded and record the associated address use if so.  */
    2424              : 
    2425              : static bool
    2426      1806312 : find_address_like_use (struct ivopts_data *data, gimple *stmt, tree *op_p,
    2427              :                        struct iv *iv)
    2428              : {
    2429              :   /* Fail if base object of this memory reference is unknown.  */
    2430      1806312 :   if (iv->base_object == NULL_TREE)
    2431              :     return false;
    2432              : 
    2433       690508 :   tree mem_type = NULL_TREE;
    2434       690508 :   if (gcall *call = dyn_cast <gcall *> (stmt))
    2435       127705 :     if (gimple_call_internal_p (call))
    2436         4902 :       mem_type = get_mem_type_for_internal_fn (call, op_p);
    2437         4902 :   if (mem_type)
    2438              :     {
    2439          730 :       iv = alloc_iv (data, iv->base, iv->step);
    2440          730 :       record_group_use (data, op_p, iv, stmt, USE_PTR_ADDRESS, mem_type);
    2441          730 :       return true;
    2442              :     }
    2443              :   return false;
    2444              : }
    2445              : 
    2446              : /* Finds interesting uses of induction variables in the statement STMT.  */
    2447              : 
    2448              : static void
    2449     15973686 : find_interesting_uses_stmt (struct ivopts_data *data, gimple *stmt)
    2450              : {
    2451     15973686 :   struct iv *iv;
    2452     15973686 :   tree op, *lhs, *rhs;
    2453     15973686 :   ssa_op_iter iter;
    2454     15973686 :   use_operand_p use_p;
    2455     15973686 :   enum tree_code code;
    2456              : 
    2457     15973686 :   find_invariants_stmt (data, stmt);
    2458              : 
    2459     15973686 :   if (gimple_code (stmt) == GIMPLE_COND)
    2460              :     {
    2461      1505110 :       find_interesting_uses_cond (data, stmt);
    2462      9329202 :       return;
    2463              :     }
    2464              : 
    2465     14468576 :   if (auto assign = dyn_cast<gassign *> (stmt))
    2466              :     {
    2467     10912154 :       lhs = gimple_assign_lhs_ptr (assign);
    2468     10912154 :       rhs = gimple_assign_rhs1_ptr (assign);
    2469              : 
    2470     10912154 :       if (TREE_CODE (*lhs) == SSA_NAME)
    2471              :         {
    2472              :           /* If the statement defines an induction variable, the uses are not
    2473              :              interesting by themselves.  */
    2474              : 
    2475      9701028 :           iv = get_iv (data, *lhs);
    2476              : 
    2477      9701028 :           if (iv && !integer_zerop (iv->step))
    2478              :             return;
    2479              :         }
    2480              : 
    2481      8506468 :       code = gimple_assign_rhs_code (assign);
    2482      8506468 :       if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
    2483      8506468 :           && (REFERENCE_CLASS_P (*rhs)
    2484      1364634 :               || is_gimple_val (*rhs)))
    2485              :         {
    2486      2931367 :           if (REFERENCE_CLASS_P (*rhs))
    2487      1776402 :             find_interesting_uses_address (data, assign, rhs);
    2488              :           else
    2489      1154965 :             find_interesting_uses_op (data, *rhs);
    2490              : 
    2491      2931367 :           if (REFERENCE_CLASS_P (*lhs))
    2492      1054149 :             find_interesting_uses_address (data, assign, lhs);
    2493              :           return;
    2494              :         }
    2495      5575101 :       else if (TREE_CODE_CLASS (code) == tcc_comparison)
    2496              :         {
    2497        82348 :           find_interesting_uses_cond (data, assign);
    2498        82348 :           return;
    2499              :         }
    2500              : 
    2501              :       /* TODO -- we should also handle address uses of type
    2502              : 
    2503              :          memory = call (whatever);
    2504              : 
    2505              :          and
    2506              : 
    2507              :          call (memory).  */
    2508              :     }
    2509              : 
    2510      9049175 :   if (gimple_code (stmt) == GIMPLE_PHI
    2511      9049175 :       && gimple_bb (stmt) == data->current_loop->header)
    2512              :     {
    2513      1503540 :       iv = get_iv (data, PHI_RESULT (stmt));
    2514              : 
    2515      1503540 :       if (iv && !integer_zerop (iv->step))
    2516              :         return;
    2517              :     }
    2518              : 
    2519     27375296 :   FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, iter, SSA_OP_USE)
    2520              :     {
    2521     11076108 :       op = USE_FROM_PTR (use_p);
    2522              : 
    2523     11076108 :       if (TREE_CODE (op) != SSA_NAME)
    2524       543520 :         continue;
    2525              : 
    2526     10532588 :       iv = get_iv (data, op);
    2527     10532588 :       if (!iv)
    2528      8726276 :         continue;
    2529              : 
    2530      1806312 :       if (!find_address_like_use (data, stmt, use_p->use, iv))
    2531      1805582 :         find_interesting_uses_op (data, op);
    2532              :     }
    2533              : }
    2534              : 
    2535              : /* Finds interesting uses of induction variables outside of loops
    2536              :    on loop exit edge EXIT.  */
    2537              : 
    2538              : static void
    2539       915175 : find_interesting_uses_outside (struct ivopts_data *data, edge exit)
    2540              : {
    2541       915175 :   gphi *phi;
    2542       915175 :   gphi_iterator psi;
    2543       915175 :   tree def;
    2544              : 
    2545      2041417 :   for (psi = gsi_start_phis (exit->dest); !gsi_end_p (psi); gsi_next (&psi))
    2546              :     {
    2547      1126242 :       phi = psi.phi ();
    2548      1126242 :       def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
    2549      2159181 :       if (!virtual_operand_p (def))
    2550       548238 :         find_interesting_uses_op (data, def);
    2551              :     }
    2552       915175 : }
    2553              : 
    2554              : /* Return TRUE if OFFSET is within the range of [base + offset] addressing
    2555              :    mode for memory reference represented by USE.  */
    2556              : 
    2557              : static GTY (()) vec<rtx, va_gc> *addr_list;
    2558              : 
    2559              : static bool
    2560       218075 : addr_offset_valid_p (struct iv_use *use, poly_int64 offset)
    2561              : {
    2562       218075 :   rtx reg, addr;
    2563       218075 :   unsigned list_index;
    2564       218075 :   addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (use->iv->base));
    2565       218075 :   machine_mode addr_mode, mem_mode = TYPE_MODE (use->mem_type);
    2566              : 
    2567       218075 :   list_index = (unsigned) as * MAX_MACHINE_MODE + (unsigned) mem_mode;
    2568       218075 :   if (list_index >= vec_safe_length (addr_list))
    2569        10355 :     vec_safe_grow_cleared (addr_list, list_index + MAX_MACHINE_MODE, true);
    2570              : 
    2571       218075 :   addr = (*addr_list)[list_index];
    2572       218075 :   if (!addr)
    2573              :     {
    2574        13474 :       addr_mode = targetm.addr_space.address_mode (as);
    2575        13474 :       reg = gen_raw_REG (addr_mode, LAST_VIRTUAL_REGISTER + 1);
    2576        13474 :       addr = gen_rtx_fmt_ee (PLUS, addr_mode, reg, NULL_RTX);
    2577        13474 :       (*addr_list)[list_index] = addr;
    2578              :     }
    2579              :   else
    2580       204601 :     addr_mode = GET_MODE (addr);
    2581              : 
    2582       218075 :   XEXP (addr, 1) = gen_int_mode (offset, addr_mode);
    2583       218075 :   return (memory_address_addr_space_p (mem_mode, addr, as));
    2584              : }
    2585              : 
    2586              : /* Comparison function to sort group in ascending order of addr_offset.  */
    2587              : 
    2588              : static int
    2589      3140237 : group_compare_offset (const void *a, const void *b)
    2590              : {
    2591      3140237 :   const struct iv_use *const *u1 = (const struct iv_use *const *) a;
    2592      3140237 :   const struct iv_use *const *u2 = (const struct iv_use *const *) b;
    2593              : 
    2594      3140237 :   return compare_sizes_for_sort ((*u1)->addr_offset, (*u2)->addr_offset);
    2595              : }
    2596              : 
    2597              : /* Check if small groups should be split.  Return true if no group
    2598              :    contains more than two uses with distinct addr_offsets.  Return
    2599              :    false otherwise.  We want to split such groups because:
    2600              : 
    2601              :      1) Small groups don't have much benefit and may interfere with
    2602              :         general candidate selection.
    2603              :      2) Size for problem with only small groups is usually small and
    2604              :         general algorithm can handle it well.
    2605              : 
    2606              :    TODO -- Above claim may not hold when we want to merge memory
    2607              :    accesses with conseuctive addresses.  */
    2608              : 
    2609              : static bool
    2610       519404 : split_small_address_groups_p (struct ivopts_data *data)
    2611              : {
    2612       519404 :   unsigned int i, j, distinct = 1;
    2613       519404 :   struct iv_use *pre;
    2614       519404 :   struct iv_group *group;
    2615              : 
    2616      2152667 :   for (i = 0; i < data->vgroups.length (); i++)
    2617              :     {
    2618      1633263 :       group = data->vgroups[i];
    2619      1633263 :       if (group->vuses.length () == 1)
    2620      1494218 :         continue;
    2621              : 
    2622       139045 :       gcc_assert (address_p (group->type));
    2623       139045 :       if (group->vuses.length () == 2)
    2624              :         {
    2625        80489 :           if (compare_sizes_for_sort (group->vuses[0]->addr_offset,
    2626        80489 :                                       group->vuses[1]->addr_offset) > 0)
    2627        14941 :             std::swap (group->vuses[0], group->vuses[1]);
    2628              :         }
    2629              :       else
    2630        58556 :         group->vuses.qsort (group_compare_offset);
    2631              : 
    2632       139045 :       if (distinct > 2)
    2633        13900 :         continue;
    2634              : 
    2635       125145 :       distinct = 1;
    2636      1823740 :       for (pre = group->vuses[0], j = 1; j < group->vuses.length (); j++)
    2637              :         {
    2638       190477 :           if (maybe_ne (group->vuses[j]->addr_offset, pre->addr_offset))
    2639              :             {
    2640       132838 :               pre = group->vuses[j];
    2641       132838 :               distinct++;
    2642              :             }
    2643              : 
    2644       190477 :           if (distinct > 2)
    2645              :             break;
    2646              :         }
    2647              :     }
    2648              : 
    2649       519404 :   return (distinct <= 2);
    2650              : }
    2651              : 
    2652              : /* For each group of address type uses, this function further groups
    2653              :    these uses according to the maximum offset supported by target's
    2654              :    [base + offset] addressing mode.  */
    2655              : 
    2656              : static void
    2657       519404 : split_address_groups (struct ivopts_data *data)
    2658              : {
    2659       519404 :   unsigned int i, j;
    2660              :   /* Always split group.  */
    2661       519404 :   bool split_p = split_small_address_groups_p (data);
    2662              : 
    2663      2725634 :   for (i = 0; i < data->vgroups.length (); i++)
    2664              :     {
    2665      1686826 :       struct iv_group *new_group = NULL;
    2666      1686826 :       struct iv_group *group = data->vgroups[i];
    2667      1686826 :       struct iv_use *use = group->vuses[0];
    2668              : 
    2669      1686826 :       use->id = 0;
    2670      1686826 :       use->group_id = group->id;
    2671      1686826 :       if (group->vuses.length () == 1)
    2672      1541971 :         continue;
    2673              : 
    2674       144855 :       gcc_assert (address_p (use->type));
    2675              : 
    2676      2022706 :       for (j = 1; j < group->vuses.length ();)
    2677              :         {
    2678       335880 :           struct iv_use *next = group->vuses[j];
    2679       335880 :           poly_int64 offset = next->addr_offset - use->addr_offset;
    2680              : 
    2681              :           /* Split group if asked to, or the offset against the first
    2682              :              use can't fit in offset part of addressing mode.  IV uses
    2683              :              having the same offset are still kept in one group.  */
    2684       395702 :           if (maybe_ne (offset, 0)
    2685       335880 :               && (split_p || !addr_offset_valid_p (use, offset)))
    2686              :             {
    2687        59822 :               if (!new_group)
    2688        53563 :                 new_group = record_group (data, group->type);
    2689        59822 :               group->vuses.ordered_remove (j);
    2690        59822 :               new_group->vuses.safe_push (next);
    2691        59822 :               continue;
    2692              :             }
    2693              : 
    2694       276058 :           next->id = j;
    2695       276058 :           next->group_id = group->id;
    2696       276058 :           j++;
    2697              :         }
    2698              :     }
    2699       519404 : }
    2700              : 
    2701              : /* Finds uses of the induction variables that are interesting.  */
    2702              : 
    2703              : static void
    2704       519404 : find_interesting_uses (struct ivopts_data *data, basic_block *body)
    2705              : {
    2706       519404 :   basic_block bb;
    2707       519404 :   gimple_stmt_iterator bsi;
    2708       519404 :   unsigned i;
    2709       519404 :   edge e;
    2710              : 
    2711      3411749 :   for (i = 0; i < data->current_loop->num_nodes; i++)
    2712              :     {
    2713      2892345 :       edge_iterator ei;
    2714      2892345 :       bb = body[i];
    2715              : 
    2716      7387014 :       FOR_EACH_EDGE (e, ei, bb->succs)
    2717      4494669 :         if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
    2718      4494669 :             && !flow_bb_inside_loop_p (data->current_loop, e->dest))
    2719       915175 :           find_interesting_uses_outside (data, e);
    2720              : 
    2721      5852710 :       for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
    2722      2960365 :         find_interesting_uses_stmt (data, gsi_stmt (bsi));
    2723     28523180 :       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
    2724     22738490 :         if (!is_gimple_debug (gsi_stmt (bsi)))
    2725     13013321 :           find_interesting_uses_stmt (data, gsi_stmt (bsi));
    2726              :     }
    2727              : 
    2728       519404 :   split_address_groups (data);
    2729              : 
    2730       519404 :   if (dump_file && (dump_flags & TDF_DETAILS))
    2731              :     {
    2732           72 :       fprintf (dump_file, "\n<IV Groups>:\n");
    2733           72 :       dump_groups (dump_file, data);
    2734           72 :       fprintf (dump_file, "\n");
    2735              :     }
    2736       519404 : }
    2737              : 
    2738              : /* Strips constant offsets from EXPR and stores them to OFFSET.  If INSIDE_ADDR
    2739              :    is true, assume we are inside an address.  If TOP_COMPREF is true, assume
    2740              :    we are at the top-level of the processed address.  */
    2741              : 
    2742              : static tree
    2743      3456850 : strip_offset_1 (tree expr, bool inside_addr, bool top_compref,
    2744              :                 poly_int64 *offset)
    2745              : {
    2746      3456850 :   tree op0 = NULL_TREE, op1 = NULL_TREE, tmp, step;
    2747      3456850 :   enum tree_code code;
    2748      3456850 :   tree type, orig_type = TREE_TYPE (expr);
    2749      3456850 :   poly_int64 off0, off1;
    2750      3456850 :   HOST_WIDE_INT st;
    2751      3456850 :   tree orig_expr = expr;
    2752              : 
    2753      3456850 :   STRIP_NOPS (expr);
    2754              : 
    2755      3456850 :   type = TREE_TYPE (expr);
    2756      3456850 :   code = TREE_CODE (expr);
    2757      3456850 :   *offset = 0;
    2758              : 
    2759      3456850 :   switch (code)
    2760              :     {
    2761       629800 :     case POINTER_PLUS_EXPR:
    2762       629800 :     case PLUS_EXPR:
    2763       629800 :     case MINUS_EXPR:
    2764       629800 :       op0 = TREE_OPERAND (expr, 0);
    2765       629800 :       op1 = TREE_OPERAND (expr, 1);
    2766              : 
    2767       629800 :       op0 = strip_offset_1 (op0, false, false, &off0);
    2768       629800 :       op1 = strip_offset_1 (op1, false, false, &off1);
    2769              : 
    2770       629800 :       *offset = (code == MINUS_EXPR ? off0 - off1 : off0 + off1);
    2771       629800 :       if (op0 == TREE_OPERAND (expr, 0)
    2772       629800 :           && op1 == TREE_OPERAND (expr, 1))
    2773              :         return orig_expr;
    2774              : 
    2775       390043 :       if (integer_zerop (op1))
    2776              :         expr = op0;
    2777         3394 :       else if (integer_zerop (op0))
    2778              :         {
    2779          693 :           if (code == MINUS_EXPR)
    2780              :             {
    2781          693 :               if (TYPE_OVERFLOW_UNDEFINED (type))
    2782              :                 {
    2783            0 :                   type = unsigned_type_for (type);
    2784            0 :                   op1 = fold_convert (type, op1);
    2785              :                 }
    2786          693 :               expr = fold_build1 (NEGATE_EXPR, type, op1);
    2787              :             }
    2788              :           else
    2789              :             expr = op1;
    2790              :         }
    2791              :       else
    2792              :         {
    2793         2701 :           if (TYPE_OVERFLOW_UNDEFINED (type))
    2794              :             {
    2795            0 :               type = unsigned_type_for (type);
    2796            0 :               if (code == POINTER_PLUS_EXPR)
    2797            0 :                 code = PLUS_EXPR;
    2798            0 :               op0 = fold_convert (type, op0);
    2799            0 :               op1 = fold_convert (type, op1);
    2800              :             }
    2801         2701 :           expr = fold_build2 (code, type, op0, op1);
    2802              :         }
    2803              : 
    2804       390043 :       return fold_convert (orig_type, expr);
    2805              : 
    2806       222734 :     case MULT_EXPR:
    2807       222734 :       op1 = TREE_OPERAND (expr, 1);
    2808       222734 :       if (!cst_and_fits_in_hwi (op1))
    2809              :         return orig_expr;
    2810              : 
    2811       181578 :       op0 = TREE_OPERAND (expr, 0);
    2812       181578 :       op0 = strip_offset_1 (op0, false, false, &off0);
    2813       181578 :       if (op0 == TREE_OPERAND (expr, 0))
    2814              :         return orig_expr;
    2815              : 
    2816         7188 :       *offset = off0 * int_cst_value (op1);
    2817         7188 :       if (integer_zerop (op0))
    2818              :         expr = op0;
    2819              :       else
    2820              :         {
    2821         7188 :           if (TYPE_OVERFLOW_UNDEFINED (type))
    2822              :             {
    2823            0 :               type = unsigned_type_for (type);
    2824            0 :               op0 = fold_convert (type, op0);
    2825            0 :               op1 = fold_convert (type, op1);
    2826              :             }
    2827         7188 :           expr = fold_build2 (MULT_EXPR, type, op0, op1);
    2828              :         }
    2829              : 
    2830         7188 :       return fold_convert (orig_type, expr);
    2831              : 
    2832            9 :     case ARRAY_REF:
    2833            9 :     case ARRAY_RANGE_REF:
    2834            9 :       if (!inside_addr)
    2835              :         return orig_expr;
    2836              : 
    2837            9 :       step = array_ref_element_size (expr);
    2838            9 :       if (!cst_and_fits_in_hwi (step))
    2839              :         break;
    2840              : 
    2841            9 :       st = int_cst_value (step);
    2842            9 :       op1 = TREE_OPERAND (expr, 1);
    2843            9 :       op1 = strip_offset_1 (op1, false, false, &off1);
    2844            9 :       *offset = off1 * st;
    2845              : 
    2846            9 :       if (top_compref
    2847            9 :           && integer_zerop (op1))
    2848              :         {
    2849              :           /* Strip the component reference completely.  */
    2850            7 :           op0 = TREE_OPERAND (expr, 0);
    2851            7 :           op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
    2852            7 :           *offset += off0;
    2853            7 :           return op0;
    2854              :         }
    2855              :       break;
    2856              : 
    2857            1 :     case COMPONENT_REF:
    2858            1 :       {
    2859            1 :         tree field;
    2860              : 
    2861            1 :         if (!inside_addr)
    2862              :           return orig_expr;
    2863              : 
    2864            1 :         tmp = component_ref_field_offset (expr);
    2865            1 :         field = TREE_OPERAND (expr, 1);
    2866            1 :         if (top_compref
    2867            1 :             && cst_and_fits_in_hwi (tmp)
    2868            2 :             && cst_and_fits_in_hwi (DECL_FIELD_BIT_OFFSET (field)))
    2869              :           {
    2870            1 :             HOST_WIDE_INT boffset, abs_off;
    2871              : 
    2872              :             /* Strip the component reference completely.  */
    2873            1 :             op0 = TREE_OPERAND (expr, 0);
    2874            1 :             op0 = strip_offset_1 (op0, inside_addr, top_compref, &off0);
    2875            1 :             boffset = int_cst_value (DECL_FIELD_BIT_OFFSET (field));
    2876            1 :             abs_off = abs_hwi (boffset) / BITS_PER_UNIT;
    2877            1 :             if (boffset < 0)
    2878            0 :               abs_off = -abs_off;
    2879              : 
    2880            1 :             *offset = off0 + int_cst_value (tmp) + abs_off;
    2881            1 :             return op0;
    2882              :           }
    2883              :       }
    2884              :       break;
    2885              : 
    2886       329193 :     case ADDR_EXPR:
    2887       329193 :       op0 = TREE_OPERAND (expr, 0);
    2888       329193 :       op0 = strip_offset_1 (op0, true, true, &off0);
    2889       329193 :       *offset += off0;
    2890              : 
    2891       329193 :       if (op0 == TREE_OPERAND (expr, 0))
    2892              :         return orig_expr;
    2893              : 
    2894            8 :       expr = build_fold_addr_expr (op0);
    2895            8 :       return fold_convert (orig_type, expr);
    2896              : 
    2897              :     case MEM_REF:
    2898              :       /* ???  Offset operand?  */
    2899              :       inside_addr = false;
    2900              :       break;
    2901              : 
    2902      2275111 :     default:
    2903      2275111 :       if (ptrdiff_tree_p (expr, offset) && maybe_ne (*offset, 0))
    2904       886565 :         return build_int_cst (orig_type, 0);
    2905              :       return orig_expr;
    2906              :     }
    2907              : 
    2908              :   /* Default handling of expressions for that we want to recurse into
    2909              :      the first operand.  */
    2910            4 :   op0 = TREE_OPERAND (expr, 0);
    2911            4 :   op0 = strip_offset_1 (op0, inside_addr, false, &off0);
    2912            4 :   *offset += off0;
    2913              : 
    2914            4 :   if (op0 == TREE_OPERAND (expr, 0)
    2915            4 :       && (!op1 || op1 == TREE_OPERAND (expr, 1)))
    2916              :     return orig_expr;
    2917              : 
    2918            1 :   expr = copy_node (expr);
    2919            1 :   TREE_OPERAND (expr, 0) = op0;
    2920            1 :   if (op1)
    2921            1 :     TREE_OPERAND (expr, 1) = op1;
    2922              : 
    2923              :   /* Inside address, we might strip the top level component references,
    2924              :      thus changing type of the expression.  Handling of ADDR_EXPR
    2925              :      will fix that.  */
    2926            1 :   expr = fold_convert (orig_type, expr);
    2927              : 
    2928            1 :   return expr;
    2929              : }
    2930              : 
    2931              : /* Strips constant offsets from EXPR and stores them to OFFSET.  */
    2932              : 
    2933              : static tree
    2934      1686458 : strip_offset (tree expr, poly_uint64 *offset)
    2935              : {
    2936      1686458 :   poly_int64 off;
    2937      1686458 :   tree core = strip_offset_1 (expr, false, false, &off);
    2938      1686458 :   *offset = off;
    2939      1686458 :   return core;
    2940              : }
    2941              : 
    2942              : /* Returns variant of TYPE that can be used as base for different uses.
    2943              :    We return unsigned type with the same precision, which avoids problems
    2944              :    with overflows.  */
    2945              : 
    2946              : static tree
    2947      8293548 : generic_type_for (tree type)
    2948              : {
    2949      8293548 :   if (POINTER_TYPE_P (type))
    2950      1455046 :     return unsigned_type_for (type);
    2951              : 
    2952      6838502 :   if (TYPE_UNSIGNED (type))
    2953              :     return type;
    2954              : 
    2955      3205613 :   return unsigned_type_for (type);
    2956              : }
    2957              : 
    2958              : /* Private data for walk_tree.  */
    2959              : 
    2960              : struct walk_tree_data
    2961              : {
    2962              :   bitmap *inv_vars;
    2963              :   struct ivopts_data *idata;
    2964              : };
    2965              : 
    2966              : /* Callback function for walk_tree, it records invariants and symbol
    2967              :    reference in *EXPR_P.  DATA is the structure storing result info.  */
    2968              : 
    2969              : static tree
    2970     34902687 : find_inv_vars_cb (tree *expr_p, int *ws ATTRIBUTE_UNUSED, void *data)
    2971              : {
    2972     34902687 :   tree op = *expr_p;
    2973     34902687 :   struct version_info *info;
    2974     34902687 :   struct walk_tree_data *wdata = (struct walk_tree_data*) data;
    2975              : 
    2976     34902687 :   if (TREE_CODE (op) != SSA_NAME)
    2977              :     return NULL_TREE;
    2978              : 
    2979      8155565 :   info = name_info (wdata->idata, op);
    2980              :   /* Because we expand simple operations when finding IVs, loop invariant
    2981              :      variable that isn't referred by the original loop could be used now.
    2982              :      Record such invariant variables here.  */
    2983      8155565 :   if (!info->iv)
    2984              :     {
    2985       398135 :       struct ivopts_data *idata = wdata->idata;
    2986       398135 :       basic_block bb = gimple_bb (SSA_NAME_DEF_STMT (op));
    2987              : 
    2988       398135 :       if (!bb || !flow_bb_inside_loop_p (idata->current_loop, bb))
    2989              :         {
    2990       398135 :           tree steptype = TREE_TYPE (op);
    2991       398135 :           if (POINTER_TYPE_P (steptype))
    2992       196690 :             steptype = sizetype;
    2993       398135 :           set_iv (idata, op, op, build_int_cst (steptype, 0), true);
    2994       398135 :           record_invariant (idata, op, false);
    2995              :         }
    2996              :     }
    2997      8155565 :   if (!info->inv_id || info->has_nonlin_use)
    2998              :     return NULL_TREE;
    2999              : 
    3000      6770248 :   if (!*wdata->inv_vars)
    3001      5236112 :     *wdata->inv_vars = BITMAP_ALLOC (NULL);
    3002      6770248 :   bitmap_set_bit (*wdata->inv_vars, info->inv_id);
    3003              : 
    3004      6770248 :   return NULL_TREE;
    3005              : }
    3006              : 
    3007              : /* Records invariants in *EXPR_P.  INV_VARS is the bitmap to that we should
    3008              :    store it.  */
    3009              : 
    3010              : static inline void
    3011     28406201 : find_inv_vars (struct ivopts_data *data, tree *expr_p, bitmap *inv_vars)
    3012              : {
    3013     28406201 :   struct walk_tree_data wdata;
    3014              : 
    3015     28406201 :   if (!inv_vars)
    3016              :     return;
    3017              : 
    3018     16345760 :   wdata.idata = data;
    3019     16345760 :   wdata.inv_vars = inv_vars;
    3020     16345760 :   walk_tree (expr_p, find_inv_vars_cb, &wdata, NULL);
    3021              : }
    3022              : 
    3023              : /* Get entry from invariant expr hash table for INV_EXPR.  New entry
    3024              :    will be recorded if it doesn't exist yet.  Given below two exprs:
    3025              :      inv_expr + cst1, inv_expr + cst2
    3026              :    It's hard to make decision whether constant part should be stripped
    3027              :    or not.  We choose to not strip based on below facts:
    3028              :      1) We need to count ADD cost for constant part if it's stripped,
    3029              :         which isn't always trivial where this functions is called.
    3030              :      2) Stripping constant away may be conflict with following loop
    3031              :         invariant hoisting pass.
    3032              :      3) Not stripping constant away results in more invariant exprs,
    3033              :         which usually leads to decision preferring lower reg pressure.  */
    3034              : 
    3035              : static iv_inv_expr_ent *
    3036      2648292 : get_loop_invariant_expr (struct ivopts_data *data, tree inv_expr)
    3037              : {
    3038      2648292 :   STRIP_NOPS (inv_expr);
    3039              : 
    3040      2648292 :   if (poly_int_tree_p (inv_expr)
    3041      2648292 :       || TREE_CODE (inv_expr) == SSA_NAME)
    3042              :     return NULL;
    3043              : 
    3044              :   /* Don't strip constant part away as we used to.  */
    3045              : 
    3046              :   /* Stores EXPR in DATA->inv_expr_tab, return pointer to iv_inv_expr_ent.  */
    3047      2558253 :   struct iv_inv_expr_ent ent;
    3048      2558253 :   ent.expr = inv_expr;
    3049      2558253 :   ent.hash = iterative_hash_expr (inv_expr, 0);
    3050      2558253 :   struct iv_inv_expr_ent **slot = data->inv_expr_tab->find_slot (&ent, INSERT);
    3051              : 
    3052      2558253 :   if (!*slot)
    3053              :     {
    3054      1179133 :       *slot = XNEW (struct iv_inv_expr_ent);
    3055      1179133 :       (*slot)->expr = inv_expr;
    3056      1179133 :       (*slot)->hash = ent.hash;
    3057      1179133 :       (*slot)->id = ++data->max_inv_expr_id;
    3058              :     }
    3059              : 
    3060      2558253 :   return *slot;
    3061              : }
    3062              : 
    3063              : 
    3064              : /* Return *TP if it is an SSA_NAME marked with TREE_VISITED, i.e., as
    3065              :    unsuitable as ivopts candidates for potentially involving undefined
    3066              :    behavior.  */
    3067              : 
    3068              : static tree
    3069     15729008 : find_ssa_undef (tree *tp, int *walk_subtrees, void *bb_)
    3070              : {
    3071     15729008 :   basic_block bb = (basic_block) bb_;
    3072     15729008 :   if (TREE_CODE (*tp) == SSA_NAME
    3073      2290682 :       && ssa_name_maybe_undef_p (*tp)
    3074     15737912 :       && !ssa_name_any_use_dominates_bb_p (*tp, bb))
    3075         3162 :     return *tp;
    3076     15725846 :   if (!EXPR_P (*tp))
    3077     10686000 :     *walk_subtrees = 0;
    3078              :   return NULL;
    3079              : }
    3080              : 
    3081              : /* Adds a candidate BASE + STEP * i.  Important field is set to IMPORTANT and
    3082              :    position to POS.  If USE is not NULL, the candidate is set as related to
    3083              :    it.  If both BASE and STEP are NULL, we add a pseudocandidate for the
    3084              :    replacement of the final value of the iv by a direct computation.  */
    3085              : 
    3086              : static struct iv_cand *
    3087      9297687 : add_candidate_1 (struct ivopts_data *data, tree base, tree step, bool important,
    3088              :                  enum iv_position pos, struct iv_use *use,
    3089              :                  gimple *incremented_at, struct iv *orig_iv = NULL,
    3090              :                  bool doloop = false)
    3091              : {
    3092      9297687 :   unsigned i;
    3093      9297687 :   struct iv_cand *cand = NULL;
    3094      9297687 :   tree type, orig_type;
    3095              : 
    3096      9297687 :   gcc_assert (base && step);
    3097              : 
    3098              :   /* -fkeep-gc-roots-live means that we have to keep a real pointer
    3099              :      live, but the ivopts code may replace a real pointer with one
    3100              :      pointing before or after the memory block that is then adjusted
    3101              :      into the memory block during the loop.  FIXME: It would likely be
    3102              :      better to actually force the pointer live and still use ivopts;
    3103              :      for example, it would be enough to write the pointer into memory
    3104              :      and keep it there until after the loop.  */
    3105      9297687 :   if (flag_keep_gc_roots_live && POINTER_TYPE_P (TREE_TYPE (base)))
    3106              :     return NULL;
    3107              : 
    3108              :   /* If BASE contains undefined SSA names make sure we only record
    3109              :      the original IV.  */
    3110      9192185 :   bool involves_undefs = false;
    3111      9192185 :   if (walk_tree (&base, find_ssa_undef, data->current_loop->header, NULL))
    3112              :     {
    3113         3162 :       if (pos != IP_ORIGINAL)
    3114              :         return NULL;
    3115              :       important = false;
    3116              :       involves_undefs = true;
    3117              :     }
    3118              : 
    3119              :   /* For non-original variables, make sure their values are computed in a type
    3120              :      that does not invoke undefined behavior on overflows (since in general,
    3121              :      we cannot prove that these induction variables are non-wrapping).  */
    3122      9189023 :   if (pos != IP_ORIGINAL)
    3123              :     {
    3124      8293548 :       orig_type = TREE_TYPE (base);
    3125      8293548 :       type = generic_type_for (orig_type);
    3126      8293548 :       if (type != orig_type)
    3127              :         {
    3128      4660659 :           base = fold_convert (type, base);
    3129      4660659 :           step = fold_convert (type, step);
    3130              :         }
    3131              :     }
    3132              : 
    3133     45845996 :   for (i = 0; i < data->vcands.length (); i++)
    3134              :     {
    3135     41093968 :       cand = data->vcands[i];
    3136              : 
    3137     41093968 :       if (cand->pos != pos)
    3138     10113392 :         continue;
    3139              : 
    3140     30980576 :       if (cand->incremented_at != incremented_at
    3141     30473829 :           || ((pos == IP_AFTER_USE || pos == IP_BEFORE_USE)
    3142            0 :               && cand->ainc_use != use))
    3143       506747 :         continue;
    3144              : 
    3145     30473829 :       if (operand_equal_p (base, cand->iv->base, 0)
    3146      9722734 :           && operand_equal_p (step, cand->iv->step, 0)
    3147     36346999 :           && (TYPE_PRECISION (TREE_TYPE (base))
    3148      5873170 :               == TYPE_PRECISION (TREE_TYPE (cand->iv->base))))
    3149              :         break;
    3150              :     }
    3151              : 
    3152     18378810 :   if (i == data->vcands.length ())
    3153              :     {
    3154      4752028 :       cand = XCNEW (struct iv_cand);
    3155      4752028 :       cand->id = i;
    3156      4752028 :       cand->iv = alloc_iv (data, base, step);
    3157      4752028 :       cand->pos = pos;
    3158      4752028 :       if (pos != IP_ORIGINAL)
    3159              :         {
    3160      3856348 :           if (doloop)
    3161            0 :             cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "doloop");
    3162              :           else
    3163      3856348 :             cand->var_before = create_tmp_var_raw (TREE_TYPE (base), "ivtmp");
    3164      3856348 :           cand->var_after = cand->var_before;
    3165              :         }
    3166      4752028 :       cand->important = important;
    3167      4752028 :       cand->involves_undefs = involves_undefs;
    3168      4752028 :       cand->incremented_at = incremented_at;
    3169      4752028 :       cand->doloop_p = doloop;
    3170      4752028 :       data->vcands.safe_push (cand);
    3171              : 
    3172      4752028 :       if (!poly_int_tree_p (step))
    3173              :         {
    3174       178112 :           find_inv_vars (data, &step, &cand->inv_vars);
    3175              : 
    3176       178112 :           iv_inv_expr_ent *inv_expr = get_loop_invariant_expr (data, step);
    3177              :           /* Share bitmap between inv_vars and inv_exprs for cand.  */
    3178       178112 :           if (inv_expr != NULL)
    3179              :             {
    3180        94616 :               cand->inv_exprs = cand->inv_vars;
    3181        94616 :               cand->inv_vars = NULL;
    3182        94616 :               if (cand->inv_exprs)
    3183        76004 :                 bitmap_clear (cand->inv_exprs);
    3184              :               else
    3185        18612 :                 cand->inv_exprs = BITMAP_ALLOC (NULL);
    3186              : 
    3187        94616 :               bitmap_set_bit (cand->inv_exprs, inv_expr->id);
    3188              :             }
    3189              :         }
    3190              : 
    3191      4752028 :       if (pos == IP_AFTER_USE || pos == IP_BEFORE_USE)
    3192              :         cand->ainc_use = use;
    3193              :       else
    3194      4752028 :         cand->ainc_use = NULL;
    3195              : 
    3196      4752028 :       cand->orig_iv = orig_iv;
    3197      4752028 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3198          733 :         dump_cand (dump_file, cand);
    3199              :     }
    3200              : 
    3201      9189405 :   cand->important |= important;
    3202      9189405 :   cand->doloop_p |= doloop;
    3203              : 
    3204              :   /* Relate candidate to the group for which it is added.  */
    3205      9189405 :   if (use)
    3206      2560862 :     bitmap_set_bit (data->vgroups[use->group_id]->related_cands, i);
    3207              : 
    3208              :   return cand;
    3209              : }
    3210              : 
    3211              : /* Returns true if incrementing the induction variable at the end of the LOOP
    3212              :    is allowed.
    3213              : 
    3214              :    The purpose is to avoid splitting latch edge with a biv increment, thus
    3215              :    creating a jump, possibly confusing other optimization passes and leaving
    3216              :    less freedom to scheduler.  So we allow IP_END only if IP_NORMAL is not
    3217              :    available (so we do not have a better alternative), or if the latch edge
    3218              :    is already nonempty.  */
    3219              : 
    3220              : static bool
    3221      8168822 : allow_ip_end_pos_p (class loop *loop)
    3222              : {
    3223              :   /* Do not allow IP_END when creating the IV would need to split the
    3224              :      latch edge as that makes all IP_NORMAL invalid.  */
    3225      8168822 :   auto pos = gsi_last_bb (ip_end_pos (loop));
    3226      8168822 :   if (!gsi_end_p (pos) && stmt_ends_bb_p (*pos))
    3227              :     return false;
    3228              : 
    3229      8168822 :   if (!ip_normal_pos (loop))
    3230              :     return true;
    3231              : 
    3232      8054992 :   if (!empty_block_p (ip_end_pos (loop)))
    3233       230655 :     return true;
    3234              : 
    3235              :   return false;
    3236              : }
    3237              : 
    3238              : /* If possible, adds autoincrement candidates BASE + STEP * i based on use USE.
    3239              :    Important field is set to IMPORTANT.  */
    3240              : 
    3241              : static void
    3242       597197 : add_autoinc_candidates (struct ivopts_data *data, tree base, tree step,
    3243              :                         bool important, struct iv_use *use)
    3244              : {
    3245       597197 :   basic_block use_bb = gimple_bb (use->stmt);
    3246       597197 :   machine_mode mem_mode;
    3247       597197 :   unsigned HOST_WIDE_INT cstepi;
    3248              : 
    3249              :   /* If we insert the increment in any position other than the standard
    3250              :      ones, we must ensure that it is incremented once per iteration.
    3251              :      It must not be in an inner nested loop, or one side of an if
    3252              :      statement.  */
    3253       597197 :   if (use_bb->loop_father != data->current_loop
    3254       594620 :       || !dominated_by_p (CDI_DOMINATORS, data->current_loop->latch, use_bb)
    3255       568805 :       || stmt_can_throw_internal (cfun, use->stmt)
    3256      1162214 :       || !cst_and_fits_in_hwi (step))
    3257              :     return;
    3258              : 
    3259       535203 :   cstepi = int_cst_value (step);
    3260              : 
    3261       535203 :   mem_mode = TYPE_MODE (use->mem_type);
    3262              :   if (((USE_LOAD_PRE_INCREMENT (mem_mode)
    3263              :         || USE_STORE_PRE_INCREMENT (mem_mode))
    3264              :        && known_eq (GET_MODE_SIZE (mem_mode), cstepi))
    3265              :       || ((USE_LOAD_PRE_DECREMENT (mem_mode)
    3266              :            || USE_STORE_PRE_DECREMENT (mem_mode))
    3267              :           && known_eq (GET_MODE_SIZE (mem_mode), -cstepi)))
    3268              :     {
    3269              :       enum tree_code code = MINUS_EXPR;
    3270              :       tree new_base;
    3271              :       tree new_step = step;
    3272              : 
    3273              :       if (POINTER_TYPE_P (TREE_TYPE (base)))
    3274              :         {
    3275              :           new_step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
    3276              :           code = POINTER_PLUS_EXPR;
    3277              :         }
    3278              :       else
    3279              :         new_step = fold_convert (TREE_TYPE (base), new_step);
    3280              :       new_base = fold_build2 (code, TREE_TYPE (base), base, new_step);
    3281              :       add_candidate_1 (data, new_base, step, important, IP_BEFORE_USE, use,
    3282              :                        use->stmt);
    3283              :     }
    3284              :   if (((USE_LOAD_POST_INCREMENT (mem_mode)
    3285              :         || USE_STORE_POST_INCREMENT (mem_mode))
    3286              :        && known_eq (GET_MODE_SIZE (mem_mode), cstepi))
    3287              :       || ((USE_LOAD_POST_DECREMENT (mem_mode)
    3288              :            || USE_STORE_POST_DECREMENT (mem_mode))
    3289              :           && known_eq (GET_MODE_SIZE (mem_mode), -cstepi)))
    3290              :     {
    3291              :       add_candidate_1 (data, base, step, important, IP_AFTER_USE, use,
    3292              :                        use->stmt);
    3293              :     }
    3294              : }
    3295              : 
    3296              : /* Adds a candidate BASE + STEP * i.  Important field is set to IMPORTANT and
    3297              :    position to POS.  If USE is not NULL, the candidate is set as related to
    3298              :    it.  The candidate computation is scheduled before exit condition and at
    3299              :    the end of loop.  */
    3300              : 
    3301              : static void
    3302      7184859 : add_candidate (struct ivopts_data *data, tree base, tree step, bool important,
    3303              :                struct iv_use *use, struct iv *orig_iv = NULL,
    3304              :                bool doloop = false)
    3305              : {
    3306      7184859 :   if (ip_normal_pos (data->current_loop))
    3307      7088351 :     add_candidate_1 (data, base, step, important, IP_NORMAL, use, NULL, orig_iv,
    3308              :                      doloop);
    3309              :   /* Exclude doloop candidate here since it requires decrement then comparison
    3310              :      and jump, the IP_END position doesn't match.  */
    3311      7184859 :   if (!doloop && ip_end_pos (data->current_loop)
    3312     14369718 :       && allow_ip_end_pos_p (data->current_loop))
    3313       296193 :     add_candidate_1 (data, base, step, important, IP_END, use, NULL, orig_iv);
    3314      7184859 : }
    3315              : 
    3316              : /* Adds standard iv candidates.  */
    3317              : 
    3318              : static void
    3319       519403 : add_standard_iv_candidates (struct ivopts_data *data)
    3320              : {
    3321       519403 :   add_candidate (data, integer_zero_node, integer_one_node, true, NULL);
    3322              : 
    3323              :   /* The same for a double-integer type if it is still fast enough.  */
    3324       519403 :   if (TYPE_PRECISION
    3325       519403 :         (long_integer_type_node) > TYPE_PRECISION (integer_type_node)
    3326       519403 :       && TYPE_PRECISION (long_integer_type_node) <= BITS_PER_WORD)
    3327       471191 :     add_candidate (data, build_int_cst (long_integer_type_node, 0),
    3328              :                    build_int_cst (long_integer_type_node, 1), true, NULL);
    3329              : 
    3330              :   /* The same for a double-integer type if it is still fast enough.  */
    3331       519403 :   if (TYPE_PRECISION
    3332       519403 :         (long_long_integer_type_node) > TYPE_PRECISION (long_integer_type_node)
    3333       567603 :       && TYPE_PRECISION (long_long_integer_type_node) <= BITS_PER_WORD)
    3334           12 :     add_candidate (data, build_int_cst (long_long_integer_type_node, 0),
    3335              :                    build_int_cst (long_long_integer_type_node, 1), true, NULL);
    3336       519403 : }
    3337              : 
    3338              : 
    3339              : /* Adds candidates bases on the old induction variable IV.  */
    3340              : 
    3341              : static void
    3342      1796238 : add_iv_candidate_for_biv (struct ivopts_data *data, struct iv *iv)
    3343              : {
    3344      1796238 :   gimple *phi;
    3345      1796238 :   tree def;
    3346      1796238 :   struct iv_cand *cand;
    3347              : 
    3348              :   /* Check if this biv is used in address type use.  */
    3349      1194180 :   if (iv->no_overflow  && iv->have_address_use
    3350       505622 :       && INTEGRAL_TYPE_P (TREE_TYPE (iv->base))
    3351      2301860 :       && TYPE_PRECISION (TREE_TYPE (iv->base)) < TYPE_PRECISION (sizetype))
    3352              :     {
    3353       285731 :       tree base = fold_convert (sizetype, iv->base);
    3354       285731 :       tree step = fold_convert (sizetype, iv->step);
    3355              : 
    3356              :       /* Add iv cand of same precision as index part in TARGET_MEM_REF.  */
    3357       285731 :       add_candidate (data, base, step, true, NULL, iv);
    3358              :       /* Add iv cand of the original type only if it has nonlinear use.  */
    3359       285731 :       if (iv->nonlin_use)
    3360        28386 :         add_candidate (data, iv->base, iv->step, true, NULL);
    3361              :     }
    3362              :   else
    3363      1510507 :     add_candidate (data, iv->base, iv->step, true, NULL);
    3364              : 
    3365              :   /* The same, but with initial value zero.  */
    3366      1796238 :   if (POINTER_TYPE_P (TREE_TYPE (iv->base)))
    3367       341058 :     add_candidate (data, size_int (0), iv->step, true, NULL);
    3368              :   else
    3369      1455180 :     add_candidate (data, build_int_cst (TREE_TYPE (iv->base), 0),
    3370              :                    iv->step, true, NULL);
    3371              : 
    3372      1796238 :   phi = SSA_NAME_DEF_STMT (iv->ssa_name);
    3373      1796238 :   if (gimple_code (phi) == GIMPLE_PHI)
    3374              :     {
    3375              :       /* Additionally record the possibility of leaving the original iv
    3376              :          untouched.  */
    3377       898210 :       def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (data->current_loop));
    3378              :       /* Don't add candidate if it's from another PHI node because
    3379              :          it's an affine iv appearing in the form of PEELED_CHREC.  */
    3380       898210 :       phi = SSA_NAME_DEF_STMT (def);
    3381       898210 :       if (gimple_code (phi) != GIMPLE_PHI)
    3382              :         {
    3383      1796420 :           cand = add_candidate_1 (data,
    3384              :                                   iv->base, iv->step, true, IP_ORIGINAL, NULL,
    3385       898210 :                                   SSA_NAME_DEF_STMT (def));
    3386       898210 :           if (cand)
    3387              :             {
    3388       895857 :               cand->var_before = iv->ssa_name;
    3389       895857 :               cand->var_after = def;
    3390              :             }
    3391              :         }
    3392              :       else
    3393            0 :         gcc_assert (gimple_bb (phi) == data->current_loop->header);
    3394              :     }
    3395      1796238 : }
    3396              : 
    3397              : /* Adds candidates based on the old induction variables.  */
    3398              : 
    3399              : static void
    3400       519403 : add_iv_candidate_for_bivs (struct ivopts_data *data)
    3401              : {
    3402       519403 :   unsigned i;
    3403       519403 :   struct iv *iv;
    3404       519403 :   bitmap_iterator bi;
    3405              : 
    3406      5653472 :   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
    3407              :     {
    3408      5134069 :       iv = ver_info (data, i)->iv;
    3409      5134069 :       if (iv && iv->biv_p && !integer_zerop (iv->step))
    3410      1796238 :         add_iv_candidate_for_biv (data, iv);
    3411              :     }
    3412       519403 : }
    3413              : 
    3414              : /* Record common candidate {BASE, STEP} derived from USE in hashtable.  */
    3415              : 
    3416              : static void
    3417      4259485 : record_common_cand (struct ivopts_data *data, tree base,
    3418              :                     tree step, struct iv_use *use)
    3419              : {
    3420      4259485 :   class iv_common_cand ent;
    3421      4259485 :   class iv_common_cand **slot;
    3422              : 
    3423      4259485 :   ent.base = base;
    3424      4259485 :   ent.step = step;
    3425      4259485 :   ent.hash = iterative_hash_expr (base, 0);
    3426      4259485 :   ent.hash = iterative_hash_expr (step, ent.hash);
    3427              : 
    3428      4259485 :   slot = data->iv_common_cand_tab->find_slot (&ent, INSERT);
    3429      4259485 :   if (*slot == NULL)
    3430              :     {
    3431      2684003 :       *slot = new iv_common_cand ();
    3432      2684003 :       (*slot)->base = base;
    3433      2684003 :       (*slot)->step = step;
    3434      2684003 :       (*slot)->uses.create (8);
    3435      2684003 :       (*slot)->hash = ent.hash;
    3436      2684003 :       data->iv_common_cands.safe_push ((*slot));
    3437              :     }
    3438              : 
    3439      4259485 :   gcc_assert (use != NULL);
    3440      4259485 :   (*slot)->uses.safe_push (use);
    3441      4259485 :   return;
    3442      4259485 : }
    3443              : 
    3444              : /* Comparison function used to sort common candidates.  */
    3445              : 
    3446              : static int
    3447     19504951 : common_cand_cmp (const void *p1, const void *p2)
    3448              : {
    3449     19504951 :   unsigned n1, n2;
    3450     19504951 :   const class iv_common_cand *const *const ccand1
    3451              :     = (const class iv_common_cand *const *)p1;
    3452     19504951 :   const class iv_common_cand *const *const ccand2
    3453              :     = (const class iv_common_cand *const *)p2;
    3454              : 
    3455     19504951 :   n1 = (*ccand1)->uses.length ();
    3456     19504951 :   n2 = (*ccand2)->uses.length ();
    3457     19504951 :   return n2 - n1;
    3458              : }
    3459              : 
    3460              : /* Adds IV candidates based on common candidated recorded.  */
    3461              : 
    3462              : static void
    3463       519403 : add_iv_candidate_derived_from_uses (struct ivopts_data *data)
    3464              : {
    3465       519403 :   unsigned i, j;
    3466       519403 :   struct iv_cand *cand_1, *cand_2;
    3467              : 
    3468       519403 :   data->iv_common_cands.qsort (common_cand_cmp);
    3469      1503366 :   for (i = 0; i < data->iv_common_cands.length (); i++)
    3470              :     {
    3471      1485904 :       class iv_common_cand *ptr = data->iv_common_cands[i];
    3472              : 
    3473              :       /* Only add IV candidate if it's derived from multiple uses.  */
    3474      1485904 :       if (ptr->uses.length () <= 1)
    3475              :         break;
    3476              : 
    3477       983963 :       cand_1 = NULL;
    3478       983963 :       cand_2 = NULL;
    3479       983963 :       if (ip_normal_pos (data->current_loop))
    3480       966641 :         cand_1 = add_candidate_1 (data, ptr->base, ptr->step,
    3481              :                                   false, IP_NORMAL, NULL, NULL);
    3482              : 
    3483       983963 :       if (ip_end_pos (data->current_loop)
    3484       983963 :           && allow_ip_end_pos_p (data->current_loop))
    3485        48292 :         cand_2 = add_candidate_1 (data, ptr->base, ptr->step,
    3486              :                                   false, IP_END, NULL, NULL);
    3487              : 
    3488              :       /* Bind deriving uses and the new candidates.  */
    3489      3543408 :       for (j = 0; j < ptr->uses.length (); j++)
    3490              :         {
    3491      2559445 :           struct iv_group *group = data->vgroups[ptr->uses[j]->group_id];
    3492      2559445 :           if (cand_1)
    3493      2479164 :             bitmap_set_bit (group->related_cands, cand_1->id);
    3494      2559445 :           if (cand_2)
    3495       142537 :             bitmap_set_bit (group->related_cands, cand_2->id);
    3496              :         }
    3497              :     }
    3498              : 
    3499              :   /* Release data since it is useless from this point.  */
    3500       519403 :   data->iv_common_cand_tab->empty ();
    3501       519403 :   data->iv_common_cands.truncate (0);
    3502       519403 : }
    3503              : 
    3504              : /* Adds candidates based on the value of USE's iv.  */
    3505              : 
    3506              : static void
    3507      1686822 : add_iv_candidate_for_use (struct ivopts_data *data, struct iv_use *use)
    3508              : {
    3509      1686822 :   poly_uint64 offset;
    3510      1686822 :   tree base;
    3511      1686822 :   struct iv *iv = use->iv;
    3512      1686822 :   tree basetype = TREE_TYPE (iv->base);
    3513              : 
    3514              :   /* Don't add candidate for iv_use with non integer, pointer or non-mode
    3515              :      precision types, instead, add candidate for the corresponding scev in
    3516              :      unsigned type with the same precision.  See PR93674 for more info.  */
    3517       789035 :   if ((TREE_CODE (basetype) != INTEGER_TYPE && !POINTER_TYPE_P (basetype))
    3518      2475531 :       || !type_has_mode_precision_p (basetype))
    3519              :     {
    3520          364 :       basetype = lang_hooks.types.type_for_mode (TYPE_MODE (basetype),
    3521          364 :                                                  TYPE_UNSIGNED (basetype));
    3522          364 :       add_candidate (data, fold_convert (basetype, iv->base),
    3523              :                      fold_convert (basetype, iv->step), false, NULL);
    3524          364 :       return;
    3525              :     }
    3526              : 
    3527      1686458 :   add_candidate (data, iv->base, iv->step, false, use);
    3528              : 
    3529              :   /* Record common candidate for use in case it can be shared by others.  */
    3530      1686458 :   record_common_cand (data, iv->base, iv->step, use);
    3531              : 
    3532              :   /* Record common candidate with initial value zero.  */
    3533      1686458 :   basetype = TREE_TYPE (iv->base);
    3534      1686458 :   if (POINTER_TYPE_P (basetype))
    3535       788709 :     basetype = sizetype;
    3536      1686458 :   record_common_cand (data, build_int_cst (basetype, 0), iv->step, use);
    3537              : 
    3538              :   /* Compare the cost of an address with an unscaled index with the cost of
    3539              :     an address with a scaled index and add candidate if useful.  */
    3540      1686458 :   poly_int64 step;
    3541      1686458 :   if (use != NULL
    3542      1686458 :       && poly_int_tree_p (iv->step, &step)
    3543      1450213 :       && address_p (use->type))
    3544              :     {
    3545       547430 :       poly_int64 new_step;
    3546       547430 :       unsigned int fact = preferred_mem_scale_factor
    3547      1094860 :         (use->iv->base,
    3548       547430 :          TYPE_MODE (use->mem_type),
    3549              :          optimize_loop_for_speed_p (data->current_loop));
    3550              : 
    3551       547430 :       if (fact != 1
    3552       547430 :           && multiple_p (step, fact, &new_step))
    3553            0 :         add_candidate (data, size_int (0),
    3554            0 :                        wide_int_to_tree (sizetype, new_step),
    3555              :                        true, NULL);
    3556              :     }
    3557              : 
    3558              :   /* Record common candidate with constant offset stripped in base.
    3559              :      Like the use itself, we also add candidate directly for it.  */
    3560      1686458 :   base = strip_offset (iv->base, &offset);
    3561      1686458 :   if (maybe_ne (offset, 0U) || base != iv->base)
    3562              :     {
    3563       886569 :       record_common_cand (data, base, iv->step, use);
    3564       886569 :       add_candidate (data, base, iv->step, false, use);
    3565              :     }
    3566              : 
    3567              :   /* Record common candidate with base_object removed in base.  */
    3568      1686458 :   base = iv->base;
    3569      1686458 :   STRIP_NOPS (base);
    3570      1686458 :   if (iv->base_object != NULL && TREE_CODE (base) == POINTER_PLUS_EXPR)
    3571              :     {
    3572            0 :       tree step = iv->step;
    3573              : 
    3574            0 :       STRIP_NOPS (step);
    3575            0 :       base = TREE_OPERAND (base, 1);
    3576            0 :       step = fold_convert (sizetype, step);
    3577            0 :       record_common_cand (data, base, step, use);
    3578              :       /* Also record common candidate with offset stripped.  */
    3579            0 :       tree alt_base, alt_offset;
    3580            0 :       split_constant_offset (base, &alt_base, &alt_offset);
    3581            0 :       if (!integer_zerop (alt_offset))
    3582            0 :         record_common_cand (data, alt_base, step, use);
    3583              :     }
    3584              : 
    3585              :   /* At last, add auto-incremental candidates.  Make such variables
    3586              :      important since other iv uses with same base object may be based
    3587              :      on it.  */
    3588      1686458 :   if (use != NULL && address_p (use->type))
    3589       597197 :     add_autoinc_candidates (data, iv->base, iv->step, true, use);
    3590              : }
    3591              : 
    3592              : /* Adds candidates based on the uses.  */
    3593              : 
    3594              : static void
    3595       519403 : add_iv_candidate_for_groups (struct ivopts_data *data)
    3596              : {
    3597       519403 :   unsigned i;
    3598              : 
    3599              :   /* Only add candidate for the first use in group.  */
    3600      2206225 :   for (i = 0; i < data->vgroups.length (); i++)
    3601              :     {
    3602      1686822 :       struct iv_group *group = data->vgroups[i];
    3603              : 
    3604      1686822 :       gcc_assert (group->vuses[0] != NULL);
    3605      1686822 :       add_iv_candidate_for_use (data, group->vuses[0]);
    3606              :     }
    3607       519403 :   add_iv_candidate_derived_from_uses (data);
    3608       519403 : }
    3609              : 
    3610              : /* Record important candidates and add them to related_cands bitmaps.  */
    3611              : 
    3612              : static void
    3613       519403 : record_important_candidates (struct ivopts_data *data)
    3614              : {
    3615       519403 :   unsigned i;
    3616       519403 :   struct iv_group *group;
    3617              : 
    3618      5271431 :   for (i = 0; i < data->vcands.length (); i++)
    3619              :     {
    3620      4752028 :       struct iv_cand *cand = data->vcands[i];
    3621              : 
    3622      4752028 :       if (cand->important)
    3623      3812822 :         bitmap_set_bit (data->important_candidates, i);
    3624              :     }
    3625              : 
    3626       519403 :   data->consider_all_candidates = (data->vcands.length ()
    3627       519403 :                                    <= CONSIDER_ALL_CANDIDATES_BOUND);
    3628              : 
    3629              :   /* Add important candidates to groups' related_cands bitmaps.  */
    3630      2206225 :   for (i = 0; i < data->vgroups.length (); i++)
    3631              :     {
    3632      1686822 :       group = data->vgroups[i];
    3633      1686822 :       bitmap_ior_into (group->related_cands, data->important_candidates);
    3634              :     }
    3635       519403 : }
    3636              : 
    3637              : /* Allocates the data structure mapping the (use, candidate) pairs to costs.
    3638              :    If consider_all_candidates is true, we use a two-dimensional array, otherwise
    3639              :    we allocate a simple list to every use.  */
    3640              : 
    3641              : static void
    3642       519403 : alloc_use_cost_map (struct ivopts_data *data)
    3643              : {
    3644       519403 :   unsigned i, size, s;
    3645              : 
    3646      2206225 :   for (i = 0; i < data->vgroups.length (); i++)
    3647              :     {
    3648      1686822 :       struct iv_group *group = data->vgroups[i];
    3649              : 
    3650      1686822 :       if (data->consider_all_candidates)
    3651      1676974 :         size = data->vcands.length ();
    3652              :       else
    3653              :         {
    3654         9848 :           s = bitmap_count_bits (group->related_cands);
    3655              : 
    3656              :           /* Round up to the power of two, so that moduling by it is fast.  */
    3657        19696 :           size = s ? (1 << ceil_log2 (s)) : 1;
    3658              :         }
    3659              : 
    3660      1686822 :       group->n_map_members = size;
    3661      1686822 :       group->cost_map = XCNEWVEC (class cost_pair, size);
    3662              :     }
    3663       519403 : }
    3664              : 
    3665              : /* Sets cost of (GROUP, CAND) pair to COST and record that it depends
    3666              :    on invariants INV_VARS and that the value used in expressing it is
    3667              :    VALUE, and in case of iv elimination the comparison operator is COMP.  */
    3668              : 
    3669              : static void
    3670     18102450 : set_group_iv_cost (struct ivopts_data *data,
    3671              :                    struct iv_group *group, struct iv_cand *cand,
    3672              :                    comp_cost cost, bitmap inv_vars, tree value,
    3673              :                    enum tree_code comp, bitmap inv_exprs)
    3674              : {
    3675     18102450 :   unsigned i, s;
    3676              : 
    3677     18102450 :   if (cost.infinite_cost_p ())
    3678              :     {
    3679      6256459 :       BITMAP_FREE (inv_vars);
    3680      6256459 :       BITMAP_FREE (inv_exprs);
    3681      6256459 :       return;
    3682              :     }
    3683              : 
    3684     11845991 :   if (data->consider_all_candidates)
    3685              :     {
    3686     11704568 :       group->cost_map[cand->id].cand = cand;
    3687     11704568 :       group->cost_map[cand->id].cost = cost;
    3688     11704568 :       group->cost_map[cand->id].inv_vars = inv_vars;
    3689     11704568 :       group->cost_map[cand->id].inv_exprs = inv_exprs;
    3690     11704568 :       group->cost_map[cand->id].value = value;
    3691     11704568 :       group->cost_map[cand->id].comp = comp;
    3692     11704568 :       return;
    3693              :     }
    3694              : 
    3695              :   /* n_map_members is a power of two, so this computes modulo.  */
    3696       141423 :   s = cand->id & (group->n_map_members - 1);
    3697       152392 :   for (i = s; i < group->n_map_members; i++)
    3698       152321 :     if (!group->cost_map[i].cand)
    3699       141352 :       goto found;
    3700          148 :   for (i = 0; i < s; i++)
    3701          148 :     if (!group->cost_map[i].cand)
    3702           71 :       goto found;
    3703              : 
    3704            0 :   gcc_unreachable ();
    3705              : 
    3706       141423 : found:
    3707       141423 :   group->cost_map[i].cand = cand;
    3708       141423 :   group->cost_map[i].cost = cost;
    3709       141423 :   group->cost_map[i].inv_vars = inv_vars;
    3710       141423 :   group->cost_map[i].inv_exprs = inv_exprs;
    3711       141423 :   group->cost_map[i].value = value;
    3712       141423 :   group->cost_map[i].comp = comp;
    3713              : }
    3714              : 
    3715              : /* Gets cost of (GROUP, CAND) pair.  */
    3716              : 
    3717              : static class cost_pair *
    3718    216347051 : get_group_iv_cost (struct ivopts_data *data, struct iv_group *group,
    3719              :                    struct iv_cand *cand)
    3720              : {
    3721    216347051 :   unsigned i, s;
    3722    216347051 :   class cost_pair *ret;
    3723              : 
    3724    216347051 :   if (!cand)
    3725              :     return NULL;
    3726              : 
    3727    210345663 :   if (data->consider_all_candidates)
    3728              :     {
    3729    195508505 :       ret = group->cost_map + cand->id;
    3730    195508505 :       if (!ret->cand)
    3731              :         return NULL;
    3732              : 
    3733    114314730 :       return ret;
    3734              :     }
    3735              : 
    3736              :   /* n_map_members is a power of two, so this computes modulo.  */
    3737     14837158 :   s = cand->id & (group->n_map_members - 1);
    3738     21113941 :   for (i = s; i < group->n_map_members; i++)
    3739     21024802 :     if (group->cost_map[i].cand == cand)
    3740              :       return group->cost_map + i;
    3741     12923718 :     else if (group->cost_map[i].cand == NULL)
    3742              :       return NULL;
    3743       258992 :   for (i = 0; i < s; i++)
    3744       231788 :     if (group->cost_map[i].cand == cand)
    3745              :       return group->cost_map + i;
    3746       230236 :     else if (group->cost_map[i].cand == NULL)
    3747              :       return NULL;
    3748              : 
    3749              :   return NULL;
    3750              : }
    3751              : 
    3752              : /* Produce DECL_RTL for object obj so it looks like it is stored in memory.  */
    3753              : static rtx
    3754        43826 : produce_memory_decl_rtl (tree obj, int *regno)
    3755              : {
    3756        43826 :   addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (obj));
    3757        43826 :   machine_mode address_mode = targetm.addr_space.address_mode (as);
    3758        43826 :   rtx x;
    3759              : 
    3760        43826 :   gcc_assert (obj);
    3761        43826 :   if (TREE_STATIC (obj) || DECL_EXTERNAL (obj))
    3762              :     {
    3763        43826 :       const char *name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (obj));
    3764        43826 :       x = gen_rtx_SYMBOL_REF (address_mode, name);
    3765        43826 :       SET_SYMBOL_REF_DECL (x, obj);
    3766        43826 :       x = gen_rtx_MEM (DECL_MODE (obj), x);
    3767        43826 :       set_mem_addr_space (x, as);
    3768        43826 :       targetm.encode_section_info (obj, x, true);
    3769              :     }
    3770              :   else
    3771              :     {
    3772            0 :       x = gen_raw_REG (address_mode, (*regno)++);
    3773            0 :       x = gen_rtx_MEM (DECL_MODE (obj), x);
    3774            0 :       set_mem_addr_space (x, as);
    3775              :     }
    3776              : 
    3777        43826 :   return x;
    3778              : }
    3779              : 
    3780              : /* Prepares decl_rtl for variables referred in *EXPR_P.  Callback for
    3781              :    walk_tree.  DATA contains the actual fake register number.  */
    3782              : 
    3783              : static tree
    3784       613564 : prepare_decl_rtl (tree *expr_p, int *ws, void *data)
    3785              : {
    3786       613564 :   tree obj = NULL_TREE;
    3787       613564 :   rtx x = NULL_RTX;
    3788       613564 :   int *regno = (int *) data;
    3789              : 
    3790       613564 :   switch (TREE_CODE (*expr_p))
    3791              :     {
    3792       175304 :     case ADDR_EXPR:
    3793       175304 :       for (expr_p = &TREE_OPERAND (*expr_p, 0);
    3794       175304 :            handled_component_p (*expr_p);
    3795            0 :            expr_p = &TREE_OPERAND (*expr_p, 0))
    3796            0 :         continue;
    3797       175304 :       obj = *expr_p;
    3798       175304 :       if (DECL_P (obj) && HAS_RTL_P (obj) && !DECL_RTL_SET_P (obj))
    3799            0 :         x = produce_memory_decl_rtl (obj, regno);
    3800              :       break;
    3801              : 
    3802            0 :     case SSA_NAME:
    3803            0 :       *ws = 0;
    3804            0 :       obj = SSA_NAME_VAR (*expr_p);
    3805              :       /* Defer handling of anonymous SSA_NAMEs to the expander.  */
    3806            0 :       if (!obj)
    3807              :         return NULL_TREE;
    3808            0 :       if (!DECL_RTL_SET_P (obj))
    3809            0 :         x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
    3810              :       break;
    3811              : 
    3812       175304 :     case VAR_DECL:
    3813       175304 :     case PARM_DECL:
    3814       175304 :     case RESULT_DECL:
    3815       175304 :       *ws = 0;
    3816       175304 :       obj = *expr_p;
    3817              : 
    3818       175304 :       if (DECL_RTL_SET_P (obj))
    3819              :         break;
    3820              : 
    3821            0 :       if (DECL_MODE (obj) == BLKmode)
    3822            0 :         x = produce_memory_decl_rtl (obj, regno);
    3823              :       else
    3824            0 :         x = gen_raw_REG (DECL_MODE (obj), (*regno)++);
    3825              : 
    3826              :       break;
    3827              : 
    3828              :     default:
    3829              :       break;
    3830              :     }
    3831              : 
    3832            0 :   if (x)
    3833              :     {
    3834            0 :       decl_rtl_to_reset.safe_push (obj);
    3835            0 :       SET_DECL_RTL (obj, x);
    3836              :     }
    3837              : 
    3838              :   return NULL_TREE;
    3839              : }
    3840              : 
    3841              : /* Predict whether the given loop will be transformed in the RTL
    3842              :    doloop_optimize pass.  Attempt to duplicate some doloop_optimize checks.
    3843              :    This is only for target independent checks, see targetm.predict_doloop_p
    3844              :    for the target dependent ones.
    3845              : 
    3846              :    Note that according to some initial investigation, some checks like costly
    3847              :    niter check and invalid stmt scanning don't have much gains among general
    3848              :    cases, so keep this as simple as possible first.
    3849              : 
    3850              :    Some RTL specific checks seems unable to be checked in gimple, if any new
    3851              :    checks or easy checks _are_ missing here, please add them.  */
    3852              : 
    3853              : static bool
    3854       519403 : generic_predict_doloop_p (struct ivopts_data *data)
    3855              : {
    3856       519403 :   class loop *loop = data->current_loop;
    3857              : 
    3858              :   /* Call target hook for target dependent checks.  */
    3859       519403 :   if (!targetm.predict_doloop_p (loop))
    3860              :     {
    3861       519403 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3862           72 :         fprintf (dump_file, "Predict doloop failure due to"
    3863              :                             " target specific checks.\n");
    3864              :       return false;
    3865              :     }
    3866              : 
    3867              :   /* Similar to doloop_optimize, check iteration description to know it's
    3868              :      suitable or not.  Keep it as simple as possible, feel free to extend it
    3869              :      if you find any multiple exits cases matter.  */
    3870            0 :   edge exit = single_dom_exit (loop);
    3871            0 :   class tree_niter_desc *niter_desc;
    3872            0 :   if (!exit || !(niter_desc = niter_for_exit (data, exit)))
    3873              :     {
    3874            0 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3875            0 :         fprintf (dump_file, "Predict doloop failure due to"
    3876              :                             " unexpected niters.\n");
    3877              :       return false;
    3878              :     }
    3879              : 
    3880              :   /* Similar to doloop_optimize, check whether iteration count too small
    3881              :      and not profitable.  */
    3882            0 :   HOST_WIDE_INT est_niter = get_estimated_loop_iterations_int (loop);
    3883            0 :   if (est_niter == -1)
    3884            0 :     est_niter = get_likely_max_loop_iterations_int (loop);
    3885            0 :   if (est_niter >= 0 && est_niter < 3)
    3886              :     {
    3887            0 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3888            0 :         fprintf (dump_file,
    3889              :                  "Predict doloop failure due to"
    3890              :                  " too few iterations (%u).\n",
    3891              :                  (unsigned int) est_niter);
    3892              :       return false;
    3893              :     }
    3894              : 
    3895              :   return true;
    3896              : }
    3897              : 
    3898              : /* Determines cost of the computation of EXPR.  */
    3899              : 
    3900              : static unsigned
    3901       262956 : computation_cost (tree expr, bool speed)
    3902              : {
    3903       262956 :   rtx_insn *seq;
    3904       262956 :   rtx rslt;
    3905       262956 :   tree type = TREE_TYPE (expr);
    3906       262956 :   unsigned cost;
    3907              :   /* Avoid using hard regs in ways which may be unsupported.  */
    3908       262956 :   int regno = LAST_VIRTUAL_REGISTER + 1;
    3909       262956 :   struct cgraph_node *node = cgraph_node::get (current_function_decl);
    3910       262956 :   enum node_frequency real_frequency = node->frequency;
    3911              : 
    3912       262956 :   node->frequency = NODE_FREQUENCY_NORMAL;
    3913       262956 :   crtl->maybe_hot_insn_p = speed;
    3914       262956 :   walk_tree (&expr, prepare_decl_rtl, &regno, NULL);
    3915       262956 :   start_sequence ();
    3916       262956 :   rslt = expand_expr (expr, NULL_RTX, TYPE_MODE (type), EXPAND_NORMAL);
    3917       262956 :   seq = end_sequence ();
    3918       262956 :   default_rtl_profile ();
    3919       262956 :   node->frequency = real_frequency;
    3920              : 
    3921       262956 :   cost = seq_cost (seq, speed);
    3922       262956 :   if (MEM_P (rslt))
    3923            0 :     cost += address_cost (XEXP (rslt, 0), TYPE_MODE (type),
    3924            0 :                           TYPE_ADDR_SPACE (type), speed);
    3925       262956 :   else if (!REG_P (rslt))
    3926       525912 :     cost += set_src_cost (rslt, TYPE_MODE (type), speed);
    3927              : 
    3928       262956 :   return cost;
    3929              : }
    3930              : 
    3931              : /* Returns variable containing the value of candidate CAND at statement AT.  */
    3932              : 
    3933              : static tree
    3934     18754195 : var_at_stmt (class loop *loop, struct iv_cand *cand, gimple *stmt)
    3935              : {
    3936     18754195 :   if (stmt_after_increment (loop, cand, stmt))
    3937      4885079 :     return cand->var_after;
    3938              :   else
    3939     13869116 :     return cand->var_before;
    3940              : }
    3941              : 
    3942              : /* If A is (TYPE) BA and B is (TYPE) BB, and the types of BA and BB have the
    3943              :    same precision that is at least as wide as the precision of TYPE, stores
    3944              :    BA to A and BB to B, and returns the type of BA.  Otherwise, returns the
    3945              :    type of A and B.  */
    3946              : 
    3947              : static tree
    3948     14429460 : determine_common_wider_type (tree *a, tree *b)
    3949              : {
    3950     14429460 :   tree wider_type = NULL;
    3951     14429460 :   tree suba, subb;
    3952     14429460 :   tree atype = TREE_TYPE (*a);
    3953              : 
    3954     14429460 :   if (CONVERT_EXPR_P (*a))
    3955              :     {
    3956      8045257 :       suba = TREE_OPERAND (*a, 0);
    3957      8045257 :       wider_type = TREE_TYPE (suba);
    3958      8045257 :       if (TYPE_PRECISION (wider_type) < TYPE_PRECISION (atype))
    3959              :         return atype;
    3960              :     }
    3961              :   else
    3962              :     return atype;
    3963              : 
    3964      8025860 :   if (CONVERT_EXPR_P (*b))
    3965              :     {
    3966      1652629 :       subb = TREE_OPERAND (*b, 0);
    3967      1652629 :       if (TYPE_PRECISION (wider_type) != TYPE_PRECISION (TREE_TYPE (subb)))
    3968              :         return atype;
    3969              :     }
    3970              :   else
    3971              :     return atype;
    3972              : 
    3973      1579786 :   *a = suba;
    3974      1579786 :   *b = subb;
    3975      1579786 :   return wider_type;
    3976              : }
    3977              : 
    3978              : /* Determines the expression by that USE is expressed from induction variable
    3979              :    CAND at statement AT in DATA's current loop.  The expression is stored in
    3980              :    two parts in a decomposed form.  The invariant part is stored in AFF_INV;
    3981              :    while variant part in AFF_VAR.  Store ratio of CAND.step over USE.step in
    3982              :    PRAT if it's non-null.  Returns false if USE cannot be expressed using
    3983              :    CAND.  */
    3984              : 
    3985              : static bool
    3986     17464121 : get_computation_aff_1 (struct ivopts_data *data, gimple *at, struct iv_use *use,
    3987              :                        struct iv_cand *cand, class aff_tree *aff_inv,
    3988              :                        class aff_tree *aff_var, widest_int *prat = NULL)
    3989              : {
    3990     17464121 :   tree ubase = use->iv->base, ustep = use->iv->step;
    3991     17464121 :   tree cbase = cand->iv->base, cstep = cand->iv->step;
    3992     17464121 :   tree common_type, uutype, var, cstep_common;
    3993     17464121 :   tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
    3994     17464121 :   aff_tree aff_cbase;
    3995     17464121 :   widest_int rat;
    3996              : 
    3997              :   /* We must have a precision to express the values of use.  */
    3998     17464121 :   if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
    3999              :     return false;
    4000              : 
    4001     17460974 :   var = var_at_stmt (data->current_loop, cand, at);
    4002     17460974 :   uutype = unsigned_type_for (utype);
    4003              : 
    4004              :   /* If the conversion is not noop, perform it.  */
    4005     17460974 :   if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
    4006              :     {
    4007       269951 :       if (cand->orig_iv != NULL && CONVERT_EXPR_P (cbase)
    4008      1698085 :           && (CONVERT_EXPR_P (cstep) || poly_int_tree_p (cstep)))
    4009              :         {
    4010        31237 :           tree inner_base, inner_step, inner_type;
    4011        31237 :           inner_base = TREE_OPERAND (cbase, 0);
    4012        31237 :           if (CONVERT_EXPR_P (cstep))
    4013         1466 :             inner_step = TREE_OPERAND (cstep, 0);
    4014              :           else
    4015              :             inner_step = cstep;
    4016              : 
    4017        31237 :           inner_type = TREE_TYPE (inner_base);
    4018              :           /* If candidate is added from a biv whose type is smaller than
    4019              :              ctype, we know both candidate and the biv won't overflow.
    4020              :              In this case, it's safe to skip the conversion in candidate.
    4021              :              As an example, (unsigned short)((unsigned long)A) equals to
    4022              :              (unsigned short)A, if A has a type no larger than short.  */
    4023        31237 :           if (TYPE_PRECISION (inner_type) <= TYPE_PRECISION (uutype))
    4024              :             {
    4025        30318 :               cbase = inner_base;
    4026        30318 :               cstep = inner_step;
    4027              :             }
    4028              :         }
    4029      1666848 :       cbase = fold_convert (uutype, cbase);
    4030      1666848 :       cstep = fold_convert (uutype, cstep);
    4031      1666848 :       var = fold_convert (uutype, var);
    4032              :     }
    4033              : 
    4034              :   /* Ratio is 1 when computing the value of biv cand by itself.
    4035              :      We can't rely on constant_multiple_of in this case because the
    4036              :      use is created after the original biv is selected.  The call
    4037              :      could fail because of inconsistent fold behavior.  See PR68021
    4038              :      for more information.  */
    4039     17460974 :   if (cand->pos == IP_ORIGINAL && cand->incremented_at == use->stmt)
    4040              :     {
    4041         2901 :       gcc_assert (is_gimple_assign (use->stmt));
    4042         2901 :       gcc_assert (use->iv->ssa_name == cand->var_after);
    4043         2901 :       gcc_assert (gimple_assign_lhs (use->stmt) == cand->var_after);
    4044         2901 :       rat = 1;
    4045              :     }
    4046     17458073 :   else if (!constant_multiple_of (ustep, cstep, &rat, data))
    4047              :     return false;
    4048              : 
    4049     14429460 :   if (prat)
    4050     12939581 :     *prat = rat;
    4051              : 
    4052              :   /* In case both UBASE and CBASE are shortened to UUTYPE from some common
    4053              :      type, we achieve better folding by computing their difference in this
    4054              :      wider type, and cast the result to UUTYPE.  We do not need to worry about
    4055              :      overflows, as all the arithmetics will in the end be performed in UUTYPE
    4056              :      anyway.  */
    4057     14429460 :   common_type = determine_common_wider_type (&ubase, &cbase);
    4058              : 
    4059              :   /* use = ubase - ratio * cbase + ratio * var.  */
    4060     14429460 :   tree_to_aff_combination (ubase, common_type, aff_inv, at);
    4061     14429460 :   tree_to_aff_combination (cbase, common_type, &aff_cbase, at);
    4062     14429460 :   tree_to_aff_combination (var, uutype, aff_var, at);
    4063              : 
    4064              :   /* We need to shift the value if we are after the increment.  */
    4065     14429460 :   if (stmt_after_increment (data->current_loop, cand, at))
    4066              :     {
    4067      3311662 :       aff_tree cstep_aff;
    4068              : 
    4069      3311662 :       if (common_type != uutype)
    4070       852107 :         cstep_common = fold_convert (common_type, cstep);
    4071              :       else
    4072              :         cstep_common = cstep;
    4073              : 
    4074      3311662 :       tree_to_aff_combination (cstep_common, common_type, &cstep_aff, at);
    4075      3311662 :       aff_combination_add (&aff_cbase, &cstep_aff);
    4076      3311662 :     }
    4077              : 
    4078     14429460 :   aff_combination_scale (&aff_cbase, -rat);
    4079     14429460 :   aff_combination_add (aff_inv, &aff_cbase);
    4080     14429460 :   if (common_type != uutype)
    4081      9729613 :     aff_combination_convert (aff_inv, uutype, at);
    4082              : 
    4083     14429460 :   aff_combination_scale (aff_var, rat);
    4084     14429460 :   return true;
    4085     17464121 : }
    4086              : 
    4087              : /* Determines the expression by that USE is expressed from induction variable
    4088              :    CAND at statement AT in DATA's current loop.  The expression is stored in a
    4089              :    decomposed form into AFF.  Returns false if USE cannot be expressed using
    4090              :    CAND.  */
    4091              : 
    4092              : static bool
    4093      1273168 : get_computation_aff (struct ivopts_data *data, gimple *at, struct iv_use *use,
    4094              :                      struct iv_cand *cand, class aff_tree *aff)
    4095              : {
    4096      1273168 :   aff_tree aff_var;
    4097              : 
    4098      1273168 :   if (!get_computation_aff_1 (data, at, use, cand, aff, &aff_var))
    4099              :     return false;
    4100              : 
    4101      1142202 :   aff_combination_add (aff, &aff_var);
    4102      1142202 :   return true;
    4103      1273168 : }
    4104              : 
    4105              : /* Return the type of USE.  */
    4106              : 
    4107              : static tree
    4108      1038207 : get_use_type (struct iv_use *use)
    4109              : {
    4110      1038207 :   tree base_type = TREE_TYPE (use->iv->base);
    4111      1038207 :   tree type;
    4112              : 
    4113      1038207 :   if (use->type == USE_REF_ADDRESS)
    4114              :     {
    4115              :       /* The base_type may be a void pointer.  Create a pointer type based on
    4116              :          the mem_ref instead.  */
    4117            0 :       type = build_pointer_type (TREE_TYPE (*use->op_p));
    4118            0 :       gcc_assert (TYPE_ADDR_SPACE (TREE_TYPE (type))
    4119              :                   == TYPE_ADDR_SPACE (TREE_TYPE (base_type)));
    4120              :     }
    4121              :   else
    4122              :     type = base_type;
    4123              : 
    4124      1038207 :   return type;
    4125              : }
    4126              : 
    4127              : /* Determines the expression by that USE is expressed from induction variable
    4128              :    CAND at statement AT in DATA's current loop.  The computation is
    4129              :    unshared.  */
    4130              : 
    4131              : static tree
    4132       400177 : get_computation_at (struct ivopts_data *data, gimple *at,
    4133              :                     struct iv_use *use, struct iv_cand *cand)
    4134              : {
    4135       400177 :   aff_tree aff;
    4136       400177 :   tree type = get_use_type (use);
    4137              : 
    4138       400177 :   if (!get_computation_aff (data, at, use, cand, &aff))
    4139              :     return NULL_TREE;
    4140       269211 :   unshare_aff_combination (&aff);
    4141       269211 :   return fold_convert (type, aff_combination_to_tree (&aff));
    4142       400177 : }
    4143              : 
    4144              : /* Like get_computation_at, but try harder, even if the computation
    4145              :    is more expensive.  Intended for debug stmts.  */
    4146              : 
    4147              : static tree
    4148       200120 : get_debug_computation_at (struct ivopts_data *data, gimple *at,
    4149              :                           struct iv_use *use, struct iv_cand *cand)
    4150              : {
    4151       200120 :   if (tree ret = get_computation_at (data, at, use, cand))
    4152              :     return ret;
    4153              : 
    4154       130966 :   tree ubase = use->iv->base, ustep = use->iv->step;
    4155       130966 :   tree cbase = cand->iv->base, cstep = cand->iv->step;
    4156       130966 :   tree var;
    4157       130966 :   tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
    4158       130966 :   widest_int rat;
    4159              : 
    4160              :   /* We must have a precision to express the values of use.  */
    4161       130966 :   if (TYPE_PRECISION (utype) >= TYPE_PRECISION (ctype))
    4162              :     return NULL_TREE;
    4163              : 
    4164              :   /* Try to handle the case that get_computation_at doesn't,
    4165              :      try to express
    4166              :      use = ubase + (var - cbase) / ratio.  */
    4167         9757 :   if (!constant_multiple_of (cstep, fold_convert (TREE_TYPE (cstep), ustep),
    4168              :                              &rat, data))
    4169              :     return NULL_TREE;
    4170              : 
    4171         8597 :   bool neg_p = false;
    4172         8597 :   if (wi::neg_p (rat))
    4173              :     {
    4174          877 :       if (TYPE_UNSIGNED (ctype))
    4175              :         return NULL_TREE;
    4176            0 :       neg_p = true;
    4177            0 :       rat = wi::neg (rat);
    4178              :     }
    4179              : 
    4180              :   /* If both IVs can wrap around and CAND doesn't have a power of two step,
    4181              :      it is unsafe.  Consider uint16_t CAND with step 9, when wrapping around,
    4182              :      the values will be ... 0xfff0, 0xfff9, 2, 11 ... and when use is say
    4183              :      uint8_t with step 3, those values divided by 3 cast to uint8_t will be
    4184              :      ... 0x50, 0x53, 0, 3 ... rather than expected 0x50, 0x53, 0x56, 0x59.  */
    4185         7720 :   if (!use->iv->no_overflow
    4186           70 :       && !cand->iv->no_overflow
    4187         7778 :       && !integer_pow2p (cstep))
    4188              :     return NULL_TREE;
    4189              : 
    4190         7705 :   int bits = wi::exact_log2 (rat);
    4191         7705 :   if (bits == -1)
    4192          772 :     bits = wi::floor_log2 (rat) + 1;
    4193         7705 :   if (!cand->iv->no_overflow
    4194         7705 :       && TYPE_PRECISION (utype) + bits > TYPE_PRECISION (ctype))
    4195              :     return NULL_TREE;
    4196              : 
    4197         7705 :   var = var_at_stmt (data->current_loop, cand, at);
    4198              : 
    4199         7705 :   if (POINTER_TYPE_P (ctype))
    4200              :     {
    4201          135 :       ctype = unsigned_type_for (ctype);
    4202          135 :       cbase = fold_convert (ctype, cbase);
    4203          135 :       cstep = fold_convert (ctype, cstep);
    4204          135 :       var = fold_convert (ctype, var);
    4205              :     }
    4206              : 
    4207         7705 :   if (stmt_after_increment (data->current_loop, cand, at))
    4208           78 :     var = fold_build2 (MINUS_EXPR, TREE_TYPE (var), var,
    4209              :                        unshare_expr (cstep));
    4210              : 
    4211         7705 :   var = fold_build2 (MINUS_EXPR, TREE_TYPE (var), var, cbase);
    4212         7705 :   var = fold_build2 (EXACT_DIV_EXPR, TREE_TYPE (var), var,
    4213              :                      wide_int_to_tree (TREE_TYPE (var), rat));
    4214         7705 :   if (POINTER_TYPE_P (utype))
    4215              :     {
    4216            0 :       var = fold_convert (sizetype, var);
    4217            0 :       if (neg_p)
    4218            0 :         var = fold_build1 (NEGATE_EXPR, sizetype, var);
    4219            0 :       var = fold_build2 (POINTER_PLUS_EXPR, utype, ubase, var);
    4220              :     }
    4221              :   else
    4222              :     {
    4223         7705 :       var = fold_convert (utype, var);
    4224        15410 :       var = fold_build2 (neg_p ? MINUS_EXPR : PLUS_EXPR, utype,
    4225              :                          ubase, var);
    4226              :     }
    4227              :   return var;
    4228       200120 : }
    4229              : 
    4230              : /* Adjust the cost COST for being in loop setup rather than loop body.
    4231              :    If we're optimizing for space, the loop setup overhead is constant;
    4232              :    if we're optimizing for speed, amortize it over the per-iteration cost.
    4233              :    If ROUND_UP_P is true, the result is round up rather than to zero when
    4234              :    optimizing for speed.  */
    4235              : static int64_t
    4236     10664951 : adjust_setup_cost (struct ivopts_data *data, int64_t cost,
    4237              :                    bool round_up_p = false)
    4238              : {
    4239     10664951 :   if (cost == INFTY)
    4240              :     return cost;
    4241     10664951 :   else if (optimize_loop_for_speed_p (data->current_loop))
    4242              :     {
    4243      8971698 :       uint64_t niters = avg_loop_niter (data->current_loop);
    4244      8971698 :       if (niters > (uint64_t) cost)
    4245      7107956 :         return (round_up_p && cost != 0) ? 1 : 0;
    4246      1863742 :       return (cost + (round_up_p ? niters - 1 : 0)) / niters;
    4247              :     }
    4248              :   else
    4249              :     return cost;
    4250              : }
    4251              : 
    4252              : /* Calculate the SPEED or size cost of shiftadd EXPR in MODE.  MULT is the
    4253              :    EXPR operand holding the shift.  COST0 and COST1 are the costs for
    4254              :    calculating the operands of EXPR.  Returns true if successful, and returns
    4255              :    the cost in COST.  */
    4256              : 
    4257              : static bool
    4258      1445694 : get_shiftadd_cost (tree expr, scalar_int_mode mode, comp_cost cost0,
    4259              :                    comp_cost cost1, tree mult, bool speed, comp_cost *cost)
    4260              : {
    4261      1445694 :   comp_cost res;
    4262      1445694 :   tree op1 = TREE_OPERAND (expr, 1);
    4263      1445694 :   tree cst = TREE_OPERAND (mult, 1);
    4264      1445694 :   tree multop = TREE_OPERAND (mult, 0);
    4265      1445694 :   int m = exact_log2 (int_cst_value (cst));
    4266      4336818 :   int maxm = MIN (BITS_PER_WORD, GET_MODE_BITSIZE (mode));
    4267      1445694 :   int as_cost, sa_cost;
    4268      1445694 :   bool mult_in_op1;
    4269              : 
    4270      1445694 :   if (!(m >= 0 && m < maxm))
    4271              :     return false;
    4272              : 
    4273       963770 :   STRIP_NOPS (op1);
    4274       963770 :   mult_in_op1 = operand_equal_p (op1, mult, 0);
    4275              : 
    4276       963770 :   as_cost = add_cost (speed, mode) + shift_cost (speed, mode, m);
    4277              : 
    4278              :   /* If the target has a cheap shift-and-add or shift-and-sub instruction,
    4279              :      use that in preference to a shift insn followed by an add insn.  */
    4280       963770 :   sa_cost = (TREE_CODE (expr) != MINUS_EXPR
    4281       963770 :              ? shiftadd_cost (speed, mode, m)
    4282              :              : (mult_in_op1
    4283       132889 :                 ? shiftsub1_cost (speed, mode, m)
    4284        28905 :                 : shiftsub0_cost (speed, mode, m)));
    4285              : 
    4286       963770 :   res = comp_cost (MIN (as_cost, sa_cost), 0);
    4287      1769802 :   res += (mult_in_op1 ? cost0 : cost1);
    4288              : 
    4289       963770 :   STRIP_NOPS (multop);
    4290       963770 :   if (!is_gimple_val (multop))
    4291       498251 :     res += force_expr_to_var_cost (multop, speed);
    4292              : 
    4293       963770 :   *cost = res;
    4294       963770 :   return true;
    4295              : }
    4296              : 
    4297              : /* Estimates cost of forcing expression EXPR into a variable.  */
    4298              : 
    4299              : static comp_cost
    4300     29379519 : force_expr_to_var_cost (tree expr, bool speed)
    4301              : {
    4302     29379519 :   static bool costs_initialized = false;
    4303     29379519 :   static unsigned integer_cost [2];
    4304     29379519 :   static unsigned symbol_cost [2];
    4305     29379519 :   static unsigned address_cost [2];
    4306     29379519 :   tree op0, op1;
    4307     29379519 :   comp_cost cost0, cost1, cost;
    4308     29379519 :   machine_mode mode;
    4309     29379519 :   scalar_int_mode int_mode;
    4310              : 
    4311     29379519 :   if (!costs_initialized)
    4312              :     {
    4313        43826 :       tree type = build_pointer_type (integer_type_node);
    4314        43826 :       tree var, addr;
    4315        43826 :       rtx x;
    4316        43826 :       int i;
    4317              : 
    4318        43826 :       var = create_tmp_var_raw (integer_type_node, "test_var");
    4319        43826 :       TREE_STATIC (var) = 1;
    4320        43826 :       x = produce_memory_decl_rtl (var, NULL);
    4321        43826 :       SET_DECL_RTL (var, x);
    4322              : 
    4323        43826 :       addr = build1 (ADDR_EXPR, type, var);
    4324              : 
    4325              : 
    4326       175304 :       for (i = 0; i < 2; i++)
    4327              :         {
    4328        87652 :           integer_cost[i] = computation_cost (build_int_cst (integer_type_node,
    4329              :                                                              2000), i);
    4330              : 
    4331        87652 :           symbol_cost[i] = computation_cost (addr, i) + 1;
    4332              : 
    4333        87652 :           address_cost[i]
    4334        87652 :             = computation_cost (fold_build_pointer_plus_hwi (addr, 2000), i) + 1;
    4335        87652 :           if (dump_file && (dump_flags & TDF_DETAILS))
    4336              :             {
    4337          114 :               fprintf (dump_file, "force_expr_to_var_cost %s costs:\n", i ? "speed" : "size");
    4338           76 :               fprintf (dump_file, "  integer %d\n", (int) integer_cost[i]);
    4339           76 :               fprintf (dump_file, "  symbol %d\n", (int) symbol_cost[i]);
    4340           76 :               fprintf (dump_file, "  address %d\n", (int) address_cost[i]);
    4341           76 :               fprintf (dump_file, "  other %d\n", (int) target_spill_cost[i]);
    4342           76 :               fprintf (dump_file, "\n");
    4343              :             }
    4344              :         }
    4345              : 
    4346        43826 :       costs_initialized = true;
    4347              :     }
    4348              : 
    4349     29379519 :   STRIP_NOPS (expr);
    4350              : 
    4351     29379519 :   if (SSA_VAR_P (expr))
    4352      5435354 :     return no_cost;
    4353              : 
    4354     23944165 :   if (is_gimple_min_invariant (expr))
    4355              :     {
    4356     14380108 :       if (poly_int_tree_p (expr))
    4357     12186330 :         return comp_cost (integer_cost [speed], 0);
    4358              : 
    4359      2193778 :       if (TREE_CODE (expr) == ADDR_EXPR)
    4360              :         {
    4361      2193778 :           tree obj = TREE_OPERAND (expr, 0);
    4362              : 
    4363      2193778 :           if (VAR_P (obj)
    4364              :               || TREE_CODE (obj) == PARM_DECL
    4365              :               || TREE_CODE (obj) == RESULT_DECL)
    4366      2128038 :             return comp_cost (symbol_cost [speed], 0);
    4367              :         }
    4368              : 
    4369        65740 :       return comp_cost (address_cost [speed], 0);
    4370              :     }
    4371              : 
    4372      9564057 :   switch (TREE_CODE (expr))
    4373              :     {
    4374      8191952 :     case POINTER_PLUS_EXPR:
    4375      8191952 :     case PLUS_EXPR:
    4376      8191952 :     case MINUS_EXPR:
    4377      8191952 :     case MULT_EXPR:
    4378      8191952 :     case EXACT_DIV_EXPR:
    4379      8191952 :     case TRUNC_DIV_EXPR:
    4380      8191952 :     case BIT_AND_EXPR:
    4381      8191952 :     case BIT_IOR_EXPR:
    4382      8191952 :     case LSHIFT_EXPR:
    4383      8191952 :     case RSHIFT_EXPR:
    4384      8191952 :       op0 = TREE_OPERAND (expr, 0);
    4385      8191952 :       op1 = TREE_OPERAND (expr, 1);
    4386      8191952 :       STRIP_NOPS (op0);
    4387      8191952 :       STRIP_NOPS (op1);
    4388      8191952 :       break;
    4389              : 
    4390      1372071 :     CASE_CONVERT:
    4391      1372071 :     case NEGATE_EXPR:
    4392      1372071 :     case BIT_NOT_EXPR:
    4393      1372071 :       op0 = TREE_OPERAND (expr, 0);
    4394      1372071 :       STRIP_NOPS (op0);
    4395      1372071 :       op1 = NULL_TREE;
    4396      1372071 :       break;
    4397              :     /* See add_iv_candidate_for_doloop, for doloop may_be_zero case, we
    4398              :        introduce COND_EXPR for IV base, need to support better cost estimation
    4399              :        for this COND_EXPR and tcc_comparison.  */
    4400            0 :     case COND_EXPR:
    4401            0 :       op0 = TREE_OPERAND (expr, 1);
    4402            0 :       STRIP_NOPS (op0);
    4403            0 :       op1 = TREE_OPERAND (expr, 2);
    4404            0 :       STRIP_NOPS (op1);
    4405            0 :       break;
    4406            0 :     case LT_EXPR:
    4407            0 :     case LE_EXPR:
    4408            0 :     case GT_EXPR:
    4409            0 :     case GE_EXPR:
    4410            0 :     case EQ_EXPR:
    4411            0 :     case NE_EXPR:
    4412            0 :     case UNORDERED_EXPR:
    4413            0 :     case ORDERED_EXPR:
    4414            0 :     case UNLT_EXPR:
    4415            0 :     case UNLE_EXPR:
    4416            0 :     case UNGT_EXPR:
    4417            0 :     case UNGE_EXPR:
    4418            0 :     case UNEQ_EXPR:
    4419            0 :     case LTGT_EXPR:
    4420            0 :     case MAX_EXPR:
    4421            0 :     case MIN_EXPR:
    4422            0 :       op0 = TREE_OPERAND (expr, 0);
    4423            0 :       STRIP_NOPS (op0);
    4424            0 :       op1 = TREE_OPERAND (expr, 1);
    4425            0 :       STRIP_NOPS (op1);
    4426            0 :       break;
    4427              : 
    4428           34 :     default:
    4429              :       /* Just an arbitrary value, FIXME.  */
    4430           34 :       return comp_cost (target_spill_cost[speed], 0);
    4431              :     }
    4432              : 
    4433      9564023 :   if (op0 == NULL_TREE
    4434      9564023 :       || TREE_CODE (op0) == SSA_NAME || CONSTANT_CLASS_P (op0))
    4435      4527076 :     cost0 = no_cost;
    4436              :   else
    4437      5036947 :     cost0 = force_expr_to_var_cost (op0, speed);
    4438              : 
    4439      9564023 :   if (op1 == NULL_TREE
    4440      8191952 :       || TREE_CODE (op1) == SSA_NAME || CONSTANT_CLASS_P (op1))
    4441      8813884 :     cost1 = no_cost;
    4442              :   else
    4443       750139 :     cost1 = force_expr_to_var_cost (op1, speed);
    4444              : 
    4445      9564023 :   mode = TYPE_MODE (TREE_TYPE (expr));
    4446      9564023 :   switch (TREE_CODE (expr))
    4447              :     {
    4448      5753943 :     case POINTER_PLUS_EXPR:
    4449      5753943 :     case PLUS_EXPR:
    4450      5753943 :     case MINUS_EXPR:
    4451      5753943 :     case NEGATE_EXPR:
    4452      5753943 :       cost = comp_cost (add_cost (speed, mode), 0);
    4453      5753943 :       if (TREE_CODE (expr) != NEGATE_EXPR)
    4454              :         {
    4455      5613531 :           tree mult = NULL_TREE;
    4456      5613531 :           comp_cost sa_cost;
    4457      5613531 :           if (TREE_CODE (op1) == MULT_EXPR)
    4458              :             mult = op1;
    4459      5240748 :           else if (TREE_CODE (op0) == MULT_EXPR)
    4460              :             mult = op0;
    4461              : 
    4462              :           if (mult != NULL_TREE
    4463      4649761 :               && is_a <scalar_int_mode> (mode, &int_mode)
    4464      1693661 :               && cst_and_fits_in_hwi (TREE_OPERAND (mult, 1))
    4465      1445694 :               && get_shiftadd_cost (expr, int_mode, cost0, cost1, mult,
    4466              :                                     speed, &sa_cost))
    4467       963770 :             return sa_cost;
    4468              :         }
    4469              :       break;
    4470              : 
    4471      1219326 :     CASE_CONVERT:
    4472      1219326 :       {
    4473      1219326 :         tree inner_mode, outer_mode;
    4474      1219326 :         outer_mode = TREE_TYPE (expr);
    4475      1219326 :         inner_mode = TREE_TYPE (op0);
    4476      1219326 :         cost = comp_cost (convert_cost (TYPE_MODE (outer_mode),
    4477      1219326 :                                        TYPE_MODE (inner_mode), speed), 0);
    4478              :       }
    4479      1219326 :       break;
    4480              : 
    4481      2489274 :     case MULT_EXPR:
    4482      2489274 :       if (cst_and_fits_in_hwi (op0))
    4483            0 :         cost = comp_cost (mult_by_coeff_cost (int_cst_value (op0),
    4484            0 :                                              mode, speed), 0);
    4485      2489274 :       else if (cst_and_fits_in_hwi (op1))
    4486      2011628 :         cost = comp_cost (mult_by_coeff_cost (int_cst_value (op1),
    4487      2011628 :                                              mode, speed), 0);
    4488              :       else
    4489       477646 :         return comp_cost (target_spill_cost [speed], 0);
    4490              :       break;
    4491              : 
    4492        45938 :     case EXACT_DIV_EXPR:
    4493        45938 :     case TRUNC_DIV_EXPR:
    4494              :       /* Division by power of two is usually cheap, so we allow it.  Forbid
    4495              :          anything else.  */
    4496        45938 :       if (integer_pow2p (TREE_OPERAND (expr, 1)))
    4497        45938 :         cost = comp_cost (add_cost (speed, mode), 0);
    4498              :       else
    4499            0 :         cost = comp_cost (target_spill_cost[speed], 0);
    4500              :       break;
    4501              : 
    4502        55542 :     case BIT_AND_EXPR:
    4503        55542 :     case BIT_IOR_EXPR:
    4504        55542 :     case BIT_NOT_EXPR:
    4505        55542 :     case LSHIFT_EXPR:
    4506        55542 :     case RSHIFT_EXPR:
    4507        55542 :       cost = comp_cost (add_cost (speed, mode), 0);
    4508        55542 :       break;
    4509            0 :     case COND_EXPR:
    4510            0 :       op0 = TREE_OPERAND (expr, 0);
    4511            0 :       STRIP_NOPS (op0);
    4512            0 :       if (op0 == NULL_TREE || TREE_CODE (op0) == SSA_NAME
    4513            0 :           || CONSTANT_CLASS_P (op0))
    4514            0 :         cost = no_cost;
    4515              :       else
    4516            0 :         cost = force_expr_to_var_cost (op0, speed);
    4517              :       break;
    4518            0 :     case LT_EXPR:
    4519            0 :     case LE_EXPR:
    4520            0 :     case GT_EXPR:
    4521            0 :     case GE_EXPR:
    4522            0 :     case EQ_EXPR:
    4523            0 :     case NE_EXPR:
    4524            0 :     case UNORDERED_EXPR:
    4525            0 :     case ORDERED_EXPR:
    4526            0 :     case UNLT_EXPR:
    4527            0 :     case UNLE_EXPR:
    4528            0 :     case UNGT_EXPR:
    4529            0 :     case UNGE_EXPR:
    4530            0 :     case UNEQ_EXPR:
    4531            0 :     case LTGT_EXPR:
    4532            0 :     case MAX_EXPR:
    4533            0 :     case MIN_EXPR:
    4534              :       /* Simply use add cost for now, FIXME if there is some more accurate cost
    4535              :          evaluation way.  */
    4536            0 :       cost = comp_cost (add_cost (speed, mode), 0);
    4537            0 :       break;
    4538              : 
    4539            0 :     default:
    4540            0 :       gcc_unreachable ();
    4541              :     }
    4542              : 
    4543      8122607 :   cost += cost0;
    4544      8122607 :   cost += cost1;
    4545      8122607 :   return cost;
    4546              : }
    4547              : 
    4548              : /* Estimates cost of forcing EXPR into a variable.  INV_VARS is a set of the
    4549              :    invariants the computation depends on.  */
    4550              : 
    4551              : static comp_cost
    4552     25183865 : force_var_cost (struct ivopts_data *data, tree expr, bitmap *inv_vars)
    4553              : {
    4554     25183865 :   if (!expr)
    4555      2089683 :     return no_cost;
    4556              : 
    4557     23094182 :   find_inv_vars (data, &expr, inv_vars);
    4558     23094182 :   return force_expr_to_var_cost (expr, data->speed);
    4559              : }
    4560              : 
    4561              : /* Returns cost of auto-modifying address expression in shape base + offset.
    4562              :    AINC_STEP is step size of the address IV.  AINC_OFFSET is offset of the
    4563              :    address expression.  The address expression has ADDR_MODE in addr space
    4564              :    AS.  The memory access has MEM_MODE.  SPEED means we are optimizing for
    4565              :    speed or size.  */
    4566              : 
    4567              : enum ainc_type
    4568              : {
    4569              :   AINC_PRE_INC,         /* Pre increment.  */
    4570              :   AINC_PRE_DEC,         /* Pre decrement.  */
    4571              :   AINC_POST_INC,        /* Post increment.  */
    4572              :   AINC_POST_DEC,        /* Post decrement.  */
    4573              :   AINC_NONE             /* Also the number of auto increment types.  */
    4574              : };
    4575              : 
    4576              : struct ainc_cost_data
    4577              : {
    4578              :   int64_t costs[AINC_NONE];
    4579              : };
    4580              : 
    4581              : static comp_cost
    4582      1775955 : get_address_cost_ainc (poly_int64 ainc_step, poly_int64 ainc_offset,
    4583              :                        machine_mode addr_mode, machine_mode mem_mode,
    4584              :                        addr_space_t as, bool speed)
    4585              : {
    4586      1775955 :   if (!USE_LOAD_PRE_DECREMENT (mem_mode)
    4587              :       && !USE_STORE_PRE_DECREMENT (mem_mode)
    4588              :       && !USE_LOAD_POST_DECREMENT (mem_mode)
    4589              :       && !USE_STORE_POST_DECREMENT (mem_mode)
    4590              :       && !USE_LOAD_PRE_INCREMENT (mem_mode)
    4591              :       && !USE_STORE_PRE_INCREMENT (mem_mode)
    4592              :       && !USE_LOAD_POST_INCREMENT (mem_mode)
    4593              :       && !USE_STORE_POST_INCREMENT (mem_mode))
    4594      1775955 :     return infinite_cost;
    4595              : 
    4596              :   static vec<ainc_cost_data *> ainc_cost_data_list;
    4597              :   unsigned idx = (unsigned) as * MAX_MACHINE_MODE + (unsigned) mem_mode;
    4598              :   if (idx >= ainc_cost_data_list.length ())
    4599              :     {
    4600              :       unsigned nsize = ((unsigned) as + 1) *MAX_MACHINE_MODE;
    4601              : 
    4602              :       gcc_assert (nsize > idx);
    4603              :       ainc_cost_data_list.safe_grow_cleared (nsize, true);
    4604              :     }
    4605              : 
    4606              :   ainc_cost_data *data = ainc_cost_data_list[idx];
    4607              :   if (data == NULL)
    4608              :     {
    4609              :       rtx reg = gen_raw_REG (addr_mode, LAST_VIRTUAL_REGISTER + 1);
    4610              : 
    4611              :       data = (ainc_cost_data *) xcalloc (1, sizeof (*data));
    4612              :       data->costs[AINC_PRE_DEC] = INFTY;
    4613              :       data->costs[AINC_POST_DEC] = INFTY;
    4614              :       data->costs[AINC_PRE_INC] = INFTY;
    4615              :       data->costs[AINC_POST_INC] = INFTY;
    4616              :       if (USE_LOAD_PRE_DECREMENT (mem_mode)
    4617              :           || USE_STORE_PRE_DECREMENT (mem_mode))
    4618              :         {
    4619              :           rtx addr = gen_rtx_PRE_DEC (addr_mode, reg);
    4620              : 
    4621              :           if (memory_address_addr_space_p (mem_mode, addr, as))
    4622              :             data->costs[AINC_PRE_DEC]
    4623              :               = address_cost (addr, mem_mode, as, speed);
    4624              :         }
    4625              :       if (USE_LOAD_POST_DECREMENT (mem_mode)
    4626              :           || USE_STORE_POST_DECREMENT (mem_mode))
    4627              :         {
    4628              :           rtx addr = gen_rtx_POST_DEC (addr_mode, reg);
    4629              : 
    4630              :           if (memory_address_addr_space_p (mem_mode, addr, as))
    4631              :             data->costs[AINC_POST_DEC]
    4632              :               = address_cost (addr, mem_mode, as, speed);
    4633              :         }
    4634              :       if (USE_LOAD_PRE_INCREMENT (mem_mode)
    4635              :           || USE_STORE_PRE_INCREMENT (mem_mode))
    4636              :         {
    4637              :           rtx addr = gen_rtx_PRE_INC (addr_mode, reg);
    4638              : 
    4639              :           if (memory_address_addr_space_p (mem_mode, addr, as))
    4640              :             data->costs[AINC_PRE_INC]
    4641              :               = address_cost (addr, mem_mode, as, speed);
    4642              :         }
    4643              :       if (USE_LOAD_POST_INCREMENT (mem_mode)
    4644              :           || USE_STORE_POST_INCREMENT (mem_mode))
    4645              :         {
    4646              :           rtx addr = gen_rtx_POST_INC (addr_mode, reg);
    4647              : 
    4648              :           if (memory_address_addr_space_p (mem_mode, addr, as))
    4649              :             data->costs[AINC_POST_INC]
    4650              :               = address_cost (addr, mem_mode, as, speed);
    4651              :         }
    4652              :       ainc_cost_data_list[idx] = data;
    4653              :     }
    4654              : 
    4655              :   poly_int64 msize = GET_MODE_SIZE (mem_mode);
    4656              :   if (known_eq (ainc_offset, 0) && known_eq (msize, ainc_step))
    4657              :     return comp_cost (data->costs[AINC_POST_INC], 0);
    4658              :   if (known_eq (ainc_offset, 0) && known_eq (msize, -ainc_step))
    4659              :     return comp_cost (data->costs[AINC_POST_DEC], 0);
    4660              :   if (known_eq (ainc_offset, msize) && known_eq (msize, ainc_step))
    4661              :     return comp_cost (data->costs[AINC_PRE_INC], 0);
    4662              :   if (known_eq (ainc_offset, -msize) && known_eq (msize, -ainc_step))
    4663              :     return comp_cost (data->costs[AINC_PRE_DEC], 0);
    4664              : 
    4665              :   return infinite_cost;
    4666              : }
    4667              : 
    4668              : /* Return cost of computing USE's address expression by using CAND.
    4669              :    AFF_INV and AFF_VAR represent invariant and variant parts of the
    4670              :    address expression, respectively.  If AFF_INV is simple, store
    4671              :    the loop invariant variables which are depended by it in INV_VARS;
    4672              :    if AFF_INV is complicated, handle it as a new invariant expression
    4673              :    and record it in INV_EXPR.  RATIO indicates multiple times between
    4674              :    steps of USE and CAND.  If CAN_AUTOINC is nonNULL, store boolean
    4675              :    value to it indicating if this is an auto-increment address.  */
    4676              : 
    4677              : static comp_cost
    4678      5566124 : get_address_cost (struct ivopts_data *data, struct iv_use *use,
    4679              :                   struct iv_cand *cand, aff_tree *aff_inv,
    4680              :                   aff_tree *aff_var, HOST_WIDE_INT ratio,
    4681              :                   bitmap *inv_vars, iv_inv_expr_ent **inv_expr,
    4682              :                   bool *can_autoinc, bool speed)
    4683              : {
    4684      5566124 :   rtx addr;
    4685      5566124 :   bool simple_inv = true;
    4686      5566124 :   tree comp_inv = NULL_TREE, type = aff_var->type;
    4687      5566124 :   comp_cost var_cost = no_cost, cost = no_cost;
    4688      5566124 :   struct mem_address parts = {NULL_TREE, integer_one_node,
    4689      5566124 :                               NULL_TREE, NULL_TREE, NULL_TREE};
    4690      5566124 :   machine_mode addr_mode = TYPE_MODE (type);
    4691      5566124 :   machine_mode mem_mode = TYPE_MODE (use->mem_type);
    4692      5566124 :   addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (use->iv->base));
    4693              :   /* Only true if ratio != 1.  */
    4694      5566124 :   bool ok_with_ratio_p = false;
    4695      5566124 :   bool ok_without_ratio_p = false;
    4696      5566124 :   code_helper code = ERROR_MARK;
    4697              : 
    4698      5566124 :   if (use->type == USE_PTR_ADDRESS)
    4699              :     {
    4700         4241 :       gcall *call = as_a<gcall *> (use->stmt);
    4701         4241 :       gcc_assert (gimple_call_internal_p (call));
    4702         4241 :       code = gimple_call_internal_fn (call);
    4703              :     }
    4704              : 
    4705      5566124 :   if (!aff_combination_const_p (aff_inv))
    4706              :     {
    4707      3722967 :       parts.index = integer_one_node;
    4708              :       /* Addressing mode "base + index".  */
    4709      3722967 :       ok_without_ratio_p = valid_mem_ref_p (mem_mode, as, &parts, code);
    4710      3722967 :       if (ratio != 1)
    4711              :         {
    4712      2835162 :           parts.step = wide_int_to_tree (type, ratio);
    4713              :           /* Addressing mode "base + index << scale".  */
    4714      2835162 :           ok_with_ratio_p = valid_mem_ref_p (mem_mode, as, &parts, code);
    4715      2835162 :           if (!ok_with_ratio_p)
    4716      1727801 :             parts.step = NULL_TREE;
    4717              :         }
    4718      2615606 :       if (ok_with_ratio_p || ok_without_ratio_p)
    4719              :         {
    4720      3722967 :           if (maybe_ne (aff_inv->offset, 0))
    4721              :             {
    4722      2428606 :               parts.offset = wide_int_to_tree (sizetype, aff_inv->offset);
    4723              :               /* Addressing mode "base + index [<< scale] + offset".  */
    4724      2428606 :               if (!valid_mem_ref_p (mem_mode, as, &parts, code))
    4725          421 :                 parts.offset = NULL_TREE;
    4726              :               else
    4727      2428185 :                 aff_inv->offset = 0;
    4728              :             }
    4729              : 
    4730      3722967 :           move_fixed_address_to_symbol (&parts, aff_inv);
    4731              :           /* Base is fixed address and is moved to symbol part.  */
    4732      3722967 :           if (parts.symbol != NULL_TREE && aff_combination_zero_p (aff_inv))
    4733       469651 :             parts.base = NULL_TREE;
    4734              : 
    4735              :           /* Addressing mode "symbol + base + index [<< scale] [+ offset]".  */
    4736      3722967 :           if (parts.symbol != NULL_TREE
    4737      3722967 :               && !valid_mem_ref_p (mem_mode, as, &parts, code))
    4738              :             {
    4739         7358 :               aff_combination_add_elt (aff_inv, parts.symbol, 1);
    4740         7358 :               parts.symbol = NULL_TREE;
    4741              :               /* Reset SIMPLE_INV since symbol address needs to be computed
    4742              :                  outside of address expression in this case.  */
    4743         7358 :               simple_inv = false;
    4744              :               /* Symbol part is moved back to base part, it can't be NULL.  */
    4745         7358 :               parts.base = integer_one_node;
    4746              :             }
    4747              :         }
    4748              :       else
    4749            0 :         parts.index = NULL_TREE;
    4750              :     }
    4751              :   else
    4752              :     {
    4753      1843157 :       poly_int64 ainc_step;
    4754      1843157 :       if (can_autoinc
    4755      1843157 :           && ratio == 1
    4756      3686306 :           && ptrdiff_tree_p (cand->iv->step, &ainc_step))
    4757              :         {
    4758      1775955 :           poly_int64 ainc_offset = (aff_inv->offset).force_shwi ();
    4759              : 
    4760      1775955 :           if (stmt_after_increment (data->current_loop, cand, use->stmt))
    4761              :             ainc_offset += ainc_step;
    4762      1775955 :           cost = get_address_cost_ainc (ainc_step, ainc_offset,
    4763              :                                         addr_mode, mem_mode, as, speed);
    4764      1775955 :           if (!cost.infinite_cost_p ())
    4765              :             {
    4766            0 :               *can_autoinc = true;
    4767            0 :               return cost;
    4768              :             }
    4769      1775955 :           cost = no_cost;
    4770              :         }
    4771      1843157 :       if (!aff_combination_zero_p (aff_inv))
    4772              :         {
    4773       997640 :           parts.offset = wide_int_to_tree (sizetype, aff_inv->offset);
    4774              :           /* Addressing mode "base + offset".  */
    4775       997640 :           if (!valid_mem_ref_p (mem_mode, as, &parts, code))
    4776           42 :             parts.offset = NULL_TREE;
    4777              :           else
    4778       997598 :             aff_inv->offset = 0;
    4779              :         }
    4780              :     }
    4781              : 
    4782      1850515 :   if (simple_inv)
    4783      5558766 :     simple_inv = (aff_inv == NULL
    4784      8818551 :                   || aff_combination_const_p (aff_inv)
    4785      8811193 :                   || aff_combination_singleton_var_p (aff_inv));
    4786      5566124 :   if (!aff_combination_zero_p (aff_inv))
    4787      3259857 :     comp_inv = aff_combination_to_tree (aff_inv);
    4788      3259857 :   if (comp_inv != NULL_TREE)
    4789      3259857 :     cost = force_var_cost (data, comp_inv, inv_vars);
    4790      5566124 :   if (ratio != 1 && parts.step == NULL_TREE)
    4791      1727809 :     var_cost += mult_by_coeff_cost (ratio, addr_mode, speed);
    4792      5566124 :   if (comp_inv != NULL_TREE && parts.index == NULL_TREE)
    4793           42 :     var_cost += add_cost (speed, addr_mode);
    4794              : 
    4795      5566124 :   if (comp_inv && inv_expr && !simple_inv)
    4796              :     {
    4797       738239 :       *inv_expr = get_loop_invariant_expr (data, comp_inv);
    4798              :       /* Clear depends on.  */
    4799       738239 :       if (*inv_expr != NULL && inv_vars && *inv_vars)
    4800       432425 :         bitmap_clear (*inv_vars);
    4801              : 
    4802              :       /* Cost of small invariant expression adjusted against loop niters
    4803              :          is usually zero, which makes it difficult to be differentiated
    4804              :          from candidate based on loop invariant variables.  Secondly, the
    4805              :          generated invariant expression may not be hoisted out of loop by
    4806              :          following pass.  We penalize the cost by rounding up in order to
    4807              :          neutralize such effects.  */
    4808       738239 :       cost.cost = adjust_setup_cost (data, cost.cost, true);
    4809       738239 :       cost.scratch = cost.cost;
    4810              :     }
    4811              : 
    4812      5566124 :   cost += var_cost;
    4813      5566124 :   addr = addr_for_mem_ref (&parts, as, false);
    4814      5566124 :   gcc_assert (memory_address_addr_space_p (mem_mode, addr, as));
    4815      5566124 :   cost += address_cost (addr, mem_mode, as, speed);
    4816              : 
    4817      5566124 :   if (parts.symbol != NULL_TREE)
    4818       524805 :     cost.complexity += 1;
    4819              :   /* Don't increase the complexity of adding a scaled index if it's
    4820              :      the only kind of index that the target allows.  */
    4821      5566124 :   if (parts.step != NULL_TREE && ok_without_ratio_p)
    4822      1107361 :     cost.complexity += 1;
    4823      5566124 :   if (parts.base != NULL_TREE && parts.index != NULL_TREE)
    4824      3259815 :     cost.complexity += 1;
    4825      5566124 :   if (parts.offset != NULL_TREE && !integer_zerop (parts.offset))
    4826      3425783 :     cost.complexity += 1;
    4827              : 
    4828              :   return cost;
    4829              : }
    4830              : 
    4831              : /* Scale (multiply) the computed COST (except scratch part that should be
    4832              :    hoisted out a loop) by header->frequency / AT->frequency, which makes
    4833              :    expected cost more accurate.  */
    4834              : 
    4835              : static comp_cost
    4836     12939581 : get_scaled_computation_cost_at (ivopts_data *data, gimple *at, comp_cost cost)
    4837              : {
    4838     12939581 :   if (data->speed
    4839     12939581 :       && data->current_loop->header->count.to_frequency (cfun) > 0)
    4840              :     {
    4841     11285912 :       basic_block bb = gimple_bb (at);
    4842     11285912 :       gcc_assert (cost.scratch <= cost.cost);
    4843     11285912 :       int scale_factor = (int)(intptr_t) bb->aux;
    4844     11285912 :       if (scale_factor == 1)
    4845     10742336 :         return cost;
    4846              : 
    4847       543576 :       int64_t scaled_cost
    4848       543576 :         = cost.scratch + (cost.cost - cost.scratch) * scale_factor;
    4849              : 
    4850       543576 :       if (dump_file && (dump_flags & TDF_DETAILS))
    4851           93 :         fprintf (dump_file, "Scaling cost based on bb prob by %2.2f: "
    4852              :                  "%" PRId64 " (scratch: %" PRId64 ") -> %" PRId64 "\n",
    4853              :                  1.0f * scale_factor, cost.cost, cost.scratch, scaled_cost);
    4854              : 
    4855              :       cost.cost = scaled_cost;
    4856              :     }
    4857              : 
    4858      2197245 :   return cost;
    4859              : }
    4860              : 
    4861              : /* Determines the cost of the computation by that USE is expressed
    4862              :    from induction variable CAND.  If ADDRESS_P is true, we just need
    4863              :    to create an address from it, otherwise we want to get it into
    4864              :    register.  A set of invariants we depend on is stored in INV_VARS.
    4865              :    If CAN_AUTOINC is nonnull, use it to record whether autoinc
    4866              :    addressing is likely.  If INV_EXPR is nonnull, record invariant
    4867              :    expr entry in it.  */
    4868              : 
    4869              : static comp_cost
    4870     20484571 : get_computation_cost (struct ivopts_data *data, struct iv_use *use,
    4871              :                       struct iv_cand *cand, bool address_p, bitmap *inv_vars,
    4872              :                       bool *can_autoinc, iv_inv_expr_ent **inv_expr)
    4873              : {
    4874     20484571 :   gimple *at = use->stmt;
    4875     20484571 :   tree ubase = use->iv->base, cbase = cand->iv->base;
    4876     20484571 :   tree utype = TREE_TYPE (ubase), ctype = TREE_TYPE (cbase);
    4877     20484571 :   tree comp_inv = NULL_TREE;
    4878     20484571 :   HOST_WIDE_INT ratio, aratio;
    4879     20484571 :   comp_cost cost;
    4880     20484571 :   widest_int rat;
    4881     40969142 :   aff_tree aff_inv, aff_var;
    4882     20484571 :   bool speed = optimize_bb_for_speed_p (gimple_bb (at));
    4883              : 
    4884     20484571 :   if (inv_vars)
    4885     18042313 :     *inv_vars = NULL;
    4886     20484571 :   if (can_autoinc)
    4887      8882697 :     *can_autoinc = false;
    4888     20484571 :   if (inv_expr)
    4889     20055058 :     *inv_expr = NULL;
    4890              : 
    4891              :   /* Check if we have enough precision to express the values of use.  */
    4892     20484571 :   if (TYPE_PRECISION (utype) > TYPE_PRECISION (ctype))
    4893      3138880 :     return infinite_cost;
    4894              : 
    4895     17345691 :   if (address_p
    4896     17345691 :       || (use->iv->base_object
    4897      2086626 :           && cand->iv->base_object
    4898      1009233 :           && POINTER_TYPE_P (TREE_TYPE (use->iv->base_object))
    4899       996937 :           && POINTER_TYPE_P (TREE_TYPE (cand->iv->base_object))))
    4900              :     {
    4901              :       /* Do not try to express address of an object with computation based
    4902              :          on address of a different object.  This may cause problems in rtl
    4903              :          level alias analysis (that does not expect this to be happening,
    4904              :          as this is illegal in C), and would be unlikely to be useful
    4905              :          anyway.  */
    4906      7975851 :       if (use->iv->base_object
    4907      7975851 :           && cand->iv->base_object
    4908     12200974 :           && !operand_equal_p (use->iv->base_object, cand->iv->base_object, 0))
    4909      1502415 :         return infinite_cost;
    4910              :     }
    4911              : 
    4912     15843276 :   if (!get_computation_aff_1 (data, at, use, cand, &aff_inv, &aff_var, &rat)
    4913     15843276 :       || !wi::fits_shwi_p (rat))
    4914      2903695 :     return infinite_cost;
    4915              : 
    4916     12939581 :   ratio = rat.to_shwi ();
    4917     12939581 :   if (address_p)
    4918              :     {
    4919      5566124 :       cost = get_address_cost (data, use, cand, &aff_inv, &aff_var, ratio,
    4920              :                                inv_vars, inv_expr, can_autoinc, speed);
    4921      5566124 :       cost = get_scaled_computation_cost_at (data, at, cost);
    4922              :       /* For doloop IV cand, add on the extra cost.  */
    4923      5566124 :       cost += cand->doloop_p ? targetm.doloop_cost_for_address : 0;
    4924      5566124 :       return cost;
    4925              :     }
    4926              : 
    4927      7373457 :   bool simple_inv = (aff_combination_const_p (&aff_inv)
    4928      2008330 :                      || aff_combination_singleton_var_p (&aff_inv));
    4929      7373457 :   tree signed_type = signed_type_for (aff_combination_type (&aff_inv));
    4930      7373457 :   aff_combination_convert (&aff_inv, signed_type);
    4931      7373457 :   if (!aff_combination_zero_p (&aff_inv))
    4932      5283774 :     comp_inv = aff_combination_to_tree (&aff_inv);
    4933              : 
    4934      7373457 :   cost = force_var_cost (data, comp_inv, inv_vars);
    4935      7373457 :   if (comp_inv && inv_expr && !simple_inv)
    4936              :     {
    4937      1396817 :       *inv_expr = get_loop_invariant_expr (data, comp_inv);
    4938              :       /* Clear depends on.  */
    4939      1396817 :       if (*inv_expr != NULL && inv_vars && *inv_vars)
    4940       843076 :         bitmap_clear (*inv_vars);
    4941              : 
    4942      1396817 :       cost.cost = adjust_setup_cost (data, cost.cost);
    4943              :       /* Record setup cost in scratch field.  */
    4944      1396817 :       cost.scratch = cost.cost;
    4945              :     }
    4946              :   /* Cost of constant integer can be covered when adding invariant part to
    4947              :      variant part.  */
    4948      5976640 :   else if (comp_inv && CONSTANT_CLASS_P (comp_inv))
    4949      3275419 :     cost = no_cost;
    4950              : 
    4951              :   /* Need type narrowing to represent use with cand.  */
    4952      7373457 :   if (TYPE_PRECISION (utype) < TYPE_PRECISION (ctype))
    4953              :     {
    4954       832948 :       machine_mode outer_mode = TYPE_MODE (utype);
    4955       832948 :       machine_mode inner_mode = TYPE_MODE (ctype);
    4956       832948 :       cost += comp_cost (convert_cost (outer_mode, inner_mode, speed), 0);
    4957              :     }
    4958              : 
    4959              :   /* Turn a + i * (-c) into a - i * c.  */
    4960      7373457 :   if (ratio < 0 && comp_inv && !integer_zerop (comp_inv))
    4961      1885919 :     aratio = -(unsigned HOST_WIDE_INT) ratio;
    4962              :   else
    4963              :     aratio = ratio;
    4964              : 
    4965      7373457 :   if (ratio != 1)
    4966      2776777 :     cost += mult_by_coeff_cost (aratio, TYPE_MODE (utype), speed);
    4967              : 
    4968              :   /* TODO: We may also need to check if we can compute  a + i * 4 in one
    4969              :      instruction.  */
    4970              :   /* Need to add up the invariant and variant parts.  */
    4971      7373457 :   if (comp_inv && !integer_zerop (comp_inv))
    4972     10560938 :     cost += add_cost (speed, TYPE_MODE (utype));
    4973              : 
    4974      7373457 :   cost = get_scaled_computation_cost_at (data, at, cost);
    4975              : 
    4976              :   /* For doloop IV cand, add on the extra cost.  */
    4977      7373457 :   if (cand->doloop_p && use->type == USE_NONLINEAR_EXPR)
    4978            0 :     cost += targetm.doloop_cost_for_generic;
    4979              : 
    4980      7373457 :   return cost;
    4981     20484571 : }
    4982              : 
    4983              : /* Determines cost of computing the use in GROUP with CAND in a generic
    4984              :    expression.  */
    4985              : 
    4986              : static bool
    4987      5641580 : determine_group_iv_cost_generic (struct ivopts_data *data,
    4988              :                                  struct iv_group *group, struct iv_cand *cand)
    4989              : {
    4990      5641580 :   comp_cost cost;
    4991      5641580 :   iv_inv_expr_ent *inv_expr = NULL;
    4992      5641580 :   bitmap inv_vars = NULL, inv_exprs = NULL;
    4993      5641580 :   struct iv_use *use = group->vuses[0];
    4994              : 
    4995              :   /* The simple case first -- if we need to express value of the preserved
    4996              :      original biv, the cost is 0.  This also prevents us from counting the
    4997              :      cost of increment twice -- once at this use and once in the cost of
    4998              :      the candidate.  */
    4999      5641580 :   if (cand->pos == IP_ORIGINAL && cand->incremented_at == use->stmt)
    5000        60137 :     cost = no_cost;
    5001              :   /* If the IV candidate involves undefined SSA values and is not the
    5002              :      same IV as on the USE avoid using that candidate here.  */
    5003      5581443 :   else if (cand->involves_undefs
    5004      5581443 :            && (!use->iv || !operand_equal_p (cand->iv->base, use->iv->base, 0)))
    5005              :     return false;
    5006              :   else
    5007      5581218 :     cost = get_computation_cost (data, use, cand, false,
    5008              :                                  &inv_vars, NULL, &inv_expr);
    5009              : 
    5010      5641355 :   if (inv_expr)
    5011              :     {
    5012       986572 :       inv_exprs = BITMAP_ALLOC (NULL);
    5013       986572 :       bitmap_set_bit (inv_exprs, inv_expr->id);
    5014              :     }
    5015      5641355 :   set_group_iv_cost (data, group, cand, cost, inv_vars,
    5016              :                      NULL_TREE, ERROR_MARK, inv_exprs);
    5017      5641355 :   return !cost.infinite_cost_p ();
    5018              : }
    5019              : 
    5020              : /* Determines cost of computing uses in GROUP with CAND in addresses.  */
    5021              : 
    5022              : static bool
    5023      6440439 : determine_group_iv_cost_address (struct ivopts_data *data,
    5024              :                                  struct iv_group *group, struct iv_cand *cand)
    5025              : {
    5026      6440439 :   unsigned i;
    5027      6440439 :   bitmap inv_vars = NULL, inv_exprs = NULL;
    5028      6440439 :   bool can_autoinc;
    5029      6440439 :   iv_inv_expr_ent *inv_expr = NULL;
    5030      6440439 :   struct iv_use *use = group->vuses[0];
    5031      6440439 :   comp_cost sum_cost = no_cost, cost;
    5032              : 
    5033      6440439 :   cost = get_computation_cost (data, use, cand, true,
    5034              :                                &inv_vars, &can_autoinc, &inv_expr);
    5035              : 
    5036      6440439 :   if (inv_expr)
    5037              :     {
    5038       460633 :       inv_exprs = BITMAP_ALLOC (NULL);
    5039       460633 :       bitmap_set_bit (inv_exprs, inv_expr->id);
    5040              :     }
    5041      6440439 :   sum_cost = cost;
    5042      6440439 :   if (!sum_cost.infinite_cost_p () && cand->ainc_use == use)
    5043              :     {
    5044            0 :       if (can_autoinc)
    5045            0 :         sum_cost -= cand->cost_step;
    5046              :       /* If we generated the candidate solely for exploiting autoincrement
    5047              :          opportunities, and it turns out it can't be used, set the cost to
    5048              :          infinity to make sure we ignore it.  */
    5049            0 :       else if (cand->pos == IP_AFTER_USE || cand->pos == IP_BEFORE_USE)
    5050            0 :         sum_cost = infinite_cost;
    5051              :     }
    5052              : 
    5053              :   /* Compute and add costs for rest uses of this group.  */
    5054      8453184 :   for (i = 1; i < group->vuses.length () && !sum_cost.infinite_cost_p (); i++)
    5055              :     {
    5056      2012745 :       struct iv_use *next = group->vuses[i];
    5057              : 
    5058              :       /* TODO: We could skip computing cost for sub iv_use when it has the
    5059              :          same cost as the first iv_use, but the cost really depends on the
    5060              :          offset and where the iv_use is.  */
    5061      2012745 :         cost = get_computation_cost (data, next, cand, true,
    5062              :                                      NULL, &can_autoinc, &inv_expr);
    5063      2012745 :         if (inv_expr)
    5064              :           {
    5065       277374 :             if (!inv_exprs)
    5066           89 :               inv_exprs = BITMAP_ALLOC (NULL);
    5067              : 
    5068              :             /* Uses in a group can share setup code,
    5069              :                so only add setup cost once.  */
    5070       277374 :             if (bitmap_bit_p (inv_exprs, inv_expr->id))
    5071       276812 :               cost -= cost.scratch;
    5072              :             else
    5073          562 :               bitmap_set_bit (inv_exprs, inv_expr->id);
    5074              :           }
    5075      2012745 :       sum_cost += cost;
    5076              :     }
    5077      6440439 :   set_group_iv_cost (data, group, cand, sum_cost, inv_vars,
    5078              :                      NULL_TREE, ERROR_MARK, inv_exprs);
    5079              : 
    5080      6440439 :   return !sum_cost.infinite_cost_p ();
    5081              : }
    5082              : 
    5083              : /* Computes value of candidate CAND at position AT in iteration DESC->NITER,
    5084              :    and stores it to VAL.  */
    5085              : 
    5086              : static void
    5087      4011232 : cand_value_at (class loop *loop, struct iv_cand *cand, gimple *at,
    5088              :                class tree_niter_desc *desc, aff_tree *val)
    5089              : {
    5090     12033696 :   aff_tree step, delta, nit;
    5091      4011232 :   struct iv *iv = cand->iv;
    5092      4011232 :   tree type = TREE_TYPE (iv->base);
    5093      4011232 :   tree niter = desc->niter;
    5094      4011232 :   bool after_adjust = stmt_after_increment (loop, cand, at);
    5095      4011232 :   tree steptype;
    5096              : 
    5097      4011232 :   if (POINTER_TYPE_P (type))
    5098       113029 :     steptype = sizetype;
    5099              :   else
    5100      3898203 :     steptype = unsigned_type_for (type);
    5101              : 
    5102              :   /* If AFTER_ADJUST is required, the code below generates the equivalent
    5103              :      of BASE + NITER * STEP + STEP, when ideally we'd prefer the expression
    5104              :      BASE + (NITER + 1) * STEP, especially when NITER is often of the form
    5105              :      SSA_NAME - 1.  Unfortunately, guaranteeing that adding 1 to NITER
    5106              :      doesn't overflow is tricky, so we peek inside the TREE_NITER_DESC
    5107              :      class for common idioms that we know are safe.  */
    5108      4011232 :   if (after_adjust
    5109      3771548 :       && desc->control.no_overflow
    5110      3764338 :       && integer_onep (desc->control.step)
    5111      1042603 :       && (desc->cmp == LT_EXPR
    5112        37700 :           || desc->cmp == NE_EXPR)
    5113      5053835 :       && TREE_CODE (desc->bound) == SSA_NAME)
    5114              :     {
    5115       529003 :       if (integer_onep (desc->control.base))
    5116              :         {
    5117       396530 :           niter = desc->bound;
    5118       396530 :           after_adjust = false;
    5119              :         }
    5120       132473 :       else if (TREE_CODE (niter) == MINUS_EXPR
    5121       132473 :                && integer_onep (TREE_OPERAND (niter, 1)))
    5122              :         {
    5123        75635 :           niter = TREE_OPERAND (niter, 0);
    5124        75635 :           after_adjust = false;
    5125              :         }
    5126              :     }
    5127              : 
    5128      4011232 :   tree_to_aff_combination (iv->step, TREE_TYPE (iv->step), &step);
    5129      4011232 :   aff_combination_convert (&step, steptype);
    5130      4011232 :   tree_to_aff_combination (niter, TREE_TYPE (niter), &nit);
    5131      4011232 :   aff_combination_convert (&nit, steptype);
    5132      4011232 :   aff_combination_mult (&nit, &step, &delta);
    5133      4011232 :   if (after_adjust)
    5134      3299383 :     aff_combination_add (&delta, &step);
    5135              : 
    5136      4011232 :   tree_to_aff_combination (iv->base, type, val);
    5137      4011232 :   if (!POINTER_TYPE_P (type))
    5138      3898203 :     aff_combination_convert (val, steptype);
    5139      4011232 :   aff_combination_add (val, &delta);
    5140      4011232 : }
    5141              : 
    5142              : /* Returns period of induction variable iv.  */
    5143              : 
    5144              : static tree
    5145      4213904 : iv_period (struct iv *iv)
    5146              : {
    5147      4213904 :   tree step = iv->step, period, type;
    5148      4213904 :   tree pow2div;
    5149              : 
    5150      4213904 :   gcc_assert (step && TREE_CODE (step) == INTEGER_CST);
    5151              : 
    5152      4213904 :   type = unsigned_type_for (TREE_TYPE (step));
    5153              :   /* Period of the iv is lcm (step, type_range)/step -1,
    5154              :      i.e., N*type_range/step - 1. Since type range is power
    5155              :      of two, N == (step >> num_of_ending_zeros_binary (step),
    5156              :      so the final result is
    5157              : 
    5158              :        (type_range >> num_of_ending_zeros_binary (step)) - 1
    5159              : 
    5160              :   */
    5161      4213904 :   pow2div = num_ending_zeros (step);
    5162              : 
    5163     12641712 :   period = build_low_bits_mask (type,
    5164      4213904 :                                 (TYPE_PRECISION (type)
    5165      4213904 :                                  - tree_to_uhwi (pow2div)));
    5166              : 
    5167      4213904 :   return period;
    5168              : }
    5169              : 
    5170              : /* Returns the comparison operator used when eliminating the iv USE.  */
    5171              : 
    5172              : static enum tree_code
    5173      4011232 : iv_elimination_compare (struct ivopts_data *data, struct iv_use *use)
    5174              : {
    5175      4011232 :   class loop *loop = data->current_loop;
    5176      4011232 :   basic_block ex_bb;
    5177      4011232 :   edge exit;
    5178              : 
    5179      4011232 :   ex_bb = gimple_bb (use->stmt);
    5180      4011232 :   exit = EDGE_SUCC (ex_bb, 0);
    5181      4011232 :   if (flow_bb_inside_loop_p (loop, exit->dest))
    5182      2969432 :     exit = EDGE_SUCC (ex_bb, 1);
    5183              : 
    5184      4011232 :   return (exit->flags & EDGE_TRUE_VALUE ? EQ_EXPR : NE_EXPR);
    5185              : }
    5186              : 
    5187              : /* Returns true if we can prove that BASE - OFFSET does not overflow.  For now,
    5188              :    we only detect the situation that BASE = SOMETHING + OFFSET, where the
    5189              :    calculation is performed in non-wrapping type.
    5190              : 
    5191              :    TODO: More generally, we could test for the situation that
    5192              :          BASE = SOMETHING + OFFSET' and OFFSET is between OFFSET' and zero.
    5193              :          This would require knowing the sign of OFFSET.  */
    5194              : 
    5195              : static bool
    5196          866 : difference_cannot_overflow_p (struct ivopts_data *data, tree base, tree offset)
    5197              : {
    5198          866 :   enum tree_code code;
    5199          866 :   tree e1, e2;
    5200         2598 :   aff_tree aff_e1, aff_e2, aff_offset;
    5201              : 
    5202          866 :   if (!nowrap_type_p (TREE_TYPE (base)))
    5203              :     return false;
    5204              : 
    5205          866 :   base = expand_simple_operations (base);
    5206              : 
    5207          866 :   if (TREE_CODE (base) == SSA_NAME)
    5208              :     {
    5209          864 :       auto *stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (base));
    5210          101 :       if (!stmt)
    5211              :         return false;
    5212              : 
    5213          101 :       code = gimple_assign_rhs_code (stmt);
    5214          101 :       if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
    5215              :         return false;
    5216              : 
    5217           34 :       e1 = gimple_assign_rhs1 (stmt);
    5218           34 :       e2 = gimple_assign_rhs2 (stmt);
    5219              :     }
    5220              :   else
    5221              :     {
    5222            2 :       code = TREE_CODE (base);
    5223            2 :       if (get_gimple_rhs_class (code) != GIMPLE_BINARY_RHS)
    5224              :         return false;
    5225            0 :       e1 = TREE_OPERAND (base, 0);
    5226            0 :       e2 = TREE_OPERAND (base, 1);
    5227              :     }
    5228              : 
    5229              :   /* Use affine expansion as deeper inspection to prove the equality.  */
    5230           34 :   tree_to_aff_combination_expand (e2, TREE_TYPE (e2),
    5231              :                                   &aff_e2, &data->name_expansion_cache);
    5232           34 :   tree_to_aff_combination_expand (offset, TREE_TYPE (offset),
    5233              :                                   &aff_offset, &data->name_expansion_cache);
    5234           34 :   aff_combination_scale (&aff_offset, -1);
    5235           34 :   switch (code)
    5236              :     {
    5237            0 :     case PLUS_EXPR:
    5238            0 :       aff_combination_add (&aff_e2, &aff_offset);
    5239            0 :       if (aff_combination_zero_p (&aff_e2))
    5240              :         return true;
    5241              : 
    5242            0 :       tree_to_aff_combination_expand (e1, TREE_TYPE (e1),
    5243              :                                       &aff_e1, &data->name_expansion_cache);
    5244            0 :       aff_combination_add (&aff_e1, &aff_offset);
    5245            0 :       return aff_combination_zero_p (&aff_e1);
    5246              : 
    5247           34 :     case POINTER_PLUS_EXPR:
    5248           34 :       aff_combination_add (&aff_e2, &aff_offset);
    5249           34 :       return aff_combination_zero_p (&aff_e2);
    5250              : 
    5251              :     default:
    5252              :       return false;
    5253              :     }
    5254          866 : }
    5255              : 
    5256              : /* Return true if STEP * VAL, computed in OFF_TYPE, is known to be a
    5257              :    non-negative offset which does not overflow, i.e. if the value of VAL is
    5258              :    non-negative and multiplying it by STEP fits in the signed range of
    5259              :    OFF_TYPE.  */
    5260              : 
    5261              : static bool
    5262          112 : nonneg_scaled_offset_p (tree val, HOST_WIDE_INT step, tree off_type)
    5263              : {
    5264          112 :   if (!INTEGRAL_TYPE_P (TREE_TYPE (val)) || step == 0)
    5265              :     return false;
    5266              : 
    5267          112 :   signop sgn = TYPE_SIGN (TREE_TYPE (val));
    5268          112 :   int_range_max r;
    5269          224 :   if (!get_range_query (cfun)->range_of_expr (r, val)
    5270          112 :       || r.undefined_p ()
    5271          336 :       || wi::neg_p (r.lower_bound (), sgn))
    5272              :     return false;
    5273              : 
    5274          112 :   widest_int max = widest_int::from (r.upper_bound (), sgn);
    5275          112 :   widest_int limit
    5276          112 :     = widest_int::from (wi::max_value (TYPE_PRECISION (off_type), SIGNED),
    5277          112 :                         SIGNED);
    5278          112 :   return wi::leu_p (max, wi::udiv_trunc (limit, absu_hwi (step)));
    5279          112 : }
    5280              : 
    5281              : /* Tries to replace loop exit by one formulated in terms of a LT_EXPR
    5282              :    comparison with CAND.  NITER describes the number of iterations of
    5283              :    the loops.  If successful, the comparison in COMP_P is altered accordingly
    5284              :    and the bound in BOUND_P is recomputed.
    5285              : 
    5286              :    We aim to handle the following situation:
    5287              : 
    5288              :    sometype *base, *p;
    5289              :    unsigned a, b, i;
    5290              : 
    5291              :    i = a;
    5292              :    p = p_0 = base + a;
    5293              : 
    5294              :    do
    5295              :      {
    5296              :        bla (*p);
    5297              :        p++;
    5298              :        i++;
    5299              :      }
    5300              :    while (i < b);
    5301              : 
    5302              :    Here, the number of iterations of the loop is (a + 1 > b) ? 0 : b - a - 1.
    5303              :    We aim to optimize this to
    5304              : 
    5305              :    p = p_0 = base + a;
    5306              :    do
    5307              :      {
    5308              :        bla (*p);
    5309              :        p++;
    5310              :      }
    5311              :    while (p < p_0 - (a + 1) + (b + 1));
    5312              : 
    5313              :    Note that the bound has to be computed as p_0 - (a + 1) + (b + 1) and not
    5314              :    from the number of iterations as p_0 + (b - a): the latter is only
    5315              :    equivalent if b - a does not wrap, which is not the case when the loop
    5316              :    rolls zero times.
    5317              : 
    5318              :    Note also that a + 1 must be used as the offset it is, i.e. converted to
    5319              :    the type of the offsets as a whole, and not rewritten into a and 1, since
    5320              :    it may wrap around in the type of a: this is precisely the case where the
    5321              :    loop rolls but b - a is not the number of iterations either.  Conversely
    5322              :    b + 1 must be computed in the type of the offsets, where it cannot wrap
    5323              :    around, since nothing constrains b when the loop rolls zero times.
    5324              : 
    5325              :    For this to preserve correctness, we need to know that the values compared
    5326              :    in the transformed loop are ordered the same way as i and b are.  Since the
    5327              :    comparison of the pointers is performed modulo the size of the address
    5328              :    space, this needs a + 1 > b to be an unsigned comparison, and the offsets
    5329              :    a, b, a + 1 and b + 1 scaled by the step of the candidate to be
    5330              :    non-negative and to not overflow.  Then:
    5331              : 
    5332              :    1) if a + 1 <= b, then the loop rolls b - (a + 1) times, so that (b + 1)
    5333              :       - (a + 1) computed on the offsets is its number of iterations, and
    5334              :       p_0 - (a + 1) + (b + 1) is the final value of p, hence there is no
    5335              :       overflow in computing it or the values of p, and the pointers increase
    5336              :       monotonically together with i.
    5337              :    2) if a + 1 > b, then the loop exits at the first test and a + 1 does not
    5338              :       wrap around, so b <= a implies that p_0 - (a + 1) + (b + 1) = p_0 - a
    5339              :       + b lies between the valid addresses p_0 - a and p_0, so the test indeed
    5340              :       fails.  Here we also need to verify that the expression p_0 - a does not
    5341              :       overflow, which we prove using p_0 = base + a.  */
    5342              : 
    5343              : static bool
    5344       225976 : iv_elimination_compare_lt (struct ivopts_data *data, struct iv_use *use,
    5345              :                            struct iv_cand *cand, enum tree_code *comp_p,
    5346              :                            class tree_niter_desc *niter, tree *bound_p)
    5347              : {
    5348       225976 :   tree cand_type, a, a1, b, b1, mbz, nit_type = TREE_TYPE (niter->niter);
    5349       225976 :   tree off_type, offset, bound;
    5350       677928 :   class aff_tree nit, tmpa, tmpb;
    5351       225976 :   enum tree_code comp;
    5352       225976 :   HOST_WIDE_INT step;
    5353              : 
    5354              :   /* We need to know that the candidate induction variable does not overflow.
    5355              :      While more complex analysis may be used to prove this, for now just
    5356              :      check that the variable appears in the original program and that it
    5357              :      is computed in a type that guarantees no overflows.  */
    5358       225976 :   cand_type = TREE_TYPE (cand->iv->base);
    5359       225976 :   if (cand->pos != IP_ORIGINAL || !nowrap_type_p (cand_type))
    5360              :     return false;
    5361              : 
    5362              :   /* Make sure that the loop iterates till the loop bound is hit, as otherwise
    5363              :      the calculation of the BOUND could overflow, making the comparison
    5364              :      invalid.  */
    5365        20787 :   if (!data->loop_single_exit_p)
    5366              :     return false;
    5367              : 
    5368              :   /* We need to be able to decide whether candidate is increasing or decreasing
    5369              :      in order to choose the right comparison operator.  */
    5370        15066 :   if (!cst_and_fits_in_hwi (cand->iv->step))
    5371              :     return false;
    5372        15066 :   step = int_cst_value (cand->iv->step);
    5373              : 
    5374              :   /* The bound we compute below is the value the candidate has after the last
    5375              :      iteration, so the exit test has to see the incremented candidate.  */
    5376        15066 :   if (!stmt_after_increment (data->current_loop, cand, use->stmt))
    5377              :     return false;
    5378              : 
    5379              :   /* Check that the number of iterations matches the expected pattern:
    5380              :      a + 1 > b ? 0 : b - a - 1.  */
    5381        10692 :   mbz = niter->may_be_zero;
    5382        10692 :   if (TREE_CODE (mbz) == GT_EXPR)
    5383              :     {
    5384              :       /* Handle a + 1 > b.  */
    5385         2099 :       tree op0 = TREE_OPERAND (mbz, 0);
    5386         2099 :       if (TREE_CODE (op0) == PLUS_EXPR && integer_onep (TREE_OPERAND (op0, 1)))
    5387              :         {
    5388         1153 :           a1 = op0;
    5389         1153 :           a = TREE_OPERAND (op0, 0);
    5390         1153 :           b = TREE_OPERAND (mbz, 1);
    5391              :         }
    5392              :       else
    5393              :         return false;
    5394              :     }
    5395         8593 :   else if (TREE_CODE (mbz) == LT_EXPR)
    5396              :     {
    5397          737 :       tree op1 = TREE_OPERAND (mbz, 1);
    5398              : 
    5399              :       /* Handle b < a + 1.  */
    5400          737 :       if (TREE_CODE (op1) == PLUS_EXPR && integer_onep (TREE_OPERAND (op1, 1)))
    5401              :         {
    5402          108 :           a1 = op1;
    5403          108 :           a = TREE_OPERAND (op1, 0);
    5404          108 :           b = TREE_OPERAND (mbz, 0);
    5405              :         }
    5406              :       else
    5407              :         return false;
    5408              :     }
    5409              :   else
    5410              :     return false;
    5411              : 
    5412              :   /* Expected number of iterations is B - A - 1.  Check that it matches
    5413              :      the actual number, i.e., that B - A - NITER = 1.  */
    5414         1261 :   tree_to_aff_combination (niter->niter, nit_type, &nit);
    5415         1261 :   tree_to_aff_combination (fold_convert (nit_type, a), nit_type, &tmpa);
    5416         1261 :   tree_to_aff_combination (fold_convert (nit_type, b), nit_type, &tmpb);
    5417         1261 :   aff_combination_scale (&nit, -1);
    5418         1261 :   aff_combination_scale (&tmpa, -1);
    5419         1261 :   aff_combination_add (&tmpb, &tmpa);
    5420         1261 :   aff_combination_add (&tmpb, &nit);
    5421         1261 :   if (tmpb.n != 0 || maybe_ne (tmpb.offset, 1))
    5422              :     return false;
    5423              : 
    5424              :   /* The comparison A + 1 > B only tells us that B is at most A if it is
    5425              :      an unsigned one; otherwise B may well be negative.  */
    5426          866 :   if (!TYPE_UNSIGNED (TREE_TYPE (a)))
    5427              :     return false;
    5428              : 
    5429              :   /* Check that CAND->IV->BASE - CAND->IV->STEP * A does not overflow.  */
    5430          866 :   off_type = TREE_TYPE (cand->iv->step);
    5431          866 :   offset = fold_build2 (MULT_EXPR, off_type, cand->iv->step,
    5432              :                         fold_convert (off_type, a));
    5433          866 :   if (!difference_cannot_overflow_p (data, cand->iv->base, offset))
    5434              :     return false;
    5435              : 
    5436              :   /* Convert A + 1 as a whole, since it may wrap around in the type of A, but
    5437              :      compute B + 1 in OFF_TYPE, where it cannot wrap around.  */
    5438           34 :   a1 = fold_convert (off_type, a1);
    5439           34 :   b1 = fold_build2 (PLUS_EXPR, off_type, fold_convert (off_type, b),
    5440              :                     build_one_cst (off_type));
    5441              : 
    5442              :   /* The candidate is compared as an unsigned quantity, so the offsets by
    5443              :      which A + 1 and B + 1 move it away from CAND->IV->BASE - CAND->IV->STEP
    5444              :      * (A + 1) have to be ordered the same way as A + 1 and B + 1 themselves.
    5445              :      The same is required of A and B, in terms of which the bound is
    5446              :      expressed when the loop rolls zero times.  */
    5447           34 :   if (!nonneg_scaled_offset_p (a, step, off_type)
    5448           26 :       || !nonneg_scaled_offset_p (b, step, off_type)
    5449           26 :       || !nonneg_scaled_offset_p (a1, step, off_type)
    5450           60 :       || !nonneg_scaled_offset_p (b1, step, off_type))
    5451              :     return false;
    5452              : 
    5453              :   /* Determine the new comparison operator.  */
    5454           26 :   comp = step < 0 ? GT_EXPR : LT_EXPR;
    5455           26 :   if (*comp_p == NE_EXPR)
    5456           26 :     *comp_p = comp;
    5457            0 :   else if (*comp_p == EQ_EXPR)
    5458            0 :     *comp_p = invert_tree_comparison (comp, false);
    5459              :   else
    5460            0 :     gcc_unreachable ();
    5461              : 
    5462              :   /* Recompute the bound as CAND->IV->BASE - CAND->IV->STEP * (A + 1)
    5463              :      + CAND->IV->STEP * (B + 1).  Deriving it from the number of iterations,
    5464              :      as cand_value_at does, is not correct here: B - A is computed in NIT_TYPE
    5465              :      and converting it to OFF_TYPE is not value preserving when the loop
    5466              :      rolls zero times and B - A is thus negative.  */
    5467           26 :   bound = fold_build2 (MINUS_EXPR, off_type,
    5468              :                        fold_build2 (MULT_EXPR, off_type, cand->iv->step, b1),
    5469              :                        fold_build2 (MULT_EXPR, off_type, cand->iv->step, a1));
    5470           26 :   cand_type = TREE_TYPE (cand->iv->base);
    5471           26 :   if (POINTER_TYPE_P (cand_type))
    5472           26 :     *bound_p = fold_build_pointer_plus (cand->iv->base, bound);
    5473              :   else
    5474            0 :     *bound_p = fold_build2 (PLUS_EXPR, cand_type, cand->iv->base,
    5475              :                             fold_convert (cand_type, bound));
    5476              : 
    5477              :   return true;
    5478       225976 : }
    5479              : 
    5480              : /* Check whether it is possible to express the condition in USE by comparison
    5481              :    of candidate CAND.  If so, store the value compared with to BOUND, and the
    5482              :    comparison operator to COMP.  */
    5483              : 
    5484              : static bool
    5485      5045511 : may_eliminate_iv (struct ivopts_data *data,
    5486              :                   struct iv_use *use, struct iv_cand *cand, tree *bound,
    5487              :                   enum tree_code *comp)
    5488              : {
    5489      5045511 :   basic_block ex_bb;
    5490      5045511 :   edge exit;
    5491      5045511 :   tree period;
    5492      5045511 :   class loop *loop = data->current_loop;
    5493      5045511 :   aff_tree bnd;
    5494      5045511 :   class tree_niter_desc *desc = NULL;
    5495              : 
    5496              :   /* If the IV candidate involves undefs do not attempt to use it to
    5497              :      express a condition.  */
    5498      5045511 :   if (cand->involves_undefs)
    5499              :     return false;
    5500              : 
    5501      5045164 :   if (TREE_CODE (cand->iv->step) != INTEGER_CST)
    5502              :     return false;
    5503              : 
    5504              :   /* For now works only for exits that dominate the loop latch.
    5505              :      TODO: extend to other conditions inside loop body.  */
    5506      4855027 :   ex_bb = gimple_bb (use->stmt);
    5507      4855027 :   if (use->stmt != last_nondebug_stmt (ex_bb)
    5508      4746377 :       || gimple_code (use->stmt) != GIMPLE_COND
    5509      9600327 :       || !dominated_by_p (CDI_DOMINATORS, loop->latch, ex_bb))
    5510              :     return false;
    5511              : 
    5512      4611725 :   exit = EDGE_SUCC (ex_bb, 0);
    5513      4611725 :   if (flow_bb_inside_loop_p (loop, exit->dest))
    5514      3456504 :     exit = EDGE_SUCC (ex_bb, 1);
    5515      4611725 :   if (flow_bb_inside_loop_p (loop, exit->dest))
    5516              :     return false;
    5517              : 
    5518      4495550 :   desc = niter_for_exit (data, exit);
    5519      4495550 :   if (!desc)
    5520              :     return false;
    5521              : 
    5522              :   /* Determine whether we can use the variable to test the exit condition.
    5523              :      This is the case iff the period of the induction variable is greater
    5524              :      than the number of iterations for which the exit condition is true.  */
    5525      4213904 :   period = iv_period (cand->iv);
    5526              : 
    5527              :   /* If the number of iterations is constant, compare against it directly.  */
    5528      4213904 :   if (TREE_CODE (desc->niter) == INTEGER_CST)
    5529              :     {
    5530              :       /* See cand_value_at.  */
    5531      2748805 :       if (stmt_after_increment (loop, cand, use->stmt))
    5532              :         {
    5533      2689338 :           if (!tree_int_cst_lt (desc->niter, period))
    5534              :             return false;
    5535              :         }
    5536              :       else
    5537              :         {
    5538        59467 :           if (tree_int_cst_lt (period, desc->niter))
    5539              :             return false;
    5540              :         }
    5541              :     }
    5542              : 
    5543              :   /* If not, and if this is the only possible exit of the loop, see whether
    5544              :      we can get a conservative estimate on the number of iterations of the
    5545              :      entire loop and compare against that instead.  */
    5546              :   else
    5547              :     {
    5548      1465099 :       widest_int period_value, max_niter;
    5549              : 
    5550      1465099 :       max_niter = desc->max;
    5551      1465099 :       if (stmt_after_increment (loop, cand, use->stmt))
    5552      1249742 :         max_niter += 1;
    5553      1465099 :       period_value = wi::to_widest (period);
    5554      1465099 :       if (wi::gtu_p (max_niter, period_value))
    5555              :         {
    5556              :           /* See if we can take advantage of inferred loop bound
    5557              :              information.  */
    5558       292282 :           if (data->loop_single_exit_p)
    5559              :             {
    5560       169669 :               if (!max_loop_iterations (loop, &max_niter))
    5561              :                 return false;
    5562              :               /* The loop bound is already adjusted by adding 1.  */
    5563       169669 :               if (wi::gtu_p (max_niter, period_value))
    5564              :                 return false;
    5565              :             }
    5566              :           else
    5567              :             return false;
    5568              :         }
    5569      1465099 :     }
    5570              : 
    5571              :   /* For doloop IV cand, the bound would be zero.  It's safe whether
    5572              :      may_be_zero set or not.  */
    5573      4011232 :   if (cand->doloop_p)
    5574              :     {
    5575            0 :       *bound = build_int_cst (TREE_TYPE (cand->iv->base), 0);
    5576            0 :       *comp = iv_elimination_compare (data, use);
    5577            0 :       return true;
    5578              :     }
    5579              : 
    5580      4011232 :   cand_value_at (loop, cand, use->stmt, desc, &bnd);
    5581              : 
    5582      4011232 :   *bound = fold_convert (TREE_TYPE (cand->iv->base),
    5583              :                          aff_combination_to_tree (&bnd));
    5584      4011232 :   *comp = iv_elimination_compare (data, use);
    5585              : 
    5586              :   /* Sometimes, it is possible to handle the situation that the number of
    5587              :      iterations may be zero unless additional assumptions by using <
    5588              :      instead of != in the exit condition.
    5589              : 
    5590              :      TODO: we could also calculate the value MAY_BE_ZERO ? 0 : NITER and
    5591              :            base the exit condition on it.  However, that is often too
    5592              :            expensive.  */
    5593      4011232 :   if (!integer_zerop (desc->may_be_zero)
    5594      4011232 :       && !iv_elimination_compare_lt (data, use, cand, comp, desc, bound))
    5595              :     return false;
    5596              : 
    5597              :   /* It is unlikely that computing the number of iterations using division
    5598              :      would be more profitable than keeping the original induction variable.  */
    5599      3785282 :   bool cond_overflow_p;
    5600      3785282 :   if (expression_expensive_p (*bound, &cond_overflow_p))
    5601         7415 :     return false;
    5602              : 
    5603              :   return true;
    5604      5045511 : }
    5605              : 
    5606              :  /* Calculates the cost of BOUND, if it is a PARM_DECL.  A PARM_DECL must
    5607              :     be copied, if it is used in the loop body and DATA->body_includes_call.  */
    5608              : 
    5609              : static int
    5610      8536228 : parm_decl_cost (struct ivopts_data *data, tree bound)
    5611              : {
    5612      8536228 :   tree sbound = bound;
    5613      8536228 :   STRIP_NOPS (sbound);
    5614              : 
    5615      8536228 :   if (TREE_CODE (sbound) == SSA_NAME
    5616      2907569 :       && SSA_NAME_IS_DEFAULT_DEF (sbound)
    5617       160403 :       && TREE_CODE (SSA_NAME_VAR (sbound)) == PARM_DECL
    5618      8694227 :       && data->body_includes_call)
    5619        35637 :     return COSTS_N_INSNS (1);
    5620              : 
    5621              :   return 0;
    5622              : }
    5623              : 
    5624              : /* Determines cost of computing the use in GROUP with CAND in a condition.  */
    5625              : 
    5626              : static bool
    5627      6020656 : determine_group_iv_cost_cond (struct ivopts_data *data,
    5628              :                               struct iv_group *group, struct iv_cand *cand)
    5629              : {
    5630      6020656 :   tree bound = NULL_TREE;
    5631      6020656 :   struct iv *cmp_iv;
    5632      6020656 :   bitmap inv_exprs = NULL;
    5633      6020656 :   bitmap inv_vars_elim = NULL, inv_vars_express = NULL, inv_vars;
    5634      6020656 :   comp_cost elim_cost = infinite_cost, express_cost, cost, bound_cost;
    5635      6020656 :   enum comp_iv_rewrite rewrite_type;
    5636      6020656 :   iv_inv_expr_ent *inv_expr_elim = NULL, *inv_expr_express = NULL, *inv_expr;
    5637      6020656 :   tree *control_var, *bound_cst;
    5638      6020656 :   enum tree_code comp = ERROR_MARK;
    5639      6020656 :   struct iv_use *use = group->vuses[0];
    5640              : 
    5641              :   /* Extract condition operands.  */
    5642      6020656 :   rewrite_type = extract_cond_operands (data, use->stmt, &control_var,
    5643              :                                         &bound_cst, NULL, &cmp_iv);
    5644      6020656 :   gcc_assert (rewrite_type != COMP_IV_NA);
    5645              : 
    5646              :   /* Try iv elimination.  */
    5647      6020656 :   if (rewrite_type == COMP_IV_ELIM
    5648      6020656 :       && may_eliminate_iv (data, use, cand, &bound, &comp))
    5649              :     {
    5650      3777867 :       elim_cost = force_var_cost (data, bound, &inv_vars_elim);
    5651      3777867 :       if (elim_cost.cost == 0)
    5652      2536642 :         elim_cost.cost = parm_decl_cost (data, bound);
    5653      1241225 :       else if (TREE_CODE (bound) == INTEGER_CST)
    5654            0 :         elim_cost.cost = 0;
    5655              :       /* If we replace a loop condition 'i < n' with 'p < base + n',
    5656              :          inv_vars_elim will have 'base' and 'n' set, which implies that both
    5657              :          'base' and 'n' will be live during the loop.    More likely,
    5658              :          'base + n' will be loop invariant, resulting in only one live value
    5659              :          during the loop.  So in that case we clear inv_vars_elim and set
    5660              :          inv_expr_elim instead.  */
    5661      3777867 :       if (inv_vars_elim && bitmap_count_bits (inv_vars_elim) > 1)
    5662              :         {
    5663       335124 :           inv_expr_elim = get_loop_invariant_expr (data, bound);
    5664       335124 :           bitmap_clear (inv_vars_elim);
    5665              :         }
    5666              :       /* The bound is a loop invariant, so it will be only computed
    5667              :          once.  */
    5668      3777867 :       elim_cost.cost = adjust_setup_cost (data, elim_cost.cost);
    5669              :     }
    5670              : 
    5671              :   /* When the condition is a comparison of the candidate IV against
    5672              :      zero, prefer this IV.
    5673              : 
    5674              :      TODO: The constant that we're subtracting from the cost should
    5675              :      be target-dependent.  This information should be added to the
    5676              :      target costs for each backend.  */
    5677      6020656 :   if (!elim_cost.infinite_cost_p () /* Do not try to decrease infinite! */
    5678      3777867 :       && integer_zerop (*bound_cst)
    5679      8703050 :       && (operand_equal_p (*control_var, cand->var_after, 0)
    5680      2426019 :           || operand_equal_p (*control_var, cand->var_before, 0)))
    5681       263020 :     elim_cost -= 1;
    5682              : 
    5683      6020656 :   express_cost = get_computation_cost (data, use, cand, false,
    5684              :                                        &inv_vars_express, NULL,
    5685              :                                        &inv_expr_express);
    5686      6020656 :   if (cmp_iv != NULL)
    5687      5133907 :     find_inv_vars (data, &cmp_iv->base, &inv_vars_express);
    5688              : 
    5689              :   /* Count the cost of the original bound as well.  */
    5690      6020656 :   bound_cost = force_var_cost (data, *bound_cst, NULL);
    5691      6020656 :   if (bound_cost.cost == 0)
    5692      5999586 :     bound_cost.cost = parm_decl_cost (data, *bound_cst);
    5693        21070 :   else if (TREE_CODE (*bound_cst) == INTEGER_CST)
    5694            0 :     bound_cost.cost = 0;
    5695      6020656 :   express_cost += bound_cost;
    5696              : 
    5697              :   /* Choose the better approach, preferring the eliminated IV. */
    5698      6020656 :   if (elim_cost <= express_cost)
    5699              :     {
    5700      4663789 :       cost = elim_cost;
    5701      4663789 :       inv_vars = inv_vars_elim;
    5702      4663789 :       inv_vars_elim = NULL;
    5703      4663789 :       inv_expr = inv_expr_elim;
    5704              :       /* For doloop candidate/use pair, adjust to zero cost.  */
    5705      4663789 :       if (group->doloop_p && cand->doloop_p && elim_cost.cost > no_cost.cost)
    5706            0 :         cost = no_cost;
    5707              :     }
    5708              :   else
    5709              :     {
    5710      1356867 :       cost = express_cost;
    5711      1356867 :       inv_vars = inv_vars_express;
    5712      1356867 :       inv_vars_express = NULL;
    5713      1356867 :       bound = NULL_TREE;
    5714      1356867 :       comp = ERROR_MARK;
    5715      1356867 :       inv_expr = inv_expr_express;
    5716              :     }
    5717              : 
    5718      6020656 :   if (inv_expr)
    5719              :     {
    5720       611713 :       inv_exprs = BITMAP_ALLOC (NULL);
    5721       611713 :       bitmap_set_bit (inv_exprs, inv_expr->id);
    5722              :     }
    5723      6020656 :   set_group_iv_cost (data, group, cand, cost,
    5724              :                      inv_vars, bound, comp, inv_exprs);
    5725              : 
    5726      6020656 :   if (inv_vars_elim)
    5727        25803 :     BITMAP_FREE (inv_vars_elim);
    5728      6020656 :   if (inv_vars_express)
    5729      1308424 :     BITMAP_FREE (inv_vars_express);
    5730              : 
    5731      6020656 :   return !cost.infinite_cost_p ();
    5732              : }
    5733              : 
    5734              : /* Determines cost of computing uses in GROUP with CAND.  Returns false
    5735              :    if USE cannot be represented with CAND.  */
    5736              : 
    5737              : static bool
    5738     18102675 : determine_group_iv_cost (struct ivopts_data *data,
    5739              :                          struct iv_group *group, struct iv_cand *cand)
    5740              : {
    5741     18102675 :   switch (group->type)
    5742              :     {
    5743      5641580 :     case USE_NONLINEAR_EXPR:
    5744      5641580 :       return determine_group_iv_cost_generic (data, group, cand);
    5745              : 
    5746      6440439 :     case USE_REF_ADDRESS:
    5747      6440439 :     case USE_PTR_ADDRESS:
    5748      6440439 :       return determine_group_iv_cost_address (data, group, cand);
    5749              : 
    5750      6020656 :     case USE_COMPARE:
    5751      6020656 :       return determine_group_iv_cost_cond (data, group, cand);
    5752              : 
    5753            0 :     default:
    5754            0 :       gcc_unreachable ();
    5755              :     }
    5756              : }
    5757              : 
    5758              : /* Return true if get_computation_cost indicates that autoincrement is
    5759              :    a possibility for the pair of USE and CAND, false otherwise.  */
    5760              : 
    5761              : static bool
    5762      1320289 : autoinc_possible_for_pair (struct ivopts_data *data, struct iv_use *use,
    5763              :                            struct iv_cand *cand)
    5764              : {
    5765      1320289 :   if (!address_p (use->type))
    5766              :     return false;
    5767              : 
    5768       429513 :   bool can_autoinc = false;
    5769       429513 :   get_computation_cost (data, use, cand, true, NULL, &can_autoinc, NULL);
    5770       429513 :   return can_autoinc;
    5771              : }
    5772              : 
    5773              : /* Examine IP_ORIGINAL candidates to see if they are incremented next to a
    5774              :    use that allows autoincrement, and set their AINC_USE if possible.  */
    5775              : 
    5776              : static void
    5777       519403 : set_autoinc_for_original_candidates (struct ivopts_data *data)
    5778              : {
    5779       519403 :   unsigned i, j;
    5780              : 
    5781      5271431 :   for (i = 0; i < data->vcands.length (); i++)
    5782              :     {
    5783      4752028 :       struct iv_cand *cand = data->vcands[i];
    5784      4752028 :       struct iv_use *closest_before = NULL;
    5785      4752028 :       struct iv_use *closest_after = NULL;
    5786      4752028 :       if (cand->pos != IP_ORIGINAL)
    5787      3856348 :         continue;
    5788              : 
    5789      3925963 :       for (j = 0; j < data->vgroups.length (); j++)
    5790              :         {
    5791      3030283 :           struct iv_group *group = data->vgroups[j];
    5792      3030283 :           struct iv_use *use = group->vuses[0];
    5793      3030283 :           unsigned uid = gimple_uid (use->stmt);
    5794              : 
    5795      3030283 :           if (gimple_bb (use->stmt) != gimple_bb (cand->incremented_at))
    5796      1184694 :             continue;
    5797              : 
    5798      1845589 :           if (uid < gimple_uid (cand->incremented_at)
    5799      1845589 :               && (closest_before == NULL
    5800       391036 :                   || uid > gimple_uid (closest_before->stmt)))
    5801              :             closest_before = use;
    5802              : 
    5803      1845589 :           if (uid > gimple_uid (cand->incremented_at)
    5804      1845589 :               && (closest_after == NULL
    5805        74127 :                   || uid < gimple_uid (closest_after->stmt)))
    5806              :             closest_after = use;
    5807              :         }
    5808              : 
    5809       895680 :       if (closest_before != NULL
    5810       895680 :           && autoinc_possible_for_pair (data, closest_before, cand))
    5811            0 :         cand->ainc_use = closest_before;
    5812       895680 :       else if (closest_after != NULL
    5813       895680 :                && autoinc_possible_for_pair (data, closest_after, cand))
    5814            0 :         cand->ainc_use = closest_after;
    5815              :     }
    5816       519403 : }
    5817              : 
    5818              : /* Relate compare use with all candidates.  */
    5819              : 
    5820              : static void
    5821          316 : relate_compare_use_with_all_cands (struct ivopts_data *data)
    5822              : {
    5823          316 :   unsigned i, count = data->vcands.length ();
    5824        10164 :   for (i = 0; i < data->vgroups.length (); i++)
    5825              :     {
    5826         9848 :       struct iv_group *group = data->vgroups[i];
    5827              : 
    5828         9848 :       if (group->type == USE_COMPARE)
    5829         1992 :         bitmap_set_range (group->related_cands, 0, count);
    5830              :     }
    5831          316 : }
    5832              : 
    5833              : /* If PREFERRED_MODE is suitable and profitable, use the preferred
    5834              :    PREFERRED_MODE to compute doloop iv base from niter: base = niter + 1.  */
    5835              : 
    5836              : static tree
    5837            0 : compute_doloop_base_on_mode (machine_mode preferred_mode, tree niter,
    5838              :                              const widest_int &iterations_max)
    5839              : {
    5840            0 :   tree ntype = TREE_TYPE (niter);
    5841            0 :   tree pref_type = lang_hooks.types.type_for_mode (preferred_mode, 1);
    5842            0 :   if (!pref_type)
    5843            0 :     return fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
    5844              :                         build_int_cst (ntype, 1));
    5845              : 
    5846            0 :   gcc_assert (TREE_CODE (pref_type) == INTEGER_TYPE);
    5847              : 
    5848            0 :   int prec = TYPE_PRECISION (ntype);
    5849            0 :   int pref_prec = TYPE_PRECISION (pref_type);
    5850              : 
    5851            0 :   tree base;
    5852              : 
    5853              :   /* Check if the PREFERRED_MODED is able to present niter.  */
    5854            0 :   if (pref_prec > prec
    5855            0 :       || wi::ltu_p (iterations_max,
    5856            0 :                     widest_int::from (wi::max_value (pref_prec, UNSIGNED),
    5857              :                                       UNSIGNED)))
    5858              :     {
    5859              :       /* No wrap, it is safe to use preferred type after niter + 1.  */
    5860            0 :       if (wi::ltu_p (iterations_max,
    5861            0 :                      widest_int::from (wi::max_value (prec, UNSIGNED),
    5862              :                                        UNSIGNED)))
    5863              :         {
    5864              :           /* This could help to optimize "-1 +1" pair when niter looks
    5865              :              like "n-1": n is in original mode.  "base = (n - 1) + 1"
    5866              :              in PREFERRED_MODED: it could be base = (PREFERRED_TYPE)n.  */
    5867            0 :           base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
    5868              :                               build_int_cst (ntype, 1));
    5869            0 :           base = fold_convert (pref_type, base);
    5870              :         }
    5871              : 
    5872              :       /* To avoid wrap, convert niter to preferred type before plus 1.  */
    5873              :       else
    5874              :         {
    5875            0 :           niter = fold_convert (pref_type, niter);
    5876            0 :           base = fold_build2 (PLUS_EXPR, pref_type, unshare_expr (niter),
    5877              :                               build_int_cst (pref_type, 1));
    5878              :         }
    5879              :     }
    5880              :   else
    5881            0 :     base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
    5882              :                         build_int_cst (ntype, 1));
    5883              :   return base;
    5884              : }
    5885              : 
    5886              : /* Add one doloop dedicated IV candidate:
    5887              :      - Base is (may_be_zero ? 1 : (niter + 1)).
    5888              :      - Step is -1.  */
    5889              : 
    5890              : static void
    5891            0 : add_iv_candidate_for_doloop (struct ivopts_data *data)
    5892              : {
    5893            0 :   tree_niter_desc *niter_desc = niter_for_single_dom_exit (data);
    5894            0 :   gcc_assert (niter_desc && niter_desc->assumptions);
    5895              : 
    5896            0 :   tree niter = niter_desc->niter;
    5897            0 :   tree ntype = TREE_TYPE (niter);
    5898            0 :   gcc_assert (INTEGRAL_NB_TYPE_P (ntype));
    5899              : 
    5900            0 :   tree may_be_zero = niter_desc->may_be_zero;
    5901            0 :   if (may_be_zero && integer_zerop (may_be_zero))
    5902              :     may_be_zero = NULL_TREE;
    5903            0 :   if (may_be_zero)
    5904              :     {
    5905            0 :       if (COMPARISON_CLASS_P (may_be_zero))
    5906              :         {
    5907            0 :           niter = fold_build3 (COND_EXPR, ntype, may_be_zero,
    5908              :                                build_int_cst (ntype, 0),
    5909              :                                rewrite_to_non_trapping_overflow (niter));
    5910              :         }
    5911              :       /* Don't try to obtain the iteration count expression when may_be_zero is
    5912              :          integer_nonzerop (actually iteration count is one) or else.  */
    5913              :       else
    5914              :         return;
    5915              :     }
    5916              : 
    5917            0 :   machine_mode mode = TYPE_MODE (ntype);
    5918            0 :   machine_mode pref_mode = targetm.preferred_doloop_mode (mode);
    5919              : 
    5920            0 :   tree base;
    5921            0 :   if (mode != pref_mode)
    5922              :     {
    5923            0 :       base = compute_doloop_base_on_mode (pref_mode, niter, niter_desc->max);
    5924            0 :       ntype = TREE_TYPE (base);
    5925              :     }
    5926              :   else
    5927            0 :     base = fold_build2 (PLUS_EXPR, ntype, unshare_expr (niter),
    5928              :                         build_int_cst (ntype, 1));
    5929              : 
    5930              :   /* For non integer types or non-mode precision types,
    5931              :      convert directly to an integer type. */
    5932            0 :   if (TREE_CODE (ntype) != INTEGER_TYPE
    5933            0 :       || !type_has_mode_precision_p (ntype))
    5934              :     {
    5935            0 :       ntype = lang_hooks.types.type_for_mode (TYPE_MODE (ntype),
    5936            0 :                                               TYPE_UNSIGNED (ntype));
    5937            0 :       base = fold_convert (ntype, base);
    5938              :     }
    5939              : 
    5940            0 :   add_candidate (data, base, build_int_cst (ntype, -1), true, NULL, NULL, true);
    5941              : }
    5942              : 
    5943              : /* Finds the candidates for the induction variables.  */
    5944              : 
    5945              : static void
    5946       519403 : find_iv_candidates (struct ivopts_data *data)
    5947              : {
    5948              :   /* Add commonly used ivs.  */
    5949       519403 :   add_standard_iv_candidates (data);
    5950              : 
    5951              :   /* Add doloop dedicated ivs.  */
    5952       519403 :   if (data->doloop_use_p)
    5953            0 :     add_iv_candidate_for_doloop (data);
    5954              : 
    5955              :   /* Add old induction variables.  */
    5956       519403 :   add_iv_candidate_for_bivs (data);
    5957              : 
    5958              :   /* Add induction variables derived from uses.  */
    5959       519403 :   add_iv_candidate_for_groups (data);
    5960              : 
    5961       519403 :   set_autoinc_for_original_candidates (data);
    5962              : 
    5963              :   /* Record the important candidates.  */
    5964       519403 :   record_important_candidates (data);
    5965              : 
    5966              :   /* Relate compare iv_use with all candidates.  */
    5967       519403 :   if (!data->consider_all_candidates)
    5968          316 :     relate_compare_use_with_all_cands (data);
    5969              : 
    5970       519403 :   if (dump_file && (dump_flags & TDF_DETAILS))
    5971              :     {
    5972           72 :       unsigned i;
    5973              : 
    5974           72 :       fprintf (dump_file, "\n<Important Candidates>:\t");
    5975          877 :       for (i = 0; i < data->vcands.length (); i++)
    5976          733 :         if (data->vcands[i]->important)
    5977          521 :           fprintf (dump_file, " %d,", data->vcands[i]->id);
    5978           72 :       fprintf (dump_file, "\n");
    5979              : 
    5980           72 :       fprintf (dump_file, "\n<Group, Cand> Related:\n");
    5981          377 :       for (i = 0; i < data->vgroups.length (); i++)
    5982              :         {
    5983          233 :           struct iv_group *group = data->vgroups[i];
    5984              : 
    5985          233 :           if (group->related_cands)
    5986              :             {
    5987          233 :               fprintf (dump_file, "  Group %d:\t", group->id);
    5988          233 :               dump_bitmap (dump_file, group->related_cands);
    5989              :             }
    5990              :         }
    5991           72 :       fprintf (dump_file, "\n");
    5992              :     }
    5993       519403 : }
    5994              : 
    5995              : /* Return the number of registers needed to hold a value of a given TYPE.  */
    5996              : 
    5997              : static unsigned
    5998      7491176 : nregs_per_value (tree type)
    5999              : {
    6000      7491176 :   machine_mode mode = TYPE_MODE (type);
    6001      7491176 :   if (SCALAR_INT_MODE_P (mode))
    6002      7437209 :     return MAX (1u, targetm.class_max_nregs (GENERAL_REGS, mode));
    6003              : 
    6004              :   return 1;
    6005              : }
    6006              : 
    6007              : /* Determines costs of computing use of iv with an iv candidate.  */
    6008              : 
    6009              : static void
    6010       519403 : determine_group_iv_costs (struct ivopts_data *data)
    6011              : {
    6012       519403 :   unsigned i, j;
    6013       519403 :   struct iv_cand *cand;
    6014       519403 :   struct iv_group *group;
    6015       519403 :   bitmap to_clear = BITMAP_ALLOC (NULL);
    6016              : 
    6017       519403 :   alloc_use_cost_map (data);
    6018              : 
    6019      2206225 :   for (i = 0; i < data->vgroups.length (); i++)
    6020              :     {
    6021      1686822 :       group = data->vgroups[i];
    6022              : 
    6023      1686822 :       if (data->consider_all_candidates)
    6024              :         {
    6025     19440246 :           for (j = 0; j < data->vcands.length (); j++)
    6026              :             {
    6027     17753424 :               cand = data->vcands[j];
    6028     17753424 :               determine_group_iv_cost (data, group, cand);
    6029              :             }
    6030              :         }
    6031              :       else
    6032              :         {
    6033         9848 :           bitmap_iterator bi;
    6034              : 
    6035       359099 :           EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, j, bi)
    6036              :             {
    6037       349251 :               cand = data->vcands[j];
    6038       349251 :               if (!determine_group_iv_cost (data, group, cand))
    6039       207828 :                 bitmap_set_bit (to_clear, j);
    6040              :             }
    6041              : 
    6042              :           /* Remove the candidates for that the cost is infinite from
    6043              :              the list of related candidates.  */
    6044         9848 :           bitmap_and_compl_into (group->related_cands, to_clear);
    6045         9848 :           bitmap_clear (to_clear);
    6046              :         }
    6047              :     }
    6048              : 
    6049       519403 :   BITMAP_FREE (to_clear);
    6050              : 
    6051       519403 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6052              :     {
    6053           72 :       bitmap_iterator bi;
    6054              : 
    6055              :       /* Dump invariant variables.  */
    6056           72 :       fprintf (dump_file, "\n<Invariant Vars>:\n");
    6057         1137 :       EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
    6058              :         {
    6059         1065 :           struct version_info *info = ver_info (data, i);
    6060         1065 :           if (info->inv_id)
    6061              :             {
    6062          242 :               fprintf (dump_file, "Inv %d:\t", info->inv_id);
    6063          242 :               print_generic_expr (dump_file, info->name, TDF_SLIM);
    6064          242 :               fprintf (dump_file, "%s\n",
    6065          242 :                        info->has_nonlin_use ? "" : "\t(eliminable)");
    6066              :             }
    6067              :         }
    6068              : 
    6069              :       /* Dump invariant expressions.  */
    6070           72 :       fprintf (dump_file, "\n<Invariant Expressions>:\n");
    6071           72 :       auto_vec <iv_inv_expr_ent *> list (data->inv_expr_tab->elements ());
    6072              : 
    6073          386 :       for (hash_table<iv_inv_expr_hasher>::iterator it
    6074          530 :            = data->inv_expr_tab->begin (); it != data->inv_expr_tab->end ();
    6075          386 :            ++it)
    6076          386 :         list.safe_push (*it);
    6077              : 
    6078           72 :       list.qsort (sort_iv_inv_expr_ent);
    6079              : 
    6080          458 :       for (i = 0; i < list.length (); ++i)
    6081              :         {
    6082          386 :           fprintf (dump_file, "inv_expr %d: \t", list[i]->id);
    6083          386 :           print_generic_expr (dump_file, list[i]->expr, TDF_SLIM);
    6084          386 :           fprintf (dump_file, "\n");
    6085              :         }
    6086              : 
    6087           72 :       fprintf (dump_file, "\n<Group-candidate Costs>:\n");
    6088              : 
    6089          305 :       for (i = 0; i < data->vgroups.length (); i++)
    6090              :         {
    6091          233 :           group = data->vgroups[i];
    6092              : 
    6093          233 :           fprintf (dump_file, "Group %d:\n", i);
    6094          233 :           fprintf (dump_file, "  cand\tcost\tcompl.\tinv.expr.\tinv.vars\n");
    6095         3137 :           for (j = 0; j < group->n_map_members; j++)
    6096              :             {
    6097         4063 :               if (!group->cost_map[j].cand
    6098         2904 :                   || group->cost_map[j].cost.infinite_cost_p ())
    6099         1159 :                 continue;
    6100              : 
    6101         1745 :               fprintf (dump_file, "  %d\t%" PRId64 "\t%d\t",
    6102         1745 :                        group->cost_map[j].cand->id,
    6103              :                        group->cost_map[j].cost.cost,
    6104         1745 :                        group->cost_map[j].cost.complexity);
    6105         1745 :               if (!group->cost_map[j].inv_exprs
    6106         1745 :                   || bitmap_empty_p (group->cost_map[j].inv_exprs))
    6107         1234 :                 fprintf (dump_file, "NIL;\t");
    6108              :               else
    6109          511 :                 bitmap_print (dump_file,
    6110              :                               group->cost_map[j].inv_exprs, "", ";\t");
    6111         1745 :               if (!group->cost_map[j].inv_vars
    6112         1745 :                   || bitmap_empty_p (group->cost_map[j].inv_vars))
    6113         1398 :                 fprintf (dump_file, "NIL;\n");
    6114              :               else
    6115          347 :                 bitmap_print (dump_file,
    6116              :                               group->cost_map[j].inv_vars, "", "\n");
    6117              :             }
    6118              : 
    6119          233 :           fprintf (dump_file, "\n");
    6120              :         }
    6121           72 :       fprintf (dump_file, "\n");
    6122           72 :     }
    6123       519403 : }
    6124              : 
    6125              : /* Determines cost of the candidate CAND.  */
    6126              : 
    6127              : static void
    6128      4752028 : determine_iv_cost (struct ivopts_data *data, struct iv_cand *cand)
    6129              : {
    6130      4752028 :   comp_cost cost_base;
    6131      4752028 :   int64_t cost, cost_step;
    6132      4752028 :   tree base;
    6133              : 
    6134      4752028 :   gcc_assert (cand->iv != NULL);
    6135              : 
    6136              :   /* There are two costs associated with the candidate -- its increment
    6137              :      and its initialization.  The second is almost negligible for any loop
    6138              :      that rolls enough, so we take it just very little into account.  */
    6139              : 
    6140      4752028 :   base = cand->iv->base;
    6141      4752028 :   cost_base = force_var_cost (data, base, NULL);
    6142              :   /* It will be exceptional that the iv register happens to be initialized with
    6143              :      the proper value at no cost.  In general, there will at least be a regcopy
    6144              :      or a const set.  */
    6145      4752028 :   if (cost_base.cost == 0)
    6146      3777559 :     cost_base.cost = COSTS_N_INSNS (1);
    6147              :   /* Doloop decrement should be considered as zero cost.  */
    6148      4752028 :   if (cand->doloop_p)
    6149              :     cost_step = 0;
    6150              :   else
    6151      4752028 :     cost_step = add_cost (data->speed, TYPE_MODE (TREE_TYPE (base)));
    6152      4752028 :   cost = cost_step + adjust_setup_cost (data, cost_base.cost);
    6153              : 
    6154              :   /* Prefer the original ivs unless we may gain something by replacing it.
    6155              :      The reason is to make debugging simpler; so this is not relevant for
    6156              :      artificial ivs created by other optimization passes.  */
    6157      4752028 :   if ((cand->pos != IP_ORIGINAL
    6158       895680 :        || !SSA_NAME_VAR (cand->var_before)
    6159       451458 :        || DECL_ARTIFICIAL (SSA_NAME_VAR (cand->var_before)))
    6160              :       /* Prefer doloop as well.  */
    6161      5295998 :       && !cand->doloop_p)
    6162      4400318 :     cost++;
    6163              : 
    6164              :   /* Prefer not to insert statements into latch unless there are some
    6165              :      already (so that we do not create unnecessary jumps).  */
    6166      4752028 :   if (cand->pos == IP_END
    6167      4752028 :       && empty_block_p (ip_end_pos (data->current_loop)))
    6168         1845 :     cost++;
    6169              : 
    6170      4752028 :   cand->cost = cost;
    6171      4752028 :   cand->cost_step = cost_step;
    6172      4752028 :   cand->nregs = nregs_per_value (TREE_TYPE (cand->iv->base));
    6173      4752028 : }
    6174              : 
    6175              : /* Determines costs of computation of the candidates.  */
    6176              : 
    6177              : static void
    6178       519403 : determine_iv_costs (struct ivopts_data *data)
    6179              : {
    6180       519403 :   unsigned i;
    6181              : 
    6182       519403 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6183              :     {
    6184           72 :       fprintf (dump_file, "<Candidate Costs>:\n");
    6185           72 :       fprintf (dump_file, "  cand\tcost\n");
    6186              :     }
    6187              : 
    6188      5271431 :   for (i = 0; i < data->vcands.length (); i++)
    6189              :     {
    6190      4752028 :       struct iv_cand *cand = data->vcands[i];
    6191              : 
    6192      4752028 :       determine_iv_cost (data, cand);
    6193              : 
    6194      4752028 :       if (dump_file && (dump_flags & TDF_DETAILS))
    6195          733 :         fprintf (dump_file, "  %d\t%d\n", i, cand->cost);
    6196              :     }
    6197              : 
    6198       519403 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6199           72 :     fprintf (dump_file, "\n");
    6200       519403 : }
    6201              : 
    6202              : /* Estimate register pressure for loop whose invariants occupy N_INV_REGS
    6203              :    registers and whose induction variables occupy N_CAND_REGS registers.
    6204              :    Note N_INV_REGS covers both invariant variables and invariant expressions.
    6205              :    All counts, including DATA->regs_used, are in GENERAL_REGS hard registers,
    6206              :    the same units as target_avail_regs.  */
    6207              : 
    6208              : static unsigned
    6209    438357468 : ivopts_estimate_reg_pressure (struct ivopts_data *data, unsigned n_inv_regs,
    6210              :                               unsigned n_cand_regs)
    6211              : {
    6212    438357468 :   unsigned cost;
    6213    438357468 :   unsigned n_old = data->regs_used, n_new = n_inv_regs + n_cand_regs;
    6214    438357468 :   unsigned regs_needed = n_new + n_old, available_regs = target_avail_regs;
    6215    438357468 :   bool speed = data->speed;
    6216              : 
    6217              :   /* If there is a call in the loop body, the call-clobbered registers
    6218              :      are not available for loop invariants.  */
    6219    438357468 :   if (data->body_includes_call)
    6220     96684448 :     available_regs = available_regs - target_clobbered_regs;
    6221              : 
    6222              :   /* If we have enough registers.  */
    6223    438357468 :   if (regs_needed <= available_regs)
    6224              :     cost = 0;
    6225              :   /* If we run out of available registers but the number of candidates
    6226              :      does not, we penalize extra registers using target_spill_cost.
    6227              :      As we tend to spill invariants here, only take loading the
    6228              :      invariant into account, because the invariant won't change for the
    6229              :      duration of the loop and storing it every iteration is unnecessary. */
    6230    139526965 :   else if (n_cand_regs <= available_regs)
    6231    119619361 :     cost = target_spill_cost [speed] * (regs_needed - available_regs) / 2;
    6232              :   /* If both IV cands and invariants spill, calculate additional cost for
    6233              :      having to store spilled candidates. */
    6234              :   else
    6235     19907604 :     cost = (target_spill_cost[speed] * (regs_needed - available_regs) / 2
    6236     19907604 :             + target_spill_cost[speed] * (n_cand_regs - available_regs) / 2);
    6237              : 
    6238    438357468 :   return cost;
    6239              : }
    6240              : 
    6241              : /* For each size of the induction variable set determine the penalty.  */
    6242              : 
    6243              : static void
    6244       519403 : determine_set_costs (struct ivopts_data *data)
    6245              : {
    6246       519403 :   unsigned j, n, n_values;
    6247       519403 :   gphi *phi;
    6248       519403 :   gphi_iterator psi;
    6249       519403 :   tree op;
    6250       519403 :   class loop *loop = data->current_loop;
    6251       519403 :   bitmap_iterator bi;
    6252              : 
    6253       519403 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6254              :     {
    6255           72 :       fprintf (dump_file, "<Global Costs>:\n");
    6256           72 :       fprintf (dump_file, "  target_avail_regs %d\n", target_avail_regs);
    6257           72 :       fprintf (dump_file, "  target_clobbered_regs %d\n", target_clobbered_regs);
    6258           72 :       fprintf (dump_file, "  target_reg_cost %d\n", target_reg_cost[data->speed]);
    6259           72 :       fprintf (dump_file, "  target_spill_cost %d\n", target_spill_cost[data->speed]);
    6260              :     }
    6261              : 
    6262       519403 :   n = 0;
    6263       519403 :   n_values = 0;
    6264      2022939 :   for (psi = gsi_start_phis (loop->header); !gsi_end_p (psi); gsi_next (&psi))
    6265              :     {
    6266      1503536 :       phi = psi.phi ();
    6267      1503536 :       op = PHI_RESULT (phi);
    6268              : 
    6269      3007072 :       if (virtual_operand_p (op))
    6270       318990 :         continue;
    6271              : 
    6272      1184546 :       if (get_iv (data, op))
    6273       899578 :         continue;
    6274              : 
    6275       524719 :       if (!POINTER_TYPE_P (TREE_TYPE (op))
    6276       524546 :           && !INTEGRAL_TYPE_P (TREE_TYPE (op)))
    6277       104897 :         continue;
    6278              : 
    6279       180071 :       n += nregs_per_value (TREE_TYPE (op));
    6280       180071 :       n_values++;
    6281              :     }
    6282              : 
    6283       519403 :   data->inv_expr_nregs.safe_grow_cleared (data->max_inv_expr_id + 1);
    6284       519403 :   data->inv_var_nregs.safe_grow_cleared (data->max_inv_var_id + 1);
    6285              : 
    6286      1698536 :   for (hash_table<iv_inv_expr_hasher>::iterator it
    6287       519403 :        = data->inv_expr_tab->begin ();
    6288      1698536 :        it != data->inv_expr_tab->end (); ++it)
    6289      1179133 :     data->inv_expr_nregs[(*it)->id] = nregs_per_value (TREE_TYPE ((*it)->expr));
    6290              : 
    6291      5738885 :   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
    6292              :     {
    6293      5219482 :       struct version_info *info = ver_info (data, j);
    6294              : 
    6295      5219482 :       if (info->inv_id)
    6296      1379944 :         data->inv_var_nregs[info->inv_id]
    6297      2759888 :           = nregs_per_value (TREE_TYPE (info->name));
    6298              : 
    6299      5219482 :       if (info->inv_id && info->has_nonlin_use)
    6300              :         {
    6301       536325 :           n += data->inv_var_nregs[info->inv_id];
    6302       536325 :           n_values++;
    6303              :         }
    6304              :     }
    6305              : 
    6306       519403 :   data->regs_used = n;
    6307       519403 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6308           72 :     fprintf (dump_file, "  regs_used %u (%u values)\n", n, n_values);
    6309              : 
    6310       519403 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6311              :     {
    6312           72 :       fprintf (dump_file, "  cost for size:\n");
    6313           72 :       fprintf (dump_file, "  regs\tcost\n");
    6314         2304 :       for (j = 0; j <= 2 * target_avail_regs; j++)
    6315         2232 :         fprintf (dump_file, "  %d\t%d\n", j,
    6316              :                  ivopts_estimate_reg_pressure (data, 0, j));
    6317           72 :       fprintf (dump_file, "\n");
    6318              :     }
    6319       519403 : }
    6320              : 
    6321              : /* Returns true if A is a cheaper cost pair than B.  */
    6322              : 
    6323              : static bool
    6324     87936359 : cheaper_cost_pair (class cost_pair *a, class cost_pair *b)
    6325              : {
    6326     87936359 :   if (!a)
    6327              :     return false;
    6328              : 
    6329     82432846 :   if (!b)
    6330              :     return true;
    6331              : 
    6332     79156587 :   if (a->cost < b->cost)
    6333              :     return true;
    6334              : 
    6335     58155512 :   if (b->cost < a->cost)
    6336              :     return false;
    6337              : 
    6338              :   /* In case the costs are the same, prefer the cheaper candidate.  */
    6339     32948243 :   if (a->cand->cost < b->cand->cost)
    6340      4883031 :     return true;
    6341              : 
    6342              :   return false;
    6343              : }
    6344              : 
    6345              : /* Compare if A is a more expensive cost pair than B.  Return 1, 0 and -1
    6346              :    for more expensive, equal and cheaper respectively.  */
    6347              : 
    6348              : static int
    6349     31440944 : compare_cost_pair (class cost_pair *a, class cost_pair *b)
    6350              : {
    6351     31440944 :   if (cheaper_cost_pair (a, b))
    6352              :     return -1;
    6353     24980449 :   if (cheaper_cost_pair (b, a))
    6354     16415881 :     return 1;
    6355              : 
    6356              :   return 0;
    6357              : }
    6358              : 
    6359              : /* Returns candidate by that USE is expressed in IVS.  */
    6360              : 
    6361              : static class cost_pair *
    6362    294241316 : iv_ca_cand_for_group (class iv_ca *ivs, struct iv_group *group)
    6363              : {
    6364    294241316 :   return ivs->cand_for_group[group->id];
    6365              : }
    6366              : 
    6367              : /* Computes the cost field of IVS structure.  */
    6368              : 
    6369              : static void
    6370    438354966 : iv_ca_recount_cost (struct ivopts_data *data, class iv_ca *ivs)
    6371              : {
    6372    438354966 :   comp_cost cost = ivs->cand_use_cost;
    6373              : 
    6374    438354966 :   cost += ivs->cand_cost;
    6375    438354966 :   cost
    6376    438354966 :     += ivopts_estimate_reg_pressure (data, ivs->n_inv_regs, ivs->n_cand_regs);
    6377    438354966 :   ivs->cost = cost;
    6378              : 
    6379    438354966 :   gcc_checking_assert (ivs->n_cand_regs >= ivs->n_cands
    6380              :                        && ivs->n_inv_regs >= ivs->n_invs);
    6381    438354966 : }
    6382              : 
    6383              : /* Remove use of invariants in set INVS by decreasing counter in N_INV_USES
    6384              :    and IVS.  */
    6385              : 
    6386              : static void
    6387    602653508 : iv_ca_set_remove_invs (class iv_ca *ivs, bitmap invs, unsigned *n_inv_uses,
    6388              :                        const vec<unsigned> &nregs)
    6389              : {
    6390    602653508 :   bitmap_iterator bi;
    6391    602653508 :   unsigned iid;
    6392              : 
    6393    602653508 :   if (!invs)
    6394    478526307 :     return;
    6395              : 
    6396    124127201 :   gcc_assert (n_inv_uses != NULL);
    6397    214970710 :   EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
    6398              :     {
    6399     90843509 :       n_inv_uses[iid]--;
    6400     90843509 :       if (n_inv_uses[iid] == 0)
    6401              :         {
    6402     67455797 :           ivs->n_invs--;
    6403     67455797 :           ivs->n_inv_regs -= nregs[iid];
    6404              :         }
    6405              :     }
    6406              : }
    6407              : 
    6408              : /* Set USE not to be expressed by any candidate in IVS.  */
    6409              : 
    6410              : static void
    6411    217492086 : iv_ca_set_no_cp (struct ivopts_data *data, class iv_ca *ivs,
    6412              :                  struct iv_group *group)
    6413              : {
    6414    217492086 :   unsigned gid = group->id, cid;
    6415    217492086 :   class cost_pair *cp;
    6416              : 
    6417    217492086 :   cp = ivs->cand_for_group[gid];
    6418    217492086 :   if (!cp)
    6419              :     return;
    6420    217492086 :   cid = cp->cand->id;
    6421              : 
    6422    217492086 :   ivs->bad_groups++;
    6423    217492086 :   ivs->cand_for_group[gid] = NULL;
    6424    217492086 :   ivs->n_cand_uses[cid]--;
    6425              : 
    6426    217492086 :   if (ivs->n_cand_uses[cid] == 0)
    6427              :     {
    6428     83834668 :       bitmap_clear_bit (ivs->cands, cid);
    6429     83834668 :       if (!cp->cand->doloop_p || !targetm.have_count_reg_decr_p)
    6430              :         {
    6431     83834668 :           ivs->n_cands--;
    6432     83834668 :           ivs->n_cand_regs -= cp->cand->nregs;
    6433              :         }
    6434     83834668 :       ivs->cand_cost -= cp->cand->cost;
    6435     83834668 :       iv_ca_set_remove_invs (ivs, cp->cand->inv_vars, ivs->n_inv_var_uses,
    6436     83834668 :                              data->inv_var_nregs);
    6437     83834668 :       iv_ca_set_remove_invs (ivs, cp->cand->inv_exprs, ivs->n_inv_expr_uses,
    6438     83834668 :                              data->inv_expr_nregs);
    6439              :     }
    6440              : 
    6441    217492086 :   ivs->cand_use_cost -= cp->cost;
    6442    217492086 :   iv_ca_set_remove_invs (ivs, cp->inv_vars, ivs->n_inv_var_uses,
    6443    217492086 :                          data->inv_var_nregs);
    6444    217492086 :   iv_ca_set_remove_invs (ivs, cp->inv_exprs, ivs->n_inv_expr_uses,
    6445    217492086 :                          data->inv_expr_nregs);
    6446    217492086 :   iv_ca_recount_cost (data, ivs);
    6447              : }
    6448              : 
    6449              : /* Add use of invariants in set INVS by increasing counter in N_INV_USES and
    6450              :    IVS.  */
    6451              : 
    6452              : static void
    6453    612364798 : iv_ca_set_add_invs (class iv_ca *ivs, bitmap invs, unsigned *n_inv_uses,
    6454              :                     const vec<unsigned> &nregs)
    6455              : {
    6456    612364798 :   bitmap_iterator bi;
    6457    612364798 :   unsigned iid;
    6458              : 
    6459    612364798 :   if (!invs)
    6460    487069170 :     return;
    6461              : 
    6462    125295628 :   gcc_assert (n_inv_uses != NULL);
    6463    217133771 :   EXECUTE_IF_SET_IN_BITMAP (invs, 0, iid, bi)
    6464              :     {
    6465     91838143 :       n_inv_uses[iid]++;
    6466     91838143 :       if (n_inv_uses[iid] == 1)
    6467              :         {
    6468     68376877 :           ivs->n_invs++;
    6469     68376877 :           ivs->n_inv_regs += nregs[iid];
    6470              :         }
    6471              :     }
    6472              : }
    6473              : 
    6474              : /* Set cost pair for GROUP in set IVS to CP.  */
    6475              : 
    6476              : static void
    6477    234226746 : iv_ca_set_cp (struct ivopts_data *data, class iv_ca *ivs,
    6478              :               struct iv_group *group, class cost_pair *cp)
    6479              : {
    6480    234226746 :   unsigned gid = group->id, cid;
    6481              : 
    6482    234226746 :   if (ivs->cand_for_group[gid] == cp)
    6483              :     return;
    6484              : 
    6485    220862880 :   if (ivs->cand_for_group[gid])
    6486    204947363 :     iv_ca_set_no_cp (data, ivs, group);
    6487              : 
    6488    220862880 :   if (cp)
    6489              :     {
    6490    220862880 :       cid = cp->cand->id;
    6491              : 
    6492    220862880 :       ivs->bad_groups--;
    6493    220862880 :       ivs->cand_for_group[gid] = cp;
    6494    220862880 :       ivs->n_cand_uses[cid]++;
    6495    220862880 :       if (ivs->n_cand_uses[cid] == 1)
    6496              :         {
    6497     85319519 :           bitmap_set_bit (ivs->cands, cid);
    6498     85319519 :           if (!cp->cand->doloop_p || !targetm.have_count_reg_decr_p)
    6499              :             {
    6500     85319519 :               ivs->n_cands++;
    6501     85319519 :               ivs->n_cand_regs += cp->cand->nregs;
    6502              :             }
    6503     85319519 :           ivs->cand_cost += cp->cand->cost;
    6504     85319519 :           iv_ca_set_add_invs (ivs, cp->cand->inv_vars, ivs->n_inv_var_uses,
    6505     85319519 :                               data->inv_var_nregs);
    6506     85319519 :           iv_ca_set_add_invs (ivs, cp->cand->inv_exprs, ivs->n_inv_expr_uses,
    6507     85319519 :                               data->inv_expr_nregs);
    6508              :         }
    6509              : 
    6510    220862880 :       ivs->cand_use_cost += cp->cost;
    6511    220862880 :       iv_ca_set_add_invs (ivs, cp->inv_vars, ivs->n_inv_var_uses,
    6512    220862880 :                           data->inv_var_nregs);
    6513    220862880 :       iv_ca_set_add_invs (ivs, cp->inv_exprs, ivs->n_inv_expr_uses,
    6514    220862880 :                           data->inv_expr_nregs);
    6515    220862880 :       iv_ca_recount_cost (data, ivs);
    6516              :     }
    6517              : }
    6518              : 
    6519              : /* Extend set IVS by expressing USE by some of the candidates in it
    6520              :    if possible.  Consider all important candidates if candidates in
    6521              :    set IVS don't give any result.  */
    6522              : 
    6523              : static void
    6524      3371702 : iv_ca_add_group (struct ivopts_data *data, class iv_ca *ivs,
    6525              :                struct iv_group *group)
    6526              : {
    6527      3371702 :   class cost_pair *best_cp = NULL, *cp;
    6528      3371702 :   bitmap_iterator bi;
    6529      3371702 :   unsigned i;
    6530      3371702 :   struct iv_cand *cand;
    6531              : 
    6532      3371702 :   gcc_assert (ivs->upto >= group->id);
    6533      3371702 :   ivs->upto++;
    6534      3371702 :   ivs->bad_groups++;
    6535              : 
    6536      6376745 :   EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
    6537              :     {
    6538      3005043 :       cand = data->vcands[i];
    6539      3005043 :       cp = get_group_iv_cost (data, group, cand);
    6540      3005043 :       if (cheaper_cost_pair (cp, best_cp))
    6541      2069009 :         best_cp = cp;
    6542              :     }
    6543              : 
    6544      3371702 :   if (best_cp == NULL)
    6545              :     {
    6546     12153393 :       EXECUTE_IF_SET_IN_BITMAP (data->important_candidates, 0, i, bi)
    6547              :         {
    6548     10769457 :           cand = data->vcands[i];
    6549     10769457 :           cp = get_group_iv_cost (data, group, cand);
    6550     10769457 :           if (cheaper_cost_pair (cp, best_cp))
    6551      2470162 :             best_cp = cp;
    6552              :         }
    6553              :     }
    6554              : 
    6555      3371702 :   iv_ca_set_cp (data, ivs, group, best_cp);
    6556      3371702 : }
    6557              : 
    6558              : /* Get cost for assignment IVS.  */
    6559              : 
    6560              : static comp_cost
    6561     87326029 : iv_ca_cost (class iv_ca *ivs)
    6562              : {
    6563              :   /* This was a conditional expression but it triggered a bug in
    6564              :      Sun C 5.5.  */
    6565            0 :   if (ivs->bad_groups)
    6566        95443 :     return infinite_cost;
    6567              :   else
    6568     87230586 :     return ivs->cost;
    6569              : }
    6570              : 
    6571              : /* Compare if applying NEW_CP to GROUP for IVS introduces more invariants
    6572              :    than OLD_CP.  Return 1, 0 and -1 for more, equal and fewer invariants
    6573              :    respectively.  */
    6574              : 
    6575              : static int
    6576     41593529 : iv_ca_compare_deps (struct ivopts_data *data, class iv_ca *ivs,
    6577              :                     struct iv_group *group, class cost_pair *old_cp,
    6578              :                     class cost_pair *new_cp)
    6579              : {
    6580     41593529 :   gcc_assert (old_cp && new_cp && old_cp != new_cp);
    6581     41593529 :   unsigned old_n_invs = ivs->n_invs;
    6582     41593529 :   iv_ca_set_cp (data, ivs, group, new_cp);
    6583     41593529 :   unsigned new_n_invs = ivs->n_invs;
    6584     41593529 :   iv_ca_set_cp (data, ivs, group, old_cp);
    6585              : 
    6586     41593529 :   return new_n_invs > old_n_invs ? 1 : (new_n_invs < old_n_invs ? -1 : 0);
    6587              : }
    6588              : 
    6589              : /* Creates change of expressing GROUP by NEW_CP instead of OLD_CP and chains
    6590              :    it before NEXT.  */
    6591              : 
    6592              : static struct iv_ca_delta *
    6593     49257558 : iv_ca_delta_add (struct iv_group *group, class cost_pair *old_cp,
    6594              :                  class cost_pair *new_cp, struct iv_ca_delta *next)
    6595              : {
    6596            0 :   struct iv_ca_delta *change = XNEW (struct iv_ca_delta);
    6597              : 
    6598     49257558 :   change->group = group;
    6599     49257558 :   change->old_cp = old_cp;
    6600     49257558 :   change->new_cp = new_cp;
    6601     49257558 :   change->next = next;
    6602              : 
    6603     49257558 :   return change;
    6604              : }
    6605              : 
    6606              : /* Joins two lists of changes L1 and L2.  Destructive -- old lists
    6607              :    are rewritten.  */
    6608              : 
    6609              : static struct iv_ca_delta *
    6610      8314553 : iv_ca_delta_join (struct iv_ca_delta *l1, struct iv_ca_delta *l2)
    6611              : {
    6612      8314553 :   struct iv_ca_delta *last;
    6613              : 
    6614            0 :   if (!l2)
    6615              :     return l1;
    6616              : 
    6617            0 :   if (!l1)
    6618              :     return l2;
    6619              : 
    6620      3385107 :   for (last = l1; last->next; last = last->next)
    6621      1120277 :     continue;
    6622      2264830 :   last->next = l2;
    6623              : 
    6624      2264830 :   return l1;
    6625      1120277 : }
    6626              : 
    6627              : /* Reverse the list of changes DELTA, forming the inverse to it.  */
    6628              : 
    6629              : static struct iv_ca_delta *
    6630            0 : iv_ca_delta_reverse (struct iv_ca_delta *delta)
    6631              : {
    6632            0 :   struct iv_ca_delta *act, *next, *prev = NULL;
    6633              : 
    6634    164947460 :   for (act = delta; act; act = next)
    6635              :     {
    6636     92131204 :       next = act->next;
    6637     92131204 :       act->next = prev;
    6638     92131204 :       prev = act;
    6639              : 
    6640     92131204 :       std::swap (act->old_cp, act->new_cp);
    6641              :     }
    6642              : 
    6643            0 :   return prev;
    6644              : }
    6645              : 
    6646              : /* Commit changes in DELTA to IVS.  If FORWARD is false, the changes are
    6647              :    reverted instead.  */
    6648              : 
    6649              : static void
    6650     76724630 : iv_ca_delta_commit (struct ivopts_data *data, class iv_ca *ivs,
    6651              :                     struct iv_ca_delta *delta, bool forward)
    6652              : {
    6653     76724630 :   class cost_pair *from, *to;
    6654     76724630 :   struct iv_ca_delta *act;
    6655              : 
    6656     76724630 :   if (!forward)
    6657     76724630 :     delta = iv_ca_delta_reverse (delta);
    6658              : 
    6659    173877192 :   for (act = delta; act; act = act->next)
    6660              :     {
    6661     97152562 :       from = act->old_cp;
    6662     97152562 :       to = act->new_cp;
    6663     97152562 :       gcc_assert (iv_ca_cand_for_group (ivs, act->group) == from);
    6664     97152562 :       iv_ca_set_cp (data, ivs, act->group, to);
    6665              :     }
    6666              : 
    6667     76724630 :   if (!forward)
    6668     76724630 :     iv_ca_delta_reverse (delta);
    6669     76724630 : }
    6670              : 
    6671              : /* Returns true if CAND is used in IVS.  */
    6672              : 
    6673              : static bool
    6674     30346860 : iv_ca_cand_used_p (class iv_ca *ivs, struct iv_cand *cand)
    6675              : {
    6676     30346860 :   return ivs->n_cand_uses[cand->id] > 0;
    6677              : }
    6678              : 
    6679              : /* Returns number of induction variable candidates in the set IVS.  */
    6680              : 
    6681              : static unsigned
    6682     13339352 : iv_ca_n_cands (class iv_ca *ivs)
    6683              : {
    6684     13339352 :   return ivs->n_cands;
    6685              : }
    6686              : 
    6687              : /* Free the list of changes DELTA.  */
    6688              : 
    6689              : static void
    6690     46022132 : iv_ca_delta_free (struct iv_ca_delta **delta)
    6691              : {
    6692     46022132 :   struct iv_ca_delta *act, *next;
    6693              : 
    6694     95279690 :   for (act = *delta; act; act = next)
    6695              :     {
    6696     49257558 :       next = act->next;
    6697     49257558 :       free (act);
    6698              :     }
    6699              : 
    6700     46022132 :   *delta = NULL;
    6701     46022132 : }
    6702              : 
    6703              : /* Allocates new iv candidates assignment.  */
    6704              : 
    6705              : static class iv_ca *
    6706      1038806 : iv_ca_new (struct ivopts_data *data)
    6707              : {
    6708      1038806 :   class iv_ca *nw = XNEW (class iv_ca);
    6709              : 
    6710      1038806 :   nw->upto = 0;
    6711      1038806 :   nw->bad_groups = 0;
    6712      2077612 :   nw->cand_for_group = XCNEWVEC (class cost_pair *,
    6713              :                                  data->vgroups.length ());
    6714      2077612 :   nw->n_cand_uses = XCNEWVEC (unsigned, data->vcands.length ());
    6715      1038806 :   nw->cands = BITMAP_ALLOC (NULL);
    6716      1038806 :   nw->n_cands = 0;
    6717      1038806 :   nw->n_invs = 0;
    6718      1038806 :   nw->n_cand_regs = 0;
    6719      1038806 :   nw->n_inv_regs = 0;
    6720      1038806 :   nw->cand_use_cost = no_cost;
    6721      1038806 :   nw->cand_cost = 0;
    6722      1038806 :   nw->n_inv_var_uses = XCNEWVEC (unsigned, data->max_inv_var_id + 1);
    6723      1038806 :   nw->n_inv_expr_uses = XCNEWVEC (unsigned, data->max_inv_expr_id + 1);
    6724      1038806 :   nw->cost = no_cost;
    6725              : 
    6726      1038806 :   return nw;
    6727              : }
    6728              : 
    6729              : /* Free memory occupied by the set IVS.  */
    6730              : 
    6731              : static void
    6732      1038806 : iv_ca_free (class iv_ca **ivs)
    6733              : {
    6734      1038806 :   free ((*ivs)->cand_for_group);
    6735      1038806 :   free ((*ivs)->n_cand_uses);
    6736      1038806 :   BITMAP_FREE ((*ivs)->cands);
    6737      1038806 :   free ((*ivs)->n_inv_var_uses);
    6738      1038806 :   free ((*ivs)->n_inv_expr_uses);
    6739      1038806 :   free (*ivs);
    6740      1038806 :   *ivs = NULL;
    6741      1038806 : }
    6742              : 
    6743              : /* Dumps IVS to FILE.  */
    6744              : 
    6745              : static void
    6746          270 : iv_ca_dump (struct ivopts_data *data, FILE *file, class iv_ca *ivs)
    6747              : {
    6748          270 :   unsigned i;
    6749          270 :   comp_cost cost = iv_ca_cost (ivs);
    6750              : 
    6751          270 :   fprintf (file, "  cost: %" PRId64 " (complexity %d)\n", cost.cost,
    6752              :            cost.complexity);
    6753          270 :   fprintf (file, "  reg_cost: %d\n",
    6754              :            ivopts_estimate_reg_pressure (data, ivs->n_inv_regs,
    6755              :                                          ivs->n_cand_regs));
    6756          270 :   fprintf (file,
    6757              :            "  regs: %u (%u values) cands, %u (%u values) invs, "
    6758              :            "%u used\n",
    6759              :            ivs->n_cand_regs, ivs->n_cands, ivs->n_inv_regs, ivs->n_invs,
    6760              :            data->regs_used);
    6761          270 :   fprintf (file, "  cand_cost: %" PRId64 "\n  cand_group_cost: "
    6762              :            "%" PRId64 " (complexity %d)\n", ivs->cand_cost,
    6763              :            ivs->cand_use_cost.cost, ivs->cand_use_cost.complexity);
    6764          270 :   bitmap_print (file, ivs->cands, "  candidates: ","\n");
    6765              : 
    6766         1670 :   for (i = 0; i < ivs->upto; i++)
    6767              :     {
    6768         1130 :       struct iv_group *group = data->vgroups[i];
    6769         1130 :       class cost_pair *cp = iv_ca_cand_for_group (ivs, group);
    6770         1130 :       if (cp)
    6771         1130 :         fprintf (file, "   group:%d --> iv_cand:%d, cost=("
    6772         1130 :                  "%" PRId64 ",%d)\n", group->id, cp->cand->id,
    6773              :                  cp->cost.cost, cp->cost.complexity);
    6774              :       else
    6775            0 :         fprintf (file, "   group:%d --> ??\n", group->id);
    6776              :     }
    6777              : 
    6778          270 :   const char *pref = "";
    6779          270 :   fprintf (file, "  invariant variables: ");
    6780         1570 :   for (i = 1; i <= data->max_inv_var_id; i++)
    6781         1030 :     if (ivs->n_inv_var_uses[i])
    6782              :       {
    6783          158 :         fprintf (file, "%s%d", pref, i);
    6784          158 :         pref = ", ";
    6785              :       }
    6786              : 
    6787          270 :   pref = "";
    6788          270 :   fprintf (file, "\n  invariant expressions: ");
    6789         2660 :   for (i = 1; i <= data->max_inv_expr_id; i++)
    6790         2120 :     if (ivs->n_inv_expr_uses[i])
    6791              :       {
    6792          316 :         fprintf (file, "%s%d", pref, i);
    6793          316 :         pref = ", ";
    6794              :       }
    6795              : 
    6796          270 :   fprintf (file, "\n\n");
    6797          270 : }
    6798              : 
    6799              : /* Try changing candidate in IVS to CAND for each use.  Return cost of the
    6800              :    new set, and store differences in DELTA.  Number of induction variables
    6801              :    in the new set is stored to N_IVS. MIN_NCAND is a flag. When it is true
    6802              :    the function will try to find a solution with minimal iv candidates.  */
    6803              : 
    6804              : static comp_cost
    6805     22607816 : iv_ca_extend (struct ivopts_data *data, class iv_ca *ivs,
    6806              :               struct iv_cand *cand, struct iv_ca_delta **delta,
    6807              :               unsigned *n_ivs, bool min_ncand)
    6808              : {
    6809     22607816 :   unsigned i;
    6810     22607816 :   comp_cost cost;
    6811     22607816 :   struct iv_group *group;
    6812     22607816 :   class cost_pair *old_cp, *new_cp;
    6813              : 
    6814     22607816 :   *delta = NULL;
    6815    128076257 :   for (i = 0; i < ivs->upto; i++)
    6816              :     {
    6817    105468441 :       group = data->vgroups[i];
    6818    105468441 :       old_cp = iv_ca_cand_for_group (ivs, group);
    6819              : 
    6820    105468441 :       if (old_cp
    6821    105468441 :           && old_cp->cand == cand)
    6822      9268464 :         continue;
    6823              : 
    6824     96199977 :       new_cp = get_group_iv_cost (data, group, cand);
    6825     96199977 :       if (!new_cp)
    6826     38592190 :         continue;
    6827              : 
    6828     57607787 :       if (!min_ncand)
    6829              :         {
    6830     41593529 :           int cmp_invs = iv_ca_compare_deps (data, ivs, group, old_cp, new_cp);
    6831              :           /* Skip if new_cp depends on more invariants.  */
    6832     41593529 :           if (cmp_invs > 0)
    6833     10152585 :             continue;
    6834              : 
    6835     31440944 :           int cmp_cost = compare_cost_pair (new_cp, old_cp);
    6836              :           /* Skip if new_cp is not cheaper.  */
    6837     31440944 :           if (cmp_cost > 0 || (cmp_cost == 0 && cmp_invs == 0))
    6838     24516734 :             continue;
    6839              :         }
    6840              : 
    6841     22938468 :       *delta = iv_ca_delta_add (group, old_cp, new_cp, *delta);
    6842              :     }
    6843              : 
    6844     22607816 :   iv_ca_delta_commit (data, ivs, *delta, true);
    6845     22607816 :   cost = iv_ca_cost (ivs);
    6846     22607816 :   if (n_ivs)
    6847     13339352 :     *n_ivs = iv_ca_n_cands (ivs);
    6848     22607816 :   iv_ca_delta_commit (data, ivs, *delta, false);
    6849              : 
    6850     22607816 :   return cost;
    6851              : }
    6852              : 
    6853              : /* Try narrowing set IVS by removing CAND.  Return the cost of
    6854              :    the new set and store the differences in DELTA.  START is
    6855              :    the candidate with which we start narrowing.  */
    6856              : 
    6857              : static comp_cost
    6858     16157893 : iv_ca_narrow (struct ivopts_data *data, class iv_ca *ivs,
    6859              :               struct iv_cand *cand, struct iv_cand *start,
    6860              :               struct iv_ca_delta **delta)
    6861              : {
    6862     16157893 :   unsigned i, ci;
    6863     16157893 :   struct iv_group *group;
    6864     16157893 :   class cost_pair *old_cp, *new_cp, *cp;
    6865     16157893 :   bitmap_iterator bi;
    6866     16157893 :   struct iv_cand *cnd;
    6867     16157893 :   comp_cost cost, best_cost, acost;
    6868              : 
    6869     16157893 :   *delta = NULL;
    6870     87454243 :   for (i = 0; i < data->vgroups.length (); i++)
    6871              :     {
    6872     81968484 :       group = data->vgroups[i];
    6873              : 
    6874     81968484 :       old_cp = iv_ca_cand_for_group (ivs, group);
    6875     81968484 :       if (old_cp->cand != cand)
    6876     58986452 :         continue;
    6877              : 
    6878     22982032 :       best_cost = iv_ca_cost (ivs);
    6879              :       /* Start narrowing with START.  */
    6880     22982032 :       new_cp = get_group_iv_cost (data, group, start);
    6881              : 
    6882     22982032 :       if (data->consider_all_candidates)
    6883              :         {
    6884    100661115 :           EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, ci, bi)
    6885              :             {
    6886     78893183 :               if (ci == cand->id || (start && ci == start->id))
    6887     37591840 :                 continue;
    6888              : 
    6889     41301343 :               cnd = data->vcands[ci];
    6890              : 
    6891     41301343 :               cp = get_group_iv_cost (data, group, cnd);
    6892     41301343 :               if (!cp)
    6893     24664496 :                 continue;
    6894              : 
    6895     16636847 :               iv_ca_set_cp (data, ivs, group, cp);
    6896     16636847 :               acost = iv_ca_cost (ivs);
    6897              : 
    6898     16636847 :               if (acost < best_cost)
    6899              :                 {
    6900      1878118 :                   best_cost = acost;
    6901      1878118 :                   new_cp = cp;
    6902              :                 }
    6903              :             }
    6904              :         }
    6905              :       else
    6906              :         {
    6907      4843166 :           EXECUTE_IF_AND_IN_BITMAP (group->related_cands, ivs->cands, 0, ci, bi)
    6908              :             {
    6909      3629066 :               if (ci == cand->id || (start && ci == start->id))
    6910      2000985 :                 continue;
    6911              : 
    6912      1628081 :               cnd = data->vcands[ci];
    6913              : 
    6914      1628081 :               cp = get_group_iv_cost (data, group, cnd);
    6915      1628081 :               if (!cp)
    6916            0 :                 continue;
    6917              : 
    6918      1628081 :               iv_ca_set_cp (data, ivs, group, cp);
    6919      1628081 :               acost = iv_ca_cost (ivs);
    6920              : 
    6921      1628081 :               if (acost < best_cost)
    6922              :                 {
    6923        41938 :                   best_cost = acost;
    6924        41938 :                   new_cp = cp;
    6925              :                 }
    6926              :             }
    6927              :         }
    6928              :       /* Restore to old cp for use.  */
    6929     22982032 :       iv_ca_set_cp (data, ivs, group, old_cp);
    6930              : 
    6931     22982032 :       if (!new_cp)
    6932              :         {
    6933     10672134 :           iv_ca_delta_free (delta);
    6934     10672134 :           return infinite_cost;
    6935              :         }
    6936              : 
    6937     12309898 :       *delta = iv_ca_delta_add (group, old_cp, new_cp, *delta);
    6938              :     }
    6939              : 
    6940      5485759 :   iv_ca_delta_commit (data, ivs, *delta, true);
    6941      5485759 :   cost = iv_ca_cost (ivs);
    6942      5485759 :   iv_ca_delta_commit (data, ivs, *delta, false);
    6943              : 
    6944      5485759 :   return cost;
    6945              : }
    6946              : 
    6947              : /* Try optimizing the set of candidates IVS by removing candidates different
    6948              :    from to EXCEPT_CAND from it.  Return cost of the new set, and store
    6949              :    differences in DELTA.  */
    6950              : 
    6951              : static comp_cost
    6952      9388586 : iv_ca_prune (struct ivopts_data *data, class iv_ca *ivs,
    6953              :              struct iv_cand *except_cand, struct iv_ca_delta **delta)
    6954              : {
    6955      9388586 :   bitmap_iterator bi;
    6956      9388586 :   struct iv_ca_delta *act_delta, *best_delta;
    6957      9388586 :   unsigned i;
    6958      9388586 :   comp_cost best_cost, acost;
    6959      9388586 :   struct iv_cand *cand;
    6960              : 
    6961      9388586 :   best_delta = NULL;
    6962      9388586 :   best_cost = iv_ca_cost (ivs);
    6963              : 
    6964     32147438 :   EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
    6965              :     {
    6966     22758852 :       cand = data->vcands[i];
    6967              : 
    6968     22758852 :       if (cand == except_cand)
    6969      6600959 :         continue;
    6970              : 
    6971     16157893 :       acost = iv_ca_narrow (data, ivs, cand, except_cand, &act_delta);
    6972              : 
    6973     16157893 :       if (acost < best_cost)
    6974              :         {
    6975      2416245 :           best_cost = acost;
    6976      2416245 :           iv_ca_delta_free (&best_delta);
    6977      2416245 :           best_delta = act_delta;
    6978              :         }
    6979              :       else
    6980     13741648 :         iv_ca_delta_free (&act_delta);
    6981              :     }
    6982              : 
    6983      9388586 :   if (!best_delta)
    6984              :     {
    6985      7121602 :       *delta = NULL;
    6986      7121602 :       return best_cost;
    6987              :     }
    6988              : 
    6989              :   /* Recurse to possibly remove other unnecessary ivs.  */
    6990      2266984 :   iv_ca_delta_commit (data, ivs, best_delta, true);
    6991      2266984 :   best_cost = iv_ca_prune (data, ivs, except_cand, delta);
    6992      2266984 :   iv_ca_delta_commit (data, ivs, best_delta, false);
    6993      2266984 :   *delta = iv_ca_delta_join (best_delta, *delta);
    6994      2266984 :   return best_cost;
    6995              : }
    6996              : 
    6997              : /* Check if CAND_IDX is a candidate other than OLD_CAND and has
    6998              :    cheaper local cost for GROUP than BEST_CP.  Return pointer to
    6999              :    the corresponding cost_pair, otherwise just return BEST_CP.  */
    7000              : 
    7001              : static class cost_pair*
    7002     29846221 : cheaper_cost_with_cand (struct ivopts_data *data, struct iv_group *group,
    7003              :                         unsigned int cand_idx, struct iv_cand *old_cand,
    7004              :                         class cost_pair *best_cp)
    7005              : {
    7006     29846221 :   struct iv_cand *cand;
    7007     29846221 :   class cost_pair *cp;
    7008              : 
    7009     29846221 :   gcc_assert (old_cand != NULL && best_cp != NULL);
    7010     29846221 :   if (cand_idx == old_cand->id)
    7011              :     return best_cp;
    7012              : 
    7013     26964845 :   cand = data->vcands[cand_idx];
    7014     26964845 :   cp = get_group_iv_cost (data, group, cand);
    7015     26964845 :   if (cp != NULL && cheaper_cost_pair (cp, best_cp))
    7016      1744818 :     return cp;
    7017              : 
    7018              :   return best_cp;
    7019              : }
    7020              : 
    7021              : /* Try breaking local optimal fixed-point for IVS by replacing candidates
    7022              :    which are used by more than one iv uses.  For each of those candidates,
    7023              :    this function tries to represent iv uses under that candidate using
    7024              :    other ones with lower local cost, then tries to prune the new set.
    7025              :    If the new set has lower cost, It returns the new cost after recording
    7026              :    candidate replacement in list DELTA.  */
    7027              : 
    7028              : static comp_cost
    7029      1037898 : iv_ca_replace (struct ivopts_data *data, class iv_ca *ivs,
    7030              :                struct iv_ca_delta **delta)
    7031              : {
    7032      1037898 :   bitmap_iterator bi, bj;
    7033      1037898 :   unsigned int i, j, k;
    7034      1037898 :   struct iv_cand *cand;
    7035      1037898 :   comp_cost orig_cost, acost;
    7036      1037898 :   struct iv_ca_delta *act_delta, *tmp_delta;
    7037      1037898 :   class cost_pair *old_cp, *best_cp = NULL;
    7038              : 
    7039      1037898 :   *delta = NULL;
    7040      1037898 :   orig_cost = iv_ca_cost (ivs);
    7041              : 
    7042      2445524 :   EXECUTE_IF_SET_IN_BITMAP (ivs->cands, 0, i, bi)
    7043              :     {
    7044      1441607 :       if (ivs->n_cand_uses[i] == 1
    7045      1063272 :           || ivs->n_cand_uses[i] > ALWAYS_PRUNE_CAND_SET_BOUND)
    7046       383142 :         continue;
    7047              : 
    7048      1058465 :       cand = data->vcands[i];
    7049              : 
    7050      1058465 :       act_delta = NULL;
    7051              :       /*  Represent uses under current candidate using other ones with
    7052              :           lower local cost.  */
    7053      5534736 :       for (j = 0; j < ivs->upto; j++)
    7054              :         {
    7055      4476271 :           struct iv_group *group = data->vgroups[j];
    7056      4476271 :           old_cp = iv_ca_cand_for_group (ivs, group);
    7057              : 
    7058      4476271 :           if (old_cp->cand != cand)
    7059      1594895 :             continue;
    7060              : 
    7061      2881376 :           best_cp = old_cp;
    7062      2881376 :           if (data->consider_all_candidates)
    7063     32612615 :             for (k = 0; k < data->vcands.length (); k++)
    7064     29739630 :               best_cp = cheaper_cost_with_cand (data, group, k,
    7065              :                                                 old_cp->cand, best_cp);
    7066              :           else
    7067       114982 :             EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, k, bj)
    7068       106591 :               best_cp = cheaper_cost_with_cand (data, group, k,
    7069              :                                                 old_cp->cand, best_cp);
    7070              : 
    7071      2881376 :           if (best_cp == old_cp)
    7072      1416907 :             continue;
    7073              : 
    7074      1464469 :           act_delta = iv_ca_delta_add (group, old_cp, best_cp, act_delta);
    7075              :         }
    7076              :       /* No need for further prune.  */
    7077      1058465 :       if (!act_delta)
    7078       264217 :         continue;
    7079              : 
    7080              :       /* Prune the new candidate set.  */
    7081       794248 :       iv_ca_delta_commit (data, ivs, act_delta, true);
    7082       794248 :       acost = iv_ca_prune (data, ivs, NULL, &tmp_delta);
    7083       794248 :       iv_ca_delta_commit (data, ivs, act_delta, false);
    7084       794248 :       act_delta = iv_ca_delta_join (act_delta, tmp_delta);
    7085              : 
    7086       794248 :       if (acost < orig_cost)
    7087              :         {
    7088        33981 :           *delta = act_delta;
    7089        33981 :           return acost;
    7090              :         }
    7091              :       else
    7092       760267 :         iv_ca_delta_free (&act_delta);
    7093              :     }
    7094              : 
    7095      1003917 :   return orig_cost;
    7096              : }
    7097              : 
    7098              : /* Tries to extend the sets IVS in the best possible way in order to
    7099              :    express the GROUP.  If ORIGINALP is true, prefer candidates from
    7100              :    the original set of IVs, otherwise favor important candidates not
    7101              :    based on any memory object.  */
    7102              : 
    7103              : static bool
    7104      3371702 : try_add_cand_for (struct ivopts_data *data, class iv_ca *ivs,
    7105              :                   struct iv_group *group, bool originalp)
    7106              : {
    7107      3371702 :   comp_cost best_cost, act_cost;
    7108      3371702 :   unsigned i;
    7109      3371702 :   bitmap_iterator bi;
    7110      3371702 :   struct iv_cand *cand;
    7111      3371702 :   struct iv_ca_delta *best_delta = NULL, *act_delta;
    7112      3371702 :   class cost_pair *cp;
    7113              : 
    7114      3371702 :   iv_ca_add_group (data, ivs, group);
    7115      3371702 :   best_cost = iv_ca_cost (ivs);
    7116      3371702 :   cp = iv_ca_cand_for_group (ivs, group);
    7117      3371702 :   if (cp)
    7118              :     {
    7119      3276259 :       best_delta = iv_ca_delta_add (group, NULL, cp, NULL);
    7120      3276259 :       iv_ca_set_no_cp (data, ivs, group);
    7121              :     }
    7122              : 
    7123              :   /* If ORIGINALP is true, try to find the original IV for the use.  Otherwise
    7124              :      first try important candidates not based on any memory object.  Only if
    7125              :      this fails, try the specific ones.  Rationale -- in loops with many
    7126              :      variables the best choice often is to use just one generic biv.  If we
    7127              :      added here many ivs specific to the uses, the optimization algorithm later
    7128              :      would be likely to get stuck in a local minimum, thus causing us to create
    7129              :      too many ivs.  The approach from few ivs to more seems more likely to be
    7130              :      successful -- starting from few ivs, replacing an expensive use by a
    7131              :      specific iv should always be a win.  */
    7132     31407258 :   EXECUTE_IF_SET_IN_BITMAP (group->related_cands, 0, i, bi)
    7133              :     {
    7134     28035556 :       cand = data->vcands[i];
    7135              : 
    7136     28035556 :       if (originalp && cand->pos !=IP_ORIGINAL)
    7137     11045312 :         continue;
    7138              : 
    7139     14017778 :       if (!originalp && cand->iv->base_object != NULL_TREE)
    7140      2562187 :         continue;
    7141              : 
    7142     14428057 :       if (iv_ca_cand_used_p (ivs, cand))
    7143      1544366 :         continue;
    7144              : 
    7145     12883691 :       cp = get_group_iv_cost (data, group, cand);
    7146     12883691 :       if (!cp)
    7147      3733222 :         continue;
    7148              : 
    7149      9150469 :       iv_ca_set_cp (data, ivs, group, cp);
    7150      9150469 :       act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL,
    7151              :                                true);
    7152      9150469 :       iv_ca_set_no_cp (data, ivs, group);
    7153      9150469 :       act_delta = iv_ca_delta_add (group, NULL, cp, act_delta);
    7154              : 
    7155      9150469 :       if (act_cost < best_cost)
    7156              :         {
    7157       371683 :           best_cost = act_cost;
    7158              : 
    7159       371683 :           iv_ca_delta_free (&best_delta);
    7160       371683 :           best_delta = act_delta;
    7161              :         }
    7162              :       else
    7163      8778786 :         iv_ca_delta_free (&act_delta);
    7164              :     }
    7165              : 
    7166      3371702 :   if (best_cost.infinite_cost_p ())
    7167              :     {
    7168       747198 :       for (i = 0; i < group->n_map_members; i++)
    7169              :         {
    7170       677880 :           cp = group->cost_map + i;
    7171       677880 :           cand = cp->cand;
    7172       677880 :           if (!cand)
    7173       559885 :             continue;
    7174              : 
    7175              :           /* Already tried this.  */
    7176       117995 :           if (cand->important)
    7177              :             {
    7178            0 :               if (originalp && cand->pos == IP_ORIGINAL)
    7179            0 :                 continue;
    7180            0 :               if (!originalp && cand->iv->base_object == NULL_TREE)
    7181            0 :                 continue;
    7182              :             }
    7183              : 
    7184       117995 :           if (iv_ca_cand_used_p (ivs, cand))
    7185            0 :             continue;
    7186              : 
    7187       117995 :           act_delta = NULL;
    7188       117995 :           iv_ca_set_cp (data, ivs, group, cp);
    7189       117995 :           act_cost = iv_ca_extend (data, ivs, cand, &act_delta, NULL, true);
    7190       117995 :           iv_ca_set_no_cp (data, ivs, group);
    7191       117995 :           act_delta = iv_ca_delta_add (group,
    7192              :                                        iv_ca_cand_for_group (ivs, group),
    7193              :                                        cp, act_delta);
    7194              : 
    7195       117995 :           if (act_cost < best_cost)
    7196              :             {
    7197        70931 :               best_cost = act_cost;
    7198              : 
    7199        70931 :               if (best_delta)
    7200         2521 :                 iv_ca_delta_free (&best_delta);
    7201        70931 :               best_delta = act_delta;
    7202              :             }
    7203              :           else
    7204        47064 :             iv_ca_delta_free (&act_delta);
    7205              :         }
    7206              :     }
    7207              : 
    7208      3371702 :   iv_ca_delta_commit (data, ivs, best_delta, true);
    7209      3371702 :   iv_ca_delta_free (&best_delta);
    7210              : 
    7211      3371702 :   return !best_cost.infinite_cost_p ();
    7212              : }
    7213              : 
    7214              : /* Finds an initial assignment of candidates to uses.  */
    7215              : 
    7216              : static class iv_ca *
    7217      1038806 : get_initial_solution (struct ivopts_data *data, bool originalp)
    7218              : {
    7219      1038806 :   unsigned i;
    7220      1038806 :   class iv_ca *ivs = iv_ca_new (data);
    7221              : 
    7222      4409600 :   for (i = 0; i < data->vgroups.length (); i++)
    7223      3371702 :     if (!try_add_cand_for (data, ivs, data->vgroups[i], originalp))
    7224              :       {
    7225          908 :         iv_ca_free (&ivs);
    7226          908 :         return NULL;
    7227              :       }
    7228              : 
    7229              :   return ivs;
    7230              : }
    7231              : 
    7232              : /* Tries to improve set of induction variables IVS.  TRY_REPLACE_P
    7233              :    points to a bool variable, this function tries to break local
    7234              :    optimal fixed-point by replacing candidates in IVS if it's true.  */
    7235              : 
    7236              : static bool
    7237      1574570 : try_improve_iv_set (struct ivopts_data *data,
    7238              :                     class iv_ca *ivs, bool *try_replace_p)
    7239              : {
    7240      1574570 :   unsigned i, n_ivs;
    7241      1574570 :   comp_cost acost, best_cost = iv_ca_cost (ivs);
    7242      1574570 :   struct iv_ca_delta *best_delta = NULL, *act_delta, *tmp_delta;
    7243      1574570 :   struct iv_cand *cand;
    7244              : 
    7245              :   /* Try extending the set of induction variables by one.  */
    7246     17375378 :   for (i = 0; i < data->vcands.length (); i++)
    7247              :     {
    7248     15800808 :       cand = data->vcands[i];
    7249              : 
    7250     15800808 :       if (iv_ca_cand_used_p (ivs, cand))
    7251      2461456 :         continue;
    7252              : 
    7253     13339352 :       acost = iv_ca_extend (data, ivs, cand, &act_delta, &n_ivs, false);
    7254     13339352 :       if (!act_delta)
    7255      8015942 :         continue;
    7256              : 
    7257              :       /* If we successfully added the candidate and the set is small enough,
    7258              :          try optimizing it by removing other candidates.  */
    7259      5323410 :       if (n_ivs <= ALWAYS_PRUNE_CAND_SET_BOUND)
    7260              :         {
    7261      5253321 :           iv_ca_delta_commit (data, ivs, act_delta, true);
    7262      5253321 :           acost = iv_ca_prune (data, ivs, cand, &tmp_delta);
    7263      5253321 :           iv_ca_delta_commit (data, ivs, act_delta, false);
    7264      5253321 :           act_delta = iv_ca_delta_join (act_delta, tmp_delta);
    7265              :         }
    7266              : 
    7267      5323410 :       if (acost < best_cost)
    7268              :         {
    7269       645422 :           best_cost = acost;
    7270       645422 :           iv_ca_delta_free (&best_delta);
    7271       645422 :           best_delta = act_delta;
    7272              :         }
    7273              :       else
    7274      4677988 :         iv_ca_delta_free (&act_delta);
    7275              :     }
    7276              : 
    7277      1574570 :   if (!best_delta)
    7278              :     {
    7279              :       /* Try removing the candidates from the set instead.  */
    7280      1074033 :       best_cost = iv_ca_prune (data, ivs, NULL, &best_delta);
    7281              : 
    7282      1074033 :       if (!best_delta && *try_replace_p)
    7283              :         {
    7284      1037898 :           *try_replace_p = false;
    7285              :           /* So far candidate selecting algorithm tends to choose fewer IVs
    7286              :              so that it can handle cases in which loops have many variables
    7287              :              but the best choice is often to use only one general biv.  One
    7288              :              weakness is it can't handle opposite cases, in which different
    7289              :              candidates should be chosen with respect to each use.  To solve
    7290              :              the problem, we replace candidates in a manner described by the
    7291              :              comments of iv_ca_replace, thus give general algorithm a chance
    7292              :              to break local optimal fixed-point in these cases.  */
    7293      1037898 :           best_cost = iv_ca_replace (data, ivs, &best_delta);
    7294              :         }
    7295              : 
    7296      1074033 :       if (!best_delta)
    7297              :         return false;
    7298              :     }
    7299              : 
    7300       536672 :   iv_ca_delta_commit (data, ivs, best_delta, true);
    7301       536672 :   iv_ca_delta_free (&best_delta);
    7302      1073344 :   return best_cost == iv_ca_cost (ivs);
    7303              : }
    7304              : 
    7305              : /* Attempts to find the optimal set of induction variables.  We do simple
    7306              :    greedy heuristic -- we try to replace at most one candidate in the selected
    7307              :    solution and remove the unused ivs while this improves the cost.  */
    7308              : 
    7309              : static class iv_ca *
    7310      1038806 : find_optimal_iv_set_1 (struct ivopts_data *data, bool originalp)
    7311              : {
    7312      1038806 :   class iv_ca *set;
    7313      1038806 :   bool try_replace_p = true;
    7314              : 
    7315              :   /* Get the initial solution.  */
    7316      1038806 :   set = get_initial_solution (data, originalp);
    7317      1038806 :   if (!set)
    7318              :     {
    7319          908 :       if (dump_file && (dump_flags & TDF_DETAILS))
    7320            0 :         fprintf (dump_file, "Unable to substitute for ivs, failed.\n");
    7321              :       return NULL;
    7322              :     }
    7323              : 
    7324      1037898 :   if (dump_file && (dump_flags & TDF_DETAILS))
    7325              :     {
    7326          144 :       fprintf (dump_file, "Initial set of candidates:\n");
    7327          144 :       iv_ca_dump (data, dump_file, set);
    7328              :     }
    7329              : 
    7330      1574570 :   while (try_improve_iv_set (data, set, &try_replace_p))
    7331              :     {
    7332       536672 :       if (dump_file && (dump_flags & TDF_DETAILS))
    7333              :         {
    7334          126 :           fprintf (dump_file, "Improved to:\n");
    7335          126 :           iv_ca_dump (data, dump_file, set);
    7336              :         }
    7337              :     }
    7338              : 
    7339              :   /* If the set has infinite_cost, it can't be optimal.  */
    7340      2075796 :   if (iv_ca_cost (set).infinite_cost_p ())
    7341              :     {
    7342            0 :       if (dump_file && (dump_flags & TDF_DETAILS))
    7343            0 :         fprintf (dump_file,
    7344              :                  "Overflow to infinite cost in try_improve_iv_set.\n");
    7345            0 :       iv_ca_free (&set);
    7346              :     }
    7347      1037898 :   return set;
    7348              : }
    7349              : 
    7350              : static class iv_ca *
    7351       519403 : find_optimal_iv_set (struct ivopts_data *data)
    7352              : {
    7353       519403 :   unsigned i;
    7354       519403 :   comp_cost cost, origcost;
    7355       519403 :   class iv_ca *set, *origset;
    7356              : 
    7357              :   /* Determine the cost based on a strategy that starts with original IVs,
    7358              :      and try again using a strategy that prefers candidates not based
    7359              :      on any IVs.  */
    7360       519403 :   origset = find_optimal_iv_set_1 (data, true);
    7361       519403 :   set = find_optimal_iv_set_1 (data, false);
    7362              : 
    7363       519403 :   if (!origset && !set)
    7364              :     return NULL;
    7365              : 
    7366       518949 :   origcost = origset ? iv_ca_cost (origset) : infinite_cost;
    7367       518949 :   cost = set ? iv_ca_cost (set) : infinite_cost;
    7368              : 
    7369       518949 :   if (dump_file && (dump_flags & TDF_DETAILS))
    7370              :     {
    7371           72 :       fprintf (dump_file, "Original cost %" PRId64 " (complexity %d)\n\n",
    7372              :                origcost.cost, origcost.complexity);
    7373           72 :       fprintf (dump_file, "Final cost %" PRId64 " (complexity %d)\n\n",
    7374              :                cost.cost, cost.complexity);
    7375              :     }
    7376              : 
    7377              :   /* Choose the one with the best cost.  */
    7378       518949 :   if (origcost <= cost)
    7379              :     {
    7380       484894 :       if (set)
    7381       484894 :         iv_ca_free (&set);
    7382       484894 :       set = origset;
    7383              :     }
    7384        34055 :   else if (origset)
    7385        34055 :     iv_ca_free (&origset);
    7386              : 
    7387      2203680 :   for (i = 0; i < data->vgroups.length (); i++)
    7388              :     {
    7389      1684731 :       struct iv_group *group = data->vgroups[i];
    7390      1684731 :       group->selected = iv_ca_cand_for_group (set, group)->cand;
    7391              :     }
    7392              : 
    7393       518949 :   return set;
    7394              : }
    7395              : 
    7396              : /* Creates a new induction variable corresponding to CAND.  */
    7397              : 
    7398              : static void
    7399       721298 : create_new_iv (struct ivopts_data *data, struct iv_cand *cand)
    7400              : {
    7401       721298 :   gimple_stmt_iterator incr_pos;
    7402       721298 :   tree base;
    7403       721298 :   struct iv_use *use;
    7404       721298 :   struct iv_group *group;
    7405       721298 :   bool after = false;
    7406              : 
    7407       721298 :   gcc_assert (cand->iv != NULL);
    7408              : 
    7409       721298 :   switch (cand->pos)
    7410              :     {
    7411       503685 :     case IP_NORMAL:
    7412       503685 :       incr_pos = gsi_last_bb (ip_normal_pos (data->current_loop));
    7413       503685 :       break;
    7414              : 
    7415        11825 :     case IP_END:
    7416        11825 :       incr_pos = gsi_last_bb (ip_end_pos (data->current_loop));
    7417        11825 :       after = true;
    7418        11825 :       gcc_assert (gsi_end_p (incr_pos) || !stmt_ends_bb_p (*incr_pos));
    7419              :       break;
    7420              : 
    7421            0 :     case IP_AFTER_USE:
    7422            0 :       after = true;
    7423              :       /* fall through */
    7424            0 :     case IP_BEFORE_USE:
    7425            0 :       incr_pos = gsi_for_stmt (cand->incremented_at);
    7426            0 :       break;
    7427              : 
    7428       205788 :     case IP_ORIGINAL:
    7429              :       /* Mark that the iv is preserved.  */
    7430       205788 :       name_info (data, cand->var_before)->preserve_biv = true;
    7431       205788 :       name_info (data, cand->var_after)->preserve_biv = true;
    7432              : 
    7433              :       /* Rewrite the increment so that it uses var_before directly.  Missed
    7434              :          optimization can result in a use IV with zero step, avoid
    7435              :          crashing in that case.  */
    7436       205788 :       use = find_interesting_uses_op (data, cand->var_after);
    7437       205788 :       if (use)
    7438              :         {
    7439       205783 :           group = data->vgroups[use->group_id];
    7440       205783 :           group->selected = cand;
    7441              :         }
    7442       205788 :       return;
    7443              :     }
    7444              : 
    7445       515510 :   gimple_add_tmp_var (cand->var_before);
    7446              : 
    7447       515510 :   base = unshare_expr (cand->iv->base);
    7448              : 
    7449              :   /* The step computation could invoke UB when the loop does not iterate.
    7450              :      Avoid inserting it on the preheader in its native form but rewrite
    7451              :      it to a well-defined form.  This also helps masking SCEV issues
    7452              :      which freely re-associates the IV computations when building up
    7453              :      CHRECs without much regard for signed overflow invoking UB.  */
    7454       515510 :   gimple_seq stmts = NULL;
    7455       515510 :   tree step = force_gimple_operand (unshare_expr (cand->iv->step), &stmts,
    7456              :                                     true, NULL_TREE);
    7457       515510 :   if (stmts)
    7458              :     {
    7459       162598 :       for (auto gsi = gsi_start (stmts); !gsi_end_p (gsi); gsi_next (&gsi))
    7460       107087 :         if (gimple_needing_rewrite_undefined (gsi_stmt (gsi)))
    7461        12342 :           rewrite_to_defined_unconditional (&gsi);
    7462        55511 :       gsi_insert_seq_on_edge_immediate
    7463        55511 :         (loop_preheader_edge (data->current_loop), stmts);
    7464              :     }
    7465              : 
    7466       515510 :   create_iv (base, PLUS_EXPR, step,
    7467              :              cand->var_before, data->current_loop,
    7468              :              &incr_pos, after, &cand->var_before, &cand->var_after);
    7469              : }
    7470              : 
    7471              : /* Creates new induction variables described in SET.  */
    7472              : 
    7473              : static void
    7474       518949 : create_new_ivs (struct ivopts_data *data, class iv_ca *set)
    7475              : {
    7476       518949 :   unsigned i;
    7477       518949 :   struct iv_cand *cand;
    7478       518949 :   bitmap_iterator bi;
    7479              : 
    7480      1240247 :   EXECUTE_IF_SET_IN_BITMAP (set->cands, 0, i, bi)
    7481              :     {
    7482       721298 :       cand = data->vcands[i];
    7483       721298 :       create_new_iv (data, cand);
    7484              :     }
    7485              : 
    7486       518949 :   if (dump_file && (dump_flags & TDF_DETAILS))
    7487              :     {
    7488           72 :       fprintf (dump_file, "Selected IV set for loop %d",
    7489           72 :                data->current_loop->num);
    7490           72 :       if (data->loop_loc != UNKNOWN_LOCATION)
    7491           70 :         fprintf (dump_file, " at %s:%d", LOCATION_FILE (data->loop_loc),
    7492          140 :                  LOCATION_LINE (data->loop_loc));
    7493           72 :       fprintf (dump_file, ", " HOST_WIDE_INT_PRINT_UNSIGNED " avg niters",
    7494              :                avg_loop_niter (data->current_loop));
    7495           72 :       fprintf (dump_file, ", %lu IVs:\n", bitmap_count_bits (set->cands));
    7496          192 :       EXECUTE_IF_SET_IN_BITMAP (set->cands, 0, i, bi)
    7497              :         {
    7498          120 :           cand = data->vcands[i];
    7499          120 :           dump_cand (dump_file, cand);
    7500              :         }
    7501           72 :       fprintf (dump_file, "\n");
    7502              :     }
    7503       518949 : }
    7504              : 
    7505              : /* Rewrites USE (definition of iv used in a nonlinear expression)
    7506              :    using candidate CAND.  */
    7507              : 
    7508              : static void
    7509       637300 : rewrite_use_nonlinear_expr (struct ivopts_data *data,
    7510              :                             struct iv_use *use, struct iv_cand *cand)
    7511              : {
    7512       637300 :   gassign *ass;
    7513       637300 :   gimple_stmt_iterator bsi;
    7514       637300 :   tree comp, type = get_use_type (use), tgt;
    7515              : 
    7516              :   /* An important special case -- if we are asked to express value of
    7517              :      the original iv by itself, just exit; there is no need to
    7518              :      introduce a new computation (that might also need casting the
    7519              :      variable to unsigned and back).  */
    7520       637300 :   if (cand->pos == IP_ORIGINAL
    7521       336019 :       && cand->incremented_at == use->stmt)
    7522              :     {
    7523       205783 :       tree op = NULL_TREE;
    7524       205783 :       enum tree_code stmt_code;
    7525              : 
    7526       205783 :       gcc_assert (is_gimple_assign (use->stmt));
    7527       205783 :       gcc_assert (gimple_assign_lhs (use->stmt) == cand->var_after);
    7528              : 
    7529              :       /* Check whether we may leave the computation unchanged.
    7530              :          This is the case only if it does not rely on other
    7531              :          computations in the loop -- otherwise, the computation
    7532              :          we rely upon may be removed in remove_unused_ivs,
    7533              :          thus leading to ICE.  */
    7534       205783 :       stmt_code = gimple_assign_rhs_code (use->stmt);
    7535       205783 :       if (stmt_code == PLUS_EXPR
    7536       205783 :           || stmt_code == MINUS_EXPR
    7537       205783 :           || stmt_code == POINTER_PLUS_EXPR)
    7538              :         {
    7539       203198 :           if (gimple_assign_rhs1 (use->stmt) == cand->var_before)
    7540       202357 :             op = gimple_assign_rhs2 (use->stmt);
    7541          841 :           else if (gimple_assign_rhs2 (use->stmt) == cand->var_before)
    7542              :             op = gimple_assign_rhs1 (use->stmt);
    7543              :         }
    7544              : 
    7545       202882 :       if (op != NULL_TREE)
    7546              :         {
    7547       202882 :           if (expr_invariant_in_loop_p (data->current_loop, op))
    7548       289623 :             return;
    7549          165 :           if (TREE_CODE (op) == SSA_NAME)
    7550              :             {
    7551          165 :               struct iv *iv = get_iv (data, op);
    7552          165 :               if (iv != NULL && integer_zerop (iv->step))
    7553              :                 return;
    7554              :             }
    7555              :         }
    7556              :     }
    7557              : 
    7558       434418 :   switch (gimple_code (use->stmt))
    7559              :     {
    7560       129501 :     case GIMPLE_PHI:
    7561       129501 :       tgt = PHI_RESULT (use->stmt);
    7562              : 
    7563              :       /* If we should keep the biv, do not replace it.  */
    7564       129501 :       if (name_info (data, tgt)->preserve_biv)
    7565              :         return;
    7566              : 
    7567        42760 :       bsi = gsi_after_labels (gimple_bb (use->stmt));
    7568        42760 :       break;
    7569              : 
    7570       304917 :     case GIMPLE_ASSIGN:
    7571       304917 :       tgt = gimple_assign_lhs (use->stmt);
    7572       304917 :       bsi = gsi_for_stmt (use->stmt);
    7573       304917 :       break;
    7574              : 
    7575            0 :     default:
    7576            0 :       gcc_unreachable ();
    7577              :     }
    7578              : 
    7579      1043031 :   aff_tree aff_inv, aff_var;
    7580       347677 :   if (!get_computation_aff_1 (data, use->stmt, use, cand, &aff_inv, &aff_var))
    7581            0 :     gcc_unreachable ();
    7582              : 
    7583       347677 :   unshare_aff_combination (&aff_inv);
    7584       347677 :   unshare_aff_combination (&aff_var);
    7585              :   /* Prefer CSE opportunity than loop invariant by adding offset at last
    7586              :      so that iv_uses have different offsets can be CSEed.  */
    7587       695354 :   poly_widest_int offset = aff_inv.offset;
    7588       347677 :   aff_inv.offset = 0;
    7589              : 
    7590       347677 :   gimple_seq stmt_list = NULL, seq = NULL;
    7591       347677 :   tree comp_op1 = aff_combination_to_tree (&aff_inv);
    7592       347677 :   tree comp_op2 = aff_combination_to_tree (&aff_var);
    7593       347677 :   gcc_assert (comp_op1 && comp_op2);
    7594              : 
    7595       347677 :   comp_op1 = force_gimple_operand (comp_op1, &seq, true, NULL);
    7596       347677 :   gimple_seq_add_seq (&stmt_list, seq);
    7597       347677 :   comp_op2 = force_gimple_operand (comp_op2, &seq, true, NULL);
    7598       347677 :   gimple_seq_add_seq (&stmt_list, seq);
    7599              : 
    7600       347677 :   if (POINTER_TYPE_P (TREE_TYPE (comp_op2)))
    7601              :     std::swap (comp_op1, comp_op2);
    7602              : 
    7603       347677 :   if (POINTER_TYPE_P (TREE_TYPE (comp_op1)))
    7604              :     {
    7605            0 :       comp = fold_build_pointer_plus (comp_op1,
    7606              :                                       fold_convert (sizetype, comp_op2));
    7607            0 :       comp = fold_build_pointer_plus (comp,
    7608              :                                       wide_int_to_tree (sizetype, offset));
    7609              :     }
    7610              :   else
    7611              :     {
    7612       347677 :       comp = fold_build2 (PLUS_EXPR, TREE_TYPE (comp_op1), comp_op1,
    7613              :                           fold_convert (TREE_TYPE (comp_op1), comp_op2));
    7614       347677 :       comp = fold_build2 (PLUS_EXPR, TREE_TYPE (comp_op1), comp,
    7615              :                           wide_int_to_tree (TREE_TYPE (comp_op1), offset));
    7616              :     }
    7617              : 
    7618       347677 :   comp = fold_convert (type, comp);
    7619       347677 :   comp = force_gimple_operand (comp, &seq, false, NULL);
    7620       347677 :   gimple_seq_add_seq (&stmt_list, seq);
    7621       347677 :   if (gimple_code (use->stmt) != GIMPLE_PHI
    7622              :       /* We can't allow re-allocating the stmt as it might be pointed
    7623              :          to still.  */
    7624       347677 :       && (get_gimple_rhs_num_ops (TREE_CODE (comp))
    7625       304917 :           >= gimple_num_ops (gsi_stmt (bsi))))
    7626              :     {
    7627         5804 :       comp = force_gimple_operand (comp, &seq, true, NULL);
    7628         5804 :       gimple_seq_add_seq (&stmt_list, seq);
    7629         5804 :       if (POINTER_TYPE_P (TREE_TYPE (tgt)))
    7630            0 :         duplicate_ssa_name_pt_solution (comp, tgt);
    7631              :     }
    7632              : 
    7633       347677 :   gsi_insert_seq_before (&bsi, stmt_list, GSI_SAME_STMT);
    7634       347677 :   if (gimple_code (use->stmt) == GIMPLE_PHI)
    7635              :     {
    7636        42760 :       ass = gimple_build_assign (tgt, comp);
    7637        42760 :       gsi_insert_before (&bsi, ass, GSI_SAME_STMT);
    7638              : 
    7639        42760 :       bsi = gsi_for_stmt (use->stmt);
    7640        42760 :       remove_phi_node (&bsi, false);
    7641              :     }
    7642              :   else
    7643              :     {
    7644       304917 :       gimple_assign_set_rhs_from_tree (&bsi, comp);
    7645       304917 :       use->stmt = gsi_stmt (bsi);
    7646              :     }
    7647              : }
    7648              : 
    7649              : /* Performs a peephole optimization to reorder the iv update statement with
    7650              :    a mem ref to enable instruction combining in later phases. The mem ref uses
    7651              :    the iv value before the update, so the reordering transformation requires
    7652              :    adjustment of the offset. CAND is the selected IV_CAND.
    7653              : 
    7654              :    Example:
    7655              : 
    7656              :    t = MEM_REF (base, iv1, 8, 16);  // base, index, stride, offset
    7657              :    iv2 = iv1 + 1;
    7658              : 
    7659              :    if (t < val)      (1)
    7660              :      goto L;
    7661              :    goto Head;
    7662              : 
    7663              : 
    7664              :    directly propagating t over to (1) will introduce overlapping live range
    7665              :    thus increase register pressure. This peephole transform it into:
    7666              : 
    7667              : 
    7668              :    iv2 = iv1 + 1;
    7669              :    t = MEM_REF (base, iv2, 8, 8);
    7670              :    if (t < val)
    7671              :      goto L;
    7672              :    goto Head;
    7673              : */
    7674              : 
    7675              : static void
    7676       872991 : adjust_iv_update_pos (struct iv_cand *cand, struct iv_use *use)
    7677              : {
    7678       872991 :   tree var_after;
    7679       872991 :   gimple *iv_update, *stmt;
    7680       872991 :   basic_block bb;
    7681       872991 :   gimple_stmt_iterator gsi, gsi_iv;
    7682              : 
    7683       872991 :   if (cand->pos != IP_NORMAL)
    7684       870807 :     return;
    7685              : 
    7686       677176 :   var_after = cand->var_after;
    7687       677176 :   iv_update = SSA_NAME_DEF_STMT (var_after);
    7688              : 
    7689       677176 :   bb = gimple_bb (iv_update);
    7690       677176 :   gsi = gsi_last_nondebug_bb (bb);
    7691       677176 :   stmt = gsi_stmt (gsi);
    7692              : 
    7693              :   /* Only handle conditional statement for now.  */
    7694       677176 :   if (gimple_code (stmt) != GIMPLE_COND)
    7695              :     return;
    7696              : 
    7697       677176 :   gsi_prev_nondebug (&gsi);
    7698       677176 :   stmt = gsi_stmt (gsi);
    7699       677176 :   if (stmt != iv_update)
    7700              :     return;
    7701              : 
    7702       539106 :   gsi_prev_nondebug (&gsi);
    7703       539106 :   if (gsi_end_p (gsi))
    7704              :     return;
    7705              : 
    7706      1406939 :   auto a_stmt = dyn_cast<gassign *> (gsi_stmt (gsi));
    7707       536132 :   if (!a_stmt)
    7708              :     return;
    7709              : 
    7710       536132 :   if (a_stmt != use->stmt)
    7711              :     return;
    7712              : 
    7713         4252 :   if (TREE_CODE (gimple_assign_lhs (a_stmt)) != SSA_NAME)
    7714              :     return;
    7715              : 
    7716         2184 :   if (dump_file && (dump_flags & TDF_DETAILS))
    7717              :     {
    7718            0 :       fprintf (dump_file, "Reordering \n");
    7719            0 :       print_gimple_stmt (dump_file, iv_update, 0);
    7720            0 :       print_gimple_stmt (dump_file, use->stmt, 0);
    7721            0 :       fprintf (dump_file, "\n");
    7722              :     }
    7723              : 
    7724         2184 :   gsi = gsi_for_stmt (use->stmt);
    7725         2184 :   gsi_iv = gsi_for_stmt (iv_update);
    7726         2184 :   gsi_move_before (&gsi_iv, &gsi);
    7727              : 
    7728         2184 :   cand->pos = IP_BEFORE_USE;
    7729         2184 :   cand->incremented_at = use->stmt;
    7730              : }
    7731              : 
    7732              : /* Return the alias pointer type that should be used for a MEM_REF
    7733              :    associated with USE, which has type USE_PTR_ADDRESS.  */
    7734              : 
    7735              : static tree
    7736          730 : get_alias_ptr_type_for_ptr_address (iv_use *use)
    7737              : {
    7738          730 :   gcall *call = as_a <gcall *> (use->stmt);
    7739          730 :   switch (gimple_call_internal_fn (call))
    7740              :     {
    7741          730 :     case IFN_MASK_LOAD:
    7742          730 :     case IFN_MASK_STORE:
    7743          730 :     case IFN_MASK_LOAD_LANES:
    7744          730 :     case IFN_MASK_STORE_LANES:
    7745          730 :     case IFN_MASK_LEN_LOAD_LANES:
    7746          730 :     case IFN_MASK_LEN_STORE_LANES:
    7747          730 :     case IFN_LEN_LOAD:
    7748          730 :     case IFN_LEN_STORE:
    7749          730 :     case IFN_MASK_LEN_LOAD:
    7750          730 :     case IFN_MASK_LEN_STORE:
    7751              :       /* The second argument contains the correct alias type.  */
    7752          730 :       gcc_assert (use->op_p == gimple_call_arg_ptr (call, 0));
    7753          730 :       return TREE_TYPE (gimple_call_arg (call, 1));
    7754              : 
    7755            0 :     default:
    7756            0 :       gcc_unreachable ();
    7757              :     }
    7758              : }
    7759              : 
    7760              : 
    7761              : /* Rewrites USE (address that is an iv) using candidate CAND.  */
    7762              : 
    7763              : static void
    7764       872991 : rewrite_use_address (struct ivopts_data *data,
    7765              :                      struct iv_use *use, struct iv_cand *cand)
    7766              : {
    7767       872991 :   aff_tree aff;
    7768       872991 :   bool ok;
    7769              : 
    7770       872991 :   adjust_iv_update_pos (cand, use);
    7771       872991 :   ok = get_computation_aff (data, use->stmt, use, cand, &aff);
    7772       872991 :   gcc_assert (ok);
    7773       872991 :   unshare_aff_combination (&aff);
    7774              : 
    7775              :   /* To avoid undefined overflow problems, all IV candidates use unsigned
    7776              :      integer types.  The drawback is that this makes it impossible for
    7777              :      create_mem_ref to distinguish an IV that is based on a memory object
    7778              :      from one that represents simply an offset.
    7779              : 
    7780              :      To work around this problem, we pass a hint to create_mem_ref that
    7781              :      indicates which variable (if any) in aff is an IV based on a memory
    7782              :      object.  Note that we only consider the candidate.  If this is not
    7783              :      based on an object, the base of the reference is in some subexpression
    7784              :      of the use -- but these will use pointer types, so they are recognized
    7785              :      by the create_mem_ref heuristics anyway.  */
    7786       872991 :   tree iv = var_at_stmt (data->current_loop, cand, use->stmt);
    7787       872991 :   tree base_hint = (cand->iv->base_object) ? iv : NULL_TREE;
    7788       872991 :   gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
    7789       872991 :   tree type = use->mem_type;
    7790       872991 :   tree alias_ptr_type;
    7791       872991 :   if (use->type == USE_PTR_ADDRESS)
    7792          730 :     alias_ptr_type = get_alias_ptr_type_for_ptr_address (use);
    7793              :   else
    7794              :     {
    7795       872261 :       gcc_assert (type == TREE_TYPE (*use->op_p));
    7796       872261 :       unsigned int align = get_object_alignment (*use->op_p);
    7797       872261 :       if (align != TYPE_ALIGN (type))
    7798        34954 :         type = build_aligned_type (type, align);
    7799       872261 :       alias_ptr_type = reference_alias_ptr_type (*use->op_p);
    7800              :     }
    7801       872991 :   tree ref = create_mem_ref (&bsi, type, &aff, alias_ptr_type,
    7802              :                              iv, base_hint, data->speed);
    7803              : 
    7804       872991 :   if (use->type == USE_PTR_ADDRESS)
    7805              :     {
    7806          730 :       ref = fold_build1 (ADDR_EXPR, build_pointer_type (use->mem_type), ref);
    7807          730 :       ref = fold_convert (get_use_type (use), ref);
    7808          730 :       ref = force_gimple_operand_gsi (&bsi, ref, true, NULL_TREE,
    7809              :                                       true, GSI_SAME_STMT);
    7810              :     }
    7811              :   else
    7812              :     {
    7813              :       /* When we end up confused enough and have no suitable base but
    7814              :          stuffed everything to indexes use a LEA for the address and
    7815              :          create a plain MEM_REF to avoid basing a memory reference
    7816              :          on address zero which create_mem_ref_raw does as fallback.  */
    7817       872261 :       if (TREE_CODE (ref) == TARGET_MEM_REF
    7818       872261 :           && integer_zerop (TREE_OPERAND (ref, 0)))
    7819              :         {
    7820           24 :           ref = fold_build1 (ADDR_EXPR, TREE_TYPE (TREE_OPERAND (ref, 0)), ref);
    7821           24 :           ref = force_gimple_operand_gsi (&bsi, ref, true, NULL_TREE,
    7822              :                                           true, GSI_SAME_STMT);
    7823           24 :           ref = build2 (MEM_REF, type, ref, build_zero_cst (alias_ptr_type));
    7824              :         }
    7825       872261 :       copy_ref_info (ref, *use->op_p);
    7826              :     }
    7827              : 
    7828       872991 :   *use->op_p = ref;
    7829       872991 : }
    7830              : 
    7831              : /* Rewrites USE (the condition such that one of the arguments is an iv) using
    7832              :    candidate CAND.  */
    7833              : 
    7834              : static void
    7835       612582 : rewrite_use_compare (struct ivopts_data *data,
    7836              :                      struct iv_use *use, struct iv_cand *cand)
    7837              : {
    7838       612582 :   tree comp, op, bound;
    7839       612582 :   gimple_stmt_iterator bsi = gsi_for_stmt (use->stmt);
    7840       612582 :   enum tree_code compare;
    7841       612582 :   struct iv_group *group = data->vgroups[use->group_id];
    7842       612582 :   class cost_pair *cp = get_group_iv_cost (data, group, cand);
    7843              : 
    7844       612582 :   bound = cp->value;
    7845       612582 :   if (bound)
    7846              :     {
    7847       412525 :       tree var = var_at_stmt (data->current_loop, cand, use->stmt);
    7848       412525 :       tree var_type = TREE_TYPE (var);
    7849       412525 :       gimple_seq stmts;
    7850              : 
    7851       412525 :       if (dump_file && (dump_flags & TDF_DETAILS))
    7852              :         {
    7853           60 :           fprintf (dump_file, "Replacing exit test: ");
    7854           60 :           print_gimple_stmt (dump_file, use->stmt, 0, TDF_SLIM);
    7855              :         }
    7856       412525 :       compare = cp->comp;
    7857       412525 :       bound = unshare_expr (fold_convert (var_type, bound));
    7858       412525 :       op = force_gimple_operand (bound, &stmts, true, NULL_TREE);
    7859       412525 :       if (stmts)
    7860       194960 :         gsi_insert_seq_on_edge_immediate (
    7861       194960 :                 loop_preheader_edge (data->current_loop),
    7862              :                 stmts);
    7863              : 
    7864       412525 :       gcond *cond_stmt = as_a <gcond *> (use->stmt);
    7865       412525 :       gimple_cond_set_lhs (cond_stmt, var);
    7866       412525 :       gimple_cond_set_code (cond_stmt, compare);
    7867       412525 :       gimple_cond_set_rhs (cond_stmt, op);
    7868       412525 :       return;
    7869              :     }
    7870              : 
    7871              :   /* The induction variable elimination failed; just express the original
    7872              :      giv.  */
    7873       200057 :   comp = get_computation_at (data, use->stmt, use, cand);
    7874       200057 :   gcc_assert (comp != NULL_TREE);
    7875       200057 :   gcc_assert (use->op_p != NULL);
    7876       200057 :   *use->op_p = force_gimple_operand_gsi (&bsi, comp, true,
    7877       200057 :                                          SSA_NAME_VAR (*use->op_p),
    7878              :                                          true, GSI_SAME_STMT);
    7879              : }
    7880              : 
    7881              : /* Rewrite the groups using the selected induction variables.  */
    7882              : 
    7883              : static void
    7884       518949 : rewrite_groups (struct ivopts_data *data)
    7885              : {
    7886       518949 :   unsigned i, j;
    7887              : 
    7888      2365803 :   for (i = 0; i < data->vgroups.length (); i++)
    7889              :     {
    7890      1846854 :       struct iv_group *group = data->vgroups[i];
    7891      1846854 :       struct iv_cand *cand = group->selected;
    7892              : 
    7893      1846854 :       gcc_assert (cand);
    7894              : 
    7895      1846854 :       if (group->type == USE_NONLINEAR_EXPR)
    7896              :         {
    7897      1274600 :           for (j = 0; j < group->vuses.length (); j++)
    7898              :             {
    7899       637300 :               rewrite_use_nonlinear_expr (data, group->vuses[j], cand);
    7900       637300 :               update_stmt (group->vuses[j]->stmt);
    7901              :             }
    7902              :         }
    7903      1209554 :       else if (address_p (group->type))
    7904              :         {
    7905      1469963 :           for (j = 0; j < group->vuses.length (); j++)
    7906              :             {
    7907       872991 :               rewrite_use_address (data, group->vuses[j], cand);
    7908       872991 :               update_stmt (group->vuses[j]->stmt);
    7909              :             }
    7910              :         }
    7911              :       else
    7912              :         {
    7913       612582 :           gcc_assert (group->type == USE_COMPARE);
    7914              : 
    7915      2459436 :           for (j = 0; j < group->vuses.length (); j++)
    7916              :             {
    7917       612582 :               rewrite_use_compare (data, group->vuses[j], cand);
    7918       612582 :               update_stmt (group->vuses[j]->stmt);
    7919              :             }
    7920              :         }
    7921              :     }
    7922       518949 : }
    7923              : 
    7924              : /* Removes the ivs that are not used after rewriting.  */
    7925              : 
    7926              : static void
    7927       518949 : remove_unused_ivs (struct ivopts_data *data, bitmap toremove)
    7928              : {
    7929       518949 :   unsigned j;
    7930       518949 :   bitmap_iterator bi;
    7931              : 
    7932              :   /* Figure out an order in which to release SSA DEFs so that we don't
    7933              :      release something that we'd have to propagate into a debug stmt
    7934              :      afterwards.  */
    7935      5724347 :   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, j, bi)
    7936              :     {
    7937      5205398 :       struct version_info *info;
    7938              : 
    7939      5205398 :       info = ver_info (data, j);
    7940      5205398 :       if (info->iv
    7941      5058464 :           && !integer_zerop (info->iv->step)
    7942      3300287 :           && !info->inv_id
    7943      3300287 :           && !info->iv->nonlin_use
    7944      7868385 :           && !info->preserve_biv)
    7945              :         {
    7946      2543940 :           bitmap_set_bit (toremove, SSA_NAME_VERSION (info->iv->ssa_name));
    7947              : 
    7948      2543940 :           tree def = info->iv->ssa_name;
    7949              : 
    7950      3304175 :           if (MAY_HAVE_DEBUG_BIND_STMTS && SSA_NAME_DEF_STMT (def))
    7951              :             {
    7952       760235 :               imm_use_iterator imm_iter;
    7953       760235 :               use_operand_p use_p;
    7954       760235 :               gimple *stmt;
    7955       760235 :               int count = 0;
    7956              : 
    7957      1505248 :               FOR_EACH_IMM_USE_STMT (stmt, imm_iter, def)
    7958              :                 {
    7959       772018 :                   if (!gimple_debug_bind_p (stmt))
    7960       650483 :                     continue;
    7961              : 
    7962              :                   /* We just want to determine whether to do nothing
    7963              :                      (count == 0), to substitute the computed
    7964              :                      expression into a single use of the SSA DEF by
    7965              :                      itself (count == 1), or to use a debug temp
    7966              :                      because the SSA DEF is used multiple times or as
    7967              :                      part of a larger expression (count > 1). */
    7968       121535 :                   count++;
    7969       121535 :                   if (gimple_debug_bind_get_value (stmt) != def)
    7970         5564 :                     count++;
    7971              : 
    7972       121535 :                   if (count > 1)
    7973              :                     break;
    7974       760235 :                 }
    7975              : 
    7976       760235 :               if (!count)
    7977       685956 :                 continue;
    7978              : 
    7979        99865 :               struct iv_use dummy_use;
    7980        99865 :               struct iv_cand *best_cand = NULL, *cand;
    7981        99865 :               unsigned i, best_pref = 0, cand_pref;
    7982        99865 :               tree comp = NULL_TREE;
    7983              : 
    7984        99865 :               memset (&dummy_use, 0, sizeof (dummy_use));
    7985        99865 :               dummy_use.iv = info->iv;
    7986       508904 :               for (i = 0; i < data->vgroups.length () && i < 64; i++)
    7987              :                 {
    7988       409039 :                   cand = data->vgroups[i]->selected;
    7989       409039 :                   if (cand == best_cand)
    7990       155391 :                     continue;
    7991       175716 :                   cand_pref = operand_equal_p (cand->iv->step,
    7992       253648 :                                                info->iv->step, 0)
    7993       253648 :                     ? 4 : 0;
    7994       253648 :                   cand_pref
    7995       253648 :                     += TYPE_MODE (TREE_TYPE (cand->iv->base))
    7996       253648 :                     == TYPE_MODE (TREE_TYPE (info->iv->base))
    7997       253648 :                     ? 2 : 0;
    7998       253648 :                   cand_pref
    7999       507296 :                     += TREE_CODE (cand->iv->base) == INTEGER_CST
    8000       253648 :                     ? 1 : 0;
    8001       253648 :                   if (best_cand == NULL || best_pref < cand_pref)
    8002              :                     {
    8003       200120 :                       tree this_comp
    8004       400240 :                         = get_debug_computation_at (data,
    8005       200120 :                                                     SSA_NAME_DEF_STMT (def),
    8006              :                                                     &dummy_use, cand);
    8007       200120 :                       if (this_comp)
    8008              :                         {
    8009       409039 :                           best_cand = cand;
    8010       409039 :                           best_pref = cand_pref;
    8011       409039 :                           comp = this_comp;
    8012              :                         }
    8013              :                     }
    8014              :                 }
    8015              : 
    8016        99865 :               if (!best_cand)
    8017        25586 :                 continue;
    8018              : 
    8019        74279 :               comp = unshare_expr (comp);
    8020        74279 :               if (count > 1)
    8021              :                 {
    8022        23528 :                   tree vexpr = build_debug_expr_decl (TREE_TYPE (comp));
    8023              :                   /* FIXME: Is setting the mode really necessary? */
    8024        23528 :                   if (SSA_NAME_VAR (def))
    8025        13681 :                     SET_DECL_MODE (vexpr, DECL_MODE (SSA_NAME_VAR (def)));
    8026              :                   else
    8027         9847 :                     SET_DECL_MODE (vexpr, TYPE_MODE (TREE_TYPE (vexpr)));
    8028        23528 :                   gdebug *def_temp
    8029        23528 :                     = gimple_build_debug_bind (vexpr, comp, NULL);
    8030        23528 :                   gimple_stmt_iterator gsi;
    8031              : 
    8032        23528 :                   if (gimple_code (SSA_NAME_DEF_STMT (def)) == GIMPLE_PHI)
    8033        13214 :                     gsi = gsi_after_labels (gimple_bb
    8034        13214 :                                             (SSA_NAME_DEF_STMT (def)));
    8035              :                   else
    8036        10314 :                     gsi = gsi_for_stmt (SSA_NAME_DEF_STMT (def));
    8037              : 
    8038        23528 :                   gsi_insert_before (&gsi, def_temp, GSI_SAME_STMT);
    8039        23528 :                   comp = vexpr;
    8040              :                 }
    8041              : 
    8042       281116 :               FOR_EACH_IMM_USE_STMT (stmt, imm_iter, def)
    8043              :                 {
    8044       206837 :                   if (!gimple_debug_bind_p (stmt))
    8045        83555 :                     continue;
    8046              : 
    8047       246616 :                   FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
    8048       123308 :                     SET_USE (use_p, comp);
    8049              : 
    8050       123282 :                   update_stmt (stmt);
    8051        74279 :                 }
    8052              :             }
    8053              :         }
    8054              :     }
    8055       518949 : }
    8056              : 
    8057              : /* Frees memory occupied by class tree_niter_desc in *VALUE. Callback
    8058              :    for hash_map::traverse.  */
    8059              : 
    8060              : bool
    8061       499615 : free_tree_niter_desc (edge const &, tree_niter_desc *const &value, void *)
    8062              : {
    8063       499615 :   if (value)
    8064              :     {
    8065       460661 :       value->~tree_niter_desc ();
    8066       460661 :       free (value);
    8067              :     }
    8068       499615 :   return true;
    8069              : }
    8070              : 
    8071              : /* Frees data allocated by the optimization of a single loop.  */
    8072              : 
    8073              : static void
    8074       902256 : free_loop_data (struct ivopts_data *data)
    8075              : {
    8076       902256 :   unsigned i, j;
    8077       902256 :   bitmap_iterator bi;
    8078       902256 :   tree obj;
    8079              : 
    8080       902256 :   if (data->niters)
    8081              :     {
    8082       986951 :       data->niters->traverse<void *, free_tree_niter_desc> (NULL);
    8083       974672 :       delete data->niters;
    8084       487336 :       data->niters = NULL;
    8085              :     }
    8086              : 
    8087      6121748 :   EXECUTE_IF_SET_IN_BITMAP (data->relevant, 0, i, bi)
    8088              :     {
    8089      5219492 :       struct version_info *info;
    8090              : 
    8091      5219492 :       info = ver_info (data, i);
    8092      5219492 :       info->iv = NULL;
    8093      5219492 :       info->has_nonlin_use = false;
    8094      5219492 :       info->preserve_biv = false;
    8095      5219492 :       info->inv_id = 0;
    8096              :     }
    8097       902256 :   bitmap_clear (data->relevant);
    8098       902256 :   bitmap_clear (data->important_candidates);
    8099              : 
    8100      2751205 :   for (i = 0; i < data->vgroups.length (); i++)
    8101              :     {
    8102      1848949 :       struct iv_group *group = data->vgroups[i];
    8103              : 
    8104      3973956 :       for (j = 0; j < group->vuses.length (); j++)
    8105      2125007 :         free (group->vuses[j]);
    8106      1848949 :       group->vuses.release ();
    8107              : 
    8108      1848949 :       BITMAP_FREE (group->related_cands);
    8109     20077829 :       for (j = 0; j < group->n_map_members; j++)
    8110              :         {
    8111     18228880 :           if (group->cost_map[j].inv_vars)
    8112      3749924 :             BITMAP_FREE (group->cost_map[j].inv_vars);
    8113     18228880 :           if (group->cost_map[j].inv_exprs)
    8114      2059007 :             BITMAP_FREE (group->cost_map[j].inv_exprs);
    8115              :         }
    8116              : 
    8117      1848949 :       free (group->cost_map);
    8118      1848949 :       free (group);
    8119              :     }
    8120       902256 :   data->vgroups.truncate (0);
    8121              : 
    8122      5654284 :   for (i = 0; i < data->vcands.length (); i++)
    8123              :     {
    8124      4752028 :       struct iv_cand *cand = data->vcands[i];
    8125              : 
    8126      4752028 :       if (cand->inv_vars)
    8127        75957 :         BITMAP_FREE (cand->inv_vars);
    8128      4752028 :       if (cand->inv_exprs)
    8129        94616 :         BITMAP_FREE (cand->inv_exprs);
    8130      4752028 :       free (cand);
    8131              :     }
    8132       902256 :   data->vcands.truncate (0);
    8133              : 
    8134       902256 :   if (data->version_info_size < num_ssa_names)
    8135              :     {
    8136          174 :       data->version_info_size = 2 * num_ssa_names;
    8137          174 :       free (data->version_info);
    8138          174 :       data->version_info = XCNEWVEC (struct version_info, data->version_info_size);
    8139              :     }
    8140              : 
    8141       902256 :   data->max_inv_var_id = 0;
    8142       902256 :   data->max_inv_expr_id = 0;
    8143              : 
    8144       902256 :   data->inv_var_nregs.truncate (0);
    8145       902256 :   data->inv_expr_nregs.truncate (0);
    8146              : 
    8147       902256 :   FOR_EACH_VEC_ELT (decl_rtl_to_reset, i, obj)
    8148            0 :     SET_DECL_RTL (obj, NULL_RTX);
    8149              : 
    8150       902256 :   decl_rtl_to_reset.truncate (0);
    8151              : 
    8152       902256 :   data->inv_expr_tab->empty ();
    8153              : 
    8154       902256 :   data->iv_common_cand_tab->empty ();
    8155       902256 :   data->iv_common_cands.truncate (0);
    8156       902256 : }
    8157              : 
    8158              : /* Finalizes data structures used by the iv optimization pass.  LOOPS is the
    8159              :    loop tree.  */
    8160              : 
    8161              : static void
    8162       251559 : tree_ssa_iv_optimize_finalize (struct ivopts_data *data)
    8163              : {
    8164       251559 :   free_loop_data (data);
    8165       251559 :   free (data->version_info);
    8166       251559 :   BITMAP_FREE (data->relevant);
    8167       251559 :   BITMAP_FREE (data->important_candidates);
    8168              : 
    8169       251559 :   decl_rtl_to_reset.release ();
    8170       251559 :   data->vgroups.release ();
    8171       251559 :   data->vcands.release ();
    8172       251559 :   data->inv_var_nregs.release ();
    8173       251559 :   data->inv_expr_nregs.release ();
    8174       251559 :   delete data->inv_expr_tab;
    8175       251559 :   data->inv_expr_tab = NULL;
    8176       251559 :   free_affine_expand_cache (&data->name_expansion_cache);
    8177       251559 :   if (data->base_object_map)
    8178       169917 :     delete data->base_object_map;
    8179       251559 :   delete data->iv_common_cand_tab;
    8180       251559 :   data->iv_common_cand_tab = NULL;
    8181       251559 :   data->iv_common_cands.release ();
    8182       251559 :   obstack_free (&data->iv_obstack, NULL);
    8183       251559 : }
    8184              : 
    8185              : /* Returns true if the loop body BODY includes any function calls.  */
    8186              : 
    8187              : static bool
    8188       650697 : loop_body_includes_call (basic_block *body, unsigned num_nodes)
    8189              : {
    8190       650697 :   gimple_stmt_iterator gsi;
    8191       650697 :   unsigned i;
    8192              : 
    8193      2940951 :   for (i = 0; i < num_nodes; i++)
    8194     24930485 :     for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi))
    8195              :       {
    8196     20136006 :         gimple *stmt = gsi_stmt (gsi);
    8197     20136006 :         if (is_gimple_call (stmt)
    8198       288377 :             && !gimple_call_internal_p (stmt)
    8199     20356489 :             && !is_inexpensive_builtin (gimple_call_fndecl (stmt)))
    8200              :           return true;
    8201              :       }
    8202              :   return false;
    8203              : }
    8204              : 
    8205              : /* Determine cost scaling factor for basic blocks in loop.  */
    8206              : #define COST_SCALING_FACTOR_BOUND (20)
    8207              : 
    8208              : static void
    8209       519403 : determine_scaling_factor (struct ivopts_data *data, basic_block *body)
    8210              : {
    8211       519403 :   int lfreq = data->current_loop->header->count.to_frequency (cfun);
    8212       519403 :   if (!data->speed || lfreq <= 0)
    8213              :     return;
    8214              : 
    8215              :   int max_freq = lfreq;
    8216      2956548 :   for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
    8217              :     {
    8218      2526353 :       body[i]->aux = (void *)(intptr_t) 1;
    8219      2526353 :       if (max_freq < body[i]->count.to_frequency (cfun))
    8220       108831 :         max_freq = body[i]->count.to_frequency (cfun);
    8221              :     }
    8222       430195 :   if (max_freq > lfreq)
    8223              :     {
    8224        68830 :       int divisor, factor;
    8225              :       /* Check if scaling factor itself needs to be scaled by the bound.  This
    8226              :          is to avoid overflow when scaling cost according to profile info.  */
    8227        68830 :       if (max_freq / lfreq > COST_SCALING_FACTOR_BOUND)
    8228              :         {
    8229              :           divisor = max_freq;
    8230              :           factor = COST_SCALING_FACTOR_BOUND;
    8231              :         }
    8232              :       else
    8233              :         {
    8234        52530 :           divisor = lfreq;
    8235        52530 :           factor = 1;
    8236              :         }
    8237      1034600 :       for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
    8238              :         {
    8239       965770 :           int bfreq = body[i]->count.to_frequency (cfun);
    8240       965770 :           if (bfreq <= lfreq)
    8241       529814 :             continue;
    8242              : 
    8243       435956 :           body[i]->aux = (void*)(intptr_t) (factor * bfreq / divisor);
    8244              :         }
    8245              :     }
    8246              : }
    8247              : 
    8248              : /* Find doloop comparison use and set its doloop_p on if found.  */
    8249              : 
    8250              : static bool
    8251            0 : find_doloop_use (struct ivopts_data *data)
    8252              : {
    8253            0 :   struct loop *loop = data->current_loop;
    8254              : 
    8255            0 :   for (unsigned i = 0; i < data->vgroups.length (); i++)
    8256              :     {
    8257            0 :       struct iv_group *group = data->vgroups[i];
    8258            0 :       if (group->type == USE_COMPARE)
    8259              :         {
    8260            0 :           gcc_assert (group->vuses.length () == 1);
    8261            0 :           struct iv_use *use = group->vuses[0];
    8262            0 :           gimple *stmt = use->stmt;
    8263            0 :           if (gimple_code (stmt) == GIMPLE_COND)
    8264              :             {
    8265            0 :               basic_block bb = gimple_bb (stmt);
    8266            0 :               edge true_edge, false_edge;
    8267            0 :               extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
    8268              :               /* This comparison is used for loop latch.  Require latch is empty
    8269              :                  for now.  */
    8270            0 :               if ((loop->latch == true_edge->dest
    8271            0 :                    || loop->latch == false_edge->dest)
    8272            0 :                   && empty_block_p (loop->latch))
    8273              :                 {
    8274            0 :                   group->doloop_p = true;
    8275            0 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    8276              :                     {
    8277            0 :                       fprintf (dump_file, "Doloop cmp iv use: ");
    8278            0 :                       print_gimple_stmt (dump_file, stmt, TDF_DETAILS);
    8279              :                     }
    8280            0 :                   return true;
    8281              :                 }
    8282              :             }
    8283              :         }
    8284              :     }
    8285              : 
    8286              :   return false;
    8287              : }
    8288              : 
    8289              : /* For the targets which support doloop, to predict whether later RTL doloop
    8290              :    transformation will perform on this loop, further detect the doloop use and
    8291              :    mark the flag doloop_use_p if predicted.  */
    8292              : 
    8293              : void
    8294       519403 : analyze_and_mark_doloop_use (struct ivopts_data *data)
    8295              : {
    8296       519403 :   data->doloop_use_p = false;
    8297              : 
    8298       519403 :   if (!flag_branch_on_count_reg)
    8299              :     return;
    8300              : 
    8301       519403 :   if (data->current_loop->unroll == USHRT_MAX)
    8302              :     return;
    8303              : 
    8304       519403 :   if (!generic_predict_doloop_p (data))
    8305              :     return;
    8306              : 
    8307            0 :   if (find_doloop_use (data))
    8308              :     {
    8309            0 :       data->doloop_use_p = true;
    8310            0 :       if (dump_file && (dump_flags & TDF_DETAILS))
    8311              :         {
    8312            0 :           struct loop *loop = data->current_loop;
    8313            0 :           fprintf (dump_file,
    8314              :                    "Predict loop %d can perform"
    8315              :                    " doloop optimization later.\n",
    8316              :                    loop->num);
    8317            0 :           flow_loop_dump (loop, dump_file, NULL, 1);
    8318              :         }
    8319              :     }
    8320              : }
    8321              : 
    8322              : /* Optimizes the LOOP.  Returns true if anything changed.  */
    8323              : 
    8324              : static bool
    8325       650697 : tree_ssa_iv_optimize_loop (struct ivopts_data *data, class loop *loop,
    8326              :                            bitmap toremove)
    8327              : {
    8328       650697 :   bool changed = false;
    8329       650697 :   class iv_ca *iv_ca;
    8330       650697 :   edge exit = single_dom_exit (loop);
    8331       650697 :   basic_block *body;
    8332              : 
    8333       650697 :   gcc_assert (!data->niters);
    8334       650697 :   data->current_loop = loop;
    8335       650697 :   data->loop_loc = find_loop_location (loop).get_location_t ();
    8336       650697 :   data->speed = optimize_loop_for_speed_p (loop);
    8337              : 
    8338       650697 :   if (dump_file && (dump_flags & TDF_DETAILS))
    8339              :     {
    8340           72 :       fprintf (dump_file, "Processing loop %d", loop->num);
    8341           72 :       if (data->loop_loc != UNKNOWN_LOCATION)
    8342           70 :         fprintf (dump_file, " at %s:%d", LOCATION_FILE (data->loop_loc),
    8343          140 :                  LOCATION_LINE (data->loop_loc));
    8344           72 :       fprintf (dump_file, "\n");
    8345              : 
    8346           72 :       if (exit)
    8347              :         {
    8348           62 :           fprintf (dump_file, "  single exit %d -> %d, exit condition ",
    8349           62 :                    exit->src->index, exit->dest->index);
    8350          124 :           print_gimple_stmt (dump_file, *gsi_last_bb (exit->src),
    8351              :                              0, TDF_SLIM);
    8352           62 :           fprintf (dump_file, "\n");
    8353              :         }
    8354              : 
    8355           72 :       fprintf (dump_file, "\n");
    8356              :     }
    8357              : 
    8358       650697 :   body = get_loop_body (loop);
    8359       650697 :   data->body_includes_call = loop_body_includes_call (body, loop->num_nodes);
    8360       650697 :   renumber_gimple_stmt_uids_in_blocks (body, loop->num_nodes);
    8361              : 
    8362       650697 :   data->loop_single_exit_p
    8363       650697 :     = exit != NULL && loop_only_exit_p (loop, body, exit);
    8364              : 
    8365              :   /* For each ssa name determines whether it behaves as an induction variable
    8366              :      in some loop.  */
    8367       650697 :   if (!find_induction_variables (data, body))
    8368       131293 :     goto finish;
    8369              : 
    8370              :   /* Finds interesting uses (item 1).  */
    8371       519404 :   find_interesting_uses (data, body);
    8372       519404 :   if (data->vgroups.length () > MAX_CONSIDERED_GROUPS)
    8373            1 :     goto finish;
    8374              : 
    8375              :   /* Determine cost scaling factor for basic blocks in loop.  */
    8376       519403 :   determine_scaling_factor (data, body);
    8377              : 
    8378              :   /* Analyze doloop possibility and mark the doloop use if predicted.  */
    8379       519403 :   analyze_and_mark_doloop_use (data);
    8380              : 
    8381              :   /* Finds candidates for the induction variables (item 2).  */
    8382       519403 :   find_iv_candidates (data);
    8383              : 
    8384              :   /* Calculates the costs (item 3, part 1).  */
    8385       519403 :   determine_iv_costs (data);
    8386       519403 :   determine_group_iv_costs (data);
    8387       519403 :   determine_set_costs (data);
    8388              : 
    8389              :   /* Find the optimal set of induction variables (item 3, part 2).  */
    8390       519403 :   iv_ca = find_optimal_iv_set (data);
    8391              :   /* Cleanup basic block aux field.  */
    8392      3411746 :   for (unsigned i = 0; i < data->current_loop->num_nodes; i++)
    8393      2892343 :     body[i]->aux = NULL;
    8394       519403 :   if (!iv_ca)
    8395          454 :     goto finish;
    8396       518949 :   changed = true;
    8397              : 
    8398              :   /* Create the new induction variables (item 4, part 1).  */
    8399       518949 :   create_new_ivs (data, iv_ca);
    8400       518949 :   iv_ca_free (&iv_ca);
    8401              : 
    8402              :   /* Rewrite the uses (item 4, part 2).  */
    8403       518949 :   rewrite_groups (data);
    8404              : 
    8405              :   /* Remove the ivs that are unused after rewriting.  */
    8406       518949 :   remove_unused_ivs (data, toremove);
    8407              : 
    8408       650697 : finish:
    8409       650697 :   free (body);
    8410       650697 :   free_loop_data (data);
    8411              : 
    8412       650697 :   return changed;
    8413              : }
    8414              : 
    8415              : /* Main entry point.  Optimizes induction variables in loops.  */
    8416              : 
    8417              : void
    8418       251559 : tree_ssa_iv_optimize (void)
    8419              : {
    8420       251559 :   struct ivopts_data data;
    8421       251559 :   auto_bitmap toremove;
    8422              : 
    8423       251559 :   tree_ssa_iv_optimize_init (&data);
    8424       251559 :   mark_ssa_maybe_undefs ();
    8425              : 
    8426       251559 :   enable_ranger (cfun, false);
    8427              : 
    8428              :   /* Optimize the loops starting with the innermost ones.  */
    8429      1405374 :   for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
    8430              :     {
    8431       650697 :       if (!dbg_cnt (ivopts_loop))
    8432            0 :         continue;
    8433              : 
    8434       650697 :       if (dump_file && (dump_flags & TDF_DETAILS))
    8435           72 :         flow_loop_dump (loop, dump_file, NULL, 1);
    8436              : 
    8437       650697 :       tree_ssa_iv_optimize_loop (&data, loop, toremove);
    8438       251559 :     }
    8439              : 
    8440       251559 :   disable_ranger (cfun);
    8441              : 
    8442              :   /* Remove eliminated IV defs.  */
    8443       251559 :   release_defs_bitset (toremove);
    8444              : 
    8445              :   /* We have changed the structure of induction variables; it might happen
    8446              :      that definitions in the scev database refer to some of them that were
    8447              :      eliminated.  */
    8448       251559 :   scev_reset_htab ();
    8449              :   /* Likewise niter and control-IV information.  */
    8450       251559 :   free_numbers_of_iterations_estimates (cfun);
    8451              : 
    8452       251559 :   tree_ssa_iv_optimize_finalize (&data);
    8453       251559 : }
    8454              : 
    8455              : #include "gt-tree-ssa-loop-ivopts.h"
        

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.